2015-11-19 29 views
2

在R中使用tm包和並行計算時,我遇到了一個問題,我不確定我是在做一些愚蠢的事情還是它是一個錯誤。不正確的維數 - 並行R計算

我創建了一個小型可重複的例子:

# Load the libraries 
library(tm) 
library(snow) 

# Create a Document Term Matrix 
test_sentence = c("this is a test", "this is another test") 
test_corpus = VCorpus(VectorSource(test_sentence)) 
test_TM = DocumentTermMatrix(test_corpus) 

# Define a simple function that returns the matrix for the i-th document 
test_function = function(i, TM){ TM[i, ] } 

如果我運行使用這個例子中,我得到了什麼期望,沒有任何問題的簡單lapply:

# This returns the expected list containing the rows of the Matrix 
res1 = lapply(1:2, test_function, test_TM) 

但是,如果我在的並行I運行得到錯誤:

第一個錯誤:不正確的維數

# This should return the same thing of the lapply above but instead it stops with an error 
cl = makeCluster(2) 
res2 = parLapply(cl, 1:2, test_function, test_TM) 
stopCluster(cl) 

回答

2

問題是不同的節點不會自動加載tm軟件包。然而,加載軟件包是必要的,因爲它爲相關對象類定義了[方法。

下面的代碼執行以下操作:

  1. 啓動羣集
  2. 負載tm包中的所有節點
  3. 出口中的所有對象的所有節點
  4. 運行函數
  5. 停止簇

cl <- makeCluster(rep("localhost",2), type="SOCK") 
clusterEvalQ(cl, library(tm)) 
clusterExport(cl, list=ls()) 
res <- parLapply(cl, as.list(1:2), test_function, test_TM) 
stopCluster(cl) 
+0

你是完全正確的..多麼愚蠢的錯誤。我認爲一旦計算矩陣,就不需要再考慮[方法在包內。非常感謝! –