9

Is there a way to automatically give names to the returned list given by purrr:map?

For example, I run code like this very often.

fn <- function(x) { paste0(x, "_") }
l <- map(LETTERS, fn)
names(l) <- LETTERS

I'd like for the vector that is being automated upon to automatically become the names of the resulting list.

user1775655
  • 317
  • 2
  • 8
  • This is not an answer because it doesn't use `purrr::map`, but just to note that `base::Map` does automatically assign names as desired. – andycraig Aug 01 '18 at 16:01

2 Answers2

7

We can use imap

imap(setNames(LETTERS, LETTERS), ~ paste0(.x, "_"))

Or map with a named vector

map(setNames(LETTERS, LETTERS), ~ paste0(.x, "_"))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 11
    Also see `purrr::set_names`, which will name a vector with itself if no names are given: `set_names(LETTERS)`. – aosmith Jun 06 '18 at 19:08
2

This seems like a clean way to do it to me:

purrr::map(LETTERS, paste0, "_") %>% purrr::set_names()

Thanks to the comment left by aosmith for identifying purrr::set_names. Note if you want to set the names to something else, just say ... %>% set_names(my_names).

flies
  • 2,017
  • 2
  • 24
  • 37