## 10 sept. 2014

### 2nd derivative using "apply" and "diff"

This is a simply exercise, where we convert the raw spectrum into its first derivative, and into its second derivative, using the function apply, and the function diff.
I use the shootout 2002 data available in the package ChemometricsWithR.

X1_diff1<-t(apply(nir.training1\$X,1,diff))

In this case the 1 is to apply the function difference to the rows (spectra).
We don´t add more than the default options to the function diff, so the lag=1 and the value of differences=1.

The spectrum changes (losing 1 data point) to the black spectrum in the plot at the end of the post.
plot(as.numeric(colnames(X1_diff1)),X1_diff1 [1,],type="l",xlab="Wavelength (nm)",ylab="1/R (1st derivative)",lty=1,col=1)

We can say briefly that the second derivative is the derivative of the firs derivative; we can do this changing the value of the option “differences” from 1 to 2, losing, in this case two data points.

X1_diff2<-t(apply(nir.training1\$X,1,diff,differences=2))

par(new=TRUE)

plot(as.numeric(colnames(X1_diff2)),X1_diff2[1,],type="l",xlab="Wavelength (nm)",ylab="1/R (2nd derivative)",lty=1,col=2)

The spectrum of the second derivative is the red one in the plot, compared with the black one of the first derivative.
This way to do the derivatives is very noisy, so in future post we will try to use gap derivative which is the way that softwares as Unscrambler, Win ISI and many others use the derivatives.