简体   繁体   中英

Add a column to an existing matrix

I have created a matrix of 100 random numbers

set.seed(1)
datae=matrix( rnorm(100*1,mean=0,sd=1), 100, 1) 

Now I need to add another column to this matrix with a sum of the previous row, keeping the first row value [1,2] same as [1,1]

Eg: the result would be cumulative like:

#           [,1]       [,2]
#[1,] -0.6264538 -0.6264538
#[2,]  0.1836433 -0.4428105
#[3,] -0.8356286 -1.2784391
#[4,]  1.5952808  0.3168417
#[5,]  0.3295078  0.6463495
#[6,] -0.8204684 -0.1741189
# ...

I am a newbie and have been trying this for the last 45 minutes.

I think this is what you're looking for

datae=matrix( rnorm(100*1,mean=0,sd=1), 100, 1)
x <- matrix(ncol = 1, nrow = 100)
for(i in 1:100){
  x[i] <- sum(datae[1:i,1])
}
new <- cbind(datae, x)

new should be a 100x2 matrix with the 2nd column being a sum of all the previous rows of your first column.

Edit : As thelatemail pointed out below vectorised solutions in R are preferable whenever possible. Using cbind(datae, cumsum(datae[,1]) ) instead of the above code is both cleaner and more efficient. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM