[R] Again: Variable names in functions
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Thu Feb 17 11:51:47 CET 2005
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
More information about the R-help
mailing list