R – Sum of first n elements of a vector

rsubsetsumvector

Let's say I have the following vector:

x <- c(5, 6, 3, 7, 5, 2, 6, 7, 5, 3, 1, 5, 6)

I would like to create a function with the parameter n that produces the sum of the first n elements.

Best Solution

How about this?

x <- c(5,6,3,7,5,2,6,7,5,3,1,5,6)
sumfun<-function(x,start,end){
  return(sum(x[start:end]))
}

x <- c(5,6,3,7,5,2,6,7,5,3,1,5,6)


> sumfun(x,1,3)
[1] 14