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
We just need to name the
list
and then extract the elements based on the name
If this needs to be done using
tidyverse
The accepted solution works, but suffers from a repeated argument (
input
) which may cause errors and interrupts the flow when using piping with%>%
.An alternative solution would be to use a bit more power of the
%>%
operatorThis takes the argument from the pipe but still lacks some beauty. An alternative could be a small helper method such as
This already looks more pretty and elegant. And would be my preferred solution.
Finally, we could even overwrite
purrr::map
in case the argument is a character or integer vector and produce a named list in such a case.However, the optimal solution would be if
purrr
would implement such behaviour out of the box.