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).
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.
set.seed(1)
x = 1:10y = 2 + 3 * x + rnorm(10)
f = linfun(x, y)
plot(x,y)
curve(f, col='red', add = TRUE) # show linear fitpoints(6.6,f(6.6),col='red') # show predicted y-value at x = 6.6