我想列表數據,以便因子變量變爲列並保留單元中另一個變量的值。在R中製表數據框
所以,我想,
a=rep(1:3,3)
d<-rep(1:3, each=3)
b=rnorm(9)
c=runif(9)
dt<-data.frame(a,d,b,c)
a d b c
1 1 1 0.3819762 0.5199602
2 2 1 0.3896063 0.9144730
3 3 1 2.4356972 0.2888464
4 1 2 1.2697016 0.9831191
5 2 2 -1.9844689 0.2046947
6 3 2 0.3473766 0.4766178
7 1 3 -1.5461235 0.6187189
8 2 3 1.0829027 0.9089551
9 3 3 -0.1305324 0.6326141
我看了data.table
,plyr
,reshape2
但找不到我想要做的。所以,我做了舊的循環方式。
mat<-matrix(NA, nrow=3, ncol=4)
for (i in 1:3){
mat[i,1]<-i
for (j in 1:3){
val=dt[a==i & d==j,3]
mat[i,j+1]<-val
}
}
mat
[,1] [,2] [,3] [,4]
[1,] 1 0.3819762 1.2697016 -1.5461235
[2,] 2 0.3896063 -1.9844689 1.0829027
[3,] 3 2.4356972 0.3473766 -0.1305324
......並且它需要永遠的大數據。
任何更好的選擇?
感謝,yeah.I看到即使使用這些包我無法弄清楚這些參數名。 – Ananta