supersambo
supersambo

Reputation: 811

R sum element by element resulting in vector

First of all sorry for this question. I suppose it's super basic but I can't find the right search terms. For a vector a lets say:

    a<-c(1,1,3,2,1)

I want to get a vector b which results when suming element by element

    >b
    1 2 5 7 8

it would be something like:

    x<-2
    b<-as.vector(a[1])
    while(x<=length(a)) {
      c<-a[x]+b[x-1]
      b=c(b,c)
      x=x+1
    }
    rm(x,c)

but isn't there a built-in function for this?

Upvotes: 3

Views: 583

Answers (1)

csgillespie
csgillespie

Reputation: 60522

You are looking for cumsum:

a = c(1,1,3,2,1)

R> cumsum(a)
[1] 1 2 5 7 8

Upvotes: 3

Related Questions