Skip to content
Prev 348400 / 398500 Next

return named list from foreach

Hello all,

I've been trying to figure out how to return a named list from foreach.  
Given that the order of the returned list is guaranteed to be in the 
order in which the object is passed to foreach, list members can be 
named afterwards.  However, I'm wondering if there's a better way to do 
it, perhaps with some sort of combine function?

    library(doParallel)
    library(foreach)

    cl <- makeCluster(4)
    registerDoParallel(cl)

    df = data.frame(nm = letters[11:20], a = 1:10, b=11:20)

    out = foreach(i=1:nrow(df)) %dopar% {
         a = list(j = sqrt(df[i,]$a), k = sqrt(df[i,]$b))
         a
    }

How do I name the elements of "out" using the corresponding values df$nm?

thanks,
allie