rlistnames

assign name of global environment variable to all elements of a list


The title is a bit loose, but I would like to assign to each element of a list the name of that element as it appears in the global environment.

a<-1
b<-2
c<-3
l<-list(a,b,c)

what I want is the equivalent of the following:

l<-list("a"=a,"b"=b,"c"=c)

or

names(l)<-c("a","b","c")

so that names(l) return c("a","b","c"). Since I could have lists with lots of elements, I would prefer to avoid all the typing needed for the most straightforward solution (l<-list("a"=a,"b"=b,"c"=c)).

I know I can list the names of all variables in the global env with names(as.list(.GlobalEnv)), but not all variables in .GlobalEnv are contained in the list l. I also know that deparse(substitute(a)) return "a", but it doesn't work in a loop or a lapply call. Maybe the solution is straightforward, but I cannot figure it out.

How could I do it programmatically?


Solution

  • tibble::lst() does this:

    library(tibble)
    
    l <- lst(a, b, c)
    
    l
    # $a
    # [1] 1
    # 
    # $b
    # [1] 2
    # 
    # $c
    # [1] 3