[R] generating an expression for a formula automatically

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Aug 26 10:41:00 CEST 2006


On Fri, 25 Aug 2006, Maria Montez wrote:

> Thank you for your answers yesterday. I now have another question!
> 
> Suppose that instead of creating a formula for a regression model I 
> simply wanted to add the variables. I believe I cannot use the 
> as.formula anymore. Again I tried to use expression to no avail. I get 
> an expression but I can't use it.
> 
> fit.sum <- function(x) {
>     fo <- expression(paste(x, collapse = "+"))
>    eval( fo)
> }
> fit.sum(c("x1","x2"))
> 
> Basically what I need is to learn how to use variables when what is 
> given to me are their names (character list).

I think we do need to tell you that parse(text=) is how to turn a 
character vector into an expression, although it is rarely a good way (see 
the fortune in the 'fortunes' package about it) and you need to be careful 
where you evaluate:

fit.sum <- function(x) eval.parent(parse(text=paste(x, collapse = "+")))

As an alternative, the answer to

> Basically what I need is to learn how to use variables when what is
> given to me are their names (character list).

is most often 'get'.  So for two objects

fit.sum2 <- function(x) {
   env <- parent.frame()
   do.call("+", lapply(x, get, envir=env))
}

but again you need to be careful where you get() from.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list