Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a function for partial sum? [duplicate]

Tags:

r

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

like image 421
Michael Avatar asked Dec 21 '22 07:12

Michael


1 Answers

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
like image 148
A5C1D2H2I1M1N2O1R2T1 Avatar answered Jan 11 '23 23:01

A5C1D2H2I1M1N2O1R2T1