2

I'm trying to use a function in order to read in different models. Using the code below without a function works. When I use the function and call it, I will get the error

Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

Can anyone tell me why?

x=rnorm(1000)+sin(c(1:1000)/100)#random data+ sinus superimposed

plot <- function(model){
    par(mfrow=c(2,2))# plot window settings
    plot(model)
    lines(filter(model,rep(1/30,30)),col='red')
    plot(filter(model,rep(1/30,30)))
    plot(model-filter(model,rep(1/30,30)))

    # variances of variable, long term variability and short term variability
    var(model)
    var(filter(model, rep(1/30,30)),na.rm=T)
    var(model-filter(model, rep(1/30,30)),na.rm=T)

}

plot(x)
scriptgirl_3000
  • 161
  • 3
  • 16

1 Answers1

2

The problem is that the plot function you are defining is also the one that gets called inside its body, so there is an infinite recursion here.

Rename your plot function to something else, like myplot, and you should be fine.

Thomas Mailund
  • 1,674
  • 10
  • 16
  • Do you by any chance know why, now that it works, it will only print the last var() command? – scriptgirl_3000 Mar 19 '18 at 17:22
  • The function only returns the last value in its body. The `var` function doesn't print anything, it returns a value, and the last `var` in the function is the result of the entire plotting function. The reason this gets printed is simply because the console always print the result of the functions you call (well, unless they are wrapped in the `invisible` function). – Thomas Mailund Mar 19 '18 at 17:28
  • If you want to print the `var` results, you can use `print` or `cat`. – Thomas Mailund Mar 19 '18 at 17:29