R/nest_cv.R

Defines functions nest_cv

Documented in nest_cv

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

#' Apply V-Fold Cross-Validation to Nested Data
#'
#' @description
#' `nest_cv` creates v-fold cross-validation splits for each nested data frame
#' of a nested `data.table` (e.g. the output of [w2l_nest()]) and returns one
#' row per fold, with the outer (non-nested) columns broadcast to every fold.
#' The cross-validation itself is performed by [split_cv()].
#'
#' @param data    A `data.frame` or `data.table` containing at least one nested
#'   `data.frame`/`data.table` column. A column named `data` is used if
#'   present, otherwise the first nested column.
#' @inheritParams split_cv
#'
#' @return A `data.table` with all non-nested columns of `data`, followed by
#'   the columns described in [split_cv()] (`id`, `id2`, `train_idx`,
#'   `validate_idx` and, if `materialize = TRUE`, `train` / `validate`, whose
#'   class follows `out_type`).
#'   Other nested columns are dropped (a message lists them).
#'
#' @seealso [split_cv()]
#'
#' @import data.table
#' @export
#' @examples
#' # Example: Cross-validation for nested data.table demonstrations
#'
#' # Setup test data
#' dt_nest <- w2l_nest(
#'   data = iris,                   # Input dataset
#'   cols = 1:2                     # Nest first 2 columns
#' )
#'
#' # Example 1: Basic 2-fold cross-validation (reproducible)
#' nest_cv(
#'   data = dt_nest,                # Input nested data.table
#'   v = 2,                         # Number of folds (2-fold CV)
#'   seed = 123                     # Reproducible folds
#' )
#'
#' # Example 2: Repeated 2-fold CV, keeping only the split objects
#' nest_cv(
#'   data = dt_nest,                # Input nested data.table
#'   v = 2,                         # Number of folds (2-fold CV)
#'   repeats = 2,                   # Number of repetitions
#'   seed = 123,
#'   materialize = FALSE            # No train/validate copies (saves memory)
#' )
#'
#' # Example 3: data.frame subsets, ready for ASReml-R / lm() / glm()
#' cv_df <- nest_cv(dt_nest, v = 2, seed = 123, out_type = "df")
#' class(cv_df$train[[1]])        # "data.frame"
#'
#' # Example 4: masking-style CV (keep all rows, hide validation phenotypes)
#' cv_idx <- nest_cv(dt_nest, v = 2, seed = 123, materialize = FALSE)
#' cv_idx[dt_nest, on = "name", full := i.data]   # attach the full nested table
#' masked <- as.data.frame(cv_idx$full[[1]])      # a copy: dt_nest stays intact
#' masked$value[cv_idx$validate_idx[[1]]] <- NA
#' sum(is.na(masked$value))       # validation records to be predicted
nest_cv <- function(data,
                    v           = 10L,
                    repeats     = 1L,
                    strata      = NULL,
                    breaks      = 4L,
                    pool        = 0.1,
                    seed        = NULL,
                    materialize = TRUE,
                    out_type    = "dt") {
  nest_dt <- data

  # -- 1. Input validation ----------------------------------------------------
  if (!is.data.frame(nest_dt))
    stop("`data` must be a data.frame or data.table. Received: ",
         paste(class(nest_dt), collapse = "/"), call. = FALSE)
  if (nrow(nest_dt) == 0L)
    stop("`data` must not be empty (0 rows).", call. = FALSE)

  # -- 2. Identify nested columns ----------------------------------------------
  nested_cols <- names(nest_dt)[vapply(nest_dt, function(col) {
    is.list(col) && length(col) > 0L &&
      all(vapply(col, is.data.frame, logical(1L)))
  }, logical(1L))]

  if (length(nested_cols) == 0L)
    stop("`data` contains no nested data.frame/data.table columns.\n",
         "  Column types detected: ",
         paste(names(nest_dt),
               vapply(nest_dt, function(x) class(x)[1L], character(1L)),
               sep = "=", collapse = ", "), call. = FALSE)

  target_col <- if ("data" %in% nested_cols) "data" else nested_cols[1L]
  if (target_col != "data")
    message("[nest_cv] No nested column named 'data' found. Using '", target_col,
            "' instead.\n          Available nested columns: ",
            paste(nested_cols, collapse = ", "))
  if (length(nested_cols) > 1L)
    message("[nest_cv] Only '", target_col, "' is split; other nested column(s) ",
            "are dropped from the result: ",
            paste(setdiff(nested_cols, target_col), collapse = ", "))

  dt <- if (data.table::is.data.table(nest_dt)) nest_dt else data.table::as.data.table(nest_dt)
  non_nested_cols <- setdiff(names(dt), nested_cols)

  # -- 3. Delegate the CV work to split_cv() (single implementation) ----------
  cv_list <- split_cv(
    data        = dt[[target_col]],
    v           = v,
    repeats     = repeats,
    strata      = strata,
    breaks      = breaks,
    pool        = pool,
    seed        = seed,
    materialize = materialize,
    out_type    = out_type
  )

  # -- 4. Broadcast each row's metadata across its CV rows and bind ------------
  cv_dt <- data.table::rbindlist(cv_list, use.names = TRUE)
  if (length(non_nested_cols) == 0L) return(cv_dt)

  n_cv <- vapply(cv_list, nrow, integer(1L))
  meta <- dt[rep(seq_len(nrow(dt)), n_cv), non_nested_cols, with = FALSE]
  cbind(meta, cv_dt)
}

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.