运行 foreach with forecast 时出错

Error when running foreach with forecast

我不知道这是否与 foreach 有任何关系,但我想更多的是与预测有关...

下面只是一个更大的小例子 table,我想 运行 这个脚本并行,因为它需要一些时间。我收到错误消息:

"Error in { : task 2 failed - "参数长度为零"

而且我不知道为什么当单独 运行 时预测功能工作正常。

# Test Data
Data <- data.frame(Date = as.Date(c("2017-01-01", "2017-02-01", "2017-03-01", "2017-04-01", "2017-05-01", "2017-06-01")),
               A    = c(1,6,3,6,5,6),
               B    = c(6,5,6,3,6,1))
Data <- as.xts(Data[-1], Data[,1]) #convert to xts for the forecast package                                      

library(foreach)
library(doSNOW)
library(forecast)
cl <- makeCluster(2, type="SOCK") # for 2 cores machine
registerDoSNOW (cl)

# forecast the values in each column and bind the result of the forecast together by column to get one data.frame
Result <- foreach(j = 1:ncol(Data), .combine = "cbind", .packages = "forecast") %dopar% {forecast(Data[,j], h = 6L)$mean}

stopCluster(cl)


# Result how it should look like
Result <- data.frame(A    = c(4.7,4.7,4.7,4.7,4.7,4.7),
                     B    = c(4.4,4.4,4.4,4.4,4.4,4.4))

感谢您的帮助!

错误源于 xts 包未被导出。环境需要访问 xts 对象 Data[ 方法。

您可以使用 .packages = c("forecast","xts")(建议)或明确使用 xts:::`[.xts`(不建议,但包括在内以证明发生错误的原因)来解决此问题。

注意:输出与您问题中发布的预期结果不符

library(foreach)
library(doSNOW)
library(forecast)

# Test Data
Data <- data.frame(Date = as.Date(c("2017-01-01", "2017-02-01", "2017-03-01", 
                                    "2017-04-01", "2017-05-01", "2017-06-01")),
                   A    = c(1,6,3,6,5,6),
                   B    = c(6,5,6,3,6,1))
Data <- xts::as.xts(Data[-1], Data[,1]) #convert to xts for the forecast package                                      

cl <- makeCluster(2, type="SOCK") # for 2 cores machine
registerDoSNOW(cl)

# forecast the values in each column and bind the result of the forecast together by column to get one data.frame
Result_export <- foreach(j = 1:ncol(Data), .combine = "cbind", 
                         .packages = c("forecast","xts")) %dopar% {
                           forecast(Data[,j], h = 6L)$mean
                           }

Result_colon  <- foreach(j = 1:ncol(Data), .combine = "cbind", 
                         .packages = c("forecast")) %dopar% {
                           forecast(xts:::`[.xts`(Data,j=j), h = 6L)$mean
                         }

identical(Result_export, Result_colon)
# [1] TRUE

as.data.frame(Result_export)
#   result.1 result.2
# 1 4.499867 4.500107
# 2 4.499867 4.500107
# 3 4.499867 4.500107
# 4 4.499867 4.500107
# 5 4.499867 4.500107
# 6 4.499867 4.500107

stopCluster(cl)