Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum columns in a matrix

Tags:

r

matrix

sum

I want to add columns 1:i of a matrix to get the cumulative sum of each. and then put the results in another matrix

so like having:

matrix
    [,1] [,2] [,3] [,4] [,5]
[1,]  A   B    C    D    E
[2,]  F   G    H    I    J
[3,]  K   L    M    N    O
[4,]  P   Q    R    S    T

become:

newmatrix
    [,1]  [,2] [,3]     [,4]     [,5]
[1,]  A   A+B  A+B+C  A+B+C+D  A+B+C+D+E  
[2,]  F   F+G  F+G+H  F+G+H+I  F+G+H+I+J
[3,]  K   K+L  K+L+M  K+L+M+N  K+L+M+N+O
[4,]  P   P+Q  P+Q+R  P+Q+R+S  P+Q+R+S+T
like image 203
Summer Gleek Avatar asked Oct 24 '25 19:10

Summer Gleek


1 Answers

> m<-matrix(rep(1:5,each=4),ncol=5)
> t(apply(m,1,cumsum))
like image 116
DatamineR Avatar answered Oct 26 '25 09:10

DatamineR