Search code examples
rlistnames

Getting R to assume/guess names of list elements


When constructing a list(), particularly large ones, I would like to find a way to get R to guess the name of the elements being passed to the list, based on the name of the element itself.

For example, to construct a list with the following data:

dog <- c(1,2,3)
cat <- c(3,2,1)

With names I currently have to write:

list(dog = dog, cat = cat)

Is there a way to simply write:

list(dog, cat)

where the names of the element are automatically guessed based on the element name?


Solution

  • We can use mget with ls() if these are the only objects in the global environment

    mget(ls())
    

    If the global environment have other variables as well, then another clean option is to create a new env, and objects created in that env, then it would be easier to call ls with envir specified

    e1 <- new.env()
    e1$dog <- 1:3
    e1$cat <- 3:1
    mget(ls(envir = e1))
    

    If we use lst from purrr, it would automatically get the identifiers as well

    library(purrr)
    lst(dog, cat)
    #$dog
    #[1] 1 2 3
    
    #$cat
    #[1] 3 2 1