[R] Again: Variable names in functions

Heinz Tuechler tuechler at gmx.at
Thu Feb 17 16:03:49 CET 2005


At 11:51 17.02.2005 +0100, Peter Dalgaard wrote:
>Heinz Tuechler <tuechler at gmx.at> writes:
>
>> > mytable1<-function(x,y){table(x,y)}
>> > mytable1(charly, delta)
>>    y
>> x   1 2
>>   1 2 1
>>   2 3 4
>> If I define the function in the following way, it does what I wish, namely
>> it returns output equivalent to the simple call "table(charly, delta)".
>> > mytable2<-function(x,y){
>> +   cat("table(",as.symbol((deparse(substitute(x)))),
>> +   "," ,  as.symbol(deparse(substitute(y))),")\n",
>> +   file="temp",sep="",append=F)
>> +   eval(parse("temp",n=-1))
>> +                       }
>> > mytable2(charly, delta)
>>       delta
>> charly 1 2
>>      1 2 1
>>      2 3 4
>> > 
>> I assume that there is a better way to solve this problem and I would be
>> happy about hints, where to find solutions in the documentation.
>
>What did Thomas L. say recently? "If the answer involves parse(), you
>probably asked the wrong question", I think it was.
>
>The canonical way is
>
>mytable <- function(x,y) eval.parent(substitute(table(x,y)))
>
>or, you could of course modify the names(dimnames(...)) and just pass
>the names along.
>
>
>-- 
>   O__  ---- Peter Dalgaard             Blegdamsvej 3  
>  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
> (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
>~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
>

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




More information about the R-help mailing list