Thorn,
Here's how I do it:
retval <- list(as.name('lm'),
formula=as.formula(paste(Response, "~", Explan,
sep='')),
data=as.name(Data))
#... optionally add other arguments
retval <- eval(as.call(retval))
Dave
From:
"Thaler, Thorn, LAUSANNE, Applied Mathematics"
To:
Date:
12/13/2010 12:16 PM
Subject:
[R] predict.lm[e] with formula passed as a variable
Sent by:
r-help-bounces@r-project.org
Dear all,
In a function I paste a string and convert it to a formula which I pass
to lm[e]. The idea is to write a function which takes the name of the
response variable and the explanatory variable and the data frame as an
argument and calculates an lm[e]. (see example below)
This works fine, but if I want to make a prediction on this model, R
complains that the object holding the formula ("form") cannot be found.
How can I circumvent this problem? I think I've to provide somehow an
environment to "predict" holding the binding for the variable "form",
such that predict can resolve the variable, but I've no clue how to do
this.
Help is very much appreciated.
BR + thanks,
Thorn
----------------8<----------------
df <- data.frame(x=factor(rep(1:2, each=10)), y=c(rnorm(10), rnorm(10,
10)), z=rep(1:10,2))
test <- function(df, resp, x, rf, LM = FALSE) {
form <- paste(resp, x, sep = " ~ ")
form <- as.formula(form)
if (LM) {
mod <- lm(form, data=df)
} else {
rand <- as.formula(paste("~1", rf, sep = " | "))
mod <- lme(form, data = df, random = rand)
}
x.new <- data.frame(levels(df[[x]]))
names(x.new) <- x
if (LM)
predict(mod, x.new)
else
predict(mod, x.new, level=0)
}
> test(df, "y", "x", "z")
Error in eval(expr, envir, enclos) : object 'form' not found
---------------->8----------------
______________________________________________
R-help@r-project.org 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.
[[alternative HTML version deleted]]