Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R get objects' names from the list of objects

Tags:

r

I try to get an object's name from the list containing this object. I searched through similar questions and find some suggestions about using the deparse(substitute(object)) formula:

> my.list <- list(model.product, model.i, model.add)
> lapply(my.list, function(model) deparse(substitute(model)))

and the result is:

[[1]]
[1] "X[[1L]]"

[[2]]
[1] "X[[2L]]"

[[3]]
[1] "X[[3L]]"

whereas I want to obtain:

[1] "model.product", "model.i", "model.add"

Thank you in advance for being of some help!

like image 718
Marta Karas Avatar asked Sep 17 '13 23:09

Marta Karas


3 Answers

You can write your own list() function so it behaves like data.frame(), i.e., uses the un-evaluated arg names as entry names:

List <- function(...) {
  names <- as.list(substitute(list(...)))[-1L]
  setNames(list(...), names)
}

my.list <- List(model.product, model.i, model.add)

Then you can just access the names via:

names(my.list)
like image 103
flodel Avatar answered Oct 20 '22 20:10

flodel


names(my.list) #..............

Oh wait, you didn't actually create names did you? There is actually no "memory" for the list function. It returns a list with the values of its arguments but not from whence they came, unless you add names to the pairlist given as the argument.

like image 41
IRTFM Avatar answered Oct 20 '22 20:10

IRTFM


You won't be able to extract the information that way once you've created my.list.

The underlying way R works is that expressions are not evaluated until they're needed; using deparse(substitute()) will only work before the expression has been evaluated. So:

deparse(substitute(list(model.product, model.i, model.add)))

should work, while yours doesn't.

like image 1
Scott Ritchie Avatar answered Oct 20 '22 19:10

Scott Ritchie