Search code examples
rmagrittr

Renaming with list with magrittr


I've been playing with magrittr, and I really like the resulting code. It's clean and can really save on typing.

How can I rename list elements in magrittr:

In typical base R:

data_lists <- paste0("q",2011:2015)
data_lists <- lapply(data_lists,get)
names(data_lists) <- paste0("q",2011:2015)

In magrittr, I thought:

data_lists <- 
   paste0("q",2011:2015) %>%
   lapply(.,get) %>%
   names(.) %<>% paste0("q",2011:2015) # this is wrong

But... no dice.


Solution

  • Magrittr uses a number of aliases for problems of this nature. Here is an example sequence using the alias set_names()

    data_lists <- 
       paste0("q",2011:2015) %>%
       lapply(.,get) %>%
       set_names(paste0("q",2011:2015))
    

    See ?extract for more aliases