Learn R Programming

spectrakit (version 0.1.2)

combineSpectra: Combine and Normalize Spectral Data from Multiple Files

Description

Reads spectral data from multiple files in a folder, merges them by a common column (e.g., wavelength), optionally filters by a range, applies normalization and returns the data in either row-wise or column-wise format.

Usage

combineSpectra(
  folder = ".",
  file_type = "csv",
  sep = ",",
  header = TRUE,
  common_col_pos = 1,
  data_col_pos = 2,
  range = NULL,
  normalization = c("none", "simple", "min-max", "z-score"),
  orientation = c("columns", "rows")
)

Value

A `tibble` that can be exported as, for example, a CSV file. Each spectrum is either a column (default) or row, depending on `orientation`; a sum or mean spectrum can optionally be computed using `rowSums()` or `colSums()`, or `rowMeans()` or `colMeans()`, respectively. The common column (e.g., wavelength) is retained.

Arguments

folder

Character. Path to the folder containing spectral files. Default is working directory (`"."`).

file_type

Character. File extension (without dot) to search for. Default is `"csv"`.

sep

Character. Delimiter for file columns. Use `","` for comma-separated (default) or `"\t"` for tab-delimited files.

header

Logical. Whether the files contain a header row. Default is `TRUE`.

common_col_pos

Integer. Column position for the common variable (e.g., wavelength). Defaults to `1`.

data_col_pos

Integer. Column position for the spectral intensity values. Defaults to `2`.

range

Numeric vector of length 2. Optional range filter for the common column (e.g., wavelength limits). Defaults to `NULL` (no filtering).

normalization

Character. Normalization method to apply to spectra. One of `"none"`, `"simple"` (divide by max), `"min-max"`, or `"z-score"`. Default is `"none"`.

orientation

Character. Output orientation. Use `"columns"` (default) to keep each spectrum as a column, or `"rows"` to transpose so each spectrum is a row.

Examples

Run this code
# Create a temporary directory for mock CSV files
tmp_dir <- tempdir()

# Define file paths
tmp1 <- file.path(tmp_dir, "file1.csv")
tmp2 <- file.path(tmp_dir, "file2.csv")

# Write two mock CSV files in the temporary folder
write.csv(data.frame(ID = c("A", "B", "C"), val = c(1, 2, 3)), tmp1, row.names = FALSE)
write.csv(data.frame(ID = c("A", "B", "C"), val = c(4, 5, 6)), tmp2, row.names = FALSE)

# Merge the CSV files in the temporary folder, normalize with z-score, and return transposed
result <- combineSpectra(
  folder = tmp_dir,
  file_type = "csv",
  sep = ",",
  common_col_pos = 1,
  data_col_pos = 2,
  normalization = "z-score",
  orientation = "rows"
)

Run the code above in your browser using DataLab