R/export.R

Defines functions iso_export_data_to_excel iso_export_calibration_to_excel

Documented in iso_export_calibration_to_excel iso_export_data_to_excel

#' Export calibration to Excel
#'
#' This function exports the passed in calibration(s) data frame to Excel. The different kinds of information (all data, model coefficients, summary, evaluation range) are exported to separate tabs within the excel file. If there are multiple different calibrations in the data frame (i.e. multiple \code{*calib_params} columns), ALL will be exported with different tabs for each.
#'
#' @param calibs_df data frame that includes calibration columns (i.e. the output of functions like \link{iso_generate_calibration}, \link{iso_apply_calibration}, \link{iso_evaluate_calibration_range}). Can be the output from \link{iso_get_calibration_data} if called after a calibration has been generated.
#' @param filepath the path where to store the Excel file.
#' @param ... named list of additional data frames to include in the summary (each will get their own tab)
#' @param include_all_data whether to include a tab for all the peak data - if this function is called after \link{iso_apply_calibration} this will include
#' @param include_calib_coefs whether to include a tab for the model coefficients
#' @param include_calib_summary whether to include a tab for the model summary
#' @param include_calib_range whether to include a tab for the evaluation range (if available, i.e. generated by \link{iso_evaluate_calibration_range})
#' @param with_explicit_units whether to include units in all column names
#' @return returns the \code{calib} object invisibly for use in pipelines
#' @export
iso_export_calibration_to_excel <- function(
  calibs_df, filepath, ...,
  include_all_data = TRUE, include_calib_coefs = TRUE,
  include_calib_summary = TRUE, include_calib_range = TRUE,
  with_explicit_units = TRUE,
  quiet = default(quiet)) {

  # safety checks
  if(missing(calibs_df) || !is.data.frame(calibs_df)) stop("calibs_df must be a data frame", call. = FALSE)
  if(!"all_data" %in% names(calibs_df)) {
    # requires nesting
    calibs_df <- iso_prepare_for_calibration(calibs_df, quiet = TRUE)
  }
  if(!is.list(calibs_df$all_data)) stop("all_data column is not a list, make sure this is still a nested calibration data frame (i.e. the direct output of iso_generate_calibration, iso_apply_calibration, or iso_evaluate_calibration_range", call. = FALSE)
  calibs <- all_calibrations(calibs_df)
  if (length(calibs) == 0) stop("there do not seem to be any calibrations in this data frame, make sure to generate calibrations using iso_generate_calibration", call. = FALSE)

  # explicit units
  with_units <- function(x) {
    if (with_explicit_units) iso_make_units_explicit(x)
    else x
  }

  # additional data
  add_data <- list(...)
  if (is.null(names(add_data)) || any(names(add_data) == ""))
    stop("additional data (...) must be named data frames", call. = FALSE)

  # path
  filepath <- isoreader:::get_export_filepath(filepath, ".xlsx")

  # info
  if (!quiet) {
    glue::glue("Info: exporting calibrations into Excel '{basename(filepath)}'... ") %>%
      message()
  }

  # make excel workbook
  wb <- openxlsx::createWorkbook()
  ws_names <- c()

  # additional data
  if (length(add_data) > 0) {
    for (tab in names(add_data)) {
      ws_names <- c(ws_names, tab)
      isoreader:::add_excel_sheet(wb, tail(ws_names, 1), with_units(add_data[[tab]]))
    }
  }

  # all data
  if (include_all_data) {
    ws_names <- c(ws_names, "all data")
    all_data <- calibs_df %>% iso_get_calibration_data(keep_calibration_parameters = FALSE, quiet = quiet)
    isoreader:::add_excel_sheet(wb, tail(ws_names, 1), with_units(all_data))
  }

  # all calibs
  for(calib in calibs) {

    calib_vars <- get_calibration_vars(calib)

    # model coefs
    if (include_calib_coefs) {
      ws_names <- c(ws_names, if (calib == "") "calib coefs" else paste(calib, "coefs"))
      calib_coefs <- calibs_df %>% iso_get_calibration_coefficients(calibration = calib, quiet = quiet)
      isoreader:::add_excel_sheet(wb, tail(ws_names, 1), calib_coefs)
    }

    # model summary
    if (include_calib_summary) {
      ws_names <- c(ws_names, if (calib == "") "calib summary" else paste(calib, "summary"))
      calib_summary <- calibs_df %>% iso_get_calibration_summary(calibration = calib)
      isoreader:::add_excel_sheet(wb, tail(ws_names, 1), calib_summary)
    }

    # model range
    if (include_calib_range && has_model_range(calibs_df, calibration = calib)) {
      ws_names <- c(ws_names, if (calib == "") "calib range" else paste(calib, "range"))
      calib_range <- calibs_df %>% iso_get_calibration_range(calibration = calib, quiet = quiet)
      isoreader:::add_excel_sheet(wb, tail(ws_names, 1), calib_range)
    }
  }

  openxlsx::saveWorkbook(wb, filepath, overwrite = TRUE)

  # info
  if (!quiet) {
    glue::glue("Info: export complete, created tabs '{glue::glue_collapse(ws_names, sep = \"', '\", last = \"' and '\")}'.") %>%
      message()
  }

  return(invisible(calibs_df))
}


#' Export data to Excel
#'
#' This is a convenience function to export data to Excel. Use \link{iso_export_calibration_to_excel} for a more specific export function for isoprocessor calibrations.
#'
#' @param filepath the path where to store the Excel file.
#' @param ... named list of data frames (each will get its own tab)
#' @param with_explicit_units whether to include units in all column names
#' @export
iso_export_data_to_excel <- function(..., filepath, with_explicit_units = TRUE, quiet = default(quiet)) {

  # safety checks
  if (missing(filepath)) {
    stop("'filepath' parameter must be set", call. = FALSE)
  }

  # data sets
  datasets <- list(...)
  if (length(datasets) == 0)
    stop("no data sets provided", call. = FALSE)

  if (!all(purrr::map_lgl(datasets, is.data.frame)))
    stop("data sets must be provided as data frames", call. = FALSE)

  if (is.null(names(datasets)))
    names(datasets) <- paste0("Sheet", seq_along(datasets))
  if (any(no_names <- names(datasets) == ""))
    names(datasets)[no_names] <- paste0("Sheet", seq_along(no_names))

   # explicit units
  with_units <- function(x) {
    if (with_explicit_units) iso_make_units_explicit(x)
    else iso_strip_units(x)
  }

  # path
  filepath <- isoreader:::get_export_filepath(filepath, ".xlsx")

  # info
  if (!quiet) {
    glue::glue(
      "Info: exporting datasets '",
      glue::glue_collapse(names(datasets), sep = "', '", last = "' and '"),
      "' into Excel file '{basename(filepath)}'... "
    ) %>% message(appendLF = FALSE)
  }

  # make excel workbook
  wb <- openxlsx::createWorkbook()

  # additional data
  for (tab in names(datasets)) {
    isoreader:::add_excel_sheet(wb, tab, with_units(datasets[[tab]]))
  }

  # write save workbook
  openxlsx::saveWorkbook(wb, filepath, overwrite = TRUE)

  # info
  if (!quiet) {
    message("finished.")
  }

  return(invisible(NULL))
}
KopfLab/isoprocessorCUB documentation built on Nov. 8, 2021, 9:54 a.m.