简体   繁体   中英

Convert matrix into cumulative matrix in R

In RI have a matrix, say:

1 0 1 2 0 0 3
2 0 2 0 2 2 1
0 1 2 1 3 2 3
4 0 1 2 1 1 0

I would like to convert this matrix into a cumulative version, so that I get out the matrix:

1 1 2 4 4 4 7
2 2 4 4 6 8 9
0 1 3 4 7 9 12
4 4 5 7 8 9 9

So the [i,j] th entry in matrix 2 is the sum of all the elements in matrix 1 such that i_1 <= i_2 . How might I do this in R?

You can do:

> t(apply(mat, 1, cumsum))

or

> ave(mat, row(mat), FUN = cumsum)

     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    1    2    4    4    4    7
[2,]    2    2    4    4    6    8    9
[3,]    0    1    3    4    7    9   12
[4,]    4    4    5    7    8    9    9

where mat is your original matrix.

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