Hi,

This is a dangerous game you are playing. I would play with the call stack, i.e sys.calls :

setMethod("fun","character",
   definition = function(y,x,...){
        
          stack <- sys.calls( )
          stack.fun <- Filter( function(.) .[[1]] == as.name("fun"), stack )
          nameOfY <- deparse( stack.fun[[1]][[2]] )
          cat("name is '",nameOfY, "'\n" , sep = "" )
  }
)

> titi <- "aze"
> fun( titi )
name is 'titi'
> fun( letters[1:4] )
name is 'letters[1:4]'

Romain


Le 25/05/10 14:54, cgenolin a écrit :


Hi all,

In a function, I need to get the name of a variable that has been used to
call the function.
For example, I want:

--- 8<  ------
toto<- 3
fun<- function(y){
    nameOfY<-deparse(substitute(y))
    cat("name is ",nameOfY)
}
fun(toto)

# [1] name is toto

--- 8<  ----

But deparse(substitute(y)) does not work all the time, especially when we
use generic function.

--- 8<  ----

setGeneric("fun",function(y,...){standardGeneric("fun")})

setMethod("fun","numeric",
    definition = function(y,...){
       nameOfY<-deparse(substitute(y))
       cat("name is ",nameOfY)
   }
)

toto<- 4
fun(toto)
# name is toto

setMethod("fun","character",
    definition = function(y,x,...){
       nameOfY<-deparse(substitute(y))
       cat("name is ",nameOfY)
   }
)

titi<- "aze"
fun(titi)
# name is y

--- 8<  ----

So is there a way to get the name of the variable "toto" or "titi" in a way
that work in all cases?

Christophe



--
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/cork4b : highlight 0.1-8
|- http://bit.ly/bklUXt : RcppArmadillo 0.2.1
`- http://bit.ly/936ck2 : Rcpp 0.8.0

______________________________________________
R-help@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.

Reply via email to