Skip to content

Instantly share code, notes, and snippets.

@wch
Created April 28, 2012 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wch/2520748 to your computer and use it in GitHub Desktop.
Save wch/2520748 to your computer and use it in GitHub Desktop.
Functions for generating predicted values from model objects in R
#' Find the range of the predictor variable, given the model object and the
#' name of the predictor variable
#'
# @examples
#' lm_mod <- lm(am ~ wt, data=mtcars)
#' model_xrange(lm_mod, "wt")
#'
#' mod_glm <- glm(am ~ wt, family=binomial, data=mtcars)
#' model_xrange(mod_glm, "wt")
#'
#' loess_mod <- loess(mpg ~ wt, data=mtcars)
#' model_xrange(loess_mod, "wt")
model_xrange <- function(model, xvar) UseMethod("model_xrange")
# This works for lm and glm (and maybe others)
model_xrange.default <- function(model, xvar) {
range(model$model[[xvar]])
}
model_xrange.loess <- function(model, xvar) {
# xvar isn't needed for loess
range(model$x)
}
#' Given a model, predict values of yvar from xvar
#'
#' This only supports one predictor and one predicted variable.
#'
#' TODO:
#' * allow specify range
#' * add se
#'
#' @examples
#' lm_mod <- lm(mpg ~ wt, data = mtcars)
#' predictvals(lm_mod, xvar = "wt", yvar = "mpg")
#'
#' loess_mod <- loess(mpg ~ wt, data=mtcars)
#' predicted <- predictvals(loess_mod, xvar = "wt", yvar = "mpg")
#'
#' # Predictions, splitting on grouping vars
#' # Using loess, predict mpg from wt, and split on cyl
#' library(plyr)
#' models <- dlply(mtcars, .(cyl), loess, formula = mpg ~ wt)
#' predicted <- ldply(models, predictvals, xvar = "wt", yvar = "mpg")
#'
#' # Using lm, predict mpg from wt, and split on cyl + am
#' models <- dlply(mtcars, .(cyl, am), lm, formula = mpg ~ wt)
#' predicted <- ldply(models, predictvals, xvar = "wt", yvar = "mpg")
predictvals <- function(model, xvar, yvar, samples = 100, type = NULL) {
xrange <- model_xrange(model, xvar)
newdata <- data.frame(x = seq(xrange[1], xrange[2], length.out = samples))
names(newdata) <- xvar
newdata[[yvar]] <- predict(model, newdata = newdata, type = type)
newdata
}
@mitochondrialist
Copy link

Hello Winston , Thank you so much for your great book.
I am a novice and self-teaching myself R.
I just wanted to bring to your attention that some of the recipes in your book does not work directly for example in the newst versions of Rstudio.

For example: the option family=binomial doesnt work unless one uses method.args=list(family="binomial" instead
I failed to figure our this though.

lm_predicted <- predictvals(modlinear, "ageYear", "heightIn")
Error: could not find function "predictvals"

Any advice will be greatly appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment