Regression Spline Functions and Classes

Regression Spline Functions and Classes [R logo]

Help pages for package `splines' version 2.4.1

splines-package | Regression Spline Functions and Classes
as.polySpline | Piecewise Polynomial Spline Representation
asVector | Coerce an Object to a Vector
backSpline | Monotone Inverse Spline
bs | B-Spline Basis for Polynomial Splines
interpSpline | Create an Interpolation Spline
ns | Generate a Basis Matrix for Natural Cubic Splines
periodicSpline | Create a Periodic Interpolation Spline
polySpline | Piecewise Polynomial Spline Representation
predict.bs | Evaluate a Spline Basis
predict.bSpline | Evaluate a Spline at New Values of x
predict.nbSpline | Evaluate a Spline at New Values of x
predict.npolySpline | Evaluate a Spline at New Values of x
predict.ns | Evaluate a Spline Basis
predict.pbSpline | Evaluate a Spline at New Values of x
predict.ppolySpline | Evaluate a Spline at New Values of x
spline.des | Design Matrix for B-splines
splineDesign | Design Matrix for B-splines
splineKnots | Knot Vector from a Spline
splineOrder | Determine the Order of a Spline
splines | Regression Spline Functions and Classes
xyVector | Construct an xyVector Object


Coerce an Object to a Vector

Description

This is a generic function. Methods for this function coerce objects of given classes to vectors.

Usage

asVector(object)

Arguments

object An object.

Details

Methods for vector coercion in new classes must be created for the asVector generic instead of as.vector. The as.vector function is internal and not easily extended. Currently the only class with an asVector method is the xyVector class.

Value

a vector

Author(s)

Douglas Bates and Bill Venables

See Also

xyVector

Examples

ispl <- interpSpline( weight ~ height,  women )
pred <- predict(ispl)
class(pred)
utils::str(pred)
asVector(pred)
[Package splines version 2.4.1 Index]


Monotone Inverse Spline

Description

Create a monotone inverse of a monotone natural spline.

Usage

backSpline(object)

Arguments

object an object that inherits from class nbSpline or npolySpline. That is, the object must represent a natural interpolation spline but it can be either in the B-spline representation or the piecewise polynomial one. The spline is checked to see if it represents a monotone function.

Value

An object of class polySpline that contains the piecewise polynomial representation of a function that has the appropriate values and derivatives at the knot positions to be an inverse of the spline represented by object. Technically this object is not a spline because the second derivative is not constrained to be continuous at the knot positions. However, it is often a much better approximation to the inverse than fitting an interpolation spline to the y/x pairs.

Author(s)

Douglas Bates and Bill Venables

See Also

interpSpline

Examples

ispl <- interpSpline( women$height, women$weight )
bspl <- backSpline( ispl )
plot( bspl )                   # plots over the range of the knots
points( women$weight, women$height )


B-Spline Basis for Polynomial Splines

Description

Generate the B-spline basis matrix for a polynomial spline.

Usage

bs(x, df = NULL, knots = NULL, degree = 3, intercept = FALSE,
   Boundary.knots = range(x))

Arguments

x | the predictor variable. Missing values are allowed.
df | degrees of freedom; one can specify df rather than knots; bs() then chooses df-degree-1 knots at suitable quantiles of x (which will ignore missing values).
knots | the internal breakpoints that define the spline. The default is NULL, which results in a basis for ordinary polynomial regression. Typical values are the mean or median for one knot, quantiles for more knots. See also Boundary.knots.
degree | degree of the piecewise polynomial—default is 3 for cubic splines.
intercept | if TRUE, an intercept is included in the basis; default is FALSE.
Boundary.knots | boundary points at which to anchor the B-spline basis (default the range of the data). If both knots and Boundary.knots are supplied, the basis parameters do not depend on x. Data can extend beyond Boundary.knots.

Value

A matrix of dimension length(x) * df, where either df was supplied or if knots were supplied, df = length(knots) + 3 + intercept. Attributes are returned that correspond to the arguments to bs, and explicitly give the knots, Boundary.knots etc for use by predict.bs().
bs() is based on the function spline.des(). It generates a basis matrix for representing the family of piecewise polynomials with the specified interior knots and degree, evaluated at the values of x. A primary use is in modeling formulas to directly specify a piecewise polynomial term in a model.

References

Hastie, T. J. (1992) Generalized additive models. Chapter 7 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

ns, poly, smooth.spline, predict.bs, SafePrediction

Examples

require(stats)
bs(women$height, df = 5)
summary(fm1 <- lm(weight ~ bs(height, df = 5), data = women))

## example of safe prediction
plot(women, xlab = "Height (in)", ylab = "Weight (lb)")
ht <- seq(57, 73, len = 200)
lines(ht, predict(fm1, data.frame(height=ht)))

## Consistency:
x <- c(1:3,5:6)
stopifnot(identical(bs(x), bs(x, df = 3)),
          !is.null(kk <- attr(bs(x), "knots")),# not true till 1.5.1
          length(kk) == 0)


Create an Interpolation Spline

Description

Create an interpolation spline, either from x and y vectors, or from a formula/data.frame combination.

Usage

interpSpline(obj1, obj2, bSpline = FALSE, period = NULL,
             na.action = na.fail)

Arguments

obj1 | Either a numeric vector of x values or a formula.
obj2 | If obj1 is numeric this should be a numeric vector of the same length. If obj1 is a formula this can be an optional data frame in which to evaluate the names in the formula.
bSpline | If TRUE the b-spline representation is returned, otherwise the piecewise polynomial representation is returned. Defaults to FALSE.
period | An optional positive numeric value giving a period for a periodic interpolation spline.
na.action | a optional function which indicates what should happen when the data contain NAs. The default action (na.omit) is to omit any incomplete observations. The alternative action na.fail causes interpSpline to print an error message and terminate if there are any incomplete observations.

Value

An object that inherits from class spline. The object can be in the B-spline representation, in which case it will be of class nbSpline for natural B-spline, or in the piecewise polynomial representation, in which case it will be of class npolySpline.

Author(s)

Douglas Bates and Bill Venables

See Also

splineKnots, splineOrder, periodicSpline.

Examples

ispl <- interpSpline( women$height, women$weight )
ispl2 <- interpSpline( weight ~ height,  women )
# ispl and ispl2 should be the same
plot( predict( ispl, seq( 55, 75, len = 51 ) ), type = "l" )
points( women$height, women$weight )
plot( ispl )    # plots over the range of the knots
points( women$height, women$weight )
splineKnots( ispl )


Generate a Basis Matrix for Natural Cubic Splines

Description

Generate the B-spline basis matrix for a natural cubic spline.

Usage

ns(x, df = NULL, knots = NULL, intercept = FALSE,
   Boundary.knots = range(x))

Arguments

x | the predictor variable. Missing values are allowed.
df | degrees of freedom. One can supply df rather than knots; ns() then chooses df - 1 - intercept knots at suitably chosen quantiles of x (which will ignore missing values).
knots | breakpoints that define the spline. The default is no knots; together with the natural boundary conditions this results in a basis for linear regression on x. Typical values are the mean or median for one knot, quantiles for more knots. See also Boundary.knots.
intercept | if TRUE, an intercept is included in the basis; default is FALSE.
Boundary.knots | boundary points at which to impose the natural boundary conditions and anchor the B-spline basis (default the range of the data). If both knots and Boundary.knots are supplied, the basis parameters do not depend on x. Data can extend beyond Boundary.knots

Value

A matrix of dimension length(x) * df where either df was supplied or if knots were supplied, df = length(knots) + 1 + intercept. Attributes are returned that correspond to the arguments to ns, and explicitly give the knots, Boundary.knots etc for use by predict.ns().
ns() is based on the function spline.des. It generates a basis matrix for representing the family of piecewise-cubic splines with the specified sequence of interior knots, and the natural boundary conditions. These enforce the constraint that the function is linear beyond the boundary knots, which can either be supplied, else default to the extremes of the data. A primary use is in modeling formula to directly specify a natural spline term in a model.

References

Hastie, T. J. (1992) Generalized additive models. Chapter 7 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

bs, predict.ns, SafePrediction

Examples

require(stats)
ns(women$height, df = 5)
summary(fm1 <- lm(weight ~ ns(height, df = 5), data = women))

## example of safe prediction
plot(women, xlab = "Height (in)", ylab = "Weight (lb)")
ht <- seq(57, 73, len = 200)
lines(ht, predict(fm1, data.frame(height=ht)))


Create a Periodic Interpolation Spline

Description

Create a periodic interpolation spline, either from x and y vectors, or from a formula/data.frame combination.

Usage

periodicSpline(obj1, obj2, knots, period = 2*pi, ord = 4)

Arguments

obj1 | either a numeric vector of x values or a formula.
obj2 | if obj1 is numeric this should be a numeric vector of the same length. If obj1 is a formula this can be an optional data frame in which to evaluate the names in the formula.
knots | optional numeric vector of knot positions.
period | positive numeric value giving the period for the periodic spline. Defaults to 2 * pi.
ord | integer giving the order of the spline, at least 2. Defaults to 4. See splineOrder for a definition of the order of a spline.

Value

An object that inherits from class spline. The object can be in the B-spline representation, in which case it will be a pbSpline object, or in the piecewise polynomial representation (a ppolySpline object).

Author(s)

Douglas Bates and Bill Venables

See Also

splineKnots, interpSpline

Examples

xx <- seq( -pi, pi, len = 16 )[-1]
yy <- sin( xx )
frm <- data.frame( xx, yy )
( pispl <- periodicSpline( xx, yy, period = 2 * pi ) )
pispl2 <- periodicSpline( yy ~ xx, frm, period = 2 * pi )
stopifnot(all.equal(pispl, pispl2))# pispl and pispl2 are the same

plot( pispl )          # displays over one period
points( yy ~ xx, col = "brown")
plot( predict( pispl, seq(-3*pi, 3*pi, len = 101) ), type = "l" )


Piecewise Polynomial Spline Representation

Description

Create the piecewise polynomial representation of a spline object.

Usage

polySpline(object, ...)
as.polySpline(object, ...)

Arguments

object | An object that inherits from class spline.
... | Optional additional arguments. At present no additional arguments are used.

Value

An object that inherits from class polySpline. This is the piecewise polynomial representation of a univariate spline function. It is defined by a set of distinct numeric values called knots. The spline function is a polynomial function between each successive pair of knots. At each interior knot the polynomial segments on each side are constrained to have the same value of the function and some of its derivatives.

Author(s)

Douglas Bates and Bill Venables

See Also

interpSpline, periodicSpline, splineKnots, splineOrder

Examples

ispl <- polySpline( interpSpline( weight ~ height,  women, bSpline = TRUE ) )
print( ispl )   # print the piecewise polynomial representation
plot( ispl )    # plots over the range of the knots
points( women$height, women$weight )


Evaluate a Spline Basis

Description

Evaluate a predefined spline basis at given values.

Usage

## S3 method for class 'bs':
predict(object, newx, ...)

## S3 method for class 'ns':
predict(object, newx, ...)

Arguments

object | the result of a call to bs or ns having attributes describing knots, degree, etc.
newx | the x values at which evaluations are required.
... | Optional additional arguments. At present no additional arguments are used.

Value

An object just like object, except evaluated at the new values of x.
These are methods for the generic function predict for objects inheriting from classes "bs" or "ns". See predict for the general behavior of this function.

See Also

bs, ns, poly.

Examples

basis <- ns(women$height, df = 5)
newX <- seq(58, 72, len = 51)
# evaluate the basis at the new data
predict(basis, newX)


Evaluate a Spline at New Values of x

Description

The predict methods for the classes that inherit from the virtual classes bSpline and polySpline are used to evaluate the spline or its derivatives. The plot method for a spline object first evaluates predict with the x argument missing, then plots the resulting xyVector with type = "l".

Usage

## S3 method for class 'bSpline':
predict(object, x, nseg=50, deriv=0, ...)
## S3 method for class 'nbSpline':
predict(object, x, nseg=50, deriv=0, ...)
## S3 method for class 'pbSpline':
predict(object, x, nseg=50, deriv=0, ...)
## S3 method for class 'npolySpline':
predict(object, x, nseg=50, deriv=0, ...)
## S3 method for class 'ppolySpline':
predict(object, x, nseg=50, deriv=0, ...)

Arguments

object | An object that inherits from the bSpline or the polySpline class.
x | A numeric vector of x values at which to evaluate the spline. If this argument is missing a suitable set of x values is generated as a sequence of nseq segments spanning the range of the knots.
nseg | A positive integer giving the number of segments in a set of equally-spaced x values spanning the range of the knots in object. This value is only used if x is missing.
deriv | An integer between 0 and splineOrder(object) - 1 specifying the derivative to evaluate.
... | further arguments passed to or from other methods.

Value

an xyVector with components

x | the supplied or inferred numeric vector of x values
y | the value of the spline (or its deriv'th derivative) at the x vector

Author(s)

Douglas Bates and Bill Venables

See Also

xyVector, interpSpline, periodicSpline

Examples

ispl <- interpSpline( weight ~ height,  women )
opar <- par(mfrow = c(2, 2), las = 1)
plot(predict(ispl, nseg = 201),     # plots over the range of the knots
     main = "Original data with interpolating spline", type = "l",
     xlab = "height", ylab = "weight")
points(women$height, women$weight, col = 4)
plot(predict(ispl, nseg = 201, deriv = 1),
     main = "First derivative of interpolating spline", type = "l",
     xlab = "height", ylab = "weight")
plot(predict(ispl, nseg = 201, deriv = 2),
     main = "Second derivative of interpolating spline", type = "l",
     xlab = "height", ylab = "weight")
plot(predict(ispl, nseg = 401, deriv = 3),
     main = "Third derivative of interpolating spline", type = "l",
     xlab = "height", ylab = "weight")
par(opar)


Design Matrix for B-splines

Description

Evaluate the design matrix for the B-splines defined by knots at the values in x.

Usage

splineDesign(knots, x, ord = 4, derivs, outer.ok = FALSE)
spline.des(knots, x, ord = 4, derivs, outer.ok = FALSE)

Arguments

knots | a numeric vector of knot positions with non-decreasing values.
x | a numeric vector of values at which to evaluate the B-spline functions or derivatives. Unless outer.ok is truee, the values in x must be between knots[ord] and knots[ length(knots) + 1 - ord ].
ord | a positive integer giving the order of the spline function. This is the number of coefficients in each piecewise polynomial segment, thus a cubic spline has order 4. Defaults to 4.
derivs | an integer vector of the same length as x and with values between 0 and ord - 1. The derivative of the given order is evaluated at the x positions. Defaults to a vector of zeroes of the same length as x.
outer.ok | logical indicating if x should be allowed outside the inner knots, see the x argument.

Value

A matrix with length( x ) rows and length( knots ) - ord columns. The i'th row of the matrix contains the coefficients of the B-splines (or the indicated derivative of the B-splines) defined by the knot vector and evaluated at the i'th value of x. Each B-spline is defined by a set of ord successive knots so the total number of B-splines is length(knots)-ord.

Note

The older spline.des function takes the same arguments but returns a list with several components including knots, ord, derivs, and design. The design component is the same as the value of the splineDesign function.

Author(s)

Douglas Bates and Bill Venables

Examples

splineDesign(knots = 1:10, x = 4:7)

knots <- c(1,1.8,3:5,6.5,7,8.1,9.2,10)# 10 => 10-4 = 6 Basis splines
x <- seq(min(knots)-1, max(knots)+1, length=501)
bb <- splineDesign(knots, x=x, outer.ok = TRUE)

plot(range(x), c(0,1), type="n", xlab="x", ylab="",
     main= "B-splines - sum to 1 inside inner knots")
mtext(expression(B[j](x) *"  and "* sum(B[j](x), j==1, 6)), adj=0)
abline(v=knots, lty=3, col="light gray")
abline(v=knots[c(4,length(knots)-3)], lty=3, col="gray10")
lines(x, rowSums(bb), col="gray", lwd=2)
matlines(x, bb, ylim = c(0,1), lty=1)


Knot Vector from a Spline

Description

Return the knot vector corresponding to a spline object.

Usage

splineKnots(object)

Arguments

object an object that inherits from class "spline".

Value

A non-decreasing numeric vector of knot positions.

Author(s)

Douglas Bates and Bill Venables

Examples

ispl <- interpSpline( weight ~ height, women )
splineKnots( ispl )


Determine the Order of a Spline

Description

Return the order of a spline object.

Usage

splineOrder(object)

Arguments

object An object that inherits from class "spline".

Details

The order of a spline is the number of coefficients in each piece of the piecewise polynomial representation. Thus a cubic spline has order 4.

Value

A positive integer.

Author(s)

Douglas Bates and Bill Venables

See Also

splineKnots, interpSpline, periodicSpline

Examples

splineOrder( interpSpline( weight ~ height, women ) )


Regression Spline Functions and Classes

Description

Regression spline functions and classes.

Details

This package provides functions for working with regression splines using the B-spline basis, the natural cubic spline basis.

For a complete list of functions, use library(help="splines").

Author(s)

Douglas M. Bates bates@stat.wisc.edu and William N. Venables Bill.Venables@cmis.csiro.au

Maintainer: R Core Team R-core@r-project.org


Construct an xyVector Object

Description

Create an object to represent a set of x-y pairs. The resulting object can be treated as a matrix or as a data frame or as a vector. When treated as a vector it reduces to the y component only.

The result of functions such as predict.spline is returned as an xyVector object so the x-values used to generate the y-positions are retained, say for purposes of generating plots.

Usage

xyVector(x, y)

Arguments

x | a numeric vector
y | a numeric vector of the same length as x

Value

An object of class xyVector with components

x | a numeric vector
y | a numeric vector of the same length as x

Author(s)

Douglas Bates and Bill Venables

Examples

ispl <- interpSpline( weight ~ height, women )
weights <- predict( ispl, seq( 55, 75, len = 51 ))
class( weights )
plot( weights, type = "l", xlab = "height", ylab = "weight" )
points( women$height, women$weight )
weights