Use the purrr map function input to create a named list as output in R

I use the function to map the package purrr to R, which gives a list as output. Now, I would like the output to be an input-based named list. 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 the list items using:

output$a

or

output$b
+11
source share
2 answers

We just need to name list

names(output) <- input

and then retrieve the items based on the name

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

If you need to do this using tidyverse

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

, (input), %>%.

%>%

1:5 %>% { set_names(map(., ~ .x + 3), .) } %>% print # ... or something else

, . ,

map_named = function(x, ...) map(x, ...) %>% set_names(x)

1:5 %>% map_named(~ .x + 1)

. .

, purrr::map , , .

map = function(x, ...){
    if (is.integer(x) | is.character(x)) {
        purrr::map(x, ...) %>% set_names(x)
    }else {
        purrr::map(x, ...) 
    }
}

1 : 5 %>% map(~ .x + 1)

, , purrr .

0

Source: https://habr.com/ru/post/1676994/


All Articles