[R] Again: Variable names in functions
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Thu Feb 17 16:36:12 CET 2005
Heinz Tuechler <tuechler at gmx.at> writes:
>
> 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
You're almost there:
eval(substitute(table(e),list(e=as.symbol(x))))
(or eval.parent, which() safeguards somewhat against scoping issues)
--
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
More information about the R-help
mailing list