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

Romain Francois romain.francois at dbmail.com
Tue May 25 15:11:40 CEST 2010


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



More information about the R-help mailing list