【问题标题】:Function input not recognised - local & global environment issue无法识别功能输入 - 本地和全球环境问题
【发布时间】:2018-04-23 17:51:09
【问题描述】:

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

第一个函数效果很好,但是当进入第二个函数时,R 不会将输入识别为 'x',而是吐出错误:'Error in eval(predvars, data, env) : object '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)

【问题讨论】:

  • 感谢您查看 - 这段代码对我来说很好,并且结果已创建。
  • 我的系统报告 decompose 来自 igraph 包。所以我现在得到的结果和你使用stats::decompose时的结果相同
  • 当您索引result-对象时,它删除了result 的第二个元素,这是$trend 项目的存储位置。查看str(result)tslm 的代码

标签: r function dplyr environment


【解决方案1】:

我可以使用以下代码使其工作。

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]] 是个问题?

【讨论】:

  • 谢谢 - 是的,当我取出索引时它工作正常。很高兴知道是什么导致了错误。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
相关资源
最近更新 更多