[R] RE: Savitzky-Golay smoothing -- an R implementation

Nicholas Lewin-Koh nikko at hailmail.net
Wed Feb 11 02:32:41 CET 2004

Savitzky and Golay were indeed pioneers of local least squares methods.
However the SG smoother is
hard to implement in practice because of missing values and problems at
the boundary. Paul Eilers 
at Leiden has presented a very nice method for smoothing series based on
penalized least squares 
known as Whittaker smoothing, develeoped in 1923 for life tables. Look at
Analytical Chemistry (2003) 75, 3299-3304.
Here is an R implementation that requires the SparseM package.

The smoothing parameter lambda, controls the amount of smoothing, and
"good" values can be found by cross validation.

difsm <- function(y, lambda, d){
# Smoothing with a finite difference penalty
# y:      signal to be smoothed
# lambda: smoothing parameter
# d:      order of differences in penalty (generally 2)
# Paul Eilers, 2002, ported from matlab by Nicholas Lewin-Koh
  m <- length(y)
  E <- as(m,"matrix.diag.csr")
  D <- diff(E,differences=d)
  B <- E + (lambda * t(D)%*%D)
  z <- solve(B,y)

More information about the R-help mailing list