kn1g kn1g - 1 year ago 71
R Question

for loop with list and sublist to foreach loop

I tried to get this

loop into a
loop to finally run it in parallel. But I think I didn't get the concept of the
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,

My foreach loop:

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,


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 Source

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){ ... })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download