[英]R programming - Adding extra column to existing matrix
I am a beginner to R programming and am trying to add one extra column to a matrix having 50 columns. 我是R编程的初学者,我正在尝试将一个额外的列添加到具有50列的矩阵中。 This new column would be the avg of first 10 values in that row.
这个新列将是该行中前10个值的平均值。
randomMatrix <- generateMatrix(1,5000,100,50)
randomMatrix51 <- matrix(nrow=100, ncol=1)
for(ctr in 1:ncol(randomMatrix)){
randomMatrix51.mat[1,ctr] <- sum(randomMatrix [ctr, 1:10])/10
}
This gives the below error 这给出了以下错误
Error in randomMatrix51.mat[1, ctr] <- sum(randomMatrix[ctr, 1:10])/10 :incorrect
number of subscripts on matrix
I tried this 我试过这个
cbind(randomMatrix,sum(randomMatrix [ctr, 1:10])/10)
But it only works for one row, if I use this cbind in the loop all the old values are over written. 但它只适用于一行,如果我在循环中使用这个cbind所有旧的值都被写了。
How do I add the average of first 10 values in the new column. 如何在新列中添加前10个值的平均值。 Is there a better way to do this other than looping over rows ?
除了循环行之外,还有更好的方法吗?
Bam! 巴姆!
a <- matrix(1:5000, nrow=100)
a <- cbind(a,apply(a[,1:10],1,mean))
On big datasets it is however faster (and arguably simpler) to use: 在大数据集上,使用它更快(并且可以说更简单):
cbind(a, rowMeans(a[,1:10]) )
Methinks you are over thinking this. 你想到了这一点。
a <- matrix(1:5000, nrow=100)
a <- transform(a, first10ave = colMeans(a[1:10,]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.