Reputation: 31
I have a matrix like
> A= [ 1 2 4
> 2 3 1
> 3 1 2 ]
and I would like to have result accumulative by each row from right to left like:
> A= [ 7 6 4
> 6 4 1
> 6 3 2 ]
I tried to use the solution in Cumulative sum in a matrix but it gives a different way of adding the matrix.
Upvotes: 2
Views: 116
Reputation: 66844
You mentioned data.frame
in the title, and there is a way of using Reduce
and rev
with a data.frame to get the result you want.
A <- data.frame(c(1,2,3),c(2,3,1),c(4,1,2))
data.frame(rev(Reduce("+",rev(A),accumulate=TRUE)))
c.7..6..6. c.6..4..3. c.4..1..2.
1 7 6 4
2 6 4 1
3 6 3 2
Upvotes: 0
Reputation: 226192
A little bit magical, but:
t(apply(A,1,function(x) rev(cumsum(rev(x)))))
does it.
apply(A, 1, FUN)
applies a function to each row of the matrix.rev()
reverses the vector and cumsum()
computes the cumulative sum: we need rev(cumsum(rev(x)))
to get the ordering you wantt()
is necessary to transpose the results because apply
always returns its results column-wise, as (very obscurely) noted here (from the "Value" section of ?apply
):If each call to ‘FUN’ returns a vector of length ‘n’, then ‘apply’ returns an array of dimension ‘c(n, dim(X)[MARGIN])’ if ‘n > 1’
Upvotes: 5