Jerry Zhang
Jerry Zhang

Reputation: 1462

Converting lapply to foreach?

I'm hoping to convert the second lapply function (# Make the new list) into a foreach loop, using the foreach package.

## Example data
lst <- lapply(1:30, function(x) lapply(1:5, function(y) rnorm(10)))

## Make the new list
res <- lapply(1:5, function(x) lapply(1:10, function(y) sapply(lst, function(z) z[[x]][[y]])))

I'm not sure if this is possible. I'm not concerned about lapply performing better than the foreach loops. For context, I'm re-organizing a list of lists of vectors in such a way:

new_thing[[5]][[10]][30] <- daily_by_security[[30]][[5]][10]

Thanks!

Upvotes: 4

Views: 2046

Answers (1)

Richard Erickson
Richard Erickson

Reputation: 2616

To figure you how to solve your problem, I looked at the foreach examples and the second one does exactly what you are looking for:

library("foreach")
example(foreach)

# equivalent to lapply(1:3, sqrt)
foreach(i=1:3) %do%  sqrt(i)

I then adapted this to your problem:

lst <- lapply(1:30, function(x) lapply(1:5, function(y) rnorm(10)))
resFE <- foreach(i = 1:5) %do% 
                 lapply(1:10, function(y) sapply(lst, function(z) z[[i]][[y]]))

Edit: The OP was able to figure out a solution based upon my work. Here is the solution:

resFE <- foreach(i = 1:5, .packages = "foreach") %dopar% 
                 { foreach(m = 1:10) %dopar% 
                    { foreach(t = lst, .combine = c) %do% 
                     { t[[i]][[m]] } } }

Upvotes: 4

Related Questions