变换矩阵使得一个因子成为rowname

时间:2012-02-02 01:02:02

标签: r dataframe plyr reshape

我有以下数据 - 它是来自规范化数据库的转储,但我无法访问数据库,数据库维护者坚持认为这不是必需的。

obs变量是唯一的观察ID,a.k.a。“转向”

具体来说,我想从此olddata转到下面的newdata数据框:

> olddata
    species obs variable value
3      ADFA   1     mean     4
4      ADFA   1      lat   118
5      ADFA   1      lon    49
6      ADFA   1     masl    74
96     HODO   8     mean    18
97     HODO   8      lat   120
98     HODO   8      lon    45
99     HODO   8     masl    36
189    HODO   9     mean    34
190    HODO   9      lat   126
191    HODO   9      lon    12
192    HODO   9     masl    35

我想重塑这个数据框看起来像:

> newdata
  species obs mean lat lon masl
1    ADFA   1    4 118  49   74
2    HODO   8   18 120  45   36
3    HODO   9   34 126  12   35

免责声明:此问题可能已经提出过,但我无法在转换数据帧/矩阵的许多问题中找到问题


以下是重现此问题时使用的数据框:

olddata <- structure(list(species = c("ADFA", "ADFA", "ADFA", "ADFA", "HODO", 
             "HODO", "HODO", "HODO", "HODO", "HODO", "HODO", "HODO"), obs = c(1, 
             1, 1, 1, 8, 8, 8, 8, 9, 9, 9, 9), variable = c("mean", "lat", 
             "lon", "masl", "mean", "lat", "lon", "masl", "mean", "lat", "lon", 
             "masl"), value = c(4, 118, 49, 74, 18, 120, 45, 36, 34, 126, 
             12, 35)), .Names = c("species", "obs", "variable", "value"), 
             row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", 
              "11", "12"), class = "data.frame")

newdata <- structure(list(species = c("ADFA", "HODO", "HODO"), obs = c(1, 
             8, 9), mean = c(4, 18, 34), lat = c(118, 120, 126), lon = c(49, 
             45, 12), masl = c(74, 36, 35)), .Names = c("species", "obs", 
             "mean", "lat", "lon", "masl"), row.names = c(NA, -3L), 
             class = "data.frame")

2 个答案:

答案 0 :(得分:2)

以下是一个例子:

> library(reshape2)
> dcast(olddata, species+obs~variable)
  species obs lat lon masl mean
1    ADFA   1 118  49   74    4
2    HODO   8 120  45   36   18
3    HODO   9 126  12   35   34

答案 1 :(得分:1)

library(reshape2)    
dcast(olddata,species+obs~variable)