as.function.lm: Transform an lm or glm model into a function

View source: R/as.function.lm.R

as.function.lmR Documentation

Transform an lm or glm model into a function

Description

Transform an lm or glm model that has only two variables into a function (useful for plotting, see examples).

Usage

## S3 method for class 'lm'
as.function(x, ...)

Arguments

x

An lm or glm model

...

Further arguments to the method (not used for now)

Value

A function with argument x that returns the values predicted by the model for these values of x.

Examples

data("trees", package = "datasets")
trees_lm1 <- lm(Volume ~ Girth, data = trees)
trees_lm2 <- lm(Volume ~ Girth + I(Girth^2), data = trees)

# Compare these two models on a chart
library(chart)
chart(trees, Volume ~ Girth) +
  geom_point() +
  stat_function(fun = as.function(trees_lm1), col = "red") +
  stat_function(fun = as.function(trees_lm2), col = "blue")

# The created function can also be used for easy predictions
trees_fn1 <- as.function(trees_lm1)
trees_fn1(10:20) # Volume for Girth 10:20

SciViews/modelit documentation built on Nov. 24, 2024, 10:23 a.m.