Convert lapply to foreach?

I hope to convert the second function lapply( # Make the new list) to a loop foreachusing a package foreach.

## 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 am not sure if this is possible. I don't care what lapplyworks better than loops foreach. For context, I will reorganize the list of vector lists in this way:

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

Thanks!

+4
source share
1 answer

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

library("foreach")
example(foreach)

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

Then I 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: OP was able to find a solution based on 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]] } } }
+4

Source: https://habr.com/ru/post/1607549/


All Articles