Search code examples
rnested-loopspurrr

Assigning elements to a list in a nested purrr map


I am trying to assign elements to a list in a nest purrr::map call -- this should basically be the same as a nested for loop:

res <- list()
for (i in 1:4) {
  for (j in letters[1:3]) {
    res[[paste(i,j)]] <- paste(i,j)
  }
}

str(res)
#> List of 12
#>  $ 1 a: chr "1 a"
#>  $ 1 b: chr "1 b"
#>  $ 1 c: chr "1 c"
#>  $ 2 a: chr "2 a"
#>  $ 2 b: chr "2 b"
#>  $ 2 c: chr "2 c"
#>  $ 3 a: chr "3 a"
#>  $ 3 b: chr "3 b"
#>  $ 3 c: chr "3 c"
#>  $ 4 a: chr "4 a"
#>  $ 4 b: chr "4 b"
#>  $ 4 c: chr "4 c"

However, when I attempt to convert this to purrr, the results get printed to the console, but are never stored in the list object res_purrr?

library(purrr)
res_purrr <- list()

map(1:4, function(i)
  map(letters[1:3], function(j)
    res_purrr[[paste(i,j)]] <- paste(i,j)
  )
)

res_purrr
#> list()

Running the same code with walk returns the same empty res_purrr object.


Solution

  • I would do the following :

    library(purrr)
    res_purrr <- expand.grid(1:4,letters[1:3],stringsAsFactors = FALSE) %>%
      pmap(paste) %>%
      set_names()
    str(res_purrr)
    # List of 12
    # $ 1 a: chr "1 a"
    # $ 2 a: chr "2 a"
    # $ 3 a: chr "3 a"
    # $ 4 a: chr "4 a"
    # $ 1 b: chr "1 b"
    # $ 2 b: chr "2 b"
    # $ 3 b: chr "3 b"
    # $ 4 b: chr "4 b"
    # $ 1 c: chr "1 c"
    # $ 2 c: chr "2 c"
    # $ 3 c: chr "3 c"
    # $ 4 c: chr "4 c"
    

    This question is relevant : purrr map equivalent of nested for loop