Re: [R] generating an expression for a formula automatically

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Sat 26 Aug 2006 - 18:41:00 EST

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

______________________________________________
R-help@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
and provide commented, minimal, self-contained, reproducible code.
Received on Sat Aug 26 18:47:56 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 29 Aug 2006 - 08:23:59 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.