Adding numbers within a vector in r

2019-03-02 01:32发布

问题:

I have a vector

v<-c(1,2,3)

I need add the numbers in the vector in the following fashion

1,1+2,1+2+3

producing a second vector

v1<-c(1,3,6)

This is probably quite simple...but I am a bit stuck.

回答1:

Use the cumulative sum function:

cumsum(v)
#[1] 1 3 6