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

42 Views Asked by At

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?

2

There are 2 best solutions below

0
zephryl On BEST ANSWER

tibble::lst() does this:

library(tibble)

l <- lst(a, b, c)

l
# $a
# [1] 1
# 
# $b
# [1] 2
# 
# $c
# [1] 3
0
G. Grothendieck On

If the components are the same length, as in the question, then create a data.frame and convert that to a list. No packages are needed.

a <- 1; b <- 2; c <- 3
data.frame(a, b, c) |> as.list()

giving

$a
[1] 1

$b
[1] 2

$c
[1] 3