Reputation: 409
I have a piece of R code like this
s<-vector()
s[1]=1
for(i in 2:10){
ds= 1/i/s[i-1]
s[i]= s[i-1]+ds
}
s
The result is:
[1] 1.000000 1.500000 1.722222 1.867384 1.974485 2.058895 2.128281 2.187014
[9] 2.237819 2.282505
The above is an toy example, what I am trying to do is updating s[i] with some sort of use of s[i-1], please help me with this case, I have tried the following:
s<-vector()
s[1]<-1
sapply(2:10,FUN = function(i){
if(i==1){
return(s[i])
}
ds<-1/i/s[i-1]
#print(paste(i,s_new,ds,ds+s[i-1]))
s[i]= s[i-1]+ds
return(s[i])
}
)
The above does not work
Upvotes: 1
Views: 276
Reputation: 6749
I think that using <<-
will let you directly assign to the global version of s
. This is not something I do frequently. See this question for good details of how environments work in R.
I'm not crazy with the below version, mostly because it's mixing a return()
with a direct assignment <<-
. At this point, it seems like you might as well use a loop as mentioned in the comments.
s <- vector()
s[1] <- 1
sapply(2:10,FUN = function(i){
if(i == 1){
return(s[i])
}
ds <- 1/i/s[i - 1]
s[i] <<- s[i - 1] + ds
}
)
Upvotes: 2