2017-06-16 34 views
0

我不知道這有什麼用的foreach,但我想更多的與預測...錯誤運行的foreach時預測

下面是更大的桌子的只是一個小例子,我想並行運行此腳本,因爲它需要一些時間。我得到的錯誤信息:

「錯誤在{:任務2失敗 - ‘的說法是長度爲零’

的和我不知道爲什麼作爲單獨運行時,預測功能工作正常

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

感謝您的幫助!

回答

2

錯誤從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) 
+0

謝謝配合!我沒有想過! – Sven