R/standardize_data.R

Defines functions standardize_data

Documented in standardize_data

#' Standardise a raw survival / proportion dataset for the TDT function library
#'
#' Rewrites user column names into the common data schema used by `fit_4pl()`
#' and the TDT compatibility helpers. Direct `fit_tls()` column and `tls_bf()`
#' formula fits can use a data frame without this conversion; supply durations
#' in minutes for those interfaces.
#'
#' Two response types are supported:
#'
#' - **Count data** (binomial / beta-binomial): supply `n_total` plus **exactly
#'   one** of `n_surv`, `n_dead`, `survival`, or `mortality`. The other counts
#'   are derived and the standardised columns include `n_total`, `n_surv`,
#'   `n_dead`, `survival`. `response_type` is recorded as `"count"`.
#' - **Continuous proportion** (Beta), e.g. a chlorophyll-fluorescence
#'   \eqn{F_v/F_m} ratio with no denominator: supply `proportion` and omit the
#'   count arguments. The value is stored in `survival`; without censoring,
#'   values are clamped into `(proportion_eps, 1 - proportion_eps)`. For explicit
#'   left-censored measurements, provide both censoring columns below. Their
#'   placeholders and exact interior proportions are retained; exact boundary
#'   values are clamped only when this keeps them above their detection limit.
#'   A warning reports affected rows whenever values are changed; no
#'   `n_total`/`n_surv` columns are created. `response_type`
#'   is recorded as `"proportion"`.
#'
#' If the dataset spans multiple categories (life stages, species, populations,
#' etc.), retain the grouping column. Use `fit_4pl(by = "group")` or grouped
#' formulas in [tls_bf()] to estimate category-level effects, or filter first
#' when separate models are scientifically preferable.
#'
#' @param data           Raw data frame or tibble.
#' @param temp           Column name of the assay temperature (°C).
#' @param duration       Column name of the exposure duration. Supply its source
#'                       unit with `duration_unit`; `standardize_data()`
#'                       converts the values to minutes.
#' @param n_total        Column name for total individuals per replicate.
#'                       Required for count responses; leave `NULL` (default)
#'                       for a continuous `proportion` response.
#' @param n_surv         Column name for survivor counts.
#' @param n_dead         Column name for death counts. Converted to `n_surv`
#'                       via `n_surv = n_total - n_dead`.
#' @param survival       Column name for survival proportions in `[0, 1]`.
#'                       Converted to integer counts via `n_total`.
#' @param mortality      Column name for mortality proportions in `[0, 1]`.
#'                       Converted to `n_surv = round((1 - mortality) * n_total)`.
#' @param proportion     Column name for a continuous proportion response in
#'                       `[0, 1]` with no denominator (modelled with a Beta
#'                       likelihood). Mutually exclusive with the count
#'                       arguments above.
#' @param proportion_eps Boundary clamp applied to exact `proportion` values so
#'                       they sit strictly inside `(0, 1)` (the Beta density is
#'                       undefined at exactly 0 or 1). With censoring columns,
#'                       exact interior values and flagged placeholders are
#'                       preserved, and an upper-boundary clamp must remain at
#'                       or above its detection limit. Must be one finite value
#'                       in `(0, 0.5)`. Default `0.001`.
#' @param left_censored Optional column name containing non-missing logical
#'                       indicators for measurements known only to lie below a
#'                       detection limit. Must be paired with `censor_limit`;
#'                       zero values are not inferred to be censored. An exact
#'                       response below its declared limit is an error before
#'                       boundary clamping; an exact value equal to its limit
#'                       is allowed.
#' @param censor_limit Optional numeric column name with one lower detection
#'                       limit per observation. Values must be finite and
#'                       strictly inside `(0, 1)`.
#' @param random_effects Optional character vector of grouping variables for
#'                       random effects, e.g. `c("Date", "Tank")`. These
#'                       columns are converted to factors and recorded in the
#'                       standardization metadata; this argument does not add
#'                       model effects. Specify supported random intercepts in
#'                       the `ctmax`, `z`, `low`, or `k` formula passed to
#'                       [fit_4pl()]. Group names cannot collide with columns
#'                       created by standardization.
#' @param duration_unit  Unit of the input `duration` column. A recognised value
#'                       (`"seconds"`, `"minutes"`, `"hours"`, or `"days"`,
#'                       with common abbreviations) is required. Durations are
#'                       converted to minutes, so `tref` / `t_ref` is always in
#'                       minutes and the one-hour default is `60`. This argument is required.
#' @param temp_mean      Value to subtract from `temp` to form `temp_c`.
#'                       `NULL` (default) uses `mean(temp)`. Supply a fixed
#'                       value to align multiple datasets to a common centre.
#' @return A tibble with the standardised columns plus a `"tdt_meta"` attribute
#'         storing `temp_mean`, `duration_unit` (always `"minutes"`),
#'         `input_duration_unit`, `random_effects`,
#'         `response_type` (`"count"` or `"proportion"`), `response_var`
#'         (the response column name for a proportion fit, else `NULL`),
#'         `proportion_eps` (the clamp used for a proportion fit, else `NULL`),
#'         and `has_left_censoring` (whether censoring columns were explicitly
#'         requested for a proportion response).
#' @examples
#' # Count data
#' raw <- data.frame(
#'   temperature_C = rep(c(30, 32, 34), each = 4),
#'   exposure_h    = rep(c(1, 2, 4, 8), times = 3),
#'   n             = 30L,
#'   alive         = c(29, 28, 25, 5, 30, 27, 18, 2, 28, 22, 10, 1)
#' )
#' standardize_data(raw,
#'                  temp     = "temperature_C",
#'                  duration = "exposure_h",
#'                  n_total  = "n",
#'                  n_surv   = "alive",
#'                  duration_unit = "hours")
#'
#' # Continuous proportion (Beta) data
#' raw_p <- data.frame(
#'   temperature_C = rep(c(30, 32, 34), each = 4),
#'   exposure_h    = rep(c(1, 2, 4, 8), times = 3),
#'   fvfm_ratio    = c(0.95, 0.9, 0.7, 0.2, 0.92, 0.6, 0.3, 0, 0.8, 0.4, 0.1, 0)
#' )
#' standardize_data(raw_p,
#'                  temp       = "temperature_C",
#'                  duration   = "exposure_h",
#'                  proportion = "fvfm_ratio",
#'                  duration_unit = "hours")
#' @export
standardize_data <- function(data,
                             temp,
                             duration,
                             n_total        = NULL,
                             n_surv         = NULL,
                             n_dead         = NULL,
                             survival       = NULL,
                             mortality      = NULL,
                             proportion     = NULL,
                             proportion_eps = 0.001,
                             random_effects = NULL,
                             duration_unit  = NULL,
                             temp_mean      = NULL,
                             left_censored  = NULL,
                             censor_limit   = NULL) {

  response_args <- list(n_surv = n_surv, n_dead = n_dead, survival = survival,
                        mortality = mortality, proportion = proportion)
  if (sum(!vapply(response_args, is.null, logical(1))) != 1L) {
    stop("Supply exactly one of n_surv, n_dead, survival, mortality, or ",
         "proportion.", call. = FALSE)
  }
  is_proportion <- !is.null(proportion)
  has_censor_flag <- !is.null(left_censored)
  has_censor_limit <- !is.null(censor_limit)
  if (!identical(has_censor_flag, has_censor_limit)) {
    cli::cli_abort("Supply {.arg left_censored} and {.arg censor_limit} together.")
  }
  if (has_censor_flag && !is_proportion) {
    cli::cli_abort("Left-censoring columns are supported only with {.arg proportion}.")
  }
  for (nm in c("left_censored", "censor_limit")) {
    value <- get(nm)
    if (!is.null(value) && (!is.character(value) || length(value) != 1L ||
                            is.na(value) || !nzchar(value))) {
      cli::cli_abort("{.arg {nm}} must be one non-missing input column name.")
    }
  }
  if (is_proportion &&
      (!is.numeric(proportion_eps) || length(proportion_eps) != 1L ||
       !is.finite(proportion_eps) || proportion_eps <= 0 ||
       proportion_eps >= 0.5)) {
    cli::cli_abort("{.arg proportion_eps} must be one finite numeric value in {.code (0, 0.5)}.")
  }
  if (!is_proportion && is.null(n_total)) {
    stop("Count responses (n_surv/n_dead/survival/mortality) require `n_total`.",
         call. = FALSE)
  }
  if (missing(duration_unit) || is.null(duration_unit)) {
    cli::cli_abort("Supply {.arg duration_unit} so durations can be converted to minutes explicitly.")
  }

  standardized_names <- c("temp", "duration", "logd", "temp_c", "survival")
  if (!is_proportion) {
    standardized_names <- c(standardized_names, "n_total", "n_surv", "n_dead")
  }
  if (has_censor_flag) {
    standardized_names <- c(standardized_names, "left_censored", "censor_limit")
  }
  grouping_collisions <- intersect(
    tdt_random_effect_variables(random_effects), standardized_names
  )
  if (length(grouping_collisions)) {
    cli::cli_abort(c(
      "{.arg random_effects} cannot use column names that collide with standardized output: {.val {grouping_collisions}}.",
      i = "Rename the grouping columns before calling {.fn standardize_data}."
    ))
  }

  needed <- c(temp, duration, n_total, n_surv, n_dead, survival, mortality,
              proportion, left_censored, censor_limit,
              tdt_random_effect_variables(random_effects))
  tdt_check_columns(data, needed, "input columns")
  duration_multiplier <- tls_minutes_multiplier(duration_unit)

  # Warn when standardized columns would overwrite an input column that was not
  # supplied as its source. For example, a raw `temp_c` or `logd` column may
  # mean something different from the standardized transform. The count and
  # response columns are intentionally excluded because they are routinely
  # supplied as sources and are recomputed to a consistent representation.
  reserved  <- c("temp", "duration", "logd", "temp_c")
  sources   <- unlist(list(temp, duration, n_total, n_surv, n_dead, survival,
                           mortality, proportion, left_censored, censor_limit))
  clobbered <- setdiff(intersect(reserved, names(data)), sources)
  if (length(clobbered))
    warning("standardize_data() overwrites existing column(s) with standardised ",
            "values: ", paste(clobbered, collapse = ", "),
            ". Rename them in the raw data to keep their original contents.",
            call. = FALSE)

  source       <- as.data.frame(data)
  out          <- source
  out$temp     <- as.numeric(source[[temp]])
  out$duration <- as.numeric(source[[duration]]) * duration_multiplier
  out$logd     <- log10(out$duration)

  if (is_proportion) {
    response_type <- "proportion"
    response_var  <- "survival"
    if ("survival" %in% names(data) && !identical(proportion, "survival"))
      warning("standardize_data() overwrites the existing `survival` column with ",
              "the clamped proportion response. Rename it in the raw data to keep ",
              "its original contents.", call. = FALSE)
    p             <- as.numeric(source[[proportion]])
    if (any(p > 1 + 1e-6, na.rm = TRUE) || any(p < -1e-6, na.rm = TRUE))
      stop("`proportion` has values outside [0, 1]. A continuous-proportion ",
           "response must be a fraction in [0, 1] (e.g. post/pre Fv/Fm).",
           call. = FALSE)
    if (has_censor_flag) {
      left_censored_v <- source[[left_censored]]
      censor_limit_v <- source[[censor_limit]]
      if (!is.logical(left_censored_v) || length(left_censored_v) != nrow(out) ||
          anyNA(left_censored_v)) {
        cli::cli_abort("Column {.arg {left_censored}} must contain non-missing logical values.")
      }
      if (!is.numeric(censor_limit_v) || length(censor_limit_v) != nrow(out) ||
          any(!is.finite(censor_limit_v)) ||
          any(censor_limit_v <= 0 | censor_limit_v >= 1)) {
        cli::cli_abort("Column {.arg {censor_limit}} must contain finite numeric values strictly in (0, 1).")
      }
      if (any(left_censored_v & (!is.finite(p) | p > censor_limit_v))) {
        cli::cli_abort("Flagged proportions must be finite placeholders at or below their {.arg censor_limit}.")
      }
      exact_below_limit <- !left_censored_v & is.finite(p) & p < censor_limit_v
      if (any(exact_below_limit)) {
        cli::cli_abort(c(
          "Exact proportions cannot be below their detection limit ({.arg censor_limit}).",
          i = "Flag observations known only to fall below the detection limit with {.arg left_censored}.",
          i = "Do not infer censoring from a zero response."
        ))
      }
      out$left_censored <- left_censored_v
      out$censor_limit <- as.numeric(censor_limit_v)
    } else {
      left_censored_v <- rep(FALSE, length(p))
    }
    if (has_censor_flag) {
      # Preserve exact interior values and censored placeholders. Only exact
      # endpoints need adjustment for the Beta density. Refuse an upper clamp
      # that would move an exact value below its declared detection limit.
      clamped <- is.finite(p) & !left_censored_v & (p <= 0 | p >= 1)
      impossible_upper_clamp <- clamped & p >= 1 &
        censor_limit_v > 1 - proportion_eps
      if (any(impossible_upper_clamp)) {
        cli::cli_abort(c(
          "The exact boundary response at row {which(impossible_upper_clamp)[1]} cannot be clamped above its detection limit with {.arg proportion_eps}.",
          i = "Choose a smaller {.arg proportion_eps} or provide an exact interior measurement."
        ))
      }
      p_for_fit <- p
      p_for_fit[clamped & p <= 0] <- proportion_eps
      p_for_fit[clamped & p >= 1] <- 1 - proportion_eps
    } else {
      clamped <- is.finite(p) & !left_censored_v &
        (p < proportion_eps | p > 1 - proportion_eps)
      p_for_fit <- pmin(pmax(p, proportion_eps), 1 - proportion_eps)
    }
    if (any(clamped)) {
      warning(
        "standardize_data() clamped ", sum(clamped), " of ",
        sum(is.finite(p)), " finite proportion values into [",
        format(proportion_eps, scientific = FALSE), ", ",
        format(1 - proportion_eps, scientific = FALSE),
        "] for the Beta likelihood. Check whether boundary values and this ",
        "epsilon are scientifically appropriate.",
        call. = FALSE
      )
    }
    out$survival <- ifelse(left_censored_v, p, p_for_fit)
    keep <- is.finite(out$survival) & is.finite(out$temp) &
            is.finite(out$duration) & out$duration > 0
  } else {
    response_type <- "count"
    response_var  <- NULL
    out$n_total   <- as.integer(round(as.numeric(source[[n_total]])))

    if (!is.null(n_surv)) {
      out$n_surv <- as.integer(round(as.numeric(source[[n_surv]])))
    } else if (!is.null(n_dead)) {
      out$n_surv <- out$n_total - as.integer(round(as.numeric(source[[n_dead]])))
    } else if (!is.null(survival)) {
      sv <- as.numeric(source[[survival]])
      if (any(sv > 1 + 1e-6, na.rm = TRUE))
        stop("`survival` has values > 1, which are not proportions. If these are ",
             "survivor COUNTS, pass them via `n_surv =` instead (with `n_total`).",
             call. = FALSE)
      out$n_surv <- as.integer(round(pmin(pmax(sv, 0), 1) * out$n_total))
    } else if (!is.null(mortality)) {
      mv <- as.numeric(source[[mortality]])
      if (any(mv > 1 + 1e-6, na.rm = TRUE))
        stop("`mortality` has values > 1, which are not proportions. If these are ",
             "death COUNTS, pass them via `n_dead =` instead (with `n_total`).",
             call. = FALSE)
      # Match bayesTLS: round the survivor fraction directly. This can differ
      # from `n_total - round(mortality * n_total)` at half-integer ties because
      # R rounds ties to even.
      out$n_surv <- as.integer(round(
        (1 - pmin(pmax(mv, 0), 1)) * out$n_total
      ))
    }

    # Defensive clamp to [0, n_total]. The survival/mortality paths already
    # reject proportions > 1; the n_surv / n_dead count paths can still produce
    # out-of-range counts from data-entry errors (survivors > trials, deaths >
    # trials), so warn rather than silently fabricating a 0%/100% cell.
    n_oob <- sum(out$n_surv > out$n_total | out$n_surv < 0, na.rm = TRUE)
    if (n_oob > 0L)
      warning(n_oob, " cell(s) had survivor counts outside [0, n_total] ",
              "(e.g. n_surv > n_total); clamped to the valid range. ",
              "Check for data-entry errors.", call. = FALSE)
    out$n_surv   <- as.integer(pmin(pmax(out$n_surv, 0), out$n_total))
    out$n_dead   <- out$n_total - out$n_surv
    out$survival <- out$n_surv / out$n_total
    keep <- is.finite(out$n_total) & is.finite(out$n_surv) &
            is.finite(out$temp)    & is.finite(out$duration) &
            out$n_total > 0 & out$duration > 0
  }

  out <- out[keep, , drop = FALSE]

  n_temp <- length(unique(out$temp))
  if (n_temp < 2L)
    warning("Only ", n_temp, " unique assay temperature(s) after cleaning: the ",
            "temperature slope (z = -1/slope) is not identified by the data and ",
            "cannot be estimated from this design. Provide multiple assay ",
            "temperatures (>= 3 recommended) for an identified z.", call. = FALSE)

  if (is.null(temp_mean)) temp_mean <- mean(out$temp, na.rm = TRUE)
  out$temp_c <- out$temp - temp_mean

  for (re_var in tdt_random_effect_variables(random_effects)) {
    out[[re_var]] <- factor(out[[re_var]])
  }

  attr(out, "tdt_meta") <- list(
    temp_mean      = temp_mean,
    duration_unit  = "minutes",
    input_duration_unit = duration_unit,
    random_effects = random_effects,
    response_type  = response_type,
    response_var   = response_var,
    proportion_eps = if (is_proportion) proportion_eps else NULL,
    has_left_censoring = has_censor_flag
  )

  tibble::as_tibble(out)
}

Try the freqTLS package in your browser

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

freqTLS documentation built on Dec. 4, 2026, 5:11 p.m.