Giving the list returned by purrr::map names
Asked Answered
C

2

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.

Cutlerr answered 6/6, 2018 at 17:38 Comment(1)
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.Saad
N
7

We can use imap

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

Or map with a named vector

map(setNames(LETTERS, LETTERS), ~ paste0(.x, "_"))
Nona answered 6/6, 2018 at 17:40 Comment(1)
Also see purrr::set_names, which will name a vector with itself if no names are given: set_names(LETTERS).Phanerozoic
S
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).

Stumper answered 26/7, 2022 at 21:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.