递归申请
Recursion on apply
我尝试执行以下操作 recursion:y[i]=y[i-1]+a[i] 我试过了:
apply(c(2:10),2,function(x) y[x]=y[x-1]+a[x])
但是没有用。有没有其他方法可以不用循环来做到这一点?
此时您需要 sapply
,如果您想在 sapply
中为 y
赋值,还需要 <<-
运算符。以下作品:
示例数据:
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
这个更快:
c(0,cumsum(a[c(-1,-length(a))])) + 1
或等同于:
c(0,cumsum(a[seq(2,10)])) + 1
我尝试执行以下操作 recursion:y[i]=y[i-1]+a[i] 我试过了:
apply(c(2:10),2,function(x) y[x]=y[x-1]+a[x])
但是没有用。有没有其他方法可以不用循环来做到这一点?
此时您需要 sapply
,如果您想在 sapply
中为 y
赋值,还需要 <<-
运算符。以下作品:
示例数据:
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
这个更快:
c(0,cumsum(a[c(-1,-length(a))])) + 1
或等同于:
c(0,cumsum(a[seq(2,10)])) + 1