0

I have this code for creating a matrix out of some calculations using a function "cop.theta" in a for loop environment

Mat.corr <- matrix(0,6,5,byrow=F)
for (i in 1:6){
Mat.corr[i,]=cop.theta(index,EXPR,SURV=survp[,i])
}

I wrote an R code using "foreach" in doParallel package to get results that is similar to what the code above generated. My code is as follows

library(doParallel)
cl <- makeCluster(3) 
registerDoParallel(cl)
getDoParWorkers()
clusterExport(cl, list("QT","EXPR","cop.theta.i"))
clusterEvalQ(cl, library(copula))

foreach(i=1:6,.combine=matrix(0,6,5,byrow=F) %dopar%
Mat.corr[i,]=cop.theta(index,EXPR,QT=survp[,i])

But I'm getting this error

Error: unexpected '=' in "foreach(i=1:6,.combine=matrix(0,6,5,byrow=F)
%dopar%  Mat.corr[i,]="

Where I'm I going wrong?

lin
  • 33
  • 5
  • If you make your example reproducible it will be easier to help. – Andrie Apr 06 '16 at 10:00
  • This is not how `foreach` works. Please read the vignettes. The expression passed to `foreach` must have a return value (in particular if you use a parallel backend). `foreach` is not just a synonym of `for`. – Roland Apr 06 '16 at 10:13

2 Answers2

1

There is a ")" missing next to byrow = F, i.e.

foreach(i=1:6,.combine=matrix(0,6,5,byrow=F)) %dopar%
  Mat.corr[i,]=cop.theta(index,EXPR,QT=survp[,i])

should fix this error. However, be aware that mat.corr[i,]=... inside the foreach loop will not write the values resulting from the cop.theta operation to this particular row as long as you are running the loop in parallel - this is only possible with single-core foreach. That means, you have to handle the merging procedure either using .combine inside foreach()or after the loop has finished. Here is a code snippet to clarify my point.

mat <- matrix(nrow = 3, ncol = 3)

### multi-core -----
foreach(i = 1:nrow(mat)) %dopar% {
  mat[i, ] <- matrix(rep(i, ncol(mat)), nrow = 1)
}

mat
     [,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]   NA   NA   NA
[3,]   NA   NA   NA


### single core -----
foreach(i = 1:nrow(mat)) %do% {
  mat[i, ] <- matrix(rep(i, ncol(mat)), nrow = 1)
}

mat
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3
fdetsch
  • 5,239
  • 3
  • 30
  • 58
0

Thank you all for your comments. The below code has actually answered my question.

foreach(i=1:6,.combine=rbind) %dopar%  cop.theta(index,EXPR,SURV=survp[,i])
lin
  • 33
  • 5