[R] Returning the name of an object passed directly or from a list by lapply

William Dunlap wdunlap at tibco.com
Thu Sep 15 23:53:01 CEST 2011


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of andrewH
> Sent: Thursday, September 15, 2011 2:11 PM
> To: r-help at r-project.org
> Subject: [R] Returning the name of an object passed directly or from a list by lapply
> 
> Dear folks:
> 
> Let’s suppose I want a function to print return the name of the object
> passed to it.
> 
> > myname <- function(object) {out<-deparse(substitute(object)); out}
> 
> This works fine on a single object:
> > O1 <-c(1:4)
> > myname(O1)
> [1] "O1"
> 
> However it does not work if you use lapply to pass it the same object from a
> list:
> > O2 <-c(1:4)
> > object.list <- list(O1,O2)
> > lapply(object.list, myname)
> [[1]]
> [1] "X[[1L]]"
> 
> [[2]]
> [1] "X[[2L]]"
> 
> Is there any way to write myname() so that it returns the same objects name
> regardless of whether it is handed the name directly or by lapply as an
> element of a list?

The short answer is "no", because object.list does
not contain the names I think you are looking for
("O1" and "O2").  Notice that
   list(O1, O2)
and
   list(1:4, 1:4)
are identical.

I suggest abandoning the myname() function and instead
attach names to your lists.  These names stay attached
to the object, unlike the name you call a dataset in a
particular evaluation frame.
  > O1 <- 1:4
  > object.list <- list(O1=O1, O2=5:8)
  > lapply(seq_along(object.list), function(i) names(object.list)[i])
  [[1]]
  [1] "O1" 
  
  [[2]]
  [1] "O2"


Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> 
> Any help you can offer would be greatly appreciated.
> 
> Warmly, andrewH
> 
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/Returning-the-name-of-an-object-passed-
> directly-or-from-a-list-by-lapply-tp3816798p3816798.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


More information about the R-help mailing list