szeta
szeta

Reputation: 599

Cumsum along one dimension in an array

say I have an array

a <- array(dim=c(2,5), dimnames=list(c(1,2),c(1:5)))
a[] <- 10

   1  2  3  4  5
1 10 10 10 10 10
2 10 10 10 10 10

and would like to create something like a cumsum() along one dimension, to get:

   1  2  3  4  5
1 10 20 30 40 50
2 10 20 30 40 50

Or a declining balance (cumulative remaining):

   1  2  3  4  5
1 50 40 30 20 10
2 50 40 30 20 10

What is the right way to do this in R (vectorized)?

Not nice, but illustrative:

for (i in 1:2) {
 for (j in 1:5) {
  b[i,j] <- sum(a[i,1:j])
 }
}

   1  2  3  4  5
1 10 20 30 40 50
2 10 20 30 40 50

declining balance sample (to show why "cumsum()" isn't the answer expected):

for (i in 1:2) {
 for (j in 1:5) {
  b[i,j] <- sum(a[i,j:5])
 }
}

Thanks

Upvotes: 0

Views: 371

Answers (2)

drw
drw

Reputation: 943

You could try something like

apply(a,2,cumsum) 

for column sums or

t(apply(a,1,cumsum)) 

for the rows. You need the t() because the shape is otherwise the wrong way round.

Upvotes: 1

Shenglin Chen
Shenglin Chen

Reputation: 4554

For cumsum():

b<-t(apply(a,1,cumsum))

For order:

t(apply(b,1,function(x)sort(x, decreasing=T)))

Upvotes: 0

Related Questions