user1775655
user1775655

Reputation: 327

Giving the list returned by purrr::map names

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.

Upvotes: 9

Views: 3018

Answers (2)

flies
flies

Reputation: 2135

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).

Upvotes: 2

akrun
akrun

Reputation: 886938

We can use imap

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

Or map with a named vector

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

Upvotes: 7

Related Questions