This section describes a number of functions for fitting piecewise smooth curves to data. Functions in this section are particularly useful for plotting charts; there are even convenience functions for using these functions to show fitted values in some graphics packages.


One method for fitting a function to source data is with splines. With a linear model, a single line is fitted to all the data. With spline methods, a set of different polynomials is fitted to different sections of the data.

You can compute simple cubic splines with the spline function in the stats package:

spline(x, y = NULL, n = 3 * length(x), method = "fmm", xmin = min(x),
    xmax = max(x), xout, ties = mean)

Here is a description of the arguments to smooth.spline.

xA vector specifying the predictor variable, or a two-column matrix specifying both the predictor and the response variables. 
yIf x is a vector, then y is a vector containing the response variable.NULL
nIf xout is not specified, then interpolation is done at n equally spaced points between xmin and xmax.3*length(x)
methodSpecifies the type of spline. Allowed values include "fmm", "natural", "periodic", and "monoH.FC"."fmm"
xminLowest x value for interpolations.min(x)
xmaxHighest x value for interpolations.max(x)
xoutAn optional vector of values specifying where interpolation should be done. 
tiesA method for handling ties. Either the string "ordered" or a function that returns a single numeric value.mean

To return a function ...

Get R in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.