From c81fa8357461b38b8e3b59d977b686797a01c026 Mon Sep 17 00:00:00 2001 From: "Win Cowger, PhD" Date: Thu, 4 Jan 2024 14:08:54 -0800 Subject: [PATCH] add csv writing. --- R/io_spec.R | 17 +++++++++++++++-- R/read_ext.R | 20 ++++++++++++++++---- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/R/io_spec.R b/R/io_spec.R index 278740bb..52b9e0ea 100644 --- a/R/io_spec.R +++ b/R/io_spec.R @@ -41,6 +41,7 @@ #' write_spec(raman_hdpe, "raman_hdpe.yml") #' write_spec(raman_hdpe, "raman_hdpe.json") #' write_spec(raman_hdpe, "raman_hdpe.rds") +#' write_spec(raman_hdpe, "raman_hdpe.csv") #' #' # Convert an OpenSpecy object to a hyperSpec object #' hyper <- as_hyperSpec(raman_hdpe) @@ -61,7 +62,7 @@ #' #' @importFrom yaml write_yaml read_yaml #' @importFrom jsonlite write_json read_json -#' @importFrom data.table as.data.table +#' @importFrom data.table as.data.table fwrite #' #' @export write_spec <- function(x, ...) { @@ -88,7 +89,19 @@ write_spec.OpenSpecy <- function(x, file, method = NULL, write_json(x, path = file, dataframe = "columns", digits = digits, ...) } else if (grepl("\\.rds$", file, ignore.case = T)) { saveRDS(x, file = file, ...) - } else { + } + else if (grepl("\\.csv$", file, ignore.case = T)){ + wave_names <- round(x$wavenumber, 0) + + spectra <- t(x$spectra) + + colnames(spectra) <- wave_names + + flat_specy <- cbind(spectra, x$metadata) + + fwrite(flat_specy, file = file) + } + else { stop("unknown file type: specify a method to write custom formats or ", "provide one of the supported .yml, .json, or .rds formats as ", "file extension", call. = F) diff --git a/R/read_ext.R b/R/read_ext.R index 4602cf39..3c6b6d35 100644 --- a/R/read_ext.R +++ b/R/read_ext.R @@ -53,7 +53,7 @@ #' \code{\link{read_zip}()} and \code{\link{read_any}()} for wrapper functions; #' \code{\link[hyperSpec]{read.jdx}()}; \code{\link[hyperSpec]{read.spc}()} #' -#' @importFrom data.table data.table as.data.table fread +#' @importFrom data.table data.table as.data.table fread transpose #' @export read_text <- function(file, colnames = NULL, method = "fread", share = NULL, @@ -91,9 +91,21 @@ read_text <- function(file, colnames = NULL, method = "fread", "use 'header = FALSE' or an ", "alternative read method", call. = F) - - os <- as_OpenSpecy(dt, colnames = colnames, metadata = metadata, - session_id = T) + if(sum(grepl("^[0-9]{1,}$",colnames(dt))) > 4){ + wavenumbers <- colnames(dt)[grepl("^[0-9]{1,}$",colnames(dt))] + + spectra <- transpose(dt[,..wavenumbers]) + + metadata_names <- colnames(dt)[!grepl("^[0-9]{1,}$",colnames(dt))] + + metadata <- dt[,..metadata_names] + + os <- as_OpenSpecy(as.numeric(wavenumbers), spectra = spectra, metadata = metadata) + } + else{ + os <- as_OpenSpecy(dt, colnames = colnames, metadata = metadata, + session_id = T) + } if (!is.null(share)) share_spec(os, file = file, share = share)