如何告诉lapply等待每一步完成

时间:2018-04-13 16:54:41

标签: r function eval lapply

您好我想运行以下代码:

library(readxl)
library(forecast)
library(dplyr)

data<-read_excel("Time Series/Items.xlsx", col_types = c("date", "numeric"))

gkuniforecast = function(data, Np, Ncolumn, tsfreq, model) {
  ## Preparation
  N = ceiling(Np*nrow(data))
  x=pull(data,Ncolumn)
  train.x = ts(x[1:N], frequency=tsfreq)
  test.x <- ts(c(rep(NA, N), x[(N+1):NROW(x)]), frequency=tsfreq)
  plot(train.x)

  ## Models
  str1=paste0("m_",model," = ",model,"(train.x)")
  str2=paste0("f_",model," = forecast(m_",model,", h=NROW(x)-N)")
  str3=paste0("plot(f_",model,")")
  str4="lines(test.x)"
  str=list(str1,str2,str3,str4)
  lapply(str,function(y) eval(parse(text=y)))
}

gkuniforecast(data, 0.75, 2, 12, "ets")

当我一个接一个地运行每一行时,它起作用。当我一起运行时,我收到以下错误:

 Error in forecast(m_ets, h = NROW(x) - N) : object 'm_ets' not found 

这是lapply中的第2步。我怀疑这是因为没有创建对象“m_ets”,因为str1的评估没有完成,但是str2启动了,它找不到它。

有什么想法吗?

谢谢!

0 个答案:

没有答案