向量的前 n 个元素的总和

向量的前 n 个元素的总和

问题描述:

假设我有以下向量:

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

我想用参数 n 创建一个函数,它产生前 n 个元素的总和.

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

这个怎么样?

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