Use input of purrr's map function to create a named list as output in R

Michael picture Michael · May 12, 2017 · Viewed 7.3k times · Source

I am using the map function of the purrr package in R which gives as output a list. Now I would like the output to be a named list based on the input. An example is given below.

input <- c("a", "b", "c")
output <- purrr::map(input, function(x) {paste0("test-", x)})

From this I would like to access elements of the list using:

output$a

Or

output$b

Answer

akrun picture akrun · May 12, 2017

We just need to name the list

names(output) <- input

and then extract the elements based on the name

output$a
#[1] "test-a"

If this needs to be done using tidyverse

library(tidyverse)
output <- map(input, ~paste0('test-', .)) %>% 
                                setNames(input)