Ollie Perkins
Ollie Perkins

Reputation: 343

Function input not recognised - local & global environment issue

I am writing a function to group together actions I regularly take on time series data. I have included all libraries I am using in the script as I think my issue may be to do with plyr / dplyr being (rightly) super specific about the environment of each variable.

The first function works great, but when getting to the second one, R doesn't recognise the input as 'x', but spits out the error: 'Error in eval(predvars, data, env) : object 'x' not found.'

Why is this happening?

library(plyr)
library(dplyr)
library(caret)
library(xts)
library(forecast)
library(imputeTS)
library(lubridate)

x1 = arima.sim(list(order = c(0,1,0)), n = 119)

timetrend <- function(x, starts, ends, frequency) { 
  y <- list()
  y[[1]] <- ts(x, start = starts, end = ends, frequency = frequency)
  y[[2]] <- decompose(y[[1]])
  y[[3]] <- y[[1]] - y[[2]]$seasonal - y[[2]]$random
  return(y)
}

plottime <- function(x) { #takes a timetrend list as input
  t <- tslm(x[[3]] ~ trend)
  plot(x[[3]])
  lines(t$fitted.values)
  return(t)
}

use functions from here

result <- timetrend(x = x1,
                  starts = c(2000, 01, 01), ends = c(2009, 12, 01), frequency = 12)


plottime(x = result)

Upvotes: 0

Views: 169

Answers (1)

Julien Massardier
Julien Massardier

Reputation: 1466

I could make it work with the following code.

plottime <- function(x) { #takes a timetrend list as input
  y=x[[3]]
  t <- tslm(formula = y ~ trend)
  plot(x[[3]])
  lines(t$fitted.values)
  return(t)
}

enter image description here

Not sure why it is happening, maybe the use of indexing x[[3]] in the formula argument is a problem?

Upvotes: 2

Related Questions