我想知道是否可以使用 lapply() 函数来改变输入的值,类似于:
a1<-runif(100)
a2<-function(i){
a1[i]<-a1[i-1]*a1[i];a1[i]
}
a3<-lapply(2:100,a2)
我正在寻找类似于 for() 循环的东西,但使用 lapply() 基础设施。我无法让 rapply() 做到这一点。
原因是“真正的”a2 函数是一个困难的函数,只有当 a1[i-1] 的值满足某些条件时才需要进行评估。
重新措辞:所以我试图用 lapply() 类型的东西替换下面代码中的 for():
a1<-runif(100)
a2<-function(i, a1){
a1[i]<-a1[i-1]*2
a1[i]
}
a3<-as.numeric(lapply(2:100, a2, a1=a1))
#compare the output of a3 with that of a1 after the recursive loop
a2<-a1 #saved for comparison
for(i in 2:length(a1)){
a1[i]<-a1[i-1]*2
}
cbind(a1[2:100],a3)
#actually this is would be like writting a lapply() version of the cumprod() function
cbind(a1,cumprod(a2))
R 邮件列表建议查看 Reduce() 函数....如:
a1<-runif(100)
cadd<-function(x) Reduce("*", x, accumulate = TRUE)
cadd(a1)
这给出了与 cumprod(a1) 相同的结果......但比循环还要慢:
a1<-runif(100000)
cadd<-function(x) Reduce("*", x, accumulate = TRUE)
looop<-function(a1){
j<-length(a1)
for(i in 2:j){
a1[i]<-a1[i-1]*a1[i]
}
a1
}
> system.time(cadd(a1))
user system elapsed
1.344 0.004 1.353
> system.time(cumprod(a1))
user system elapsed
0.004 0.000 0.002
> system.time(loop(a1))
user system elapsed
0.772 0.000 0.775
>
任何的想法 ?