kn1g kn1g - 2 months ago 6
R Question

for loop with list and sublist to foreach loop

I tried to get this

for
loop into a
foreach
loop to finally run it in parallel. But I think I didn't get the concept of the
foreach
loop right. I tried around with simpler loops and always got stuck.

The simplified code of the original for loop:

varName <- rep("name",1000)
testlist <- list()
for(j in 1:1000){

testlist [[j]] <- list()
testlist [[j]]$UsedAlgo <- "Name"
testlist [[j]]$UsedPMethod <- varName[j]
testlist [[j]]$datalists <- list()
testlist [[j]]$datalists <- lapply(Dataset[[j]]$data,
function(x){#whateverfunction})


My foreach loop:

library(foreach)
library(doMC)
registerDoMC(35)
varName <- rep("name",1000)

testlist <- foreach(j=1:1000) %dopar% {

testlist[[j]] <- list()
testlist[[j]]$UsedAlgo <- "Name"
testlist[[j]]$UsedPMethod <- varName[j]
testlist[[j]]$patterns <- list()
testlist[[j]]$patterns <- lapply(Dataset[[j]]$data,
function(x){#whateverfunction})

}


So it runs kind of fine. It outputs the lists which are returned by #whateverfunction. But completely ignores the other variable settings.

List returned is a list ranging from 1:1000 with the output of #whateverfunction. The function is compley and returns lots of lists and is written in C++. That's why I did not attach a completely running example. But I can figure one out if needed. But I think I just did a basic mistake and maybe I just googled the wrong tags.

Answer

Try replacing testlist[[j]] with temp and adding an explicit return at end: return(temp):

testlist <- foreach(j=1:1000) %dopar% {    
   temp <- list()
   temp$UsedAlgo     <- "Name"
   temp$UsedPMethod  <- varName[j]
   temp$patterns     <- lapply(Dataset[[j]]$data,                
                               function(x){ ... })
   return(temp)
}