This vignette shows you the main functionalities of the ‘ir’ package.
This includes data import, functions for spectral preprocessing, and
plotting.
This vignette does not explain the data structure of ir
objects (the objects the package ir uses to store spectra) in detail and
it does not describe general data manipulation functions
(e.g. subsetting rows or columns, modifying variables) (for this, see
vignette Introduction to the
ir
class). Moreover, this vignette does not explain the
purpose of the spectral preprocessing functions.
The vignette has three parts:
In part Data import and export,
I will show how spetra can be imported from csv
files and
from Thermo Galactic’s spectral files (file extension
.spc
). I will also show how ir
objects can be
exported as csv
files. To this end, I will use sample data
which comes along with the ‘ir’ package. In part Plotting spectra, I will show how spectra
can be plotted and how these plots can be modified.
In part Spectral preprocessing I
will demonstrate the main preprocessing functions included in the ‘ir’
package and how these can be combined to execute complex preprocessing
pipelines.
To test importing spectra from files, I’ll use sample data which is
contained in the ‘ir’ package (in folder inst/extdata
).
First, I’ll show how to import spectra from csv files and then how to
import Thermo Galactic’s spectral files (file extension
.spc
).
csv
filesSpectra from csv
files can be imported with
ir_import_csv()
. This function can import spectra from one
or more csv
files with the format shown here:
wavenumber | GN.11.389 | GN.11.400 | GN.11.407 | GN.11.411 |
---|---|---|---|---|
4000 | 0.0003612 | 0.0001991 | 0.0001044 | 0.0001983 |
3999 | 0.0004313 | 0.0003787 | 0.0002027 | 0.0002307 |
3998 | 0.0005014 | 0.0005583 | 0.0003203 | 0.0002631 |
3997 | 0.0005712 | 0.0007378 | 0.0003938 | 0.0002954 |
3996 | 0.0006667 | 0.0009148 | 0.0004075 | 0.0003405 |
3995 | 0.0007045 | 0.0009870 | 0.0004077 | 0.0003683 |
This is a subset of the data we will import in a few moments. The first column must contain spectral channel values (“x axis values”, e.g. wavenumbers for mid infrared spectra), and each additional column represents the intensity values (“y axis values”, e.g. absorbances) of one spectrum. In the example above, there are four spectra in the csv file.
Then, you can simply pass the path to the file to
ir_import_csv()
and this will import the spectra:
The argument sample_id = "from_colnames"
tells
ir_import_csv()
to extract names for the spectra from the
column names of the csv
file.
If you have additional metadata available, you can bind these to the
ir
object in a second step (note: here, I use functions
from [dplyr] to reformat the metadata; you don’t need to understand the
details of this data cleanup):
library(dplyr)
library(stringr)
# import the metadata
d_csv_metadata <-
read.csv("./../inst/extdata/klh_hodgkins_reference.csv",
header = TRUE,
as.is = TRUE) %>%
dplyr::rename(
sample_id = "Sample.Name",
sample_type = "Category",
comment = "Description",
holocellulose = "X..Cellulose...Hemicellulose..measured.",
klason_lignin = "X..Klason.lignin..measured."
) %>%
# make the sample_id values fir to those in `d_csv$sample_id` to make combining easier
dplyr::mutate(
sample_id =
sample_id %>%
stringr::str_replace_all(pattern = "( |-)", replacement = "\\.")
)
d_csv <-
d_csv %>%
dplyr::full_join(d_csv_metadata, by = "sample_id")
Now, d_csv
has addition columns with the added
metadata.
spc
filesSpectra from spc
files can be imported with
ir_import_spc()
. This function can import spectra from one
or more spc
files:
In this case, names for the spectra and other metadata are extracted
from the spc
file(s) and added to the ir
object. You can inspect d_spc
to see these additional
variables.
Data in ir
objects can in principle be exported in many
ways. Here, I show hot to export to a csv
file with the
same format as the sample data we imported in subsection csv
files.
To this end, we first have to “flatten” the spectra
column in ir_sample_data
(using ir_flatten()
)
and export this as csv
file using write.csv()
.
Second, to export the metadata, we have to drop the spectra from
ir_sample_data
(using ir_drop_spectra()
), and
then write the remaining data to a separate csv
file using
write.csv()
:
The ‘ir’ package provides a function to create simple plots of spectra out-of-the box:
This will plot the intensity values (“y axis values”,
e.g. absorbances) of each spectrum versus the spectral channel values
(“x axis values”, e.g. wavenumbers), connected by a line. All spectra in
an ir
object are plotted on top of each other.
ir relies on ggplot. This makes it possible to modify the plot with the functions from ggplot2. For example, we could color spectra according to the sample class:
An of course, we can change axis labels, layout, etc:
ir provides many functions for spectral preprocessing. Here, I’ll show how to use a subset of them. To make it easier to compare the effect, I’ll show here how the sample spectrum looks before any preprocessing:
Baseline correction with a rubberband algorithm (see the
spc.rubberband
function in the hyperspec
package):
Normalization of intensity values by dividing each intensity value by the sum of all intensity values (note the different scale of the y axis in comparison to the spectrum before preprocessing):
Normalization of intensity values by dividing each intensity value by the the intensity value at a specific wavenumber (the horizontal and vertical lines highlight that the intensity at the selected wavenumber is 1 after normalization):
d_spc %>%
ir_normalize(method = 1090) %>%
plot() +
geom_hline(yintercept = 1, linetype = 2) +
geom_vline(xintercept = 1090, linetype = 2)
#> Warning: 1089.59485352039 selected instead of 1090.
The warning just says that the spectrum’s wavenumber values did not exactly match the desired value and therefore the nearest value available was selected. To disable this warning, you can interpolate the spectrum appropriately (see below, section Interpolating).
Smoothing of spectra with the Savitzky-Golay algorithm (see the
sgolayfilt()
function from the signal package for
details):
Savitzky-Golay smoothing can also be used to compute derivative
spectra (here the first derivative is computed by setting the argument
m
to 1
. See ?ir_smooth()
for more
information):
Spectra can be clipped to desired ranges for spectral channels (“x axis values”, e.g. wavenumbers). Here, I clip the spectrum to the range [1000, 3000]:
d_spc %>%
ir_clip(range = data.frame(start = 1000, end = 3000)) %>%
plot()
#> Warning: 1000.88447606564 selected instead of 1000.
#> • 3000.7249417305 selected instead of 3000.
#> Warning: There was 1 warning in `is.data.frame()`.
#> ℹ In argument: `spectra = purrr::map2(...)`.
#> Caused by warning:
#> ! Slicing with a 1-column matrix was deprecated in dplyr 1.1.0.
#> ℹ The deprecated feature was likely used in the ir package.
#> Please report the issue at <https://github.com/henningte/ir/issues/>.
Spectral interpolation (interpolating intensity values for new
wavenumber values) can be performed. Here, intensity values are
interpolated for integer wavenumbers increasing by 1 (by setting
dw = 1
) within the range of the data:
This is not easy to see from the plot, but the warning shown above (section Normalization) during normalization now does not appear:
Sometimes, it is useful to replace parts of spectra by straight lines
which connect the start and end points of a specified range. This can be
done with ir_interpolate_region()
:
Spectral binning collects all intensity values in contiguous spectral ranges (“bins”) with specified widths and averages these:
With ir, it is very easy to build complex reprocessing workflows by
“piping” (using magrittr’s pipe
(%>%
) operator) together different preprocessing
steps:
d_spc %>%
ir_interpolate(dw = 1) %>%
ir_clip(range = data.frame(start = 700, end = 3900)) %>%
ir_bc(method = "rubberband") %>%
ir_normalise(method = "area") %>%
ir_bin(width = 10) %>%
plot()
Now, we have a baseline corrected spectrum, "area"
normalized, clipped to [650, 3900], and binned to bin widths of 10
cm−1.
Many more functions and options to handle and process spectra are
available in the ‘ir’ package. These are described in the documentation.
In the documentation, you can also read more details about the functions
and options presented here.
To learn more about the structure and general functions to handle
ir
objects, see the vignette Introduction to the ir
class.
The data contained in the csv
file used in this vignette
are derived from Hodgkins et al.
(2018)
#> R version 4.4.2 (2024-10-31)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.1 LTS
#>
#> Matrix products: default
#> BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so; LAPACK version 3.12.0
#>
#> locale:
#> [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
#> [3] LC_TIME=en_US.UTF-8 LC_COLLATE=C
#> [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
#> [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
#> [9] LC_ADDRESS=C LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
#>
#> time zone: Etc/UTC
#> tzcode source: system (glibc)
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> other attached packages:
#> [1] stringr_1.5.1 kableExtra_1.4.0 ggplot2_3.5.1 purrr_1.0.2
#> [5] dplyr_1.1.4 ir_0.3.0 rmarkdown_2.29
#>
#> loaded via a namespace (and not attached):
#> [1] gtable_0.3.6 xfun_0.49 bslib_0.8.0
#> [4] latticeExtra_0.6-30 baseline_1.3-5 lattice_0.22-6
#> [7] quadprog_1.5-8 vctrs_0.6.5 tools_4.4.2
#> [10] Rdpack_2.6.2 hyperSpec_0.100.2 generics_0.1.3
#> [13] tibble_3.2.1 fansi_1.0.6 pkgconfig_2.0.3
#> [16] RColorBrewer_1.1-3 lifecycle_1.0.4 compiler_4.4.2
#> [19] farver_2.1.2 deldir_2.0-4 brio_1.1.5
#> [22] munsell_0.5.1 limSolve_1.5.7.1 SparseM_1.84-2
#> [25] htmltools_0.5.8.1 sys_3.4.3 buildtools_1.0.0
#> [28] sass_0.4.9 yaml_2.3.10 lazyeval_0.2.2
#> [31] pillar_1.9.0 jquerylib_0.1.4 tidyr_1.3.1
#> [34] MASS_7.3-61 cachem_1.1.0 tidyselect_1.2.1
#> [37] digest_0.6.37 stringi_1.8.4 maketools_1.3.1
#> [40] labeling_0.4.3 fastmap_1.2.0 grid_4.4.2
#> [43] colorspace_2.1-1 cli_3.6.3 magrittr_2.0.3
#> [46] utf8_1.2.4 withr_3.0.2 scales_1.3.0
#> [49] jpeg_0.1-10 signal_1.8-1 interp_1.1-6
#> [52] png_0.1-8 evaluate_1.0.1 lpSolve_5.6.22
#> [55] knitr_1.49 rbibutils_2.3 testthat_3.2.1.1
#> [58] viridisLite_0.4.2 rlang_1.1.4 Rcpp_1.0.13-1
#> [61] glue_1.8.0 xml2_1.3.6 svglite_2.1.3
#> [64] rstudioapi_0.17.1 jsonlite_1.8.9 R6_2.5.1
#> [67] systemfonts_1.1.0