In R, how to get the name of an object after it is sent to a function?

I am looking for the back side of get() .

Given the name of the object, I want the character string representing this object to be extracted directly from the object.

The trivial foo example is a placeholder for the function I'm looking for.

 z <- data.frame(x=1:10, y=1:10) test <- function(a){ mean.x <- mean(a$x) print(foo(a)) return(mean.x)} test(z) 

It will be printed:

  "z" 

My work, which is harder to implement in my current problem:

 test <- function(a="z"){ mean.x <- mean(get(a)$x) print(a) return(mean.x)} test("z") 
+110
r
May 09 '12 at 17:05
source share
3 answers

Old substitute trick:

 a<-data.frame(x=1:10,y=1:10) test<-function(z){ mean.x<-mean(z$x) nm <-deparse(substitute(z)) print(nm) return(mean.x)} test(a) #[1] "a" ... this is the side-effect of the print() call # ... you could have done something useful with that character value #[1] 5.5 ... this is the result of the function call 

Change: run it with a new test object

Note: this will not be done inside the local function when the set of list items is passed from the first argument to lapply (and also fails when the object is passed from the list passed for for -loop.) You can extract the ".Names" -attribute and order processing from the result of the structure, if it was a named vector that was being processed.

 > lapply( list(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\\[')} ) $a $a[[1]] [1] "X" "" "1L]]" $b $b[[1]] [1] "X" "" "2L]]" > lapply( c(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\\[')} ) $a $a[[1]] [1] "structure(c(4, 5), .Names = c(\"a\", \"b\"))" "" [3] "1L]]" $b $b[[1]] [1] "structure(c(4, 5), .Names = c(\"a\", \"b\"))" "" [3] "2L]]" 
+135
May 42-09 '12 at 17:09
source share
β€” -

Note that for printing methods, the behavior may be different.

 print.foo=function(x){ print(deparse(substitute(x))) } test = list(a=1, b=2) class(test)="foo" #this shows "test" as expected print(test) #this shows #"structure(list(a = 1, b = 2), .Names = c(\"a\", \"b\"), class = \"foo\")" test 

Other comments that I saw on the forums show that the latter behavior is inevitable. This is sad if you write printing methods for packages.

+4
Oct 02 '13 at 20:24
source share
 deparse(quote(var)) 

My intuitive understanding is that a quote freezes a variable or expression from a calculation, and a parsing function, which is the inverse of parsing, turns this locked character back into a string

+3
Jan 30 '18 at 7:57
source share



All Articles