8

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!

2
  • It would be easier with a reproductible example. Here, setnames if a fonction exported from data.table package and you seem not to work with data.table. Base R function is setNames and should work. You could also use set_names from purrr package.
    – cderv
    Commented Aug 9, 2016 at 13:40
  • You should read the docs for the functions you're trying to use, not simply guess at the name of the function you need. In this case, try ?setnames.
    – Frank
    Commented Aug 9, 2016 at 13:55

1 Answer 1

10

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.