有部分和的函数吗?

Mic*_*ael 4 r

我想做点什么

foo = c(1, 1, 1)
bar = magic_function(foo, sum, init=0)
Run Code Online (Sandbox Code Playgroud)

其中bar是1 2 3,即的部分和foo.是否有这样的功能,或者最好的方法是什么(避免for-loop)?

A5C*_*2T1 11

将詹姆斯的评论和我的评论结合成一个正式的答案,这里有几个选择:

> 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
Run Code Online (Sandbox Code Playgroud)