R data.frame测量到数组维度

时间:2016-11-11 14:54:42

标签: arrays r dataframe casting

我有data.frame。我想将类(c1c3)转换为维度和度量(m1m2)到另一个维度。

df
   c1    c2 c3        m1     m2
1   0 FALSE  C 0.4572084 26.453
2   0 FALSE  V 0.4033657 11.505
3   0  TRUE  C        NA     NA
4   0  TRUE  V 0.4665911 23.062
5   8 FALSE  C 0.4566605 27.685
6   8 FALSE  V 0.3920727  3.505
7   8  TRUE  C        NA     NA
8   8  TRUE  V 0.4528438 16.155
9   2 FALSE  C 0.4401774 29.609
10  2 FALSE  V 0.4161140 10.410
11  2  TRUE  C 0.3979405  5.840
12  2  TRUE  V 0.4268235 10.168

可以这样做:

library(reshape2)
a=acast(df,c1~c2~c3,value.var = 'm1',fun.aggregate=mean)
b=acast(df,c1~c2~c3,value.var = 'm2',fun.aggregate=mean)
c=array(c(a,b),dim=c(3,2,2,2))
dimnames(c)=list(c('0','2','8'),c('F','T'),c('C','V'),c('m1','m2'))
c
, , C, m1

          F         T
0 0.4572084        NA
2 0.4401774 0.3979405
8 0.4566605        NA

, , V, m1

          F         T
0 0.4033657 0.4665911
2 0.4161140 0.4268235
8 0.3920727 0.4528438

, , C, m2

       F    T
0 26.453   NA
2 29.609 5.84
8 27.685   NA

, , V, m2

       F      T
0 11.505 23.062
2 10.410 10.168
8  3.505 16.155 

有没有办法一步到位? 我的最终目标是这样做:

c['8','F','V','m2']
[1] 3.505 

在不使用数组的情况下,另一种方法是根据连接的id命名行。

rownames(df) = paste0(df$c1, substr(df$c2,1,1), df$c3)
df['8FV','m2']
[1] 3.505 
df <- structure(list(c1 = c(0L, 0L, 0L, 0L, 8L, 8L, 8L, 8L, 2L, 2L, 
2L, 2L), c2 = c(FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, 
TRUE, FALSE, FALSE, TRUE, TRUE), c3 = c("C", "V", "C", "V", "C", 
"V", "C", "V", "C", "V", "C", "V"), m1 = c(0.4572084, 0.4033657, 
NA, 0.4665911, 0.4566605, 0.3920727, NA, 0.4528438, 0.4401774, 
0.416114, 0.3979405, 0.4268235), m2 = c(26.453, 11.505, NA, 23.062, 
27.685, 3.505, NA, 16.155, 29.609, 10.41, 5.84, 10.168)), .Names = c("c1", 
"c2", "c3", "m1", "m2"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))

1 个答案:

答案 0 :(得分:1)

我想我找到了一个更简单的选择:

library(reshape2)
m <- melt(df, id.vars = c("c1", "c2", "c3"))
a <- acast(m,formula = c1 ~ c2 ~ c3 ~ variable)
a['8','FALSE','V','m2']
[1] 3.505