我尝试执行以下递归:y [i] = y [i-1] + a [i]我试过了:
apply(c(2:10),2,function(x) y[x]=y[x-1]+a[x])
但它没有用。是否有其他方法可以在没有循环的情况下执行此操作?
答案 0 :(得分:3)
这更快:
c(0,cumsum(a[c(-1,-length(a))])) + 1
或等效地:
c(0,cumsum(a[seq(2,10)])) + 1
答案 1 :(得分:2)
如果您想在sapply
内为<<-
分配值,则此时需要y
,还需要sapply
运算符。以下作品:
示例数据:
y <- vector() #initiate a vector (can also simply do y <- 1 )
y[1] <- 1 #I suppose the first value will be provided
a <- 20:30 #some random data for a
解决方案:
#sapply works for vectors i.e. for your 2:10, c() is unnecessary btw
#<<- operator modifies the y vector outside the sapply according to the formula
> sapply(c(2:10), function(x) {y[x] <<- y[x-1] + a[x]} )
[1] 22 44 67 91 116 142 169 197 226
#y looks like this after the assignments
> y
[1] 1 22 44 67 91 116 142 169 197 226