Summing up list members step by step

118 views Asked by At

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]
2

There are 2 answers

2
Zheyuan Li On BEST ANSWER

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)).

0
Abdou On

Try using Reduce with the accumulate parameter set to TRUE:

Reduce("+",rand.list, accumulate = T)

I hope this helps.