[英]R data.frame measures into array dimensions
I have this data.frame
. 我有这个
data.frame
。 I want to transform classes ( c1
to c3
) into dimensions and measures ( m1
, m2
) into another dimension. 我想将类(
c1
到c3
)转换为维度,并将度量( m1
, m2
)转换为另一个维度。
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
It can be done like this: 可以这样完成:
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
Is there a way to do this in one step? 有没有办法一步一步做到这一点?
My final goal is to do this: 我的最终目标是做到这一点:
c['8','F','V','m2']
[1] 3.505
An alternative way to do this, without using arrays, is to name the rows according to concatenated ids. 一种不使用数组的替代方法是根据连接的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"))
I think I found a more easy option for you: 我想我为您找到了一个更简单的选择:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.