R programming - Adding extra column to existing matrix
r, statistics
Solution
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]) )
Problem
I am a beginner to R programming and am trying to add one extra column to a matrix having 50 columns. This new column would be the avg of first 10 values in that row. ``` 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. How do I add the average of first 10 values in the new column. Is there a better way to do this other than looping over rows ?