I want to do something like
foo = c(1, 1, 1)
bar = magic_function(foo, sum, init=0)
where bar
is 1 2 3
, i.e. the partial sum of foo
. Is there such a function, or what is the best way of doing it (avoiding a for-loop)?
Combining James's comment and mine into a formal answer, here are a few options:
> foo = c(1, 1, 1)
> cumsum(foo)
[1] 1 2 3
> Reduce("+", foo, accumulate = TRUE)
[1] 1 2 3
> Reduce("sum", foo, accumulate = TRUE)
[1] 1 2 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With