Search code examples
rpipelinenames

setnames in pipeline R code


I was wondering if it was possible to set the names of elements of a list at the end of a pipeline code.

  data <- input_vars %>% 
    purrr::map(get_data)

  names(data) <- input_vars

Currently I pass a string of variables into a function which retrieves a list of dataframes. Unfortunately this list does not automatically have named elements, but I add them "manually" afterwards. In order to improve readability I would like to have something as follows

  data <- input_vars%>% 
    purrr::map(get_comm_data) %>%
    setnames(input_vars)

However, this gives me the following error: Error in setnames(., input_vars) : x is not a data.table or data.frame

Does someone have an elegant solution to this?

Any help is appreciated!


Solution

  • To set names of an object in a pipeline, use setNames or purrr::set_names

    1:3 %>%
      purrr::map(~ rnorm(5, .x)) %>%
      purrr::set_names(paste0('V', 1:3))
    #> $V1
    #> [1] 1.4101568 2.0189473 1.0042691 1.4561920 0.8683156
    #> 
    #> $V2
    #> [1] 2.0577889 2.4805984 1.4519552 0.9438844 0.4097615
    #> 
    #> $V3
    #> [1] 0.4065113 4.0044538 2.8644864 2.4632038 4.0581380
    
    1:3 %>%
      purrr::map(~ rnorm(5, .x)) %>%
      setNames(paste0('V', 1:3))
    #> $V1
    #> [1] 0.52503624 0.69096126 0.08765667 0.97904520 0.29317579
    #> 
    #> $V2
    #> [1] 2.561081 1.535689 1.681768 2.739482 1.842833
    #> 
    #> $V3
    #> [1] 2.619798 1.341227 2.897310 2.860252 1.664778
    

    With purrr::map you could also name your input_vars as map keep names.

    c(V1 = 1, V2 = 2, V3 = 3) %>%
      purrr::map(~ rnorm(5, .x))
    #> $V1
    #> [1]  1.74474389  1.69347668 -1.03898393  0.09779935  0.95341349
    #> 
    #> $V2
    #> [1] 1.5993430 0.8684279 1.6690726 2.9890697 3.8602331
    #> 
    #> $V3
    #> [1] 3.453653 3.392207 2.734143 1.256568 3.692433