Create a named list with list object's variable names as the list names

I often find myself creating a list from several variables, then renaming the list to use those variable names as the name of the list so I can access them with $ notation or use bind_rows with the .id argument:

a <- 1:10
b <- 11:20
mylist <- list(a, b)
names(mylist) <- c("a", "b")
mylist$a
[1]  1  2  3  4  5  6  7  8  9 10

I can’t figure out how to skip this second step and tell R to just use the variable names as the names within the list:

list(a, b)$a
NULL

This seems like it should be doable because it’s the default behavior for data.frame:

data.frame(a, b)$a
[1]  1  2  3  4  5  6  7  8  9 10

but using this method only works if the variables all have exactly the same length. It might seem like a simple thing to just use something like

mylist <- list(a=a, b=b)

but this feels redundant, becomes painful with long variable names, and I’ve often introduced bugs with typos that I don’t notice until later.

Is there a way to construct a list in R from some variables that automatically names the list with the variable names?

>Solution :

We may use dplyr::lst

library(dplyr)
lst(a, b)$a
 [1]  1  2  3  4  5  6  7  8  9 10

Or in a chain

lst(a, b)  %>% 
 pluck("a")
 [1]  1  2  3  4  5  6  7  8  9 10

Leave a Reply