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

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Tue 29 Aug 2006 - 06:09:18 EST

On Mon, 28 Aug 2006, Maria Montez wrote:

> Thank you for your responses.
>
> Prof Ripley's code only worked for a vector with 2 variables but I need the

True for my second version (as stated).

If you want elementwise sums (which is news to me), use

rowSums(do.call("cbind", lapply(x, get)))

or

X <- do.call("cbind", lapply(x, get))
colnames(X) <- x
(data2 <- cbind(X, totx=rowSums(X)))

> code to work for a vector of any size. To solve this I created a for loop. I'm
> not sure this is the most efficient way of doing it but it works.
>
> x1 <- c(1,0,0,1)
> x2 <- c(0,0,1,1)
> x3 <- c(0,0,0,0)
> x4 <- c(1,0,0,1)
> data1 <- cbind(x1,x2,x3,x4)
> x <- c("x1","x2","x3","x4")
>
> do.sum <- function(x,env=parent.frame()) {
> s <- get(x[1],env=env)
> for(i in 2:length(x)) {
> s <- s + get(x[i],env=env)
> }
> }
> totx <- do.sum(x)
> data2 <- cbind(data1,totx)
> data2
>
> Maria
>
> Prof Brian Ripley wrote:
>
> >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