Applying Savitzky-Golay filters in “R”

March 20, 2012

(This article was first published on NIR-Quimiometría, and kindly contributed to R-bloggers)

When applying SG, we select a moving average window with an odd value “n” for the number of data points. SG fit a polynomial of “p” degree to this data points and give the value to the central point (this is the reason to have an odd value).
We apply also an smooth in the case of “m” = 0, or the first (m=1), second (m=2) or third (m=3) derivatives.
Apply a Savitzky-Golay smoothing filter
Smooth data with a Savitzky-Golay smoothing filter.
sgolayfilt(x, p = 3, n = p + 3 – p%%2, m = 0, ts = 1)
## S3 method for class ‘sgolayFilter’
filter(filt, x, …)

signal to be filtered.
filter order.
filter length (must be odd).
return the m-th derivative of the filter coefficients.
time scaling factor.
filter characteristics (normally generated by sgolay).

Playing with these three parameter we change the shape of the spectra.
The upper spectra was taken with p=2, n=7 and m=2
The lower one with p=2, n=31 and m=2
As we can see the size of the window has a big influence on the resolution of the peaks.
How to apply it in R:
(For the lower spectrum)
 + xlab=”nm”,ylab=”SG_2_31_2_abs”)

To leave a comment for the author, please follow the link and comment on their blog: NIR-Quimiometría. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...


Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)