Search code examples
rfor-loopgraphplotautoregressive-models

Why would an R function not write to the environment?


I'm trying to write a relatively simple AR(1) representation in R. I cannot find any glaring issues with this code, and furthermore I am returning not errors, it simple isn't writing to the environment, or recognizing areone2 as a function. Any suggestions would be much appreciated.

areone2<-function(y,N,p,d){
  yvec<-c(rep(y, times = N))
  for(i in 1:N){
    yvec[i+1]<-
      ((1+p*(yvec[i]-d))
      + d)
               }
  plot(yvec, type='l', xlab="N", ylab="yeild")
                          }

areone2(.3,10,.9,.2)

Solution

  • It doesn't trigger an error or warning because you broke the line in the middle of a binary operation, but that binary operation wasn't recognized by the parser. It's perfectly legal to begin a line with + 3 It's just 3, which is not what you want.

    For example, 2 + 3 is 5, we would expect. But +3 on a new line does not add it to the previous line

    > 2        ## break the line here and R returns 2
    [1] 2
    > +3       ## adding three next is not recognized as a continuation of a call
    [1] 3
    

    But you can still break the line if you wrap the call in parentheses (not brackets)

    (2 
     + 3)
    # [1] 5   ## correct
    {2 
     + 3} 
    # [1] 3   ## incorrect
    

    Bringing your yvec[]<- assignment call up onto one line is the cleaner and safer way to go.

    yvec[i+1] <- ((1+p*(yvec[i]-d)) + d)