0

I create a list called list_ok:

 list_ok <- list()
 a=c(1,2,3,4,5)
 b=c(6,7,8,9,10)
 c=c(11,12,13,14,15)
 d=c(16, 17, 18, 19, 20)
 e=c(21,22,23,24,25)

 list_ok[[1]]=a
 list_ok[[2]]=b
 list_ok[[3]]=c
 list_ok[[4]]=d
 list_ok[[5]]=e

This code below, creates the same list_ok by using a for loop:

new_list <- vector(mode = "list", length=5)

for (i in 1:5) {
  for(k in 1:5) {     
    new_list[[i]][k] <- list_ok[[i]][k]
  }
}

> new_list

How can I do the same exercise using the map function? My problem is to know how to deal with the two different indexes (i and k) in map function.

I will use the same idea in another exercise wich is more complex.

Any help?

Laura
  • 675
  • 10
  • 32
  • 5
    I don't understand what you're trying to do. `new_list` and `list_ok` are identical. Why do you want to create an identical copy of a `list` with a `for` loop (or with `purrr::map`)? This sounds like an XY problem to me. Can you provide a few more details? – Maurits Evers Aug 27 '18 at 01:03
  • Its just an exercise. Its to simple, I just want to replace the for code by the map function. Its another way of doing the same thing. – Laura Aug 27 '18 at 01:11
  • 3
    I still don't understand; `new_list <- map(list_ok, I)` would create an identical copy of `ok_list`. But in that case why not just `new_list <- list_ok`? – Maurits Evers Aug 27 '18 at 01:18
  • @MauritsEvers my iidea is to know how to work with map functions with 2 different indexes as the for command above. – Laura Aug 27 '18 at 01:32
  • 1
    You're thinking about this the wrong way. The advantage of `map` is that it allows for vectorised functions, i.e. loop throw the elements of a `list` and then apply a vectorised function on its elements. Thinking about this in terms of 2 "array" indices is the wrong way to think about `map` (or `*apply` for that matter), and you end up with convoluted solutions like the ones presented below. If you must use array indices, use a `for` loop; there is nothing wrong with `for` loops in R, provided you use them correctly! – Maurits Evers Aug 27 '18 at 01:35

2 Answers2

2

How about lapply and sapply with the parallel package to speed up?

library(parallel)

numCores <- detectCores()
cl = makeCluster(numCores)

parLapply(list_ok, function(x)
  sapply(x, function(y) y), cl = cl)
Paul
  • 2,877
  • 1
  • 12
  • 28
1

You'll find this Q&A useful: purrr map equivalent of nested for loop

For loops within loops, the easiest thing is to create an anonymous function as the second argument for map and within that anonymous function use map again (in this case I'm using map_dbl) with another anonymous function where you can combine one level of loop (x) with another level of loop (y).

library(purrr)

map(list_ok, function(x) map_dbl(seq_along(list_ok), function(y) x[[y]]))

[[1]]
[1] 1 2 3 4 5

[[2]]
[1]  6  7  8  9 10

[[3]]
[1] 11 12 13 14 15

[[4]]
[1] 16 17 18 19 20

[[5]]
[1] 21 22 23 24 25
Phil
  • 7,287
  • 3
  • 36
  • 66