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

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Fri 25 Aug 2006 - 07:13:14 EST

Use as.formula to convert the character string to an object of class "formula" and note that we want to set the formula's environment appropriately:

fit.main <- function(resp, x, env = parent.frame()) {

	fo <- as.formula(paste("y", "~", paste(x, collapse = "+")))
	environment(fo) <- env
	fo

}

# test
fit.main("y", letters[1:3])

On 8/24/06, Maria Montez <montez@bu.edu> 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@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.
>



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 Fri Aug 25 10:24:42 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 Fri 25 Aug 2006 - 12:26:06 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.