I am new to R. I've written this very simple script to highlight my problem. If I run this regular for loop testdata is updated on each iteration just as I want it.
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
}
However this parallel version using foreach completes the computations but they are not updated in 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
}
I have attempted to follow examples here and elsewhere on the internet but most of the examples were too deep in R shoptalk and I couldn't follow. How can I make this parallel version do what the non-parallel version does. Thanks.