1

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

GeekCat
  • 309
  • 5
  • 18
  • 1
    Why not just return `s[i-1]+ds`? The assignment `s[i] <- s[i-1]+ds` will only take place inside the function, not globally. – TARehman Dec 21 '15 at 17:07
  • Sometimes you just have to use a `for` loop. If that gets too slow, you might have to rewrite in C++ or FORTRAN. What's the problem with that? There are tricks that help `for` loop speed, like pre-defining vectors rather than growing them like your first example. – Spacedman Dec 21 '15 at 17:08
  • @TARehman I have tried what you said but still it does not work. – GeekCat Dec 21 '15 at 17:09
  • Sorry, I had a brain fart looking at it. I get the problem now. You need (I believe) `<<-`. – TARehman Dec 21 '15 at 17:10

1 Answers1

2

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
    }
)
Community
  • 1
  • 1
TARehman
  • 6,659
  • 3
  • 33
  • 60
  • Since I am trying to update S[i] with using S[i-1], I dont have any better solution for this. If you can change this, it would be very helpful – GeekCat Dec 21 '15 at 17:18
  • I am confused. Does this version not do what is needed? `s[i] <<- ...` should give you an updated version of `s[i]`. – TARehman Dec 21 '15 at 17:19
  • sorry, thanks for your comments, I thought you could change the global use of S and give a better version of this function. – GeekCat Dec 21 '15 at 17:23
  • Oh. I think, as Spacedman says, you just need to loop here. I'm not sure how else you can do this, since the values rely on previous values. – TARehman Dec 21 '15 at 17:25