Title: | Class and Methods for Spectral Data |
---|---|
Description: | Input/Output, processing and visualization of spectra taken with different spectrometers, including SVC (Spectra Vista), ASD and PSR (Spectral Evolution). Implements an S3 class spectra that other packages can build on. Provides methods to access, plot, manipulate, splice sensor overlap, vector normalize and smooth spectra. |
Authors: | Jose Eduardo Meireles [aut, cre], Anna K. Schweiger [aut], Jeannine Cavender-Bares [aut] |
Maintainer: | Jose Eduardo Meireles <[email protected]> |
License: | GPL-3 |
Version: | 0.0.19 |
Built: | 2025-01-14 06:08:54 UTC |
Source: | https://github.com/meireles/spectrolab |
`[`
Subsets spectra by sample names (rows) or (and) bands (columns)
## S3 method for class 'spectra' x[i, j, simplify = TRUE]
## S3 method for class 'spectra' x[i, j, simplify = TRUE]
x |
spectra object |
i |
Sample names (preferred), index, or a logical vector of length nrow(x) |
j |
band labels, as numeric or character or a logical vector of length ncol(x). Do not use indexes! |
simplify |
Boolean. If TRUE (default), single band selections are returned as a named vector of values |
Subset operations based on samples (first argument) will match sample names or indexes, in that order. The spectra constructor ensures that names are not numeric nor are coercible to numeric, such that x[1:2, ] will return the first and second samples in the 'spectra' object. Subsetting based on bands (second argument) matches the band labels, not indices! That is, x[ , 600] will give you the value data for the 600nm band and not the 600th band. Boolean vectors of the appropriate length can be used to subset samples and bands.
usually a spectra object, but see param 'simplify'
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) head(names(spec), n = 3) # by name spec1 = spec[ "species_7" , ] spec1 # by band spec2 = spec[ , 400:700 ] spec2
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) head(names(spec), n = 3) # by name spec1 = spec[ "species_7" , ] spec1 # by band spec2 = spec[ , 400:700 ] spec2
`[<-`
assigns the rhs values to spectra
## S3 replacement method for class 'spectra' x[i, j] <- value
## S3 replacement method for class 'spectra' x[i, j] <- value
x |
spectra object (lhs) |
i |
Sample names (preferred), index, or a logical vector of length nrow(x) |
j |
band labels, as numeric or character or a logical vector of length ncol(x). Do not use indexes! |
value |
value to be assigned (rhs). Must either data coercible to numeric or another 'spectra' obj |
nothing. modifies spectra as side effect
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec[ , 400:500] = spec[ , 400:500] * 1.2 spec
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec[ , 400:500] = spec[ , 400:500] * 1.2 spec
Applies FUN (and FUN_meta) over spectra aggregating by factor 'by'.
## S3 method for class 'spectra' aggregate(x, by, FUN, FUN_meta = NULL, ...)
## S3 method for class 'spectra' aggregate(x, by, FUN, FUN_meta = NULL, ...)
x |
spectra object |
by |
vector of factors to guide the aggregation |
FUN |
function to be applied to value (and meta if FUN_meta is NULL) |
FUN_meta |
function to be applied to metadata. If NULL (default), same FUN applied to value is used. |
... |
extra args to FUN |
Argument FUN_meta is useful if you want to apply a different function to
metadata and value. If you want to aggregate spectra and metadata
using 'mean', 'sd', 'median' etc. but try to keep the text values, wrap your
function in try_keep_txt(f)
.
spectra object
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec_mean = aggregate(spec, by = names(spec), mean, try_keep_txt(mean))
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec_mean = aggregate(spec, by = names(spec), mean, try_keep_txt(mean))
apply_by_band
is conceptually similar to apply(as.matrix(x), 2, fun),
but returns a spectra object while dealing with metadata and attributes.
Applying a function that does not act on numeric values may crash the function
or render all values NA.
apply_by_band(x, fun, na.rm = TRUE, keep_txt_meta = TRUE, name = NULL, ...) ## S3 method for class 'spectra' apply_by_band(x, fun, na.rm = TRUE, keep_txt_meta = TRUE, name = NULL, ...)
apply_by_band(x, fun, na.rm = TRUE, keep_txt_meta = TRUE, name = NULL, ...) ## S3 method for class 'spectra' apply_by_band(x, fun, na.rm = TRUE, keep_txt_meta = TRUE, name = NULL, ...)
x |
spectra |
fun |
numeric function to be applied to each band. |
na.rm |
boolean. remove NAs? |
keep_txt_meta |
boolean. try to keep text in the metadata? |
name |
name for each sample in the output spectra. The default (NULL) will give samples sequential numeric names. Recycled if necessary. |
... |
extra arguments passed to fun |
spectra
apply_by_band(spectra)
: Apply a numeric function by band
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec_mean = apply_by_band(spec, mean)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec_mean = apply_by_band(spec, mean)
Convert matrix or data frame to spectra
as_spectra(x, name_idx = NULL, meta_idxs = NULL)
as_spectra(x, name_idx = NULL, meta_idxs = NULL)
x |
matrix or dataframe. Samples are in rows and bands in columns. Any data that are not the spectra themselves (labels or metadata) must have their column index included in 'name_idx' or 'meta_idxs'. |
name_idx |
column index with sample names. Defaults to NULL. If NULL or 0, rownames(x) or a sequence of integers will be assigned as names. |
meta_idxs |
column indices with metadata (not name and not value). Defaults to NULL |
spectra object
Jose Eduardo Meireles
library(spectrolab) as_spectra(spec_matrix_example, name_idx = 1)
library(spectrolab) as_spectra(spec_matrix_example, name_idx = 1)
Convert data.frame to spectra
## S3 method for class 'data.frame' as_spectra(x, name_idx = NULL, meta_idxs = NULL)
## S3 method for class 'data.frame' as_spectra(x, name_idx = NULL, meta_idxs = NULL)
x |
data.frame |
name_idx |
column index with sample names. Defaults to NULL. |
meta_idxs |
column indices with metadata (not name and not value). Defaults to NULL |
spectra object
Jose Eduardo Meireles
Convert matrix to spectra
## S3 method for class 'matrix' as_spectra(x, name_idx = NULL, meta_idxs = NULL)
## S3 method for class 'matrix' as_spectra(x, name_idx = NULL, meta_idxs = NULL)
x |
matrix |
name_idx |
column index with sample names. Defaults to NULL |
meta_idxs |
column indices with metadata (not name and not value). Defaults to NULL |
spectra object
Jose Eduardo Meireles
Returns a data.frame that includes sample names, metadata (if present) and value data. One advantage over as.matrix, is that the metadata are returned.
## S3 method for class 'spectra' as.data.frame( x, row.names = NULL, optional = FALSE, fix_names = "none", metadata = TRUE, ... )
## S3 method for class 'spectra' as.data.frame( x, row.names = NULL, optional = FALSE, fix_names = "none", metadata = TRUE, ... )
x |
spectra object |
row.names |
does nothing. Here for compatibility with S3 generics |
optional |
does nothing. Here for compatibility with S3 generics |
fix_names |
Use make.names to normalize names? Pick one: "none" "row" "col" "both". |
metadata |
boolean. Include spectral metadata? Defaults to TRUE |
... |
extra parameters passed to the generic as_spectra |
data.frame with: sample_name, metadata (if any) and value.
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) df = as.data.frame(spec, fix_names = "none")
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) df = as.data.frame(spec, fix_names = "none")
Convert spectra to matrix
## S3 method for class 'spectra' as.matrix(x, fix_names = "none", ...)
## S3 method for class 'spectra' as.matrix(x, fix_names = "none", ...)
x |
spectra object |
fix_names |
Use make.names to normalize names? Pick one: "none" "row" "col" "both". |
... |
does nothing. Here for compatibility with S3 generics |
matrix of spectral value. columns are bands and rows are samples
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) mat = as.matrix(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) mat = as.matrix(spec)
bands
returns a vector of band labels from spectra
bands(x, min = NULL, max = NULL, return_num = TRUE) ## S3 method for class 'spectra' bands(x, min = NULL, max = NULL, return_num = TRUE)
bands(x, min = NULL, max = NULL, return_num = TRUE) ## S3 method for class 'spectra' bands(x, min = NULL, max = NULL, return_num = TRUE)
x |
spectra object |
min |
= NULL |
max |
= NULL |
return_num |
boolean. return vector of numeric values (default). otherwise, a vector of strings is returned |
vector of bands. numeric if 'return_num' = TRUE (default).
bands(spectra)
: Get spectra band labels
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) head(bands(spec))
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) head(bands(spec))
bands
sets band labels of lhs to the rhs values
bands(x) <- value
bands(x) <- value
x |
spectra object (lhs) |
value |
rhs |
nothing. called for its side effect.
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) bands(spec) = bands(spec) / 1000
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) bands(spec) = bands(spec) / 1000
combine
binds two spectral datasets. Both spectra must have the
very same band labels, but different metadata are acceptable
combine(s1, s2) ## S3 method for class 'spectra' combine(s1, s2)
combine(s1, s2) ## S3 method for class 'spectra' combine(s1, s2)
s1 |
spectra object 1 |
s2 |
spectra object 2 |
combined spectra object
combine(spectra)
: Combines two spectral datasets
Jose Eduardo Meireles
library(spectrolab) # Create dummy spectra datasets. Pretend that these are all different... s1 = as_spectra(spec_matrix_example, name_idx = 1) s2 = as_spectra(spec_matrix_example, name_idx = 1) s3 = as_spectra(spec_matrix_example, name_idx = 1) # combine 2 spectra objects s_1and2 = combine(s1, s2) # combine n spectra objects using the `Reduce` function s_n = Reduce(combine, list(s1, s2, s3))
library(spectrolab) # Create dummy spectra datasets. Pretend that these are all different... s1 = as_spectra(spec_matrix_example, name_idx = 1) s2 = as_spectra(spec_matrix_example, name_idx = 1) s3 = as_spectra(spec_matrix_example, name_idx = 1) # combine 2 spectra objects s_1and2 = combine(s1, s2) # combine n spectra objects using the `Reduce` function s_n = Reduce(combine, list(s1, s2, s3))
Return default spectral regions matrix
default_spec_regions()
default_spec_regions()
matrix with default_spec_regions
Jose Eduardo Meireles
library(spectrolab) # matrix that defines regions on the spectra # Useful for plotting w/ plot_regions()
library(spectrolab) # matrix that defines regions on the spectra # Useful for plotting w/ plot_regions()
dim
returns a vector with number of samples and bands (bands)
## S3 method for class 'spectra' dim(x)
## S3 method for class 'spectra' dim(x)
x |
spectra object |
tuple of integers: c("n_samples", "n_bands")
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) dim(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) dim(spec)
Guess splice bands (bounds between senors)
guess_splice_at(x) ## S3 method for class 'spectra' guess_splice_at(x)
guess_splice_at(x) ## S3 method for class 'spectra' guess_splice_at(x)
x |
spectra object |
vector of band values
guess_splice_at(spectra)
: Guess splice bands (bounds between senors)
Jose Eduardo Meireles
is_spectra
tests if the argument is a spectra class object
is_spectra(x)
is_spectra(x)
x |
any object |
boolean
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec1 = unclass(spec) is_spectra(spec) is_spectra(spec1)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec1 = unclass(spec) is_spectra(spec) is_spectra(spec1)
Resample the FWHM to a new set of bands using a gaussian model
make_fwhm(spec, new_bands, new_fwhm = NULL, return_type = "max", k = 3)
make_fwhm(spec, new_bands, new_fwhm = NULL, return_type = "max", k = 3)
spec |
spectra object |
new_bands |
band values to resample the spectra to |
new_fwhm |
FWHM for the new bands |
return_type |
either "max" or "old". If "old" (default), it returns the fwhm inferred from the original's spectra bands. If max (default), it returns the max between the new and old fwhm. |
k |
number of unique FHWM to estimate |
FWHM as a numeric vector
match_sensors
scales values of sensors 1 (VIS) and 3 (SWIR 2)
match_sensors(x, splice_at, fixed_sensor = 2, interpolate_wvl = c(5, 1)) ## S3 method for class 'spectra' match_sensors(x, splice_at, fixed_sensor = 2, interpolate_wvl = c(5, 2))
match_sensors(x, splice_at, fixed_sensor = 2, interpolate_wvl = c(5, 1)) ## S3 method for class 'spectra' match_sensors(x, splice_at, fixed_sensor = 2, interpolate_wvl = c(5, 2))
x |
spectra object |
splice_at |
bands that serve as splice points, i.e the beginnings of the rightmost sensor. Must be length 1 or 2 (max 3 sensors) |
fixed_sensor |
sensor to keep fixed. Can be 1 or 2 if matching 2 sensors. If matching 3 sensors, 'fixed_sensor' must be 2 (default). |
interpolate_wvl |
extent around splice_at values over which the splicing factors will be calculated. Defaults to 5 |
Splice_at has no default because sensor transition points vary between vendors
and individual instruments.
The function guess_splice_at
can help you guess what those values could
be. However, splice_at
is an important parameter though, so you should
visually inspect your spectra before assigning it.
Typical values in our own individual instruments were:
SVC ~ c(990, 1900),
ASD ~ c(1001, 1801).
If the factors used to match spectra are unreasonable, match_sensors
will throw. Unreasonable factors (f) are defined as 0.5 > f > 3 or NaN,
which happens when the value for the right sensor is 0.
spectra object
match_sensors(spectra)
: Match sensor overlap regions
Jose Eduardo Meireles and Anna Schweiger
max
Returns the maximum value in a spectra object
## S3 method for class 'spectra' max(..., na.rm = FALSE)
## S3 method for class 'spectra' max(..., na.rm = FALSE)
... |
spectra object |
na.rm |
boolean. remove NAs? Defaults to FALSE |
single numeric value
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) max(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) max(spec)
mean
computes the arithmetic mean spectrum.
## S3 method for class 'spectra' mean(x, na.rm = TRUE, keep_txt_meta = TRUE, ...)
## S3 method for class 'spectra' mean(x, na.rm = TRUE, keep_txt_meta = TRUE, ...)
x |
spectra |
na.rm |
boolean. remove NAs? Defaults to TRUE |
keep_txt_meta |
try to keep text in the metadata |
... |
nothing |
single spectrum
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) mean(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) mean(spec)
median
computes the median spectrum
## S3 method for class 'spectra' median(x, na.rm = TRUE, keep_txt_meta = TRUE, ...)
## S3 method for class 'spectra' median(x, na.rm = TRUE, keep_txt_meta = TRUE, ...)
x |
spectra |
na.rm |
boolean. remove NAs? Defaults to TRUE |
keep_txt_meta |
try to keep text in the metadata |
... |
nothing |
single spectrum
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) median(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) median(spec)
meta
returns metadata of spectra
meta(x, label = NULL, sample = NULL, simplify = FALSE, quiet = TRUE) ## S3 method for class 'spectra' meta(x, label = NULL, sample = NULL, simplify = FALSE, quiet = TRUE)
meta(x, label = NULL, sample = NULL, simplify = FALSE, quiet = TRUE) ## S3 method for class 'spectra' meta(x, label = NULL, sample = NULL, simplify = FALSE, quiet = TRUE)
x |
spectra object |
label |
metadata column index or label |
sample |
sample index or name |
simplify |
boolean. defaults to FALSE |
quiet |
boolean. warn about non-existent metadata? defaults to TRUE |
data frame or vector
meta(spectra)
: get metadata
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec = normalize(spec) meta(spec, "normalization_magnitude")
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec = normalize(spec) meta(spec, "normalization_magnitude")
meta
sets metadata
meta(x, label = NULL, sample = NULL) <- value
meta(x, label = NULL, sample = NULL) <- value
x |
spectra object (lhs) |
label |
metadata column label |
sample |
sample name |
value |
rhs. TODO |
nothing. called for its side effect
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) meta(spec, "random") = rnorm(nrow(spec), mean(10), sd = 2)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) meta(spec, "random") = rnorm(nrow(spec), mean(10), sd = 2)
min
Returns the minimum value in a spectra object
## S3 method for class 'spectra' min(..., na.rm = FALSE)
## S3 method for class 'spectra' min(..., na.rm = FALSE)
... |
spectra object |
na.rm |
boolean. remove NAs? Defaults to FALSE |
single numeric value
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) min(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) min(spec)
names
returns a vector of sample names
## S3 method for class 'spectra' names(x)
## S3 method for class 'spectra' names(x)
x |
spectra object |
vector of sample names
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) names(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) names(spec)
names
assigns sample names to lhs
## S3 replacement method for class 'spectra' names(x) <- value
## S3 replacement method for class 'spectra' names(x) <- value
x |
spectra object (lhs) |
value |
values to be assigned (rhs) |
nothing. called for its side effect.
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) names(spec) = toupper(names(spec))
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) names(spec) = toupper(names(spec))
normalize
returns a spectra obj with vector normalized values.
Normalization value for each spectrum computed as sqrt(sum(x^2))
normalize(x, quiet = FALSE, ...) ## S3 method for class 'spectra' normalize(x, quiet = FALSE, ...)
normalize(x, quiet = FALSE, ...) ## S3 method for class 'spectra' normalize(x, quiet = FALSE, ...)
x |
spectra object. bands must be strictly increasing |
quiet |
boolean. Warn about change in y value units? Defaults to FALSE |
... |
nothing |
spectra object with normalized spectra
normalize(spectra)
: Vector normalize spectra
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec = normalize(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec = normalize(spec)
Overloads arithmetic operators for spectra using 'Ops.'
## S3 method for class 'spectra' Ops(e1, e2)
## S3 method for class 'spectra' Ops(e1, e2)
e1 |
lhs |
e2 |
rhs |
Depends on the operator. math operators will return spectra and logical or comparison operators will return boolean matrices
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec1 = spec * 2 spec2 = spec + spec all(spec1 == spec2)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec1 = spec * 2 spec2 = spec + spec all(spec1 == spec2)
pairwise_indices
computes pairwise spectral indices.
Indices are computed as (a - b) / (a + b) where a is the lower band.
The column names of the resulting matrix are given as "a|b".
pairwise_indices(x, max_out_elements = 5e+08)
pairwise_indices(x, max_out_elements = 5e+08)
x |
spectra |
max_out_elements |
maximum number of elements in the output object |
list that includes the *indices* between bands a and b (column names a|b) and the pairwise *band_combinations*
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) # Resampling spectra since a spectral dataset with 2,001 bands # results in 2,001,000 unique spectral indices per sample new_bands = seq(400, 2400, 10) spec = resample(spec, new_bands, make_fwhm(spec, new_bands) ) p_idx = pairwise_indices(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) # Resampling spectra since a spectral dataset with 2,001 bands # results in 2,001,000 unique spectral indices per sample new_bands = seq(400, 2400, 10) spec = resample(spec, new_bands, make_fwhm(spec, new_bands) ) p_idx = pairwise_indices(spec)
Interactively plots spectra with a shiny app. Useful to inspect large datasets.
plot_interactive( spec, colpalette = function(n) RColorBrewer::brewer.pal(n, "Dark2"), ... )
plot_interactive( spec, colpalette = function(n) RColorBrewer::brewer.pal(n, "Dark2"), ... )
spec |
spectra object |
colpalette |
a color palette function, e.g. rainbow, terrain.colors, or a function returned by colorRampPalette() or colorRamps package |
... |
Other arguments passed to plot |
plot_interact
limits the number of spectra displayed at once to 600 for
performance reasons. As of now, the function does not return anything and does
not have side effects. This means that spectra can be selected and highlighted
but not yet deleted or subset from the shiny app.
interactive plot
Jose Eduardo Meireles and Anna K. Schweiger
if(interactive()){ # Create a spectra object spec = as_spectra(spec_matrix_example, name_idx = 1) # Start interactive plot plot_interactive(spec) }
if(interactive()){ # Create a spectra object spec = as_spectra(spec_matrix_example, name_idx = 1) # Start interactive plot plot_interactive(spec) }
plot_quantile
plots polygons for the quantiles of spectra per band.
plot_quantile( spec, total_prob = 0.95, col = rgb(0, 0, 0, 0.1), border = TRUE, add = FALSE, na.rm = TRUE, ... )
plot_quantile( spec, total_prob = 0.95, col = rgb(0, 0, 0, 0.1), border = TRUE, add = FALSE, na.rm = TRUE, ... )
spec |
spectra object |
total_prob |
total probability mass to encompass. Single number between 0.0 and 1.0. Defaults to 0.95. |
col |
polygon color |
border |
boolean. Draw border? |
add |
if add = FALSE (default), a new plot is created. Otherwise (add = TRUE), the quantile is added to the current plot. |
na.rm |
boolean. remove NAs to compute quantiles? Defaults to TRUE |
... |
other parameters passed to polygon() or to plot. |
nothing. Called for its side effect.
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) plot_quantile(spec, total_prob = 0.5)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) plot_quantile(spec, total_prob = 0.5)
plot_regions
plots polygons for default (VIS, NIR, SWIR 1, SWIR 2) or customized regions of the spectrum.
plot_regions( spec, regions = default_spec_regions(), col = grDevices::rgb(0.7, 0.7, 0.7, 0.3), border = FALSE, add = TRUE, add_label = TRUE, cex_label = 1, ... )
plot_regions( spec, regions = default_spec_regions(), col = grDevices::rgb(0.7, 0.7, 0.7, 0.3), border = FALSE, add = TRUE, add_label = TRUE, cex_label = 1, ... )
spec |
spectra object |
regions |
matrix with spectral regions in columns and only two rows named "begin" and "end". Values are the bands where a spectral regions begins and ends. See details for how the default regions are defined. |
col |
color for regions. Single value or vector of length ncol (regions). |
border |
color for region borders. Defaults to FALSE (no border). |
add |
boolean. If TRUE (default) adds polygons to current plot (if a plot exists) or throws an error if a plot does not exist. If FALSE, a new plot is created **without** any spectra. |
add_label |
boolean. Add region column names on top of the polygons? |
cex_label |
label scale |
... |
additional parameters passed to polygon(). |
Default regions: spec_regions = cbind("VIS" = c(begin = 400, end = 700), "NIR" = c(begin = 800, end = 1300), "SWIR1" = c(begin = 1550, end = 1800), "SWIR2" = c(begin = 2000, end = 2400)).
nothing. Called for its side effect.
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) plot_regions(spec, default_spec_regions()) plot(spec, add = TRUE) # Alternatively, if you want to get fancy... col_fun = colorRampPalette(c(rgb(1, 1, 0, 0.7),rgb(1, 0, 0, 0.7)), alpha = TRUE) colors = col_fun(4) plot_regions(spec,default_spec_regions(), col = colors) plot(spec, add = TRUE)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) plot_regions(spec, default_spec_regions()) plot(spec, add = TRUE) # Alternatively, if you want to get fancy... col_fun = colorRampPalette(c(rgb(1, 1, 0, 0.7),rgb(1, 0, 0, 0.7)), alpha = TRUE) colors = col_fun(4) plot_regions(spec,default_spec_regions(), col = colors) plot(spec, add = TRUE)
plot
plots spectra.
## S3 method for class 'spectra' plot(x, ylab = "value", xlab = "band", col = "black", lty = 1, type = "l", ...)
## S3 method for class 'spectra' plot(x, ylab = "value", xlab = "band", col = "black", lty = 1, type = "l", ...)
x |
spectra object |
ylab |
label for y axis. Defaults to "value". |
xlab |
label for x axis. Defaults to "band". |
col |
line color. Defaults to "black". |
lty |
line type. Defaults to 1. |
type |
type of plot. Meant to take either line "l" or no plotting "n". |
... |
other arguments passed to matplot. |
nothing. Called for side effect.
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) plot(spec, lwd = 1.2)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) plot(spec, lwd = 1.2)
print
prints basic information about the spectra obj to the console
## S3 method for class 'spectra' print(x, ...)
## S3 method for class 'spectra' print(x, ...)
x |
spectra object |
... |
other arguments passed to print. not implemented for spectra |
nothing. called for side effect
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) print(spec) ## or simply spec
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) print(spec) ## or simply spec
quantile
computes quantiles by band and returns them as 'spectra'.
## S3 method for class 'spectra' quantile( x, probs = c(0.025, 0.25, 0.5, 0.75, 0.975), na.rm = TRUE, names = NULL, ... )
## S3 method for class 'spectra' quantile( x, probs = c(0.025, 0.25, 0.5, 0.75, 0.975), na.rm = TRUE, names = NULL, ... )
x |
spectra object. Must have at least the same number of sample that length(probs) has. |
probs |
Probabilities to compute quantiles. Must be a vector of numerics between 0.0 and 1.0. Defaults to c(0.025, 0.25, 0.5, 0.75, 0.975). Duplicated probs will be removed. |
na.rm |
remove NAs before computing quantiles? Defaults to TRUE |
names |
names for each quantile spectrum. If NULL (default), names are set to 'probs'. A char vector should otherwise be given. Recycled. |
... |
other arguments passed to quantile. |
spectra object with one spectrum for each prob
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) quantile(spec, probs = c(0.25, 0.75))
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) quantile(spec, probs = c(0.25, 0.75))
range
Returns the range of (min, max) values in spectra
## S3 method for class 'spectra' range(..., na.rm = FALSE)
## S3 method for class 'spectra' range(..., na.rm = FALSE)
... |
spectra object |
na.rm |
boolean. remove NAs? Defaults to FALSE |
tuple of numeric values (min, max)
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) range(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) range(spec)
Read files from various formats into 'spectra'
read_spectra( path, format = NULL, type = "target_reflectance", extract_metadata = FALSE, exclude_if_matches = NULL, ignore_extension = FALSE )
read_spectra( path, format = NULL, type = "target_reflectance", extract_metadata = FALSE, exclude_if_matches = NULL, ignore_extension = FALSE )
path |
Path to directory or input files. |
format |
File format. Defaults to NULL so spectrolab tries to guess it from the file name. Alternatively, use "asd" for ASD; "sig" for SVC (Spectra Vista); or "sed" for PSR (Spectral Evolution) |
type |
Data type to read. "target_reflectance", "target_radiance", or "reference_radiance". Defaults to "target_reflectance". |
extract_metadata |
Boolean. Defaults to FALSE. Only implemented for the Spectra Vista (.sig) and Spectral Evolution (.sed) file types. |
exclude_if_matches |
excludes files that match this regular expression. Example: "BAD" |
ignore_extension |
Boolean. If TRUE, the parser will try to read every file in path regardless of the expected extension. |
a single 'spectra' or a list of 'spectra' (in case files have incompatible band number or bands values)
Jose Eduardo Meireles
library(spectrolab) dir_path = system.file("extdata", "Acer_example", package = "spectrolab") spec = read_spectra(path = dir_path, format = "sig")
library(spectrolab) dir_path = system.file("extdata", "Acer_example", package = "spectrolab") spec = read_spectra(path = dir_path, format = "sig")
Resample spectra
resample(spec, new_bands, fwhm)
resample(spec, new_bands, fwhm)
spec |
spectra object |
new_bands |
band values to resample the spectra to |
fwhm |
FWHM for the new bands |
resampled spectra
sd
computes the standard deviation spectrum. Note that values will not
reflect value anymore, but the sd of the value instead.
sd(x, na.rm = FALSE)
sd(x, na.rm = FALSE)
x |
a numeric vector or an R object which is coercible to one by as.double(x) |
na.rm |
logical. Should missing values be removed? |
standard deviation
sd
computes the standard deviation of the values in x. If na.rm is TRUE then missing values are removed before computation proceeds.
## Default S3 method: sd(x, na.rm = FALSE)
## Default S3 method: sd(x, na.rm = FALSE)
x |
a numeric vector or an R object which is coercible to one by as.double(x) |
na.rm |
logical. Should missing values be removed? |
standard deviation of x
x = rnorm(n = 200, mean = 0, sd = 1) sd(x)
x = rnorm(n = 200, mean = 0, sd = 1) sd(x)
Forces keep_txt_meta = TRUE
## S3 method for class 'spectra' sd(x, na.rm = TRUE)
## S3 method for class 'spectra' sd(x, na.rm = TRUE)
x |
spectra |
na.rm |
boolean. remove NAs? |
single spectrum
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) sd(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) sd(spec)
Generic Smoothing function
smooth(x, ...)
smooth(x, ...)
x |
data to smooth over |
... |
additional arguments |
smoothed data
Smooth spectra with a gaussian model
smooth_fwhm(x, fwhm = NULL)
smooth_fwhm(x, fwhm = NULL)
x |
spectra |
fwhm |
Full Width at Half Maximum. |
smoothed spectra
Smooth moving average for spectra
smooth_moving_avg(x, n = NULL, save_bands_to_meta = TRUE)
smooth_moving_avg(x, n = NULL, save_bands_to_meta = TRUE)
x |
spectra object |
n |
= NULL |
save_bands_to_meta |
boolean. keep lost ends of original wvls in metadata |
spectra object
Jose Eduardo Meireles
Gets spline functions for each spectrum in a spectra object.
smooth_spline(x, parallel = TRUE, return_fn = FALSE, ...)
smooth_spline(x, parallel = TRUE, return_fn = FALSE, ...)
x |
spectra object. bands must be strictly increasing |
parallel |
boolean. Do computation in parallel? Defaults to TRUE. Unfortunately, the parallelization does not work on Windows. |
return_fn |
Boolean. If TRUE, |
... |
additional parameters passed to smooth.spline except nknots, which is computed internally |
Smoothed spectra or, if return_fn = TRUE, a list of spline functions.
Jose Eduardo Meireles
Default smoothing function
## Default S3 method: smooth(x, ...)
## Default S3 method: smooth(x, ...)
x |
data to smooth over |
... |
additional arguments |
smoothed data
smooth
runs each spectrum by a smoothing and returns the spectra
## S3 method for class 'spectra' smooth(x, method = "gaussian", ...)
## S3 method for class 'spectra' smooth(x, method = "gaussian", ...)
x |
spectra object. bands must be strictly increasing |
method |
Choose smoothing method: "gaussian" (default), "spline", or "moving_average" |
... |
additional parameters passed to methods |
a spectra object of with smoothed spectra
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec = smooth(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec = smooth(spec)
Simulated spectral dataset as a matrix. First column hold species names and the remaining ones store the spectra values. band labels are given as column names
spec_matrix_example
spec_matrix_example
An object of class matrix
(inherits from array
) with 50 rows and 2102 columns.
Jose Eduardo Meireles
spectra
"manually" creates a spectra object
spectra(value, bands, names, meta = NULL, ...)
spectra(value, bands, names, meta = NULL, ...)
value |
N by M numeric matrix. N samples in rows and M bands in columns |
bands |
band names in vector of length M |
names |
sample names in vector of length N |
meta |
spectra metadata. defaults to NULL. Must be either of length or nrow equals to the number of samples (nrow(value) or length(names)) |
... |
additional arguments to metadata creation. not implemented yet |
spectra object
This function resorts to an ugly hack to deal with metadata assignment. Need to think a little harder to find a solution.
Jose Eduardo Meireles
library(spectrolab) # 1. Create a value matrix. # In this case, by removing the first column that holds the species name rf = spec_matrix_example[ , -1] # (2) Create a vector with band labels that match # the value matrix columns. wl = colnames(rf) # (3) Create a vector with sample labels that match # the value matrix rows. # In this case, use the first colum of spec_matrix_example sn = spec_matrix_example[ , 1] # Finally, construct the spectra object using the `spectra` constructor spec = spectra(value = rf, bands = wl, names = sn)
library(spectrolab) # 1. Create a value matrix. # In this case, by removing the first column that holds the species name rf = spec_matrix_example[ , -1] # (2) Create a vector with band labels that match # the value matrix columns. wl = colnames(rf) # (3) Create a vector with sample labels that match # the value matrix rows. # In this case, use the first colum of spec_matrix_example sn = spec_matrix_example[ , 1] # Finally, construct the spectra object using the `spectra` constructor spec = spectra(value = rf, bands = wl, names = sn)
split
a spectra object into a list of spectra according to grouping f.
## S3 method for class 'spectra' split(x, f, drop = FALSE, ...)
## S3 method for class 'spectra' split(x, f, drop = FALSE, ...)
x |
spectra object |
f |
factor vector defining the grouping. Must have length nrow(x) |
drop |
NOT used |
... |
NOT used |
list of spectra
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec_list = split(spec, names(spec))
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) spec_list = split(spec, names(spec))
Structure of the spectra object
## S3 method for class 'spectra' str(object, ...)
## S3 method for class 'spectra' str(object, ...)
object |
spectra object |
... |
additional args. not implemented |
prints to console
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) str(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) str(spec)
subset_by
subsets spectra by a factor 'by' ensuring that it appears at
most 'n_max' times **and** at least 'n_min' times in the dataset.
subset_by(x, by, n_min, n_max, random = TRUE) ## S3 method for class 'spectra' subset_by(x, by, n_min, n_max, random = TRUE)
subset_by(x, by, n_min, n_max, random = TRUE) ## S3 method for class 'spectra' subset_by(x, by, n_min, n_max, random = TRUE)
x |
spectra object |
by |
vector coercible to factor and of same length as nrow(x) |
n_min |
int. only keep spectra with at least (inclusive) 'n_min' number of samples per unique 'by'. |
n_max |
int. keep at most (incl) this number of spectra per unique 'by' |
random |
boolean. Sample randomly or keep first n_max? Defaults to TRUE |
Note that subset_by
forces you to provide both a minimum and a maximum
number of spectra to be kept for each unique value of ‘by'. In case you’re
interested in subsetting only based on 'n_min', set 'n_max' to 'Inf'.
spectra
subset_by(spectra)
: Subset spectra by factor
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) # remove spec of species with less than 4 samples spec = subset_by(spec, by = names(spec), n_min = 4, n_max = Inf)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) # remove spec of species with less than 4 samples spec = subset_by(spec, by = names(spec), n_min = 4, n_max = Inf)
Summarize spectra
## S3 method for class 'spectra' summary(object, ...)
## S3 method for class 'spectra' summary(object, ...)
object |
spectra object |
... |
additional params to summary. not used yet |
nothing yet (just prints to console)
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) summary(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) summary(spec)
spectra are not transposable. Transpose the value instead
## S3 method for class 'spectra' t(x)
## S3 method for class 'spectra' t(x)
x |
spectra |
No return value. Operation not allowed
Jose Eduardo Meireles
library(spectrolab) s = as_spectra(spec_matrix_example, name_idx = 1) t(value(s)) t(as.matrix(s))
library(spectrolab) s = as_spectra(spec_matrix_example, name_idx = 1) t(value(s)) t(as.matrix(s))
Function operator returning a function f that tries to keep text.
try_keep_txt(f)
try_keep_txt(f)
f |
function to be applied |
try_keep_txt
takes a function f as argument, typically a mathematical
operation such as mean, median, etc. and returns a modified version of it that
will try return a string of unique values in case function f emits a warning.
Useful when aggregating over spectral metadata that has both numeric values
(which you want to aggregate) and text values, which you want to keep.
modified function f (f').
Jose Eduardo Meireles
library(spectrolab) g = try_keep_txt(mean) g(c(1, 2)) g(c("a", "b"))
library(spectrolab) g = try_keep_txt(mean) g(c(1, 2)) g(c("a", "b"))
value
returns the value matrix from spectra
value(x) ## S3 method for class 'spectra' value(x)
value(x) ## S3 method for class 'spectra' value(x)
x |
spectra object |
matrix with samples in rows and bands in columns
value(spectra)
: Get spectra value
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) is.matrix(value(spec))
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) is.matrix(value(spec))
value<-
Assigns the rhs to the value of the lhs spectra obj
value(x) <- value
value(x) <- value
x |
spectra object |
value |
value to be assigned to the lhs |
nothing. called for its side effect
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) # scale all refletance values by 2 value(spec) = value(spec) * 2
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) # scale all refletance values by 2 value(spec) = value(spec) * 2
var
computes the variance spectrum. Note that values will not reflect
value anymore, but the variance of the value instead.
var(x, y = NULL, na.rm = FALSE, use)
var(x, y = NULL, na.rm = FALSE, use)
x |
a numeric vector, matrix or data frame |
y |
NULL (default) or a vector, matrix or data frame with compatible dimensions to x. |
na.rm |
logical. Should missing values be removed? |
use |
an optional character string giving a method for computing covariances in the presence of missing values. This must be (an abbreviation of) one of the strings "everything", "all.obs", "complete.obs", "na.or.complete", or "pairwise.complete.obs" |
variance
var
computes the variance spectrum. Note that values will not reflect
value anymore, but the variance of the value instead.
## Default S3 method: var(x, y = NULL, na.rm = FALSE, use)
## Default S3 method: var(x, y = NULL, na.rm = FALSE, use)
x |
a numeric vector, matrix or data frame |
y |
NULL (default) or a vector, matrix or data frame with compatible dimensions to x. |
na.rm |
logical. Should missing values be removed? |
use |
an optional character string giving a method for computing covariances in the presence of missing values. This must be (an abbreviation of) one of the strings "everything", "all.obs", "complete.obs", "na.or.complete", or "pairwise.complete.obs" |
variance
Forces keep_txt_meta = TRUE
## S3 method for class 'spectra' var(x, y = NULL, na.rm = TRUE, use)
## S3 method for class 'spectra' var(x, y = NULL, na.rm = TRUE, use)
x |
spectra |
y |
nothing |
na.rm |
boolean. remove NAs? |
use |
nothing |
single spectrum
Jose Eduardo Meireles
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) var(spec)
library(spectrolab) spec = as_spectra(spec_matrix_example, name_idx = 1) var(spec)