Reputation: 91
I have a data frame with multiple identically named columns:
> df <- data.frame(X1=c(1:4),Y1=c(16:13),X2=c(4:7),Y2=c(-1:-4),X3=c(3:6),Y3=c(2:-1))
> df
X1 Y1 X2 Y2 X3 Y3
1 1 16 4 -1 3 2
2 2 15 5 -2 4 1
3 3 14 6 -3 5 0
4 4 13 7 -4 6 -1
> names(df)[c(1,3,5)] <- "X"
I want to melt this data frame with id.vars='X', however only the first 'X' column is recognized. This is giving me:
> df2 <- melt(df, id.vars = 'X')
> df2
X variable value
1 1 Y1 16
2 2 Y1 15
3 3 Y1 14
4 4 Y1 13
5 1 Y2 -1
6 2 Y2 -2
7 3 Y2 -3
8 4 Y2 -4
9 1 Y3 2
10 2 Y3 1
11 3 Y3 0
12 4 Y3 -1
My desired output would be:
> df2
X variable value
1 1 Y1 16
2 2 Y1 15
3 3 Y1 14
4 4 Y1 13
5 4 Y2 -1
6 5 Y2 -2
7 6 Y2 -3
8 7 Y2 -4
9 3 Y3 2
10 4 Y3 1
11 5 Y3 0
12 6 Y3 -1
Upvotes: 1
Views: 833
Reputation: 8880
library(tidyverse)
library(tidyselect)
df %>% pivot_longer(everything(),
names_to = c(".value", "set"),
names_pattern = "(.)(.)")
Upvotes: 0
Reputation: 887158
We can use melt
from data.table
library(data.table)
names(df) <- make.unique(names(df))
melt(setDT(df), measure = patterns("^X", "^Y"))
Upvotes: 4