Daniel
Daniel

Reputation: 1262

How to get the list of objects with its corresponding name rather than the index number?

I'd like to know if there would be a way to get the corresponding indexing name in a list ?

as example :

lapply(list(mtcars, airquality), dim )
[[1]]
[1] 32 11

[[2]]
[1] 153   6

I would like to get

mtcars
[1] 32 11

airquality
[1] 153   6

Upvotes: 1

Views: 71

Answers (1)

akrun
akrun

Reputation: 886938

We can use mget to return the value of string objects in a list and this will also name the list elements

lapply(mget(c("mtcars", "airquality")), dim)
#$mtcars
#[1] 32 11

#$airquality
#[1] 153   6

If the data is not already loaded i.e. by calling

data(mtcars)
data(airquality)

then, we specify inherits = TRUE in mget

lapply(mget(c("mtcars", "airquality"), inherits = TRUE), dim)

Upvotes: 2

Related Questions