Movatterモバイル変換


[0]ホーム

URL:


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 TeicknerORCID iD [aut, cre, cph]
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:


Pipe operator

Description

See⁠magrittr::[\%>\%][magrittr::pipe]⁠ for details.

Usage

lhs %>% rhs

Arguments

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 classir.

e2

An object of classir or a numeric value.

Value

e1 with intensity values of the spectra added to/subtractedwith/multiplied with/divided by those ine2:

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 classir.

...

<data-masking> Variables, orfunctions of variables. Usedesc() to sort a variable in descendingorder.

.by_group

IfTRUE, will sort first by grouping variable. Applies togrouped data frames only.

Value

.data with arranged rows.

Source

dplyr::arrange()

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. Forcbind, only the first of theobjects is allowed to be of classir.

deparse.level

An integer value; seerbind().

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 classir.

...

<data-masking> Optional variables touse when determining uniqueness. If there are multiple rows for a givencombination of inputs, only the first row will be preserved. If omitted,will use all variables in the data frame.

.keep_all

IfTRUE, keep all variables in.data.If a combination of... is not distinct, this keeps thefirst row of values.

Value

.data with distinct rows.

Source

dplyr::distinct()

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 classir.

col

<tidy-select> Column to expand.

into

Names of new variables to create as character vector.UseNA to omit the variable in the output.

regex

A string representing a regular expression used to extract thedesired values. There should be one group (defined by⁠()⁠) for eachelement ofinto.

remove

IfTRUE, remove input column from output data frame.

convert

IfTRUE, will runtype.convert() withas.is = TRUE on new columns. This is useful if the componentcolumns are integer, numeric or logical.

NB: this will cause string"NA"s to be converted toNAs.

...

Additional arguments passed on to methods.

Value

data with an extracted character column. Seetidyr::extract().

Source

tidyr::extract()

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 classir.

y

A data frame.

by

A join specification created withjoin_by(), or a charactervector of variables to join by.

IfNULL, the default,⁠*_join()⁠ will perform a natural join, using allvariables in common acrossx andy. A message lists the variables sothat you can check they're correct; suppress the message by supplyingbyexplicitly.

To join on different variables betweenx andy, use ajoin_by()specification. For example,join_by(a == b) will matchx$a toy$b.

To join by multiple variables, use ajoin_by() specification withmultiple expressions. For example,join_by(a == b, c == d) will matchx$a toy$b andx$c toy$d. If the column names are the same betweenx andy, you can shorten this by listing only the variable names, likejoin_by(a, c).

join_by() can also be used to perform inequality, rolling, and overlapjoins. See the documentation at?join_by for details onthese types of joins.

For simple equality joins, you can alternatively specify a character vectorof variable names to join by. For example,by = c("a", "b") joinsx$atoy$a andx$b toy$b. If variable names differ betweenx andy,use a named character vector likeby = c("x_a" = "y_a", "x_b" = "y_b").

To perform a cross-join, generating all combinations ofx andy, seecross_join().

copy

Ifx andy are not from the same data source,andcopy isTRUE, theny will be copied into thesame src asx. This allows you to join tables across srcs, butit is a potentially expensive operation so you must opt into it.

...

Other parameters passed onto methods.

na_matches

Should twoNA or twoNaN values match?

  • "na", the default, treats twoNA or twoNaN values as equal, like%in%,match(), andmerge().

  • "never" treats twoNA or twoNaN values as different, and willnever match them together or to any other values. This is similar to joinsfor database sources and tobase::merge(incomparables = NA).

Value

x andy joined. If thespectra column is renamed, theirclass is dropped. Seefilter-joins.

Source

filter-joins

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 classir.

...

<data-masking> Expressions thatreturn a logical value, and are defined in terms of the variables in.data. If multiple expressions are included, they are combined with the& operator. Only rows for which all conditions evaluate toTRUE arekept.

.preserve

Relevant when the.data input is grouped.If.preserve = FALSE (the default), the grouping structureis recalculated based on the resulting data, otherwise the grouping is kept as is.

Value

.data with filtered rows.

Source

dplyr::filter()

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 classir.

...

Ingroup_by(), variables or computations to group by.Computations are always done on the ungrouped data frame.To perform computations on the grouped data, you need to usea separatemutate() step before thegroup_by().Computations are not allowed innest_by().Inungroup(), variables to remove from the grouping.

.add

WhenFALSE, the default,group_by() willoverride existing groups. To add to the existing groups, use.add = TRUE.

This argument was previously calledadd, but that preventedcreating a new grouping variable calledadd, and conflicts withour naming conventions.

.drop

Drop groups formed by factor levels that don't appear in thedata? The default isTRUE except when.data has been previouslygrouped with.drop = FALSE. Seegroup_by_drop_default() for details.

Value

.data with grouped rows (group_by.ir()) or ungrouped rows(ungroup.ir()).

Source

dplyr::group_by()

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 classir.

y

An object of classir or a numeic value. Ifyis an object of classir, it must have the same number of rows asx and the same x axis values (e.g. wavenumber values) in each matchingspectrum as inx.

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.

  • Ifx is a data frame, an object of classir, an object of classhyperSpec (from package 'hyperSpec'), or an object of classSpectra(from package 'ChemoSpec'), these are ignored.

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 classir.

...

Variables inx to use as groups.

na.rm

A logical value indicating ifNA values should be dropped(TRUE) or not (FALSE).

.groups

[Experimental] Grouping structure of theresult.

  • "drop_last": dropping the last level of grouping. This was theonly supported option before version 1.0.0.

  • "drop": All levels of grouping are dropped.

  • "keep": Same grouping structure as.data.

  • "rowwise": Each row is its own group.

When.groups is not specified, it is chosenbased on the number of rows of the results:

  • If all the results have 1 row, you get "drop_last".

  • If the number of rows varies, you get "keep" (note that returning avariable number of rows was deprecated in favor ofreframe(), whichalso unconditionally drops all levels of grouping).

In addition, a message informs you of that choice, unless the result is ungrouped,the option "dplyr.summarise.inform" is set toFALSE,or whensummarise() is called from a function in a package.

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 classir.

method

A character value indicating which method should be usedfor baseline correction. Ifmethod = "polynomial", a polynomialis used for baseline correction. Ifmethod = "rubberband", arubberband function is used for baseline correction. Ifmethod = "sg",a Savitzky-Golay smoothed version of the input spectra is used for baselinecorrection.

return_bl

A logical value indicating if for each spectrum the baselineshould be returned instead of the corrected intensity values(return_bl = TRUE) or not (return_bl = FALSE).

...

Further arguments passed toir_bc_polynomial(),ir_bc_rubberband() orir_bc_sg().

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 classir.

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(return_bl = TRUE) or not (return_bl = FALSE).

...

Ignored.

Value

An object of classir with the baseline corrected spectra ifreturnbl = FALSE or the baselines ifreturnbl = TRUE.

See Also

ir_bc()

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 classir.

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 (TRUE) or not (FALSE). This can be useful in casebaseline correction without imputation causes artifacts which sometimeshappens with this method.

return_bl

A logical value indicating if for each spectrum the baselineshould be returned instead of the corrected intensity values(return_bl = TRUE) or not (return_bl = FALSE).

...

Ignored.

Value

An object of classir with the baseline corrected spectra and,ifreturnbl = TRUE, the baselines.

See Also

ir_bc()

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 classir.

...

Arguments passed toir_smooth() (except formethod which is always set to"sg").

return_bl

A logical value indicating if for each spectrum the baselineshould be returned instead of the corrected intensity values(return_bl = TRUE) or not (return_bl = FALSE).

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 classir with integer wavenumbervalues increasing by 1.

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 ofx after binning. Mustbe one of:

"start"

New wavenumbers for binned intensities are the startwavenumber value which defines the start of each bin. The default(for historical reasons).

"mean"

New wavenumbers for binned intensities are the averageof the start and end wavenumber values which define the start and end ofeach bin.

"end"

New wavenumbers for binned intensities are the endwavenumber value which defines the end of each bin.

return_ir_flat

Logical value. IfTRUE, the spectra are returned asir_flat object.

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 classir.

range

Adata.frame with two columns and a row for eachwavenumber range to keep. The columns are:

start

A numeric vector with start values for wavenumber ranges.

end

A numeric vector with end values for wavenumber ranges.

Ifrange has more than one row, multiple ranges are clipped fromx and merged together. Overlapping ranges are not allowed.

return_ir_flat

Logical value. IfTRUE, the spectra are returned asir_flat object.

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 classir containing the spectra tocorrect (with intensities representing absorbances).

ref

An object of classir containing the referencespectra to use for correction (with intensities representing absorbances).ref must have the same number of rows asx, the contained spectra mustcover the wavenumber range of all spectra inx, and ifdo_interpolate = FALSE, all spectra must have identical wavenumber values.

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:

H_2O

3902 cm^{-1}.

CO_2

2361 cm^{-1}.

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:

H_2O

3912 cm^{-1}.

CO_2

2349 cm^{-1}.

return_contribution

A logical value indicating whether in addition tothe corrected spectra, the computed relative contribution ofref to eachspectrum inx should be added to the returned object as new columncontribution (TRUE) or not (FALSE).

do_interpolate

A logical value indicating ifx andref should beinterpolated prior correction (TRUE) or not (FALSE).

start

Seeir_interpolate().

dw

Seeir_interpolate().

warn

A logical value indicating whether warnings about mismatchingwavenumber values should be displayed (TRUE) or not (FALSE). If set toTRUE andwn1 orwn2 do not exactly match the wavenumber values inxandref, a warning will be printed to inform about the wavenumberdifference between the selected and targeted wavenumber value.

return_ir_flat

Logical value. IfTRUE, the spectra are returned asir_flat object.

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$contribution

Divide 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 classir.

y

An object of classir or a numeic value. Ifyis an object of classir, it must have the same number of rows asx and the same x axis values (e.g. wavenumber values) in each matchingspectrum as inx.

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 classir.

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 classir.

what

A character value defining what to prepare for export.If"metadata", the metadata will be prepared for export and columnspectra will be dropped. If"spectra",x is converted to an object ofclassir_flat.

measurement_id

A character vector an element for each row inxthat contains the names to use as column names for the spectra in their_flat object to create.

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 classir_flat.

return_empty

A logical value indicating if the empty spectra should bereturned (return_empty = TRUE) or the non-empty spectra(return_empty = FALSE).

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 classir.

measurement_id

A character vector an element for each row inxthat contains the names to use as column names for the spectra in their_flat object to create.

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 classir.

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(TRUE) or not (FALSE).

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 withir_get_wavenumberindex() applied onwavenumber and 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 classir.

what

A numeric vector with each element representing a row inxfor which to extract the spectrum.

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 classir_flat).

wavenumber

A numeric vector with wavenumber values for which to getindices.

warn

logical value indicating if warnings should be displayed(TRUE) or not (FALSE).

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 classir.

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.csv files to import.

sample_id

Either:

  • NULL: Nothing additional happens.

  • A character vector with the same length asfilenames: Thisvector will be added as columnsample_id to their object.

  • "from_filenames": The file name(s) will be used as values fora new columnsample_id to add (the default).

  • "from_colnames": The header in the csv file will be used asvalues for a new columnsample_id to add.

...

Further arguments passed toread.csv().

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.spc files to import.

log.txt

A logical value indicating whether to import metadata (TRUE)or not (FALSE). See the details section. If set toFALSE, only themetadata variablesexponentiation_factor tomeasurement_device listed inthe Value section below are included in their object.

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 classir.

start

A numerical value indicating the start wavenumber value relativeto which new wavenumber values will be interpolated. The value is not allowedto be <floor(firstvalue) - 2, wherebyfirstvalue is the firstwavenumber value withinx. Ifstart = NULL,floor(firstvalue) will be used as first wavenumber value.

dw

A numerical value representing the desired wavenumber valuedifference between adjacent values.

return_ir_flat

Logical value. IfTRUE, the spectra are returned asir_flat object.

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 classir.

range

Adata.frame with a row for each region to interpolatelinearly and two columns:

start

A numeric vector with start values for regions to interpolatelinearly (x axis values).

end

A numeric vector with end values for regions to interpolatelinearly (x axis values).

For each row inrange, the values inrange$start have to besmaller than the values inrange$end.

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 classir.

y

An object of classir or a numeic value. Ifyis an object of classir, it must have the same number of rows asx and the same x axis values (e.g. wavenumber values) in each matchingspectrum as inx.

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 adata.frame with twocolumns and a row for each wavenumber value in the spectra data. The firstcolumn must contain unique wavenumber values and the second column intensityvalues of the measured spectrum of the sample.

metadata

An optionaldata.frame with additionalcolumns containing metadata for the spectra inspectra. Optionally, anemptydata.frame can be defined if no metadata are available.

Value

An object of classir with the following columns:

spectra

A list column identical tospectra.

...

Additional columns contained inmetadata.

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

Adata.frame with only numeric columns and only the firstcolumn name being "x".

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 classir.

method

A character value specifying which normalization method toapply:

"zeroone"

All intensity values will be normalized to [0;1].

"area"

All intensity values will be divided by the sum of theintensity values at all wavenumber values of the spectrum.

"area_absolute"

All intensity values will be divided by the sumof the intensity values at all wavenumber values of the spectrum.

"vector"

All intensity values will be divided by the norm ofthe intensity vector (vector normalization).

"snv"

Standard Normal Variate correction: For each spectrum, theaverage intensity value is subtracted and then divided by the standarddeviation.

A numeric value

Ifmethod is convertible to a numeric value, e.g.method = "980", the intensity of all spectra at a wavenumber value of980 will be set to 1 and the minimum intensity value of each spectrumwill be set to 0, i.e. the spectra will be normalized referring to aspecific wavenumber value.

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 classir.

remove_rows

A logical value indicating if rows inx with emptyspectra should be discarded (remove_rows = TRUE) or not(remove_rows = FALSE).

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_data

Format

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

Seeir_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 (naes(),kenStone(),duplex(),puchwein(),shenkWest(),honig()). See the 'prospectr' package for details.

...

Arguments passed tosampling_function. See the 'prospectr'package for details.

return_prospectr_output

Logical value. IfTRUE, the output ofsampling_function is returned. IfFALSE, values of elementsmodelandtest are included as columns inx andx is returned.

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 elementmodel of the prospectr output (TRUE) or not(FALSE).

for_prospectr_test

Logical value indicating whether the spectrum islisted in elementtest of the prospectr output (TRUE) or not(FALSE).

prospectr_model

Integer representing the order in which spectra arelisted in elementmodel of the prospectr output.

prospectr_test

Integer representing the order in which spectra arelisted in elementtest of 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 classir, where all non-empty spectra have identicalwavenumber values.

center

either a logical value or numeric-alike vector of lengthequal to the number of columns ofx, where‘numeric-alike’ means thatas.numeric(.) willbe applied successfully ifis.numeric(.) is not true.

scale

either a logical value or a numeric-alike vector of lengthequal to the number of columns ofx.

return_ir_flat

Logical value. IfTRUE, the spectra are returned asir_flat object.

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 classir.

method

A character value specifying which smoothing method to apply.Ifmethod = "sg", a Savitzky-Golay filter will be applied on thespectra. The Savitzky-Golay smoothing will be performed using the functionsignal::sgolayfilt(). Ifmethod = "fourier",Fourier smoothing will be performed. Fourier transformation of the spectra isperformed using the fast discrete Fourier transformation (FFT) as implementedinfda::smooth.basis(). A smoothing function can bedefined by the argmentf.

p

An integer value representing the filter order (i.e. the degree ofthe polynom) of the Savitzky-Golay filter ifmethod = "sg".

n

An odd integer value representing the length (i.e. the number ofwavenumber values used to construct the polynom) of the Savitzky-Golay filterifmethod = "sg".

ts

time scaling factor. Seesignal::sgolayfilt().

m

An integer value representing the mth derivative to compute. Thisoption can be used to compute derivatives of spectra. Seesignal::sgolayfilt().

k

A positive odd integer representing the number of Fourier basisfunctions to use as smoothed representation of the spectra ifmethod = "fourier".

...

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 (x) containing "xaxis values" of the spectra (e.g. wavenumbers) and all remaining columnscontaining intensity values of spectra.

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 classir.

y

An object of classir or a numeic value. Ifyis an object of classir, it must have the same number of rows asx and the same x axis values (e.g. wavenumber values) in each matchingspectrum as inx.

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 classir.

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:

ifsubtract_smoothed = FALSE

it computes the variance of theintensity values for each spectrum inx. If in additionrangeis notNULL, it computes the variance only for the region(s)represented byrange.

ifsubtract_smoothed = TRUE

it smoothesx, subtractsthe smoothedx from the unsmoothedx and computes thevariance of the difference intensity values. If in additionrange isnotNULL, 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 classir. These are the spectra forwhich to compute the variance.

subtract_smoothed

A logical value. Ifsubtract_smoothed = TRUE,x is copied, the copy smoothed usingir_smooth withmethod = "sg" and subtracted fromx before the variance of theintensity values fromx is computed. This allows e.g. to estimate thenoise level in a specific region of spectra. Ifsubtract_smoothed = FALSE (the default), nothing is subtracted fromx before computing the variance of the intensity values.

do_normalize

A logical value. If set toTRUE, the spectra inx are normalized after subtraction of a smoothed version, else nonormalization is performed.

normalize_method

Seeir_normalize().

...

Arguments passed toir_smooth() (except formethod which is always set to"sg" ifsubtract_smoothed isTRUE). Ifsubtract_smoothed = FALSE, these arguments will beignored.

range

Seeir_clip(). This is the range for which thevariance of the intensity values will be computed.

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 classir.

...

<data-masking> Name-value pairs.The name gives the name of the column in the output.

The value can be:

  • A vector of length 1, which will be recycled to the correct length.

  • A vector the same length as the current group (or the whole data frameif ungrouped).

  • NULL, to remove the column.

  • A data frame or tibble, to create multiple columns in the output.

.keep

Control which columns from.data are retained in the output. Groupingcolumns and columns created by... are always kept.

  • "all" retains all columns from.data. This is the default.

  • "used" retains only the columns used in... to create newcolumns. This is useful for checking your work, as it displays inputsand outputs side-by-side.

  • "unused" retains only the columnsnot used in... to create newcolumns. This is useful if you generate new columns, but no longer needthe columns used to generate them.

  • "none" doesn't retain any extra columns from.data. Only the groupingvariables and columns created by... are kept.

.before,.after

<tidy-select> Optionally, control where new columnsshould appear (the default is to add to the right hand side). Seerelocate() for more details.

Value

.data with modified columns. If thespectra column is dropped orinvalidated (seeir_new_ir()), their class is dropped, else the objectis of classir.

Source

dplyr::mutate()

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 classir.

y

A data frame.

by

A join specification created withjoin_by(), or a charactervector of variables to join by.

IfNULL, the default,⁠*_join()⁠ will perform a natural join, using allvariables in common acrossx andy. A message lists the variables sothat you can check they're correct; suppress the message by supplyingbyexplicitly.

To join on different variables betweenx andy, use ajoin_by()specification. For example,join_by(a == b) will matchx$a toy$b.

To join by multiple variables, use ajoin_by() specification withmultiple expressions. For example,join_by(a == b, c == d) will matchx$a toy$b andx$c toy$d. If the column names are the same betweenx andy, you can shorten this by listing only the variable names, likejoin_by(a, c).

join_by() can also be used to perform inequality, rolling, and overlapjoins. See the documentation at?join_by for details onthese types of joins.

For simple equality joins, you can alternatively specify a character vectorof variable names to join by. For example,by = c("a", "b") joinsx$atoy$a andx$b toy$b. If variable names differ betweenx andy,use a named character vector likeby = c("x_a" = "y_a", "x_b" = "y_b").

To perform a cross-join, generating all combinations ofx andy, seecross_join().

copy

Ifx andy are not from the same data source,andcopy isTRUE, theny will be copied into thesame src asx. This allows you to join tables across srcs, butit is a potentially expensive operation so you must opt into it.

suffix

If there are non-joined duplicate variables inx andy, these suffixes will be added to the output to disambiguate them.Should be a character vector of length 2.

...

Other parameters passed onto methods.

keep

Should the join keys from bothx andy be preserved in theoutput?

  • IfNULL, the default, joins on equality retain only the keys fromx,while joins on inequality retain the keys from both inputs.

  • IfTRUE, all keys from both inputs are retained.

  • IfFALSE, only keys fromx are retained. For right and full joins,the data in key columns corresponding to rows that only exist iny aremerged into the key columns fromx. Can't be used when joining oninequality conditions.

na_matches

Should twoNA or twoNaN values match?

  • "na", the default, treats twoNA or twoNaN values as equal, like%in%,match(), andmerge().

  • "never" treats twoNA or twoNaN values as different, and willnever match them together or to any other values. This is similar to joinsfor database sources and tobase::merge(incomparables = NA).

Value

x andy joined. If thespectra column is renamed, theirclass is dropped. Seemutate-joins.

Source

mutate-joins

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 classir.

...

<tidy-select> Columns to nest; these willappear in the inner data frames.

Specified using name-variable pairs of the formnew_col = c(col1, col2, col3). The right hand side can be any validtidyselect expression.

If not supplied, then... is derived as all columnsnot selected by.by, and will use the column name from.key.

[Deprecated]:previously you could writedf %>% nest(x, y, z).Convert todf %>% nest(data = c(x, y, z)).

.key

The name of the resulting nested column. Only applicable when... isn't specified, i.e. in the case ofdf %>% nest(.by = x).

IfNULL, then"data" will be used by default.

data

A data frame.

cols

<tidy-select> List-columns to unnest.

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 (likeNULL or an empty data frame or vector), then thatentire row will be dropped from the output. If you want to preserve allrows, usekeep_empty = TRUE to replace size-0 elements with a single rowof missing values.

ptype

Optionally, a named list of column name-prototype pairs tocoercecols to, overriding the default that will be guessed fromcombining the individual values. Alternatively, a single empty ptypecan be supplied, which will be applied to allcols.

names_sep,.names_sep

IfNULL, the default, the names will be leftas is. Innest(), inner names will come from the former outer names;inunnest(), the new outer names will come from the inner names.

If a string, the inner and outer names will be used together. Inunnest(), the names of the new outer columns will be formed by pastingtogether the outer and the inner column names, separated bynames_sep. Innest(), the new inner names will have the outer names +names_sepautomatically stripped. This makesnames_sep roughly symmetric betweennesting and unnesting.

names_repair

Used to check that output data frame has validnames. Must be one of the following options:

  • ⁠"minimal⁠": no name repair or checks, beyond basic existence,

  • ⁠"unique⁠": make sure names are unique and not empty,

  • ⁠"check_unique⁠": (the default), no name repair, but check they are unique,

  • ⁠"universal⁠": make the names unique and syntactic

  • a function: apply custom name repair.

  • tidyr_legacy: use the name repair from tidyr 0.8.

  • a formula: a purrr-style anonymous function (seerlang::as_function())

Seevctrs::vec_as_names() for more details on these terms and thestrategies used to enforce them.

.drop,.preserve

[Deprecated]:all list-columns are now preserved; If there are any that youdon't want in the output useselect() to remove them prior tounnesting.

.id

[Deprecated]:convertdf %>% unnest(x, .id = "id") to⁠df %>% mutate(id = names(x)) %>% unnest(x))⁠.

.sep

[Deprecated]:usenames_sep instead.

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

tidyr::nest()

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 classir.

cols

<tidy-select> Columns to pivot intolonger format.

names_to

A character vector specifying the new column or columns tocreate from the information stored in the column names ofdata specifiedbycols.

  • If length 0, or ifNULL is supplied, no columns will be created.

  • If length 1, a single column will be created which will contain thecolumn names specified bycols.

  • If length >1, multiple columns will be created. In this case, one ofnames_sep ornames_pattern must be supplied to specify how thecolumn names should be split. There are also two additional charactervalues you can take advantage of:

    • NA will discard the corresponding component of the column name.

    • ".value" indicates that the corresponding component of the columnname defines the name of the output column containing the cell values,overridingvalues_to entirely.

names_prefix

A regular expression used to remove matching textfrom the start of each variable name.

names_sep,names_pattern

Ifnames_to contains multiple values,these arguments control how the column name is broken up.

names_sep takes the same specification asseparate(), and can eitherbe a numeric vector (specifying positions to break on), or a single string(specifying a regular expression to split on).

names_pattern takes the same specification asextract(), a regularexpression containing matching groups (⁠()⁠).

If these arguments do not give you enough control, usepivot_longer_spec() to create a spec object and process manually asneeded.

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 (likeinteger() ornumeric()) that defines the type,class, and attributes of a vector. Use these arguments if you want toconfirm that the created columns are the types that you expect. Note thatif you want to change (instead of confirm) the types of specific columns,you should usenames_transform orvalues_transform instead.

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,names_transform = list(week = as.integer) would convert a character variable calledweekto an integer.

If not specified, the type of the columns generated fromnames_to willbe character, and the type of the variables generated fromvalues_towill be the common type of the input columns used to generate them.

names_repair

What happens if the output has invalid column names?The default,"check_unique" is to error if the columns are duplicated.Use"minimal" to allow duplicates in the output, or"unique" tode-duplicated by adding numeric suffixes. Seevctrs::vec_as_names()for more options.

values_to

A string specifying the name of the column to createfrom the data stored in cell values. Ifnames_to is a charactercontaining the special.value sentinel, this value will be ignored,and the name of the value column will be derived from part of theexisting column names.

values_drop_na

IfTRUE, will drop rows that contain onlyNAsin thevalue_to column. This effectively converts explicit missing valuesto implicit missing values, and should generally be used only when missingvalues indata were created by its structure.

...

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

tidyr::pivot_longer()

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 classir.

id_cols

<tidy-select> A set of columns thatuniquely identify each observation. Typically used when you haveredundant variables, i.e. variables whose values are perfectly correlatedwith existing variables.

Defaults to all columns indata except for the columns specified throughnames_from andvalues_from. If a tidyselect expression is supplied, itwill be evaluated ondata after removing the columns specified throughnames_from andvalues_from.

names_from,values_from

<tidy-select> A pair ofarguments describing which column (or columns) to get the name of theoutput column (names_from), and which column (or columns) to get thecell values from (values_from).

Ifvalues_from contains multiple values, the value will be added to thefront of the output column.

names_prefix

String added to the start of every variable name. This isparticularly useful ifnames_from is a numeric vector and you want tocreate syntactic variable names.

names_sep

Ifnames_from orvalues_from contains multiplevariables, this will be used to join their values together into a singlestring to use as a column name.

names_glue

Instead ofnames_sep andnames_prefix, you can supplya glue specification that uses thenames_from columns (and special.value) to create custom column names.

names_sort

Should the column names be sorted? IfFALSE, the default,column names are ordered by first appearance.

names_repair

What happens if the output has invalid column names?The default,"check_unique" is to error if the columns are duplicated.Use"minimal" to allow duplicates in the output, or"unique" tode-duplicated by adding numeric suffixes. Seevctrs::vec_as_names()for more options.

values_fill

Optionally, a (scalar) value that specifies what eachvalue should be filled in with when missing.

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 ofid_cols andnames_from columns does not uniquely identify anobservation.

This can be a named list if you want to apply different aggregationsto differentvalues_from columns.

...

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

tidyr::pivot_wider()

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 classir.

...

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 classir.

...

Further arguments, ignored.

na.rm

A logical value. Seemax().

.dimension

A character value. Must be one of the following:

"x"

In this case, the minimum/maximum/range/median of x axis valuesof the spectra inx are extracted.

"y"

In this case, the minimum/maximum/range/median of intensityvalues of the spectra inx are extracted.

.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 classir.

...

Forrename(): <tidy-select> Usenew_name = old_name to rename selected variables.

Forrename_with(): additional arguments passed onto.fn.

.fn

A function used to transform the selected.cols. Shouldreturn a character vector the same length as the input.

.cols

<tidy-select> Columns to rename;defaults to all columns.

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

dplyr::rename()

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 class

Replicate 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 classir.

...

Seerep().

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.

...

<tidy-select> Variables to be preservedwhen callingsummarise(). This is typically a set of variables whosecombination uniquely identify each row.

NB: unlikegroup_by() you can not create new variables here butinstead you can select multiple variables with (e.g.)everything().

data

An object of classir.

Value

data as row-wise data frame. Seedplyr::rowwise().

Source

dplyr::rowwise()

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 classir.

...

<tidy-select> One or more unquotedexpressions separated by commas. Variable names can be used as if theywere positions in the data frame, so expressions likex:y canbe used to select a range of variables.

Value

.data with the selected columns. If thespectra column is dropped,their class is dropped, else the object is of classir.

Source

dplyr::select()

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 class

Separate 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 classir.

col

<tidy-select> Column to expand.

into

Names of new variables to create as character vector.UseNA to omit the variable in the output.

sep

Separator between columns.

If character,sep is interpreted as a regular expression. The defaultvalue is a regular expression that matches any sequence ofnon-alphanumeric values.

If numeric,sep is interpreted as character positions to split at. Positivevalues start at 1 at the far-left of the string; negative value start at -1 atthe far-right of the string. The length ofsep should be one less thaninto.

remove

IfTRUE, remove input column from output data frame.

convert

IfTRUE, will runtype.convert() withas.is = TRUE on new columns. This is useful if the componentcolumns are integer, numeric or logical.

NB: this will cause string"NA"s to be converted toNAs.

extra

Ifsep is a character vector, this controls whathappens when there are too many pieces. There are three valid options:

  • "warn" (the default): emit a warning and drop extra values.

  • "drop": drop any extra values without a warning.

  • "merge": only splits at mostlength(into) times

fill

Ifsep is a character vector, this controls whathappens when there are not enough pieces. There are three valid options:

  • "warn" (the default): emit a warning and fill from the right

  • "right": fill with missing values on the right

  • "left": fill with missing values on the left

...

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

tidyr::separate()

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 classir.

...

<tidy-select> Columns to separate acrossmultiple rows

sep

Separator delimiting collapsed values.

convert

IfTRUE will automatically runtype.convert() on the key column. This is useful if the columntypes are actually numeric, integer, or logical.

Value

data with a collapsed column separated into multiple rows. Seetidyr::separate_rows().

Source

tidyr::separate_rows()

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 classir.

...

Forslice(): <data-masking>Integer row values.

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⁠slice_*()⁠, these arguments are passed on to methods.

.preserve

Relevant when the.data input is grouped.If.preserve = FALSE (the default), the grouping structureis recalculated based on the resulting data, otherwise the grouping is kept as is.

n,prop

Provide eithern, the number of rows, orprop, theproportion of rows to select. If neither are supplied,n = 1 will beused. Ifn is greater than the number of rows in the group(orprop > 1), the result will be silently truncated to the group size.prop will be rounded towards zero to generate an integer number ofrows.

A negative value ofn orprop will be subtracted from the groupsize. For example,n = -2 with a group of 5 rows will select 5 - 2 = 3rows;prop = -0.25 with 8 rows will select 8 * (1 - 0.25) = 6 rows.

weight_by

<data-masking> Samplingweights. This must evaluate to a vector of non-negative numbers the samelength as the input. Weights are automatically standardised to sum to 1.

replace

Should sampling be performed with (TRUE) or without(FALSE, the default) replacement.

Value

.data with subsetted rows.

Source

dplyr::slice()

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]] <- value

Arguments

x

An object of classir.

i,j

Row and column indices. Ifj is omitted,i is used as column index.

...

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 classir.

...

<data-masking> Name-value pairs ofsummary functions. The name will be the name of the variable in the result.

The value can be:

  • A vector of length 1, e.g.min(x),n(), orsum(is.na(y)).

  • A data frame, to add multiple columns from a single expression.

[Deprecated] Returning values with size 0 or >1 wasdeprecated as of 1.1.0. Please usereframe() for this instead.

.groups

[Experimental] Grouping structure of theresult.

  • "drop_last": dropping the last level of grouping. This was theonly supported option before version 1.0.0.

  • "drop": All levels of grouping are dropped.

  • "keep": Same grouping structure as.data.

  • "rowwise": Each row is its own group.

When.groups is not specified, it is chosenbased on the number of rows of the results:

  • If all the results have 1 row, you get "drop_last".

  • If the number of rows varies, you get "keep" (note that returning avariable number of rows was deprecated in favor ofreframe(), whichalso unconditionally drops all levels of grouping).

In addition, a message informs you of that choice, unless the result is ungrouped,the option "dplyr.summarise.inform" is set toFALSE,or whensummarise() is called from a function in a package.

Value

.data with summarized columns. If thespectra column is droppedor invalidated (seeir_new_ir()), their class is dropped, else theobject is of classir.

Source

dplyr::summarize()

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 classir.

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 withrlang::ensym() (note that this kind of interface wheresymbols do not represent actual objects is now discouraged in thetidyverse; we support it here for backward compatibility).

...

<tidy-select> Columns to unite

sep

Separator to use between values.

remove

IfTRUE, remove input columns from output data frame.

na.rm

IfTRUE, missing values will be removed prior to unitingeach value.

Value

.data with united columns. If thespectra column isdropped or invalidated (seeir_new_ir()), their class is dropped, elsethe object is of classir.

Source

tidyr::unite()

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)

[8]ページ先頭

©2009-2025 Movatter.jp