[R] Again: Variable names in functions

Berton Gunter gunter.berton at gene.com
Thu Feb 17 17:32:24 CET 2005


I thought Thomas L. was clear, but apparently not...

** Do not pass character string names as arguments to functions. ** Pass the
objects (or expressions) which can consist of lists of vectors, dataframes,
etc. instead. 

If you need the names (e.g. as labels) you can use the deparse(substitute())
construction. I strongly recommend that you study pp. 44-46 and section 3.5
("Computing on the Language") of V&R's S PROGRAMMING. The point is that one
can, of course, do things the way you want, but it makes life unnecessarily
difficult and complex because R is set up to pass arguments by value and can
keep better track of proper evaluation environments when this is done (which
means you don't have to).

-- Bert Gunter

> >
> 
> Thank you, this method works well. One step further I am again using
> parse(), but maybe there is a better solution for that situation too.
> The example would be a function, where I pass the variable 
> name as string
> instead of the name. The motivation for this is that it seems 
> easier to
> handle if I want to pass several variables (i.e. a vector of variable
> names) to the function (as I learned recently from this help-list). 
> In this case I have to use get(). In the case of calling table() the
> variable name disappeares.
> 
> > alpha<-c(rep(1:5,10))
> > name.alpha<-"alpha"
> > mytable1<-function(x){print(table(get(x)))}
> > mytable1(name.alpha)
> 
>  1  2  3  4  5 
> 10 10 10 10 10 
> 
> If I use eval(parse()) instead, it works as expected. I tried several
> combinations of eval() and substitute() but I did not find a solution.
> Is there a similar "trick"?
> 
> > mytable2<-function(x){
> +   string<-paste("print(table(",as.symbol(x),"))")
> +   eval(parse(text=string))}
> > mytable2(name.alpha)
> alpha
>  1  2  3  4  5 
> 10 10 10 10 10 
> 
> 
> Thanks,
> Heinz Tüchler
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list