R: stack multiple columns into single column while keeping column names in rows [duplicate]
Say I have the following data.frame (df
):
c1 <- c(1,2,3,4);c2 <- c(5,6,7,8);c3 <- c(9,10,11,12)
df <- data.frame(c1, c2,c3)
# c1 c2 c3
# 1 1 5 9
# 2 2 6 10
# 3 3 7 11
# 4 4 8 12
I would like to stack every df
's columns in a single column but keep the identifier of each column in a new variable (id
).
values <- c(c1,c2,c3)
wanted <- as.data.frame(values )
wanted$id <- c(rep("c1", 4),rep("c2", 4),rep("c3", 4))
# values id
# 1 1 c1
# 2 2 c1
# 3 3 c1
# 4 4 c1
# 5 5 c2
# 6 6 c2
# 7 7 c2
# 8 8 c2
# 9 9 c3
# 10 10 c3
# 11 11 c3
# 12 12 c3
We can use stack
> stack(df)
values ind
1 1 c1
2 2 c1
3 3 c1
4 4 c1
5 5 c2
6 6 c2
7 7 c2
8 8 c2
9 9 c3
10 10 c3
11 11 c3
12 12 c3