# PCA for NIR Spectra_part 005: "Reconstruction"

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**NIR-Quimiometría**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

We saw how to plot the raw spectra (X), how to calculate the mean spectrum, how to center the sprectra (subtracting the mean spectrum from every spectra of the original matrix X). After that we have developed the PCAs with the NIPALS algorithm, getting two matrices: T (scores) and P (loadings).

We have to decide the number of PCs, looking to the plots, or to the numbers (explained variance).

Depending of the numbers of PCs, these matrices will have more or less columns.

With these two matrices we can reconstruct again the X centered matrix, but we´ll get also a residual matrix “E”.

**X**

_{c }= T.P^{t}+EThis post just shows this in R:

**> P3pc_nipals<-P_nipals[,1:3]**

**> tP3pc_nipals<-t(P3pc_nipals)**

**> Xc3pc_reconst<-T3pc_nipals**

**> Xc3pc_reconst<-T3pc_nipals%*%tP3pc_nipals**

**> matplot(wavelengths,t(Xc3pc_reconst),lty=1,**

**+ pch=1,xlab=”data_points”,ylab=”log(1/R)”)**

**> resid3pc<-Xc- Xc3pc_reconst**

**> matplot(wavelengths,t(resid3pc),lty=1,**

**+ pch=1,xlab=”data_points”,ylab=”log(1/R)”)**

To

**leave a comment**for the author, please follow the link and comment on their blog:**NIR-Quimiometría**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.