| Title: | Functions to Handle and Preprocess Infrared Spectra |
| Version: | 0.4.1 |
| Description: | Functions to import and handle infrared spectra (import from '.csv' and Thermo Galactic's '.spc', baseline correction, binning, clipping, interpolating, smoothing, averaging, adding, subtracting, dividing, multiplying, atmospheric correction, 'tidyverse' methods, plotting). |
| License: | GPL-3 |
| Encoding: | UTF-8 |
| LazyData: | true |
| RoxygenNote: | 7.3.2 |
| Depends: | R (≥ 4.1.0) |
| Imports: | tidyr, dplyr, purrr, tibble, ggplot2, stringr, hyperSpec (≥0.99.20200527), grDevices, rlang, methods, units, Rdpack,magrittr, stats, lifecycle |
| Suggests: | baseline, ChemoSpec (≥ 5.2.12), kableExtra, fda, knitr,quantities, rmarkdown, signal, spelling, vctrs, tidyselect,prospectr |
| VignetteBuilder: | knitr |
| RdMacros: | Rdpack |
| Date: | 2025-04-06 |
| URL: | https://henningte.github.io/ir/,https://github.com/henningte/ir/ |
| BugReports: | https://github.com/henningte/ir/issues/ |
| Language: | en-US |
| NeedsCompilation: | no |
| Packaged: | 2025-04-06 04:17:46 UTC; henni |
| Author: | Henning Teickner |
| Maintainer: | Henning Teickner <henning.teickner@uni-muenster.de> |
| Repository: | CRAN |
| Date/Publication: | 2025-04-06 04:30:02 UTC |
ir: Functions to Handle and Preprocess Infrared Spectra
Description
Functions to import and handle infrared spectra (import from '.csv' and Thermo Galactic's '.spc', baseline correction, binning, clipping, interpolating, smoothing, averaging, adding, subtracting, dividing, multiplying, atmospheric correction, 'tidyverse' methods, plotting).
Author(s)
Maintainer: Henning Teicknerhenning.teickner@uni-muenster.de (ORCID) [copyright holder]
See Also
Useful links:
Report bugs athttps://github.com/henningte/ir/issues/
Pipe operator
Description
Seemagrittr::[\%>\%][magrittr::pipe] for details.
Usage
lhs %>% rhsArguments
lhs | A value or the magrittr placeholder. |
rhs | A function call using the magrittr semantics. |
Value
The result of callingrhs(lhs).
Arithmetic operations forir objects
Description
Arithmetic operations forir objects
Usage
## S3 method for class 'ir'Ops(e1, e2)Arguments
e1 | An object of class |
e2 | An object of class |
Value
e1 with intensity values of the spectra added to/subtractedwith/multiplied with/divided by those ine2:
If
e2is a numeric value, all intensity values in the spectra ofe1areadded/subtracted/multiplied/divided bye2.If
e2is anirobject with one row, it is replicated (seerep.ir) sothat the row numbers match to those ofe1and intensity values areadded/subtracted/multiplied/divided row-wise.If
e2is anirobject with the same number of rows ase1, intensityvalues are added/subtracted/multiplied/divided row-wise.
Examples
## additionir::ir_sample_data + ir::ir_sample_datair::ir_sample_data + 2ir::ir_sample_data + seq(from = 0, to = 2, length.out = nrow(ir::ir_sample_data))## subtractionir::ir_sample_data - ir::ir_sample_datair::ir_sample_data - 2ir::ir_sample_data - seq(from = 0, to = 2, length.out = nrow(ir::ir_sample_data))## multiplicationir::ir_sample_data * ir::ir_sample_datair::ir_sample_data * 2ir::ir_sample_data * seq(from = 0, to = 2, length.out = nrow(ir::ir_sample_data))## divisionir::ir_sample_data / ir::ir_sample_datair::ir_sample_data / 2ir::ir_sample_data / seq(from = 0.1, to = 2, length.out = nrow(ir::ir_sample_data))Arrange rows inir objects by column values
Description
Arrange rows inir objects by column values
Usage
arrange.ir(.data, ..., .by_group = FALSE)Arguments
.data | An object of class |
... | < |
.by_group | If |
Value
.data with arranged rows.
Source
See Also
Other tidyverse:distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## arrangedplyr::arrange(ir_sample_data, dplyr::desc(sample_type))Bind rows ofir objects
Description
Bind rows ofir objects
Usage
## S3 method for class 'ir'rbind(..., deparse.level = 1)## S3 method for class 'ir'cbind(..., deparse.level = 1)Arguments
... | Objects to bind together. For |
deparse.level | An integer value; see |
Value
An object of classir.rbind returns all inputir objects combined row-wise.cbind returns the inputirobject and the other objects combined column-wise.
Examples
# rbindrbind(ir_sample_data, ir_sample_data)rbind(ir_sample_data |> dplyr::select(spectra), ir_sample_data |> dplyr::select(spectra))# cbindcbind(ir_sample_data, a = seq_len(nrow(ir_sample_data)))Subset distinct/unique rows inir objects
Description
Subset distinct/unique rows inir objects
Usage
distinct.ir(.data, ..., .keep_all = FALSE)Arguments
.data | An object of class |
... | < |
.keep_all | If |
Value
.data with distinct rows.
Source
See Also
Other tidyverse:arrange.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## distinctdplyr::distinct(rep(ir_sample_data, 2))Extract a character column in anir object into multiple columns using regular expression groups
Description
Extract a character column in anir object into multiple columns using regular expression groups
Usage
extract.ir( data, col, into, regex = "([[:alnum:]]+)", remove = TRUE, convert = FALSE, ...)Arguments
data | An object of class |
col | < |
into | Names of new variables to create as character vector.Use |
regex | A string representing a regular expression used to extract thedesired values. There should be one group (defined by |
remove | If |
convert | If NB: this will cause string |
... | Additional arguments passed on to methods. |
Value
data with an extracted character column. Seetidyr::extract().
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## extractir_sample_data |> tidyr::extract( id_sample, "a" )Filtering joins for anir object
Description
Filtering joins for anir object
Usage
semi_join.ir(x, y, by = NULL, copy = FALSE, ..., na_matches = c("na", "never"))anti_join.ir(x, y, by = NULL, copy = FALSE, ..., na_matches = c("na", "never"))Arguments
x | An object of class |
y | A data frame. |
by | A join specification created with If To join on different variables between To join by multiple variables, use a
For simple equality joins, you can alternatively specify a character vectorof variable names to join by. For example, To perform a cross-join, generating all combinations of |
copy | If |
... | Other parameters passed onto methods. |
na_matches | Should two |
Value
x andy joined. If thespectra column is renamed, theirclass is dropped. Seefilter-joins.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## semi_joinset.seed(234)dplyr::semi_join( ir_sample_data, tibble::tibble( id_measurement = c(1:5, 101:105), nitrogen_content = rbeta(n = 10, 0.2, 0.1) ), by = "id_measurement")## anti_joinset.seed(234)dplyr::anti_join( ir_sample_data, tibble::tibble( id_measurement = c(1:5, 101:105), nitrogen_content = rbeta(n = 10, 0.2, 0.1) ), by = "id_measurement")Subset rows inir objects using column values
Description
Subset rows inir objects using column values
Usage
filter.ir(.data, ..., .preserve = FALSE)Arguments
.data | An object of class |
... | < |
.preserve | Relevant when the |
Value
.data with filtered rows.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## filterdplyr::filter(ir_sample_data, sample_type == "office paper")Group rows inir objects by one or more variables
Description
Group rows inir objects by one or more variables
Usage
group_by.ir( .data, ..., .add = FALSE, .drop = dplyr::group_by_drop_default(.data))ungroup.ir(.data, ...)Arguments
.data | An object of class |
... | In |
.add | When This argument was previously called |
.drop | Drop groups formed by factor levels that don't appear in thedata? The default is |
Value
.data with grouped rows (group_by.ir()) or ungrouped rows(ungroup.ir()).
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## group_bydplyr::group_by(ir_sample_data, sample_type)## ungroupdplyr::ungroup(dplyr::group_by(ir_sample_data, sample_type))Add infrared spectra
Description
ir_add takes two objects of classir,x andy, and adds the intensity values of spectra in matching rows fromy to that ofx.
Usage
ir_add(x, y)Arguments
x | An object of class |
y | An object of class |
Value
x where for each spectrum the respective intensity values iny are added.
Examples
x1 <- ir::ir_add(ir::ir_sample_data, ir::ir_sample_data)x2 <- ir::ir_add(ir::ir_sample_data, ir::ir_sample_data[1, ])# adding a numeric value to an object of class `ir`.x3 <- ir::ir_add(ir::ir_sample_data, 1)# adding a numeric vector from an object of class `ir`.x4 <- ir::ir_add( ir::ir_sample_data, seq(from = 0, to = 2, length.out = nrow(ir::ir_sample_data)) )Converts an object to classir
Description
ir_as_ir converts an object to an object of classir.
Usage
ir_as_ir(x, ...)## S3 method for class 'ir'ir_as_ir(x, ...)## S3 method for class 'data.frame'ir_as_ir(x, ...)## S3 method for class 'ir_flat'ir_as_ir(x, ...)## S3 method for class 'hyperSpec'ir_as_ir(x, ...)## S3 method for class 'Spectra'ir_as_ir(x, ...)Arguments
x | An object. |
... | Further arguments passed to individual methods.
|
Value
An object of classir with available metadata from originalobjects.
Examples
# conversion from an ir objectir::ir_sample_data |> ir_as_ir()# conversion from a data framex_ir <- ir::ir_sample_datax_df <- x_ir |> ir_drop_spectra() |> dplyr::mutate( spectra = x_ir$spectra ) |> ir_as_ir()# check that ir_as_ir preserves the input classir_sample_data |> structure(class = setdiff(class(ir_sample_data), "ir")) |> dplyr::group_by(sample_type) |> ir_as_ir()# conversion from an ir_flat objectx_ir <- ir::ir_sample_data |> ir::ir_flatten() |> ir::ir_as_ir()# conversion from a hyperSpec object from package hyperSpecif(requireNamespace("hyperSpec")) { x_hyperSpec <- hyperSpec::laser x_ir <- ir_as_ir(x_hyperSpec)}# conversion from a Spectra object from class ChemoSpecif(requireNamespace("ChemoSpec")) { ## sample data x <- ir_sample_data x_flat <- ir_flatten(x) ## creation of the object of class "Spectra" (the ChemoSpec package does ## not contain a sample Spectra object) n <- nrow(x) group_vector <- seq(from = 1, to = n, by = 1) color_vector <- rep("black", times = n) x_Spectra <- list() # dummy list x_Spectra$freq <- as.numeric(x_flat[,1, drop = TRUE]) # wavenumber vector x_Spectra$data <- as.matrix(t(x_flat[,-1])) # absorbance values as matrix x_Spectra$names <- as.character(seq_len(nrow(x))) # sample names x_Spectra$groups <- as.factor(group_vector) # grouping vector x_Spectra$colors <- color_vector # colors used for groups in plots x_Spectra$sym <- as.numeric(group_vector) # symbols used for groups in plots x_Spectra$alt.sym <- letters[as.numeric(group_vector)] # letters used for groups in plots x_Spectra$unit <- c("wavenumbers", "intensity") # unit of x and y axes x_Spectra$desc <- "NULL" # optional descriptions in plots attr(x_Spectra, "class") <- "Spectra" # conversion to ir x_ir <- ir_as_ir(x_Spectra)}Averages infrared spectra within groups
Description
ir_average averages infrared spectra within a user-defined group.NAvalues are omitted by default.
Usage
ir_average(x, ..., na.rm = TRUE, .groups = "drop")Arguments
x | An object of class |
... | Variables in |
na.rm | A logical value indicating if |
.groups |
When
In addition, a message informs you of that choice, unless the result is ungrouped,the option "dplyr.summarise.inform" is set to |
Value
An object of classir where spectra have been averaged withingroups defined by....
Examples
# average the sample data spectra across sample typesx <- ir_sample_data |> ir_average(sample_type)Performs baseline correction on infrared spectra
Description
ir_bc performs baseline correction for infrared spectra. Baselinecorrection is either performed by using a polynomial with user defineddegree fitted to each spectrum (seeChemoSpec::baselineSpectra()), or byusing a rubberband function that is fitted to each spectrum (seehyperSpec::spc.rubberband()), or using a Savitzky-Golay smoothed version ofthe input spectra (seeir_bc_sg()).
Usage
ir_bc(x, method = "rubberband", return_bl = FALSE, ...)Arguments
x | An object of class |
method | A character value indicating which method should be usedfor baseline correction. If |
return_bl | A logical value indicating if for each spectrum the baselineshould be returned instead of the corrected intensity values( |
... | Further arguments passed to |
Value
An object of classir with the baseline corrected spectra, or ifreturn_bl = TRUE, the baselines instead of the spectra in columnspectra.
Examples
library(dplyr)# rubberband baseline correctionx1 <- ir::ir_sample_data |> dplyr::slice(1:10) |> ir::ir_bc(method = "rubberband")# polynomial baseline correctionif(!requireNamespace("ChemoSpec", quietly = TRUE)) { x2 <- ir::ir_sample_data |> dplyr::slice(1:10) |> ir::ir_bc(method = "polynomial", degree = 2)}# Savitzky-Golay baseline correctionif(!requireNamespace("signal", quietly = TRUE)) { x3 <- ir::ir_sample_data |> dplyr::slice(1:10) |> ir::ir_bc(method = "sg", p = 3, n = 199, ts = 1, m = 0)}# return the baseline instead of the baseline corrected spectrax1_bl <- ir::ir_sample_data |> dplyr::slice(1:10) |> ir::ir_bc(method = "rubberband", return_bl = TRUE)Performs baseline correction on infrared spectra using a polynomial
Description
ir_bc_polynomial performs baseline correction for infraredspectra using a polynomial.ir_bc_polynomial is an extended wrapper functionforChemoSpec::baselineSpectra().
Usage
ir_bc_polynomial(x, degree = 2, return_bl = FALSE, ...)Arguments
x | An object of class |
degree | An integer value representing the degree of the polynomialused for baseline correction. |
return_bl | A logical value indicating if for each spectrum the baselineshould be returned instead of the corrected intensity values( |
... | Ignored. |
Value
An object of classir with the baseline corrected spectra ifreturnbl = FALSE or the baselines ifreturnbl = TRUE.
See Also
Examples
if(! requireNamespace("ChemoSpec", quietly = TRUE)) { x2 <- ir::ir_sample_data |> ir::ir_bc_polynomial(degree = 2, return_bl = FALSE)}Performs baseline correction on infrared spectra using a rubberband algorithm
Description
ir_bc_rubberband performs baseline correction for infrared spectrausing a rubberband algorithm.ir_bc_rubberband is an extended wrapperfunction forhyperSpec::spc.rubberband().
Usage
ir_bc_rubberband(x, do_impute = FALSE, return_bl = FALSE, ...)Arguments
x | An object of class |
do_impute | A logical value indicating whether the in baseline the firstand last values should be imputed with the second first and second lastvalues, respectively ( |
return_bl | A logical value indicating if for each spectrum the baselineshould be returned instead of the corrected intensity values( |
... | Ignored. |
Value
An object of classir with the baseline corrected spectra and,ifreturnbl = TRUE, the baselines.
See Also
Examples
x1 <- ir::ir_sample_data |> ir::ir_bc_rubberband(return_bl = FALSE)Performs baseline correction on infrared spectra using a Savitzky-Golay baseline
Description
ir_bc_sg computes a smoothed version of spectra usingir_smooth() withmethod = "sg" and uses this as baselinewhich is subtracted from the spectra to perform a baseline correction(Lasch 2012).
Usage
ir_bc_sg(x, ..., return_bl = FALSE)Arguments
x | An object of class |
... | Arguments passed to |
return_bl | A logical value indicating if for each spectrum the baselineshould be returned instead of the corrected intensity values( |
Value
An object of classir with the baseline corrected spectra and,ifreturnbl = TRUE, the baselines.
References
Lasch P (2012).“Spectral Pre-Processing for Biomedical Vibrational Spectroscopy and Microspectroscopic Imaging.”Chemometrics and Intelligent Laboratory Systems,117, 100–114.ISSN 01697439,doi:10.1016/j.chemolab.2012.03.011.
Examples
if(! requireNamespace("signal", quietly = TRUE)) { x <- ir::ir_sample_data |> ir::ir_bc_sg(p = 3, n = 199, ts = 1, m = 0, return_bl = FALSE)}Bins infrared spectra
Description
ir_bin bins intensity values of infrared spectra into bins of adefined width or into a defined number of bins.
Usage
ir_bin(x, width = 10, new_x_type = "start", return_ir_flat = FALSE)Arguments
x | An object of class |
width | An integer value indicating the wavenumber width of eachresulting bin. |
new_x_type | A character value denoting how new wavenumber values forthe computed bins should be stored in the spectra of
|
return_ir_flat | Logical value. If |
Details
If a wavenumber value exactly matches the boundary of a bin window, therespective intensity value will be assigned to both neighboring bins.
Value
An object of classir (orir_flat, ifreturn_ir_flat = TRUE),where spectra have been binned.
Examples
# new wavenumber values are the first wavenumber value for each binx1 <- ir::ir_sample_data |> ir_bin(width = 50, new_x_type = "start")# new wavenumber values are the last wavenumber value for each binx2 <- ir::ir_sample_data |> ir_bin(width = 50, new_x_type = "mean")# new wavenumber values are the average of the wavenumber values assigned to# each binx3 <- ir::ir_sample_data |> ir_bin(width = 50, new_x_type = "end")# compare wavenumber values for first spectra.cbind(x1$spectra[[1]]$x, x2$spectra[[1]]$x, x3$spectra[[1]]$x)Clips infrared spectra to new wavenumber ranges
Description
ir_clip clips infrared spectra to a new, specified, wavenumber rangeor multiple new specified wavenumber ranges.
Usage
ir_clip(x, range, return_ir_flat = FALSE)Arguments
x | An object of class |
range | A
If |
return_ir_flat | Logical value. If |
Value
An object of classir (orir_flat, ifreturn_ir_flat = TRUE)where spectra have been clipped.
Examples
## clipping with one range# define clipping rangerange <- data.frame(start = 900, end = 1000)# clipx <- ir::ir_sample_data |> ir::ir_clip(range = range)## clipping with mutliple ranges# define clipping rangerange <- data.frame(start = c(900, 1900), end = c(1000, 2200))# clipx <- ir::ir_sample_data |> ir::ir_clip(range = range)Corrects artifacts in a spectrum based on reference spectra of the artifact compound
Description
ir_correct_atmosphere takes two objects of classir with the same numberof spectra in each and corrects the spectra of the first object with thespectra of the second object according to the procedure presented by(Perez-Guaita et al. 2013).
Usage
ir_correct_atmosphere( x, ref, wn1, wn2, return_contribution = FALSE, do_interpolate = FALSE, start = NULL, dw = 1, warn = TRUE, return_ir_flat = FALSE)Arguments
x | An object of class |
ref | An object of class |
wn1 | A numeric value representing the first wavenumber value to use asreference point (Perez-Guaita et al. 2013). Examples used byPerez-Guaita et al. (2013) are:
|
wn2 | A numeric value representing the second wavenumber value to use asreference point (Perez-Guaita et al. 2013). Examples used byPerez-Guaita et al. (2013) are:
|
return_contribution | A logical value indicating whether in addition tothe corrected spectra, the computed relative contribution of |
do_interpolate | A logical value indicating if |
start | See |
dw | See |
warn | A logical value indicating whether warnings about mismatchingwavenumber values should be displayed ( |
return_ir_flat | Logical value. If |
Value
x corrected with the reference spectra inref.
Source
There are no references for Rd macro\insertAllCites on this help page.
Examples
x1 <- ir_correct_atmosphere( ir_sample_data[1:5, ], ir_sample_data[1:5, ], wn1 = 2361, wn2 = 2349 )x2 <- ir_correct_atmosphere( ir_sample_data[1:5, ], ir_sample_data[1:5, ], wn1 = 2361, wn2 = 2349, return_contribution = TRUE )x2$contributionDivide infrared spectra or divide infrared spectra by a numeric value
Description
ir_divide takes two objects of classir,x andy, and divides their intensity values, or it takes one object ofclassir,x, and one numeric value,y, and dividesall intensity values inx byy.
Usage
ir_divide(x, y)Arguments
x | An object of class |
y | An object of class |
Value
x where for each spectrum intensity values are divided bythe respective intensity values iny (ify is an object ofclassir), or where all intensity values are divided byy ify is a numeric value.
Examples
# division with y as ir objectx1 <- ir::ir_divide(ir::ir_sample_data, ir::ir_sample_data)x2 <- ir::ir_divide(ir::ir_sample_data, ir::ir_sample_data[1, ])# division with y being a numeric valuex3 <- ir::ir_divide(ir::ir_sample_data, y = 20)# division with y being a numeric vectorx4 <- ir::ir_divide( ir::ir_sample_data, seq(from = 0.1, to = 2, length.out = nrow(ir::ir_sample_data)) )Drops the columnspectra from an object is of classir
Description
ir_drop_spectra removes the columnspectra from an objectof classir and removes the"ir" class attribute.
Usage
ir_drop_spectra(x)Arguments
x | An object of class |
Value
x without columnspectra and without"ir" classattribute.
Examples
ir::ir_sample_data |> ir_drop_spectra()Preparesir objects for export tocsv
Description
Preparesir objects for export tocsv files. To exportir objects tocsv, thespectra column has to be converted to an own data frame and beexported separately from the metadata.When preparing metadata for export,ir_export_prepare takes care ofseparating measurement units and measurement errors in columns of classunits::units,errors::errors, andquantities::quantities (see theexamples).
Usage
ir_export_prepare( x, what = "metadata", measurement_id = as.character(seq_len(nrow(x))))Arguments
x | An object of class |
what | A character value defining what to prepare for export.If |
measurement_id | A character vector an element for each row in |
Value
A data frame.
Note
This function supersededirp_export_prepare() from the'irpeat' package.
Examples
x_spectra <- ir_export_prepare(ir_sample_data[1:5, ], what = "spectra")x_metadata <- ir_export_prepare(ir_sample_data[1:5, ], what = "metadata")Cleans objects of classir_flat
Description
ir_flatten_clean takes an object of classir_flat and eitherreturns all non-empty spectra or all empty spectra as object of classir_flat.
Usage
ir_flat_clean(x, return_empty = FALSE)Arguments
x | An object of class |
return_empty | A logical value indicating if the empty spectra should bereturned ( |
Value
x where empty spectra are dropped (ifreturn_empty = TRUE) oronly empty spectra are returned (return_empty = FALSE).
Converts objects of classir to objects of classir_flat
Description
ir_flatten takes and object of classir, extracts thespectra column and combines the spectra into an object of classir_flat. Metadata are not retained during flattening.
Usage
ir_flatten(x, measurement_id = as.character(seq_len(nrow(x))))Arguments
x | An object of class |
measurement_id | A character vector an element for each row in |
Value
An object of classir_flat.
Examples
x_flat <- ir::ir_sample_data |> ir::ir_flatten()Extracts intensities from spectra in anir object for specific spectral channels
Description
ir_get_intensity extracts intensity values of spectra for specificuser-defined spectral channels ("x axis values", e.g. wavenumber values).
Usage
ir_get_intensity(x, wavenumber, warn = TRUE)Arguments
x | An object of class |
wavenumber | A numeric vector with spectral channels ("x axis values",e.g. wavenumber values) for which to extract intensities. |
warn | logical value indicating if warnings should be displayed( |
Value
x with an additional columnintensity.x$intensity is a list column with each element representing adata.frame with a row for each element inwavenumber and twocolumns:
- x
The "x axis values" extracted with
ir_get_wavenumberindex()applied onwavenumberand thecorresponding spectrum inx.- y
The extracted intensity values
.
Examples
x <- ir::ir_sample_data |> ir::ir_get_intensity(wavenumber = 1090)Extracts selected spectra from an object of classir
Description
ir_get_spectrum extracts selected spectra from an object of classir.
Usage
ir_get_spectrum(x, what)Arguments
x | An object of class |
what | A numeric vector with each element representing a row in |
Value
An integer vector with the same length aswavenumber with therow indices ofx corresponding to the wavenumber values inwavenumber.
Examples
x <- ir::ir_sample_data |> ir::ir_get_spectrum(what = c(5, 9))Gets the index of a defined wavenumber value for a spectrum
Description
ir_get_wavenumberindex gets for a defined wavenumber value or set ofwavenumber values the corresponding indices (row number) in an object ofclassir that has been flattened withir_flatten(). If thespecified wavenumber values do not match exactly the wavenumber values in their object, the indices for the next wavenumber values will bereturned, along with a warning.
Usage
ir_get_wavenumberindex(x, wavenumber, warn = TRUE)Arguments
x | A data.frame with a column x representing the x units of a spectrumor several spectra (e.g. in the form of an object of class |
wavenumber | A numeric vector with wavenumber values for which to getindices. |
warn | logical value indicating if warnings should be displayed( |
Value
An integer vector with the same length aswavenumber with therow indices ofx corresponding to the wavenumber values inwavenumber.
Examples
x_index_1090 <- ir::ir_sample_data |> ir::ir_flatten() |> ir::ir_get_wavenumberindex(wavenumber = 1090)Identifies empty spectra in anir object
Description
ir_identify_empty_spectra() identifies empty spectra in an object of classir. An empty spectrum is a spectrum which has no data values(no rows) or where all intensity values (columny) areNA.
Usage
ir_identify_empty_spectra(x)Arguments
x | An object of class |
Value
A logical vector indicating for each spectrum inx whether it isempty (TRUE) or not (FALSE).
Examples
ir_identify_empty_spectra(ir::ir_sample_data)Imports infrared spectra from various files
Description
ir_import_csv imports raw infrared spectra from one or more.csv filethat contains at least one spectrum, with x axis values (e.g. wavenumbers) inthe first column and intensity values of spectra in remaining columns. Notethat the function does not perform any checks for the validity of the contentread from the .csv file.
Usage
ir_import_csv(filenames, sample_id = "from_filenames", ...)Arguments
filenames | A character vector representing the complete paths tothe |
sample_id | Either:
|
... | Further arguments passed to |
Value
An object of classir containing theinfrared spectra extracted from the.csv file(s).
Examples
# import data from csv filesd <- ir::ir_import_csv( system.file(package = "ir", "extdata/klh_hodgkins_mir.csv"), sample_id = "from_colnames" )Imports infrared spectra from Thermo Galactic's files
Description
ir_import_spc imports raw infrared spectra from a Thermo Galactic's.spc file or several of such files.ir_import_spc is a wrapperfunction tohyperSpec::read.spc().
Usage
ir_import_spc(filenames, log.txt = TRUE)Arguments
filenames | A character vector representing the complete paths tothe |
log.txt | A logical value indicating whether to import metadata ( |
Details
Currently,log.txt must be set toFALSE due to a bug inhyperSpec::read.spc(). This bug fill be fixed in the upcoming weeks andcurrently can be circumvented by using the development version of 'hyperSpec'.See https://github.com/r-hyperspec/hyperSpec/issues/80.
Value
An object of classir containing theinfrared spectra extracted from the.spc file(s) and the metadata asextracted byhyperSpec::read.spc(). Metadata variables are:
- scan_number
An integer value representing the number of scans.
- detection_gain_factor
The detection gain factor.
- scan_speed
The scan speed [kHz].
- laser_wavenumber
The wavenumber of the laser.
- detector_name
The name of the detector.
- source_name
The name of the infrared radiation source.
- purge_delay
The duration of purge delay before a measurement [s].
- zero_filling_factor
A numeric value representing the zero fillingfactor.
- apodisation_function
The name of the apodisation function.
- exponentiation_factor
The exponentiation factor used for filecompression.
- data_point_number
The number of data points in the spectrum
- x_variable_type
The type of the x variable.
- y_variable_type
The type of the y variable.
- measurement_date
A POSIXct representing the measurement date andtime.
- measurement_device
The name of the measurement device.
Examples
# import a sample .spc filex <- ir::ir_import_spc( system.file("extdata/1.spc", package = "ir"), log.txt = FALSE )Interpolates intensity values of infrared spectra in anir object for new wavenumber values
Description
ir_interpolate interpolates intensity values for infrared spectra fornew wavenumber values.
Usage
ir_interpolate(x, start = NULL, dw = 1, return_ir_flat = FALSE)Arguments
x | An object of class |
start | A numerical value indicating the start wavenumber value relativeto which new wavenumber values will be interpolated. The value is not allowedto be < |
dw | A numerical value representing the desired wavenumber valuedifference between adjacent values. |
return_ir_flat | Logical value. If |
Value
An object of classir (orir_flat, ifreturn_ir_flat = TRUE),containing the interpolated spectra. AnyNA values resulting frominterpolation will be automatically dropped.
Examples
x <- ir::ir_sample_data |> ir::ir_interpolate(start = NULL, dw = 1)Interpolates selected regions in infrared spectra in anir object
Description
ir_interpolate_region linearly interpolates a user-defined region ininfrared spectra.
Usage
ir_interpolate_region(x, range)Arguments
x | An object of class |
range | A
For each row in |
Value
x with the defined wavenumber region(s) interpolated linearly.
Examples
# interpolation rangerange <- data.frame(start = 1000, end = 1500)# do the interpolationx <- ir::ir_sample_data |> ir::ir_interpolate_region(range = range)Multiply infrared spectra or multiply infrared spectra with a numeric value
Description
ir_multiply takes two objects of classir,x andy, and multiplies their intensity values, or it takes one object ofclassir,x, and one numeric value,y, and multipliesall intensity values inx withy.
Usage
ir_multiply(x, y)Arguments
x | An object of class |
y | An object of class |
Value
x where for each spectrum intensity values are multiplied withthe respective intensity values iny (ify is an object ofclassir), or where all intensity values are multiplied withyify is a numeric value.
Examples
# multiplication with y as ir objectx1 <- ir::ir_multiply(ir::ir_sample_data, ir::ir_sample_data)x2 <- ir::ir_multiply(ir::ir_sample_data, ir::ir_sample_data[1, ])# multiplication with y being a numeric valuex3 <- ir::ir_multiply(ir::ir_sample_data, y = -1)# multiplication with y being a numeric vectorx4 <- ir::ir_multiply( ir::ir_sample_data, seq(from = 0, to = 2, length.out = nrow(ir::ir_sample_data)) )Creates an object of classir
Description
ir_new_ir is the constructor function for objects of classir.An object of classir is atibble::tbl_df() with asample in each row and a list column containing spectra for each sample.
Usage
ir_new_ir(spectra, metadata = tibble::tibble())Arguments
spectra | A named list in which each element contains spectral datafor one measurement. Each list element must be a |
metadata | An optional |
Value
An object of classir with the following columns:
- spectra
A list column identical to
spectra.- ...
Additional columns contained in
metadata.
Examples
ir_new_ir( spectra = ir_sample_data$spectra, metadata = ir_sample_data |> dplyr::select(-spectra))Creates an object of classir_flat
Description
ir_new_ir_flat is the constructor function for objects of classir_flat.An object of classir_flat is adata.frame where the firstcolumn ("x") contains unique x values of spectra (e.g. wavenumbers)and all remaining columns represent intensity values from spectracorresponding to the x values.
Usage
ir_new_ir_flat(x)Arguments
x | A |
Value
An object of classir_flat.
Examples
x_flat <- ir::ir_sample_data |> ir::ir_flatten()Normalizes infrared spectra in anir object
Description
ir_normalize normalizes the intensity values of infrared spectra. Differentmethods for normalization are available.
Usage
ir_normalize(x, method = "area")ir_normalise(x, method = "area")Arguments
x | An object of class |
method | A character value specifying which normalization method toapply:
|
Value
An object of classir representing a normalized version ofx.
Examples
# with method = "area"x1 <- ir::ir_sample_data |> ir::ir_normalize(method = "area")# second derivative spectrum with method = "area" or method = "area_absolute"x2 <- ir::ir_sample_data |> ir::ir_smooth(method = "sg", n = 31, m = 2) |> ir::ir_normalize(method = "area")x3 <- ir::ir_sample_data |> ir::ir_smooth(method = "sg", n = 31, m = 2) |> ir::ir_normalize(method = "area_absolute")# with method = "zeroone"x4 <- ir::ir_sample_data |> ir::ir_normalize(method = "zeroone")# with method = "vector"x5 <- ir::ir_sample_data |> ir::ir_normalize(method = "vector")# with method = "snv"x6 <- ir::ir_sample_data |> ir::ir_normalize(method = "snv")# normalizing to a specific peakx7 <- ir::ir_sample_data |> ir::ir_normalize(method = 1090)Removes empty data values in an object of classir
Description
ir_remove_missing takes and object of classir and removes allrows in thedata.frames of the list columnspectra that haveNA intensity values (columny). Additionally, one can specifyto remove rows in their object to discard if they contain emptyspectra.
Usage
ir_remove_missing(x, remove_rows = FALSE)Arguments
x | An object of class |
remove_rows | A logical value indicating if rows in |
Value
x with cleaned spectra.
Examples
# create sample data with some missing rows and one entire missing spectrax <- ir::ir_sample_datax$spectra[[1]] <- x$spectra[[1]][0, ]x$spectra[[2]][1:100, "y"] <- NA_real_# remove missing values (but remove no rows in x)x1 <- x |> ir::ir_remove_missing(remove_rows = FALSE)# remove missing values (and remove rows in x if a compete spectrum is# missing)x2 <- x |> ir::ir_remove_missing(remove_rows = TRUE)nrow(x)nrow(x1)nrow(x2)Sample object of classir
Description
A sample object of classir. The data setcontains ATR-MIR spectra for a set of organic reference materialsalong with their metadata (types of samples and a description) andaccessory data (Klason lignin mass fraction and holocellulose mass fraction).
Usage
ir_sample_dataFormat
A data frame with 58 rows and 7 variables:
- id_measurement
An integer vector with a unique id for eachspectrum.
- id_sample
A character vector with a unique id for each sample.
- sample_type
A character vector containing class labelsfor the types of reference materials.
- sample_comment
A character vector containing comments toeach sample.
- klason_lignin
A numeric vector with the mass fractions ofKlason lignin in each sample.
- holocellulose
A numeric vector with the mass fractions ofholocellulose in each sample.
- spectra
See
ir_new_ir().
Source
The data set was derived fromhttps://www.nature.com/articles/s41467-018-06050-2and published by Hodgkins et al. (2018) under the CC BY 4.0 licensehttps://creativecommons.org/licenses/by/4.0/.Hodgkins et al. (2018) originally derived the data on Klason Lignin and Holocellulose content fromDe la Cruz et al. (2016).
References
De la Cruz FB, Osborne J, Barlaz MA (2016).“Determination of Sources of Organic Matter in Solid Waste by Analysis of Phenolic Copper Oxide Oxidation Products of Lignin.”Journal of Environmental Engineering,142(2), 04015076.ISSN 0733-9372, 1943-7870,doi:10.1061/(ASCE)EE.1943-7870.0001038.
Hodgkins SB, Richardson CJ, Dommain R, Wang H, Glaser PH, Verbeke B, Winkler BR, Cobb AR, Rich VI, Missilmani M, Flanagan N, Ho M, Hoyt AM, Harvey CF, Vining SR, Hough MA, Moore TR, Richard PJH, De La Cruz FB, Toufaily J, Hamdan R, Cooper WT, Chanton JP (2018).“Tropical Peatland Carbon Storage Linked to Global Latitudinal Trends in Peat Recalcitrance.”Nature Communications,9(1), 3640.ISSN 2041-1723,doi:10.1038/s41467-018-06050-2.
Wrapper to sampling functions from the 'prospectr' package
Description
Wrapper functions that allows to directly use 'ir' objects with samplingfunctions from the 'prospectr' package.
Usage
ir_sample_prospectr(x, sampling_function, ..., return_prospectr_output = FALSE)Arguments
x | An object of class 'ir' containing the spectra based on whichto sample measurements. |
sampling_function | A function from the 'prospectr' package to performsampling based on spectra ( |
... | Arguments passed to |
return_prospectr_output | Logical value. If |
Value
Ifreturn_prospectr_output = TRUE, the output ofsampling_function. Seethe 'prospectr' package for details. Ifreturn_prospectr_output = FALSE,xwith the following additional columns:
- for_prospectr_model
Logical value indicating whether the spectrum islisted in element
modelof the prospectr output (TRUE) or not(FALSE).- for_prospectr_test
Logical value indicating whether the spectrum islisted in element
testof the prospectr output (TRUE) or not(FALSE).- prospectr_model
Integer representing the order in which spectra arelisted in element
modelof the prospectr output.- prospectr_test
Integer representing the order in which spectra arelisted in element
testof the prospectr output.
Examples
if(requireNamespace("prospectr", quietly = TRUE)) { x <- ir_sample_prospectr( ir::ir_sample_data, prospectr::kenStone, metric = "euclid", k = 30, return_prospectr_output = FALSE ) x <- ir_sample_prospectr( ir::ir_sample_data, prospectr::kenStone, metric = "euclid", k = 30, return_prospectr_output = TRUE )}Scales spectra in anir object
Description
Scales spectra in anir object
Usage
ir_scale(x, center = TRUE, scale = TRUE, return_ir_flat = FALSE)Arguments
x | An object of class |
center | either a logical value or numeric-alike vector of lengthequal to the number of columns of |
scale | either a logical value or a numeric-alike vector of lengthequal to the number of columns of |
return_ir_flat | Logical value. If |
Value
x where spectra have been scaled, i.e. from each intensity value,the average across all spectra is subtracted (whencenter is a logicalvalue), or the respective value incenter is subtracted (whencenter isnumerical), and each intensity value is divided by the standard deviation ofthe intensity values at this wavenumber across all spectra (whenscale is alogical value), or the respective value inscale (whenscale isnumerical).NAs are omitted during this process.
Examples
ir_sample_data |> ir_scale() |> plot()Smooths infrared spectra in anir object
Description
ir_smooth applies smoothing functions to infrared spectra.ir_smooth either performs Savitzky-Golay smoothing, using onsignal::sgolayfilt(), or Fourier smoothing usingfda::smooth.basis(). Savitzky-Golay smoothing canalso be used to compute derivatives of spectra.
Usage
ir_smooth( x, method = "sg", p = 3, n = p + 3 - p%%2, ts = 1, m = 0, k = 111, ...)Arguments
x | An object of class |
method | A character value specifying which smoothing method to apply.If |
p | An integer value representing the filter order (i.e. the degree ofthe polynom) of the Savitzky-Golay filter if |
n | An odd integer value representing the length (i.e. the number ofwavenumber values used to construct the polynom) of the Savitzky-Golay filterif |
ts | time scaling factor. See |
m | An integer value representing the mth derivative to compute. Thisoption can be used to compute derivatives of spectra. See |
k | A positive odd integer representing the number of Fourier basisfunctions to use as smoothed representation of the spectra if |
... | additional arguments (ignored). |
Details
Whenx contains spectra with different wavenumber values, thefilters are applied for each spectra only on existing wavenumber values. Thismeans that the filter window (ifmethod == "sg") will be different forthese different spectra.
Value
x with smoothed spectra.
Examples
#' # Savitzky-Golay smoothingif(! requireNamespace("signal", quietly = TRUE)) { x1 <- ir::ir_sample_data[1:5, ] |> ir::ir_smooth(method = "sg", p = 3, n = 51, ts = 1, m = 0)}# Fourier smoothingif(! requireNamespace("fda", quietly = TRUE)) { x2 <- ir::ir_sample_data[1:5, ] |> ir::ir_smooth(method = "fourier", k = 21)}# computing derivative spectra with Savitzky-Golay smoothing (here: first# derivative)if(! requireNamespace("signal", quietly = TRUE)) { x3 <- ir::ir_sample_data[1:5, ] |> ir::ir_smooth(method = "sg", p = 3, n = 51, ts = 1, m = 1)}Stacks a matrix or data frame with spectra into a list column
Description
ir_stack takes a matrix or data frame with infrared spectra andconverts it into a list column corresponding to the columnspectra inobjects of classir.
Usage
ir_stack(x)Arguments
x | A matrix or data frame with a first column ( |
Value
Atibble::tibble() with the stacked spectra in columnspectra.
Examples
# from data framex1 <- ir::ir_sample_data |> ir::ir_flatten() |> ir::ir_stack()# from matrixx2 <- ir::ir_sample_data |> ir::ir_flatten() |> as.matrix() |> ir::ir_stack()Subtract infrared spectra
Description
ir_subtract takes two objects of classir,x andy, and subtracts the intensity values of spectra in matching rows fromy from that ofx. Alternatively, takes an object of classir,x, and a numeric value,y, and subtractsyfrom all intensity values inx.
Usage
ir_subtract(x, y)Arguments
x | An object of class |
y | An object of class |
Value
x where for each spectrum the respective intensity values iny are subtracted (ify is an object of classir), orwhere for each spectrumy has been subtracted from the intensityvalues.
Examples
# subtracting two objects of class irx1 <- ir::ir_subtract(ir::ir_sample_data, ir::ir_sample_data)x2 <- ir::ir_subtract(ir::ir_sample_data, ir::ir_sample_data[1, ])# subtracting a numeric value from an object of class `ir`.x3 <- ir::ir_subtract(ir::ir_sample_data, 20)# subtracting a numeric vector from an object of class `ir`.x4 <- ir::ir_subtract( ir::ir_sample_data, seq(from = 0, to = 2, length.out = nrow(ir::ir_sample_data)) )Converts absorbance spectra to transmittance spectra or vice versa
Description
ir_to_transmittance converts absorbance spectra to transmittancespectra.ir_to_absorbance converts transmittance spectra to absorbancespectra. Note that neither function checks whether the input spectra areabsorbance or transmittance spectra.
Usage
ir_to_transmittance(x)ir_to_absorbance(x)Arguments
x | An object of class |
Value
x with y values fore each spectrum as transmittance values(in case ofir_to_transmittance) or absorbance values (in case ofir_to_absorbance).
Source
(Stuart 2004).
References
Stuart BH (2004).Infrared Spectroscopy: Fundamentals and Applications, Analytical Techniques in the Sciences.John Wiley and Sons, Ltd, Chichester, UK.ISBN 978-0-470-01114-0 978-0-470-85428-0,doi:10.1002/0470011149.
Examples
# convert from absorbance to transmittancex1 <- ir_sample_data |> ir_to_transmittance()# convert from transmittance to absorbancex2 <- x1 |> ir::ir_to_absorbance()vapply( seq_along(x2$spectra), FUN = function(i) all.equal(x2$spectra[[i]], ir::ir_sample_data$spectra[[i]]), FUN.VALUE = logical(1L)) |> all()Computes the variance of a spectrum in anir object in a given region
Description
ir_variance_region takes a spectrumx and, depending on thearguments computes the following summary:
- if
subtract_smoothed = FALSE it computes the variance of theintensity values for each spectrum in
x. If in additionrangeis notNULL, it computes the variance only for the region(s)represented byrange.- if
subtract_smoothed = TRUE it smoothes
x, subtractsthe smoothedxfrom the unsmoothedxand computes thevariance of the difference intensity values. If in additionrangeisnotNULL, it computes the variance only for the region(s)represented byrange.
Usage
ir_variance_region( x, subtract_smoothed = FALSE, do_normalize = FALSE, normalize_method, ..., range = NULL)Arguments
x | An object of class |
subtract_smoothed | A logical value. If |
do_normalize | A logical value. If set to |
normalize_method | See |
... | Arguments passed to |
range | See |
Value
x with two additional columns:
- variance
A numeric vector with the computed variances of theintensity values for the respective spectra.
- n_variance
An integer vector with the number of intensity valuesused during computing the variance.
Examples
# Whole spectra variancex1 <- ir::ir_sample_data |> ir::ir_variance_region( subtract_smoothed = FALSE, do_normalize = TRUE, normalize_method = "area", range = NULL )# Spectra variance, but only from a specific regionrange <- data.frame(start = 2700, end = 2800)x2 <- ir::ir_sample_data |> ir::ir_normalize(method = "area") |> ir::ir_variance_region( subtract_smoothed = FALSE, do_normalize = TRUE, normalize_method = "area", range = range )# Spectra variance after subtracting a smoothed version of the spectra and# only from a specific regionx3 <- ir::ir_sample_data %>% ir::ir_variance_region( subtract_smoothed = TRUE, do_normalize = FALSE, range = range, p = 3, n = 31, ts = 1, m = 0 )Mutate anir object by adding new or replacing existing columns
Description
Mutate anir object by adding new or replacing existing columns
Usage
mutate.ir( .data, ..., .keep = c("all", "used", "unused", "none"), .before = NULL, .after = NULL)transmute.ir(.data, ...)Arguments
.data | An object of class |
... | < The value can be:
|
.keep | Control which columns from
|
.before,.after | < |
Value
.data with modified columns. If thespectra column is dropped orinvalidated (seeir_new_ir()), their class is dropped, else the objectis of classir.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## mutatedplyr::mutate(ir_sample_data, hkl = klason_lignin + holocellulose)## transmutedplyr::transmute(ir_sample_data, hkl = klason_lignin + holocellulose)Mutating joins for anir object
Description
Mutating joins for anir object
Usage
inner_join.ir( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = FALSE, na_matches = c("na", "never"))left_join.ir( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = FALSE, na_matches = c("na", "never"))right_join.ir( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = FALSE, na_matches = c("na", "never"))full_join.ir( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = FALSE, na_matches = c("na", "never"))Arguments
x | An object of class |
y | A data frame. |
by | A join specification created with If To join on different variables between To join by multiple variables, use a
For simple equality joins, you can alternatively specify a character vectorof variable names to join by. For example, To perform a cross-join, generating all combinations of |
copy | If |
suffix | If there are non-joined duplicate variables in |
... | Other parameters passed onto methods. |
keep | Should the join keys from both
|
na_matches | Should two |
Value
x andy joined. If thespectra column is renamed, theirclass is dropped. Seemutate-joins.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## inner_joinset.seed(234)dplyr::inner_join( ir_sample_data, tibble::tibble( id_measurement = c(1:5, 101:105), nitrogen_content = rbeta(n = 10, 0.2, 0.1) ), by = "id_measurement")## left_joinset.seed(234)dplyr::left_join( ir_sample_data, tibble::tibble( id_measurement = c(1:5, 101:105), nitrogen_content = rbeta(n = 10, 0.2, 0.1) ), by = "id_measurement")## right_joinset.seed(234)dplyr::right_join( ir_sample_data, tibble::tibble( id_measurement = c(1:5, 101:105), nitrogen_content = rbeta(n = 10, 0.2, 0.1) ), by = "id_measurement")## full_joinset.seed(234)dplyr::full_join( ir_sample_data, tibble::tibble( id_measurement = c(1:5, 101:105), nitrogen_content = rbeta(n = 10, 0.2, 0.1) ), by = "id_measurement")Nest and un-nest anir object
Description
Nest and un-nest anir object
Usage
nest.ir(.data, ..., .names_sep = NULL, .key = deprecated())unnest.ir( data, cols, ..., keep_empty = FALSE, ptype = NULL, names_sep = NULL, names_repair = "check_unique", .drop = deprecated(), .id = deprecated(), .sep = deprecated(), .preserve = deprecated())Arguments
.data | An object of class |
... | < Specified using name-variable pairs of the form If not supplied, then
|
.key | The name of the resulting nested column. Only applicable when If |
data | A data frame. |
cols | < When selecting multiple columns, values from the same row will be recycledto their common size. |
keep_empty | By default, you get one row of output for each elementof the list that you are unchopping/unnesting. This means that if there's asize-0 element (like |
ptype | Optionally, a named list of column name-prototype pairs tocoerce |
names_sep,.names_sep | If If a string, the inner and outer names will be used together. In |
names_repair | Used to check that output data frame has validnames. Must be one of the following options:
See |
.drop,.preserve |
|
.id |
|
.sep |
Value
.data with nested or unnested columns. If thespectra column isdropped or invalidated (seeir_new_ir()), their class is dropped, elsethe object is of classir.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## nestir_sample_data |> tidyr::nest( contents = c(holocellulose, klason_lignin) )## unnestir_sample_data |> tidyr::nest( contents = c(holocellulose, klason_lignin) ) |> tidyr::unnest("contents")Pivot anir object from wide to long
Description
Pivot anir object from wide to long
Usage
pivot_longer.ir( data, cols, names_to = "name", names_prefix = NULL, names_sep = NULL, names_pattern = NULL, names_ptypes = list(), names_transform = list(), names_repair = "check_unique", values_to = "value", values_drop_na = FALSE, values_ptypes = list(), values_transform = list(), ...)Arguments
data | An object of class |
cols | < |
names_to | A character vector specifying the new column or columns tocreate from the information stored in the column names of
|
names_prefix | A regular expression used to remove matching textfrom the start of each variable name. |
names_sep,names_pattern | If
If these arguments do not give you enough control, use |
names_ptypes,values_ptypes | Optionally, a list of column name-prototypepairs. Alternatively, a single empty prototype can be supplied, which willbe applied to all columns. A prototype (or ptype for short) is azero-length vector (like |
names_transform,values_transform | Optionally, a list of columnname-function pairs. Alternatively, a single function can be supplied,which will be applied to all columns. Use these arguments if you need tochange the types of specific columns. For example, If not specified, the type of the columns generated from |
names_repair | What happens if the output has invalid column names?The default, |
values_to | A string specifying the name of the column to createfrom the data stored in cell values. If |
values_drop_na | If |
... | Additional arguments passed on to methods. |
Value
data in a long format. If thespectra column is droppedor invalidated (seeir_new_ir()), their class is dropped, else theobject is of classir.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## pivot_longerir_sample_data |> tidyr::pivot_longer( cols = dplyr::any_of(c("holocellulose", "klason_lignin")) )Pivot anir object from wide to long
Description
Pivot anir object from wide to long
Usage
pivot_wider.ir( data, id_cols = NULL, names_from = "name", names_prefix = "", names_sep = "_", names_glue = NULL, names_sort = FALSE, names_repair = "check_unique", values_from = "value", values_fill = NULL, values_fn = NULL, ...)Arguments
data | An object of class |
id_cols | < Defaults to all columns in |
names_from,values_from | < If |
names_prefix | String added to the start of every variable name. This isparticularly useful if |
names_sep | If |
names_glue | Instead of |
names_sort | Should the column names be sorted? If |
names_repair | What happens if the output has invalid column names?The default, |
values_fill | Optionally, a (scalar) value that specifies what each This can be a named list if you want to apply different fill values todifferent value columns. |
values_fn | Optionally, a function applied to the value in each cellin the output. You will typically use this when the combination of This can be a named list if you want to apply different aggregationsto different |
... | Additional arguments passed on to methods. |
Value
data in a wide format. If thespectra column is droppedor invalidated (seeir_new_ir()), their class is dropped, else theobject is of classir.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## pivot_widerir_sample_data |> tidyr::pivot_longer( cols = dplyr::any_of(c("holocellulose", "klason_lignin")) ) |> tidyr::pivot_wider(names_from = "name", values_from = "value")Plots an object of classir
Description
plot.ir is the plot method for objects of classir.
Usage
## S3 method for class 'ir'plot(x, ...)Arguments
x | An object of class |
... | Further arguments, will be ignored. |
Value
An object of classggplot2.
Examples
# simple plottingplot(ir::ir_sample_data[1:2, ])# advanced functionsplot(ir::ir_sample_data) + ggplot2::facet_wrap(~ sample_type)Get the minima/maxima/range/median of x axis values or intensity values of infrared spectra
Description
range.ir extracts the range of x axis values (e.g. wavenumbers) orintensity values of infrared spectra.
min.ir extracts the minimum x axis value (e.g. wavenumber) orintensity value of infrared spectra.
max.ir extracts the maximum x axis value (e.g. wavenumber) orintensity value of infrared spectra.
median.ir extracts the median x axis value (e.g. wavenumber) orintensity value of infrared spectra.
Usage
## S3 method for class 'ir'range( x, ..., na.rm = FALSE, .dimension = "y", .col_names = c("y_min", "y_max"))## S3 method for class 'ir'min(x, ..., na.rm = FALSE, .dimension = "y", .col_name = "y_min")## S3 method for class 'ir'max(x, ..., na.rm = FALSE, .dimension = "y", .col_name = "y_max")## S3 method for class 'ir'median(x, na.rm = FALSE, ..., .dimension = "y", .col_name = "y_median")Arguments
x | An object of class |
... | Further arguments, ignored. |
na.rm | A logical value. See |
.dimension | A character value. Must be one of the following:
|
.col_names | A character vector of length 2 representing the names of thecolumns in which to store the extracted values. The first element is the namefor the column with minima values, the second the name for the column withmaxima values. |
.col_name | A character value representing the name of the column inwhich to store the extracted values. |
Value
x with the extracted values.
Examples
# range of intensity valuesx1 <- ir::ir_sample_data |> range(.dimension = "y")# minimum intensity valuesx1 <- ir::ir_sample_data |> min(.dimension = "y")# maximum intensity valuesx1 <- ir::ir_sample_data |> max(.dimension = "y")# median intensity valuesx1 <- ir::ir_sample_data |> stats::median(.dimension = "y")Rename columns inir objects
Description
Rename columns inir objects
Usage
rename.ir(.data, ...)rename_with.ir(.data, .fn, .cols = dplyr::everything(), ...)Arguments
.data | An object of class |
... | For For |
.fn | A function used to transform the selected |
.cols | < |
Value
.data with renamed columns. If thespectra column is renamed,and no new validspectra column is created, their class is dropped, elsethe object is of classir.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## renamedplyr::rename(ir_sample_data, hol = "holocellulose")dplyr::rename(ir_sample_data, spec = "spectra") # drops ir class## rename_withdplyr::rename_with(ir_sample_data, .cols = dplyr::starts_with("id_"), toupper)dplyr::rename_with(ir_sample_data, toupper) # drops ir classReplicate ir objects
Description
rep.ir is the replicate method forir objects.Replicating andir object means to replicate its rows and bind thesetogether to a largerir object.
Usage
## S3 method for class 'ir'rep(x, ...)Arguments
x | An object of class |
... | See |
Value
An object of classir with replicated spectra.
Examples
# replicate the sample datax <- rep(ir::ir_sample_data, times = 2)x <- rep(ir::ir_sample_data, each = 2)x <- rep(ir::ir_sample_data, length.out = 3)Group inputir objects by rows
Description
Group inputir objects by rows
Usage
rowwise.ir(.data, ...)Arguments
.data | Input data frame. |
... | < NB: unlike |
data | An object of class |
Value
data as row-wise data frame. Seedplyr::rowwise().
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,select.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## rowwisedplyr::rowwise(ir_sample_data) |> dplyr::mutate( hkl = mean( units::drop_units(klason_lignin), units::drop_units(holocellulose) ) )Subset columns inir objects using column names and types
Description
Subset columns inir objects using column names and types
Usage
select.ir(.data, ...)Arguments
.data | An object of class |
... | < |
Value
.data with the selected columns. If thespectra column is dropped,their class is dropped, else the object is of classir.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),separate.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## selectdplyr::select(ir_sample_data, spectra)dplyr::select(ir_sample_data, holocellulose) # drops ir classSeparate a character column in anir object into multiple columns with a regular expression or numeric locations
Description
Separate a character column in anir object into multiple columns with a regular expression or numeric locations
Usage
separate.ir( data, col, into, sep = "[^[:alnum:]]+", remove = TRUE, convert = FALSE, extra = "warn", fill = "warn", ...)Arguments
data | An object of class |
col | < |
into | Names of new variables to create as character vector.Use |
sep | Separator between columns. If character, If numeric, |
remove | If |
convert | If NB: this will cause string |
extra | If
|
fill | If
|
... | Additional arguments passed on to methods. |
Value
.data with separated columns. If thespectra column isdropped or invalidated (seeir_new_ir()), their class is dropped, elsethe object is of classir.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate_rows.ir(),slice,summarize,unite.ir()
Examples
## separateir_sample_data |> tidyr::separate( col = "id_sample", c("a", "b", "c") )Separate a collapsed column in anir object into multiple rows
Description
Separate a collapsed column in anir object into multiple rows
Usage
separate_rows.ir(data, ..., sep = "[^[:alnum:].]+", convert = FALSE)Arguments
data | An object of class |
... | < |
sep | Separator delimiting collapsed values. |
convert | If |
Value
data with a collapsed column separated into multiple rows. Seetidyr::separate_rows().
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),slice,summarize,unite.ir()
Examples
## separate_rowsir_sample_data |> tidyr::unite( col = content, holocellulose, klason_lignin ) |> tidyr::separate_rows( col )Subset rows inir objects using their positions
Description
Subset rows inir objects using their positions
Usage
slice.ir(.data, ..., .preserve = FALSE)slice_sample.ir(.data, ..., n, prop, weight_by = NULL, replace = FALSE)Arguments
.data | An object of class |
... | For Provide either positive values to keep, or negative values to drop.The values provided must be either all positive or all negative.Indices beyond the number of rows in the input are silently ignored. For |
.preserve | Relevant when the |
n,prop | Provide either A negative value of |
weight_by | < |
replace | Should sampling be performed with ( |
Value
.data with subsetted rows.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),summarize,unite.ir()
Examples
## slicedplyr::slice(ir_sample_data, 1:5)dplyr::slice_min(ir_sample_data, holocellulose, n = 3)dplyr::slice_max(ir_sample_data, holocellulose, n = 3)dplyr::slice_head(ir_sample_data, n = 5)dplyr::slice_tail(ir_sample_data, n = 5)## slice_sampleset.seed(234)dplyr::slice_sample(ir_sample_data, n = 3)Subsettingir objects
Description
Subsettingir objects
Usage
## S3 method for class 'ir'x[i, j, ..., exact = TRUE]## S3 method for class 'ir'x$i## S3 method for class 'ir'x[[i, j, ..., exact = TRUE]]## S3 replacement method for class 'ir'x$i, j, ... <- value## S3 replacement method for class 'ir'i[j, ..., exact = TRUE] <- value## S3 replacement method for class 'ir'i[[j, ..., exact = TRUE]] <- valueArguments
x | An object of class |
i,j | Row and column indices. If |
... | Ignored. |
exact | Ignored, with a warning. |
value | A value to store in a row, column, range or cell.Tibbles are stricter than data frames in what is accepted here. |
Value
If the subsetting operation preserves a validspectra column(seeir()), an object of classir withaccordingly subsetted rows or columns. Else atibble::tbl_df() orvector.
Examples
# subsetting rowsir_sample_data[1, ]ir_sample_data[10:15, ]ir_sample_data[ir_sample_data$sample_type == "office paper", ]# subsetting columnsir_sample_data[, "spectra"]ir_sample_data[["spectra"]]ir_sample_data$spectra# not explicitly selecting the spectra column drops the ir classclass(ir_sample_data[, 1])class(ir_sample_data[, "spectra"])# subsetting valuesir_sample_data[, 1] # drops the ir classir_sample_data[, c("id_sample", "spectra")]ir_sample_data$id_sampleir_sample_data[[1, 1]]# setting and replacing columnsx <- ir::ir_sample_datax$a <- 3x[, "a"] <- 4x$sample_type <- "a"x[[1]] <- rev(x[[1]])# deleting the spectra column drops the ir classx$spectra <- NULLclass(x)# setting and replacing rowsx <- ir::ir_sample_datax[1, ] <- x[2, ]class(x)# setting invalid values in the spectra column drops the ir classx_replacement <- x[1, ]x_replacement$spectra <- list(1)x[1, ] <- x_replacementclass(x)# setting and replacing valuesx <- ir::ir_sample_datax[[1, 1]] <- 100# replacing an element in the spectra column by an invalid element drops the# ir class attributex[[3, "spectra"]] <- list(1)class(x)Summarize each group in air object to fewer rows
Description
Summarize each group in air object to fewer rows
Usage
summarize.ir(.data, ..., .groups = NULL)summarise.ir(.data, ..., .groups = NULL)Arguments
.data | An object of class |
... | < The value can be:
|
.groups |
When
In addition, a message informs you of that choice, unless the result is ungrouped,the option "dplyr.summarise.inform" is set to |
Value
.data with summarized columns. If thespectra column is droppedor invalidated (seeir_new_ir()), their class is dropped, else theobject is of classir.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,unite.ir()
Examples
## summarize# select in each sample_type groups the first spectrumir_sample_data |> dplyr::group_by(sample_type) |> dplyr::summarize(spectra = spectra[[1]])Unite multiple columns in anir object into one by pasting strings together
Description
Unite multiple columns in anir object into one by pasting strings together
Usage
unite.ir(data, col, ..., sep = "_", remove = TRUE, na.rm = FALSE)Arguments
data | An object of class |
col | The name of the new column, as a string or symbol. This argument is passed by expression and supportsquasiquotation (you can unquote stringsand symbols). The name is captured from the expression with |
... | < |
sep | Separator to use between values. |
remove | If |
na.rm | If |
Value
.data with united columns. If thespectra column isdropped or invalidated (seeir_new_ir()), their class is dropped, elsethe object is of classir.
Source
See Also
Other tidyverse:arrange.ir(),distinct.ir(),extract.ir(),filter-joins,filter.ir(),group_by,mutate,mutate-joins,nest,pivot_longer.ir(),pivot_wider.ir(),rename,rowwise.ir(),select.ir(),separate.ir(),separate_rows.ir(),slice,summarize
Examples
## uniteir_sample_data |> tidyr::separate( "id_sample", c("a", "b", "c") ) |> tidyr::unite(id_sample, a, b, c)