[R] passing a variable (containing the value of the argument) to a function

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Oct 22 22:35:44 CEST 2003


Spencer Graves <spencer.graves at pdf.com> writes:

> Hi, Peter:     How does that compare with the following: for (myname
> in names(myframe)[1:4]){
>   mdl <- formula(paste(myname, "~ etc.etc"))
>   myfit <- lm(mdl, data=myframe)
>   print(summary(myfit))
> }
> 
>       Or: for (myname in names(myframe)[1:4]){
>   lm.txt <- paste("lm(", myname, "~ etc.etc, data=myframe)")
>    myfit <- eval(parse(text=lm.txt))
>   print(summary(myfit))
> }
> 
>       You are teaching me new uses of "substitute", and I just wonder
> about the relative advantages and disadvantages of the different
> approaches.     Thanks,
>       spencer graves

Those variants should work (and similar code is all over the place in
the modelling functions). I just tend to prefer to avoid going via the
textual representation. There are a couple of devils lurking in there,
in particular if a data frame has variables with "funny names" -
spaces or special characters inside, for example.

To wit:

> myname <- "foo bar"
> lm.txt <- paste("lm(", myname, "~ etc.etc, data=myframe)")
> lm.txt
[1] "lm( foo bar ~ etc.etc, data=myframe)"
> parse(text=lm.txt)
Error in parse(file, n, text, prompt) : parse error


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