Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading