create named list

I am interested in creating a list of objects in which list elements are automatically named by the name of the input objects. I have two approaches below, but is there a way to convert this to a function for a single step solution for any number of inputs? These approaches can be tedious for many objects.

x <- 1
y <- "A"

# approach 1 ----
z <- list(x = x, y = y)
z
#> $x
#> [1] 1
#> 
#> $y
#> [1] "A"


# approach 2 ----
# step 1 - create list
z <- list(x, y)
z
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] "A"

# step 2 - add names to list
z <- setNames(z, c("x", "y"))
z
#> $x
#> [1] 1
#> 
#> $y
#> [1] "A"

Created on 2021-12-07 by the reprex package (v2.0.1)

Maybe you can use mget, which is the opposite of what you asked for. You give it the names of the objects, as characters, and it returns a named list of the objects.

 x=1
 y="A"
 mget(c("x","y"))
$x
[1] 1

$y
[1] "A"
1 Like

Thank you for the contribution!

Madhur Parihar shared on twitter the exact solution I was seeking:

x <- 1
y <- "A"
tibble::lst(x, y)
#> $x
#> [1] 1
#> 
#> $y
#> [1] "A"

Created on 2021-12-08 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.