[R] generating an expression for a formula automatically

Gabor Grothendieck ggrothendieck at gmail.com
Sat Aug 26 03:54:08 CEST 2006


Try this and note we must pay attention to which environment
the expression is evaluated in.


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

# test
x1 <- x2 <- 1
fit.sum(c("x1","x2"))



On 8/25/06, Maria Montez <montez at bu.edu> 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).
>
> Thanks again, Maria
>
>
>
>
> Sundar Dorai-Raj wrote:
>
> >
> > Maria Montez wrote:
> >
> >> Hi!
> >>
> >> I would like to be able to create formulas automatically. For
> >> example, I want to be able to create a function that takes on two
> >> values: resp and x, and then creates the proper formula to regress
> >> resp on x.
> >>
> >> My code:
> >>
> >> fit.main <- function(resp,x) {
> >>  form <- expression(paste(resp," ~ ",paste(x,sep="",collapse=" +
> >> "),sep=""))
> >>   z <- lm(eval(form))
> >>  z
> >> }
> >> main <- fit.main("y",c("x1","x2","x3","x4"))
> >>
> >> and I get this error:
> >> Error in terms.default(formula, data = data) :
> >>         no terms component
> >>
> >> Any suggestions?
> >>
> >> Thanks, Maria
> >>
> >> ______________________________________________
> >> R-help at 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.
> >
> >
> > Hi, Maria,
> >
> > Try
> >
> > regr <- paste(x, collapse = "+")
> > form <- as.formula(sprintf("%s ~ %s", resp, regr))
> >
> > HTH,
> >
> > --sundar
> >
>
> ______________________________________________
> R-help at 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.
>



More information about the R-help mailing list