[R] predict.lm[e] with formula passed as a variable

Thaler, Thorn, LAUSANNE, Applied Mathematics Thorn.Thaler at rdls.nestle.com
Mon Dec 13 19:10:05 CET 2010

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

Help is very much appreciated.

BR + thanks,


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)
    predict(mod, x.new, level=0)

> test(df, "y", "x", "z")
Error in eval(expr, envir, enclos) : object 'form' not found

More information about the R-help mailing list