xm1 xm1 - 25 days ago 9
R Question

R data.frame measures into array dimensions

I have this

data.frame
. I want to transform classes (
c1
to
c3
) into dimensions and each measure(
m1
,
m2
) into another dimension.

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





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"))

Answer

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