Reputation: 553
I've got a very simple problem but I was unable to find a simple solution in R because I was used to solve such problems by iterating through an incrementing for-loop in other languages.
Let's say I've got a random distributed numeric list like:
rand.list <- list(4,3,3,2,5)
I'd like to change this random distributed pattern into a constantly rising pattern so the result would look like:
[4,7,10,12,17]
Upvotes: 1
Views: 119
Reputation: 73385
It came to me first to do cumsum(unlist(rand.list))
, where unlist
collapses the list into a plain vector. However, my lucky try shows that cumsum(rand.list)
also works.
It is not that clear to me how this work, as the source code of cumsum
calls .Primitive
, an internal S3 method dispatcher which is not easy to further investigate. But I make another complementary experiment as follow:
x <- list(1:2,3:4,5:6)
cumsum(x) ## does not work
x <- list(c(1,2), c(3,4), c(5,6))
cumsum(x) ## does not work
In this case, we have to do cumsum(unlist(x))
.
Upvotes: 1
Reputation: 13274
Try using Reduce
with the accumulate
parameter set to TRUE
:
Reduce("+",rand.list, accumulate = T)
I hope this helps.
Upvotes: 2