2016-03-23 9 views
0

私はRを初めて使っています。この非常に簡単なスクリプトを書いて問題を浮き彫りにしました。私がこのforループを実行すると、必要に応じて各繰り返しでtestdataが更新されます。R:foreachとの並列化

a = 5 
b = 4 
c = 3 
testdata = matrix(nrow=100, ncol=5) 
for(j in 1:100){ 
testdata[j,1] <- a*j 
testdata[j,2] <- b*j 
testdata[j,3] <- c*j 
testdata[j,4] <- (a+b)*j 
testdata[j,5] <- (a+c)*j 
} 

しかし、foreachを使用するこの並列バージョンでは計算が完了しますが、testdataでは更新されません。

a = 5 
b = 4 
c = 3 
testdata = matrix(nrow=100, ncol=5) 
library(foreach) 
library(doParallel) 
library(doMC) 
registerDoMC() 
getDoParWorkers() # Checking the number of cores. 

foreach(j = 1:100) %dopar% { 
    testdata[j,1] <- a*j 
    testdata[j,2] <- b*j 
    testdata[j,3] <- c*j 
    testdata[j,4] <- (a+b)*j 
    testdata[j,5] <- (a+c)*j 
} 

私はインターネット上で、ここで、他の場所の例に従うことを試みたが、例のほとんどは、Rのshoptalkで深すぎだったと私は従うことができませんでした。どのように私はこの並列バージョンを、非並行バージョンがするものにすることができます。ありがとう。

+0

'.combine'引数を見てください。 – nrussell

答えて

0

foreachパッケージのドキュメントをチェックしてください。コードのforeach(j = 100)セクションでは、引数.combineを指定して、結果をコンパイルする方法をforeachに伝えることができます。 5×100のデータフレーム/マトリックスが必要なので、5つの引数のベクトル(つまりc(a*j, b*j, c*j, (a+b)*j, (a+c)*j))を論理的に書き込み、rbindを1つのデータフレームにします。以下の私のコードチェックアウト:

a = 5 
b = 4 
c = 3 

library(foreach) 
library(doParallel) 
library(parallel) 

## Assuming you want to use all of your cores 
registerDoParallel(cores = detectCores()) 

## Specify your .combine argument below 
foreach(j = 1:100, .combine = "rbind") %dopar% { 
    c(a*j, b*j, c*j, (a+b)*j, (a+c)*j) 
} 

をそして、これは吐く:

  [,1] [,2] [,3] [,4] [,5] 
result.1  5 4 3 9 8 
result.2  10 8 6 18 16 
result.3  15 12 9 27 24 
result.4  20 16 12 36 32 
result.5  25 20 15 45 40 
... 

あなたは、あなたがしたい変数にこれを割り当てることによって、さらにこの1歩を踏み出すことができます:

... 
testdata <- foreach(j = 1:100, .combine = "rbind") %dopar% { 
       c(a*j, b*j, c*j, (a+b)*j, (a+c)*j) 
      } 
testdata <- as.data.frame(testdata, row.names = FALSE) 

・ホープこれは役に立ちます!

+0

美しい!正確に私が必要としたもの。ありがとう! – Jericho