I have a question about adding up the column of the matrix for example:
I have a matrix
[,1] [,2] [,3]
[1,] 1 3 1
[2,] 2 4 2
I want it to
We can apply cumsum
on each row by looping over the rows with apply
and MARGIN
specified as 1 and transpose the output
t(apply(m1, 1, cumsum))
# [,1] [,2] [,3]
#[1,] 1 4 5
#[2,] 2 6 8
Or with a for
loop
for(i in seq_len(ncol(m1))[-1]) m1[,i] <- m1[, i] + m1[, i-1]
Or another option is to split it a list
of vectors with asplit
and then Reduce
with +
and accumulate = TRUE
do.call(cbind, Reduce(`+`, asplit(m1, 2), accumulate = TRUE))
# [,1] [,2] [,3]
#[1,] 1 4 5
#[2,] 2 6 8
or with a convenient function rowCumsums
from matrixStats
library(matrixStats)
rowCumsums(m1)
# [,1] [,2] [,3]
#[1,] 1 4 5
#[2,] 2 6 8
m1 <- cbind(1:2, 3:4, 1:2)