[R] Again: Variable names in functions

Heinz Tuechler tuechler at gmx.at
Thu Feb 17 11:30:07 CET 2005


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)
      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




More information about the R-help mailing list