我有一个数据集(显示的只是一个快照),我需要创建一个矩阵,其中处理为行,年份为列。矩阵内部需要包含Y列的均值和方差。
Y<-c(0,1,1,1,0,0,0,2,0,2)
Treatment<-c(0,0,0,0,1,1,1,1,1,1)
Year<-c(1,2,3,4,5,1,2,3,4,5)
dat<-as.data.frame(cbind(Y,Treatment,Year))
print(dat)
Y Treatment Year
1 0 0 1
2 1 0 2
3 1 0 3
4 1 0 4
5 0 1 5
6 0 1 1
7 0 1 2
8 2 1 3
9 0 1 4
10 2 1 5
我希望我的矩阵能够显示Y列的均值和方差。
答案 0 :(得分:1)
我认为你正在寻找类似的东西:
library(reshape2)
as.matrix(dcast(Treatment ~ Year, data = df, value.var = "Y", fun.aggregate = mean))
Treatment 1 2 3 4 5
[1,] 0 0 1 1 1 NaN
[2,] 1 0 0 2 0 1
答案 1 :(得分:0)
这是你在找什么?
Y<-c(0,1,1,1,0,0,0,2,0,2)
Treatment<-c(0,0,0,0,1,1,1,1,1,1)
Year<-c(1,2,3,4,5,1,2,3,4,5)
dat<-cbind(Y,Treatment,Year)
meanY<-mean(Y)
varY<-var(y)
dat1<-cbind(dat,meanY,varY)
print(dat1)
Y Treatment Year meanY varY
[1,] 0 0 1 0.7 19.09091
[2,] 1 0 2 0.7 19.09091
[3,] 1 0 3 0.7 19.09091
[4,] 1 0 4 0.7 19.09091
[5,] 0 1 5 0.7 19.09091
[6,] 0 1 1 0.7 19.09091
[7,] 0 1 2 0.7 19.09091
[8,] 2 1 3 0.7 19.09091
[9,] 0 1 4 0.7 19.09091
[10,] 2 1 5 0.7 19.09091
如果计算该值并将其作为列添加到矩阵或数据框中,则R将扩展列的长度。