lspline: Linear spline

View source: R/stat.R

lsplineR Documentation

Linear spline

Description

Fit a linear spline regression model with pre-specified knots.

Usage

lspline(x, y, knots = NULL)

## S3 method for class 'lspline'
plot(x, col = NULL, which = 1:2, ...)

## S3 method for class 'lspline'
points(x, y = NULL, type = "p", col = NULL, ...)

## S3 method for class 'lspline'
lines(x, y = NULL, type = "l", col = NULL, ...)

Arguments

x, y

the x- and y-axis variables

knots

value(s) of x where knots will be fixed

col

a vector of colors for each spline

which

an integer vector specifying the plot(s); see details

...

additional arguments passed to plot.default or further to par

type

character indicating the type of plotting; see plot.default

Details

rawr:::lsdata creates a data set to fit lm for the knots. Adjusted values may be extracted with predict.lm.

The plotting method draws one or two figures: if which = 1, the original x and y values are plotted with fit lines for each spline, and {x, y} coordinates are projected onto the line. If which = 2, the x values are plotted with the fitted y values and colored by spline.

Value

lspline returns an lm object with class "lspline" and attribute attr(., "knots"). The data used to fit the model can be accessed with $model or created using rawr:::lsdata.

Examples

x <- cars$speed
y <- cars$dist

lspline(x, y, NULL)
lm(y ~ x)

ls <- lspline(x, y, c(10, 20))
predict(ls)
plot(ls)

plot(y ~ x)
points(ls, col = 3:5, pch = 16)
lines(ls, col = 3:5, lwd = 2)

## compare
plot(lspline(x, y, knots = 15), col = 2:3, which = 1L)

knot <- 15
fit <- lm(dist ~ speed + I((speed - knot) * (speed >= knot)), cars)
plot(y ~ x)
xx <- seq(min(x), knot, length.out = 1000L)
co <- coef(fit)
lines(xx, co[1] + co[2] * xx, col = 2)
xx <- seq(knot, max(x), length.out = 1000L)
lines(xx, co[1] + co[2] * xx + co[3] * (xx - knot), col = 3)


raredd/rawr documentation built on March 4, 2024, 1:36 a.m.