Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R programming - Adding extra column to existing matrix

Tags:

r

statistics

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 ?

like image 870
user2085566 Avatar asked Feb 20 '13 05:02

user2085566


People also ask

How do I add a column to an existing table in R?

How do I add a column to a DataFrame in R? To add a new column to a dataframe in R you can use the $-operator. For example, to add the column “NewColumn”, you can do like this: dataf$NewColumn <- Values . Now, this will effectively add your new variable to your dataset.

How do I add an extra column to a matrix in R?

For adding a column to a Matrix in we use cbind() function. To know more about cbind() function simply type ? cbind() or help(cbind) in R. It will display documentation of cbind() function in R documentation as shown below.

How do you add data to a matrix in R?

To enter an n dimension identity matrix in R we use diag (n) function. I-diag(3), this will enter a 3×3 matrix of dimension 3. Operations in Matrices: To add and subtract the matrices with same number of rows and columns.


Video Answer


2 Answers

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]) )
like image 62
thelatemail Avatar answered Oct 11 '22 00:10

thelatemail


Methinks you are over thinking this.

a <- matrix(1:5000, nrow=100)
a <- transform(a,  first10ave = colMeans(a[1:10,]))
like image 41
N8TRO Avatar answered Oct 11 '22 00:10

N8TRO