Learn R Programming

cooltools (version 2.33)

linfun: Linear Function Fitter

Description

Fits a global linear model \(y = a + b x\) and returns a function that predicts \(y\) for arbitrary \(x\), similar in spirit to approxfun, but using a single least-squares line instead of piecewise interpolation.

Usage

linfun(x, y, na.rm = FALSE, ...)

Value

A function f(xnew) that evaluates the fitted linear regression at numeric values xnew.

Arguments

x

Numeric vector of predictor values.

y

Numeric vector of response values.

na.rm

Logical; if TRUE, remove NA, NaN, and infinite values before fitting (default: FALSE).

...

Additional arguments passed to lm.

Details

This is a convenience wrapper around lm. It returns a callable function analogous to approxfun, but with a single global linear fit: $$f(x) = a + b x,$$ where \(a\) and \(b\) are the intercept and slope from a least-squares regression of y on x.

See Also

[stats::lm()], [stats::approxfun()]

Examples

Run this code
set.seed(1)
x = 1:10
y = 2 + 3 * x + rnorm(10)
f = linfun(x, y)
plot(x,y)
curve(f, col='red', add = TRUE) # show linear fit
points(6.6,f(6.6),col='red') # show predicted y-value at x = 6.6

Run the code above in your browser using DataLab