dplanet
dplanet

Reputation: 5413

Convert matrix into cumulative matrix in R

In R I 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?

Upvotes: 2

Views: 161

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61214

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.

Upvotes: 4

Related Questions