foreach: Keep names

I was using your solution until I needed to use a nested foreach (with the %:% operator). I came up with this:

foo <- list(a = 1, b = 2)
bar <- foreach (x = foo, .final = function(x) setNames(x, names(foo))) %do% {
    x * 2
    }

The trick is to use the .final argument (which is a function applied once at the final result) to set the names. This is nicer because it doesn't use a temporary variable and is overall cleaner. It works with nested lists so that you can preserve the names accross several layers of the structure.

Note that this only works correctly if foreach has the argument .inorder=T (which is the default).


Thanks for your recommendations. This is what I came up with:

foo <- list(a = 1, b = 2)
bar <- foreach (x = foo, n = names(foo), .combine = c) %do% {
    rv <- list()
    rv[[n]] <- x * 2
    rv
}

Tags:

Foreach

R