I’m trying to use the foreach package in a nested loop, but my inner loop don’t recognizes the outer’s counter, what m I missing?
v3 <- search.compounds.by.mass(100.05,0.5)
foreach(j=2:length(v2)) %:% {
foreach(i=1:length(v3), .combine=rbind) %dopar% {
write.table(paste(v3[i], paste(get.reactions.by.compound(v3[i]), collapse=" "), sep=" "), "file1",quote=FALSE, row.names=FALSE, col.names=FALSE, append=TRUE)
write.table(paste(v3[i], paste(get.pathways.by.compounds(v3[i]), collapse=" "), sep=" "), "file2",quote=FALSE, row.names=FALSE, col.names=FALSE, append=TRUE)
v3 <- search.compounds.by.mass(v2[j],0.5)
}
}
The problem is that you are incorrectly applying the
%:%operator. It is designed to merge twoforeachobjects, resulting in a singleforeachobject that can be used to repeatedly evaluate whatever expression you supply to it. So, if you want to use%:%, you need to first merge the twoforeach()statements, and then use the resulting object to drive a single call to%do%(or in your case,%dopar%). See (1) below for an example.Alternatively, if you want to nest the two
foreach()objects, use%do%twice, as in (2) below.Either way works, although for parallel jobs I might prefer the one using
%:%. Your code, though, like (3) below, combines elements of the two strategies to produce a hybrid that can’t do anything.