[R] using the name of an argument in a function

cgenolin cgenolin at u-paris10.fr
Tue May 25 14:54:59 CEST 2010


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

-- 
View this message in context: http://r.789695.n4.nabble.com/using-the-name-of-an-argument-in-a-function-tp2229947p2229947.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list