如何将数据帧从宽到长转换

时间:2013-07-18 17:47:18

标签: r dataframe reshape melt

我有这个数据框:

data=structure(list(X3CO = c(24.88993835, 25.02366257, 24.90308762), X3CS = c(25.70629883,25.26747704, 25.1953907), X3CD = c(26.95723343, 26.84725571, 26.2314415)), .Names = c("X3CO", "X3CS", "X3CD"), class = "data.frame", row.names = c(NA, -3L))

> data
      X3CO     X3CS     X3CD
1 24.88994 25.70630 26.95723
2 25.02366 25.26748 26.84726
3 24.90309 25.19539 26.23144

我想要做的是创建一个新的数据帧,将所有行放入一列,将列名称放入第二列:

24.88994 X3CO
25.02366 X3CO
24.90309 X3CO
25.70630 X3CS  
25.26748 X3CS

你知道一个简单的方法吗?

修改:有没有办法添加一个尊重ind的顺序的ID?

24.88994 X3CO 1
25.02366 X3CO 1
24.90309 X3CO 1
25.70630 X3CS 2
25.26748 X3CS 2

3 个答案:

答案 0 :(得分:9)

更快,并使用R-base:

 stack(data)
       values  ind
1 24.88993835 X3CO
2 25.02366257 X3CO
3 24.90308762 X3CO
4 25.70629883 X3CS
5 25.26747704 X3CS
6 25.19539070 X3CS
7 26.95723343 X3CD

答案 1 :(得分:3)

> library(reshape2)
> melt(data)
Using  as id variables
  variable    value
1     X3CO 24.88994
2     X3CO 25.02366
3     X3CO 24.90309
4     X3CS 25.70630
5     X3CS 25.26748
6     X3CS 25.19539
7     X3CD 26.95723
8     X3CD 26.84726
9     X3CD 26.23144

答案 2 :(得分:2)

轻松自在!您需要查看reshape2包的所有数据整形能力

library(reshape2)

melt(data)