Skip to content
Prev 334610 / 398506 Next

Help using mapply to run multiple models

Try something like the following.  Because lm() evaluates many
of its arguments in nonstandard ways, f() manipulates the call
and then evaluates it in the frame from which f() was called.
It also puts that environment on the formula that it creates so
it can refer to variables in that environment.
    f <- function (responseName, predictorNames, data, ..., envir = parent.frame())
    {
        call <- match.call()
        call$formula <- formula(envir = envir, paste(responseName, sep = " ~ ",
            paste0("`", predictorNames, "`", collapse = " + ")))
                call[[1]] <- quote(glm) # 'f' -> 'glm'
        call$responseName <- NULL # omit responseName=
        call$predictorNames <- NULL # omit 'predictorNames='
                eval(call, envir = envir)
    }
as in
    z <- lapply(list(c("hp","drat"), c("cyl"), c("am","gear")), FUN=function(preds)f("carb", preds, data=mtcars, family=poisson))
    lapply(z, summary)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com