[R] Again: Variable names in functions
Uwe Ligges
ligges at statistik.uni-dortmund.de
Thu Feb 17 11:48:44 CET 2005
Heinz Tuechler wrote:
> Hello,
>
> still I have difficulties with variable names in functions. I know the
> famous example form help for deparse/substitute but I will give a simpler
> one to explain my problem.
> I know from Reid Huntsinger (Tue, 8 Feb 2005 12:39:32 -0500) that:
> "Semantically, R is pass-by-value, so you don't really have the names, just
> the values. In implementation, though, R *does* pass names, in part at least
> in order to do "lazy evaluation". You can get them via "substitute" ; see
> the help for that."
>
> The output of several functions does not make much sense, if these names do
> not appear (e.g. parameter estimates in Cox-regression, ...)
> Only to give a trivial example I show my problem with the table function.
>
> As you know, if I call table as follows, the output is labelled properly.
>
>>charly<-c(rep(1,3),rep(2,7));delta<-c(rep(1:2,5))
>>table(charly, delta)
>
> delta
> charly 1 2
> 1 2 1
> 2 3 4
> If I define a trivial function to call table, the output is less satisfying.
> (Of course, I know that this function is useless.)
>
>>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)
See argument "dnn" in ?table:
mytable2 <- function(x,y){
table(x, y, dnn = c(deparse(substitute(x)),
deparse(substitute(y))))
}
Uwe Ligges
> 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.
>
> 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