[R] How to pass expression as an argument

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Sep 27 10:57:15 CEST 2006


Tong Wang <wangtong at usc.edu> writes:

> Hi,
>      I am writing a function and need to pass a function expression as an argument,   for instance, 
>             myfun <-  function( express) {
>                    x<- c(1,2,3)
>                   y<-express
>          }
> 
>     if I call the above function by myfun( x*2 ), I get  2  as the result,  instead of  2,4,6 ,  could someone help me to 
> fix this problem ? 
>     Furthermore,  is that possible to operate this expression on different variables?  for example, in myfun(), I 
> might want to get  u*2,  z*2,  etc. without having to say x<-u, x<-z to match the expression.
> 
> Thanks a lot for your help.

Either pass the expression explicitly using myfun(quote(x*2)) or
myfun(expression(x*2)) or use substitute(express) inside the function. 

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list