[R] return named list from foreach

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Fri Feb 20 17:08:30 CET 2015


You cannot do that in one step. Do it right after:

names(out) <- df$nm

Please don't post using HTML format.. it scrambles code, and since we cannot see what you saw it doesn't help in any way.

Also note that "df" is a function in the base stats package... not a good name to use.

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On February 20, 2015 7:44:41 AM PST, Alexander Shenkin <ashenkin at ufl.edu> wrote:
>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
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list