功能输入无法识别 - 本地和全球环境问题

Function input not recognised - local & global environment issue

我正在编写一个函数来将我经常对时间序列数据执行的操作组合在一起。我已经在脚本中包含了我正在使用的所有库,因为我认为我的问题可能与 plyr / dplyr 对每个变量的环境(正确地)超级特定有关。

第一个函数运行良好,但是当进入第二个函数时,R 无法将输入识别为 'x',而是吐出错误:'error in eval(predvars, data, env) : 未找到对象 'x'。'

为什么会这样?

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)
}

使用此处的函数

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


plottime(x = result)

我可以用下面的代码让它工作。

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)
}

不确定为什么会这样,也许在公式参数中使用索引 x[[3]] 有问题?