Ich habe dieses data.frame
. Ich möchte Klassen (c1
zu c3
) in Dimensionen und Maße (m1
, m2
) in eine andere Dimension umwandeln.R data.frame misst in Array-Dimensionen
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
Es kann wie folgt geschehen:
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
Gibt es eine Möglichkeit, dies in einem Schritt zu tun?
Mein Endziel ist, dies zu tun:
c['8','F','V','m2']
[1] 3.505
Eine alternative Möglichkeit, dies zu tun, ohne Verwendung von Arrays, ist die Zeilen nach verketteten ids zu nennen.
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"))
@nrussell, wie soll ich Befehle von seinem Druck unterscheiden? – xm1