R/export_nest.R

Defines functions export_nest

Documented in export_nest

# WARNING - Generated by {fusen} from dev/flat_import_export.Rmd: do not edit by hand # nolint: line_length_linter.

#' Export Nested Data Structures with Hierarchical Directory Organization
#'
#' @description
#' Exports list-columns containing \code{data.frame} or \code{data.table} objects from a
#' \code{data.frame}/\code{data.table} to \code{txt} or \code{csv} files, automatically
#' constructing a hierarchical directory structure from non-nested columns.
#' Exportable nested columns (those holding \code{data.frame}/\code{data.table} elements)
#' are distinguished from non-exportable custom-object columns (e.g. fitted model
#' objects); only the former are written to disk by default.
#'
#' @param data        A \code{data.frame} or \code{data.table} containing at least one
#'   nested list-column. Must have one or more rows.
#' @param by          Optional character vector of column names used to build the
#'   hierarchical output directory structure. When \code{NULL} (default), all non-nested
#'   columns are used automatically.
#' @param cols        Optional character vector of nested column names to export. When
#'   \code{NULL} (default), all columns whose elements are \code{data.frame}/\code{data.table}
#'   objects are exported automatically; custom-object list-columns are reported and skipped.
#'   Specifying a non-\code{data.frame} column triggers a warning and that column is skipped.
#' @param path        Single character string specifying the root export directory.
#'   Defaults to \code{tempdir()}. Created recursively if it does not exist.
#' @param file_type   Either \code{"txt"} (tab-separated, default) or \code{"csv"}
#'   (comma-separated). Case-insensitive.
#' @param na          Single string written for missing values. Default \code{"NA"}
#'   (\code{fwrite}'s own default, an empty field, breaks whitespace-delimited
#'   readers). Use e.g. \code{"-9999"} for DMU.
#' @param quote       Passed to \code{\link[data.table]{fwrite}}. Default
#'   \code{FALSE}: with a non-empty \code{na}, \code{fwrite}'s \code{"auto"}
#'   would quote every header and character field, which command-line
#'   breeding programs (HIBLUP, DMU, ...) cannot parse. Use \code{"auto"} if
#'   values may contain the separator.
#' @param ...         Further arguments passed to \code{\link[data.table]{fwrite}}
#'   (e.g. \code{col.names = FALSE} for software that expects no header).
#'
#' @return An invisible \code{character} vector of the files written
#'   (length 0 when nothing was written).
#'
#' @details
#' **Nested column classification (mutually exclusive):**
#' \itemize{
#'   \item \emph{Exportable} — every element inherits from \code{data.frame} or \code{data.table}.
#'   \item \emph{Non-exportable} — empty lists or elements of any other class
#'     (e.g. model objects). Reported to the console; never written.
#' }
#'
#' **Directory layout:**
#' \code{path / <group1_value> / <group2_value> / <nest_col_name>.<file_type>}
#'
#' Group values are sanitised (characters that are invalid in file names,
#' such as slashes, colons or asterisks, become underscores), so they can
#' never create extra directory levels. The
#' grouping columns must identify every row uniquely; otherwise rows would
#' overwrite each other's files and the function stops with an error listing
#' the duplicated targets.
#'
#' **Performance notes:**
#' \itemize{
#'   \item Row data is accessed via \code{.subset2()} (zero-copy column access) rather than
#'     \code{data[i]}, eliminating per-row \code{data.table} allocation in the hot loop.
#'   \item All output directory paths are pre-computed in a single vectorised
#'     \code{do.call(file.path, ...)} call; only the unique directories are created.
#'   \item The field separator and output filenames are computed once before the loop.
#' }
#'
#' @seealso \code{\link[data.table]{fwrite}}
#'
#' @importFrom data.table is.data.table as.data.table fwrite
#' @export
#' @examples
#' # Example: Basic nested data export workflow
#' # A dedicated sub-folder of tempdir() keeps the clean-up safe
#' out_dir <- file.path(tempdir(), "mintyr_export_nest")
#'
#' # Step 1: Create nested data structure
#' dt_nest <- w2l_nest(
#'   data = iris,              # Input iris dataset
#'   cols = 1:2,               # Columns to be nested
#'   by = "Species"            # Grouping variable
#' )
#'
#' # Step 2: Export nested data to files
#' files <- export_nest(
#'   data = dt_nest,                    # Input nested data.table
#'   cols = "data",                     # Column containing nested data
#'   by = c("name", "Species"),         # Columns to create directory structure
#'   path = out_dir
#' )
#' # Returns (invisibly) the paths of the written files
#' # Directory structure: out_dir/<name>/<Species>/data.txt
#' files
#'
#' # Clean up
#' unlink(out_dir, recursive = TRUE)
export_nest <- function(data,
                        by        = NULL,
                        cols      = NULL,
                        path      = tempdir(),
                        file_type = "txt",
                        na        = "NA",
                        quote     = FALSE,
                        ...) {
  # Internally the long, explicit names are used for readability.
  nest_dt     <- data
  group_cols  <- by
  nest_cols   <- cols
  export_path <- path

  # -- 1. Validation (fail fast) ------------------------------------------------
  if (!is.data.frame(nest_dt))
    stop("`data` must be a data.frame or data.table.", call. = FALSE)
  if (!data.table::is.data.table(nest_dt))
    nest_dt <- data.table::as.data.table(nest_dt)
  if (nrow(nest_dt) == 0L)
    stop("`data` must not be empty (nrow == 0).", call. = FALSE)
  if (!is.character(export_path) || length(export_path) != 1L || is.na(export_path))
    stop("`path` must be a single non-NA character string.", call. = FALSE)
  if (!is.character(na) || length(na) != 1L || is.na(na))
    stop("`na` must be a single character string, e.g. \"NA\" or \"-9999\".",
         call. = FALSE)
  file_type <- .check_choice(tolower(trimws(file_type)), c("txt", "csv"), "file_type")
  sep  <- if (file_type == "txt") "\t" else ","
  dots <- list(...)
  .check_fwrite_dots(dots, "export_nest")

  # -- 2. Classify list-columns -------------------------------------------------
  .is_df_list_col <- function(x) {
    if (!is.list(x) || length(x) == 0L) return(FALSE)
    all(vapply(x, function(e) is.null(e) || is.data.frame(e), logical(1L))) &&
      any(vapply(x, is.data.frame, logical(1L)))
  }
  all_list_cols <- names(nest_dt)[vapply(nest_dt, is.list, logical(1L))]
  if (length(all_list_cols) == 0L)
    stop("`data` contains no list-columns (nested columns).", call. = FALSE)
  df_nested_cols  <- all_list_cols[vapply(nest_dt[, all_list_cols, with = FALSE],
                                          .is_df_list_col, logical(1L))]
  other_list_cols <- setdiff(all_list_cols, df_nested_cols)

  # -- 3. Resolve nested columns to export -------------------------------------
  if (is.null(nest_cols)) {
    if (length(df_nested_cols) == 0L)
      stop("No data.frame/data.table nested columns found. Specify `cols` ",
           "explicitly or convert list-column elements first.", call. = FALSE)
    nest_cols <- df_nested_cols
    message("[ export_nest ] Auto-selected nested columns: ",
            paste(nest_cols, collapse = ", "))
    if (length(other_list_cols) > 0L)
      message("[ export_nest ] Skipping columns holding custom objects ",
              "(cannot be written as txt/csv): ",
              paste(other_list_cols, collapse = ", "))
  } else {
    if (!is.character(nest_cols) || length(nest_cols) == 0L)
      stop("`cols` must be a non-empty character vector.", call. = FALSE)
    invalid_cols <- setdiff(nest_cols, names(nest_dt))
    if (length(invalid_cols) > 0L)
      stop("Column(s) in `cols` not found in `data`: ",
           paste(invalid_cols, collapse = ", "), call. = FALSE)
    non_df_cols <- setdiff(nest_cols, df_nested_cols)
    if (length(non_df_cols) > 0L) {
      warning("Column(s) not holding data.frame/data.table objects will be skipped: ",
              paste(non_df_cols, collapse = ", "), call. = FALSE)
      nest_cols <- intersect(nest_cols, df_nested_cols)
    }
    if (length(nest_cols) == 0L)
      stop("No valid data.frame/data.table columns remain after filtering.",
           call. = FALSE)
  }

  # -- 4. Resolve grouping columns ----------------------------------------------
  if (is.null(group_cols)) {
    group_cols <- setdiff(names(nest_dt), all_list_cols)
    message("[ export_nest ] ",
            if (length(group_cols)) paste0("Auto-selected grouping columns: ",
                                           paste(group_cols, collapse = ", "))
            else "No grouping columns found; writing to the root export path.")
  } else {
    if (!is.character(group_cols) || length(group_cols) == 0L)
      stop("`by` must be a non-empty character vector (or NULL).", call. = FALSE)
    missing_cols <- setdiff(group_cols, names(nest_dt))
    if (length(missing_cols) > 0L)
      stop("Column(s) in `by` not found in `data`: ",
           paste(missing_cols, collapse = ", "), call. = FALSE)
    bad_type <- intersect(group_cols, all_list_cols)
    if (length(bad_type) > 0L)
      stop("`by` must not contain list-columns: ",
           paste(bad_type, collapse = ", "), call. = FALSE)
  }

  # -- 5. Directory paths (vectorised, sanitised) -------------------------------
  # Group values are sanitised so that "/", "..", ":" etc. can never create
  # unexpected directory levels or invalid file names.
  if (length(group_cols) > 0L) {
    segs <- lapply(nest_dt[, group_cols, with = FALSE], .safe_path_segment)
    group_paths <- do.call(file.path, c(list(export_path), unname(segs)))
  } else {
    group_paths <- rep(export_path, nrow(nest_dt))
  }

  # Each row writes <dir>/<nest_col>.<ext>; identical directories would make
  # rows overwrite each other's files, so this is an error, not a silent loss.
  # The comparison is case-insensitive because Windows/macOS file systems are.
  dup <- duplicated(tolower(group_paths))
  if (any(dup))
    stop("`by` (", if (length(group_cols)) paste(group_cols, collapse = ", ")
         else "none", ") do not uniquely identify the rows of `data`, so files ",
         "would overwrite each other. Duplicated target(s):\n  ",
         paste(utils::head(unique(group_paths[dup]), 5L), collapse = "\n  "),
         "\nAdd more columns to `by`.", call. = FALSE)

  for (d in unique(group_paths)) dir.create(d, showWarnings = FALSE, recursive = TRUE)
  not_created <- unique(group_paths)[!dir.exists(unique(group_paths))]
  if (length(not_created) > 0L)
    stop("Could not create directory/directories:\n  ",
         paste(not_created, collapse = "\n  "), call. = FALSE)

  # -- 6. Write ---------------------------------------------------------------
  filenames <- stats::setNames(paste0(.safe_path_segment(nest_cols), ".", file_type),
                               nest_cols)
  written <- character(0L)

  for (i in seq_len(nrow(nest_dt))) {
    for (col_name in nest_cols) {
      elem <- .subset2(nest_dt, col_name)[[i]]          # zero-copy access
      if (is.null(elem) || nrow(elem) == 0L) next       # nothing to write
      file_path <- file.path(group_paths[i], filenames[[col_name]])
      ok <- tryCatch({
        do.call(data.table::fwrite,
                c(list(x = elem, file = file_path, sep = sep, na = na, quote = quote),
                  dots))
        TRUE
      }, error = function(e) {
        warning(sprintf("[ export_nest ] Failed to export column '%s' at row %d: %s",
                        col_name, i, conditionMessage(e)), call. = FALSE)
        FALSE
      })
      if (ok) written <- c(written, file_path)
    }
  }

  message(sprintf("[ export_nest ] Export complete. %d file(s) written to: %s",
                  length(written), export_path))
  invisible(written)
}

Try the mintyr package in your browser

Any scripts or data that you put into this service are public.

mintyr documentation built on Nov. 9, 2026, 5:07 p.m.