Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Package: vpc
Title: Create Visual Predictive Checks
Version: 1.3.5
Version: 1.3.6
Date: 2026-11-12
Authors@R:
c(
Expand Down
24 changes: 24 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
# vpc 1.3.6
- Bins can now be determined per stratum (#11). With `bin_by_strata = TRUE` in
`vpc()` and `vpc_cens()`, automatic binning methods are applied to the data
of each stratum separately. Manual bins can be specified per stratum by
passing a list to `bins` (named by stratum, or unnamed in the order of the
strata), e.g. `bins = list(A = c(0, 2, 6, 24), B = c(0, 4, 12, 48))`, which
can also mix binning methods and numeric separators. `n_bins` can likewise be
given per stratum. The bin separators shown in the plot are drawn per panel.
With per-stratum binning, `db$bins` in the vpcdb object is a named list.
Missing values of the stratification variable are binned as their own
stratum (with an `NA` name in `db$bins`; distinct from a stratum with the
literal value `"NA"`). Not available for `bins = "percentiles"`.
- With two stratification variables, missing values are now labeled `"<NA>"`
in the combined stratum (e.g. `"<NA>, X"`), so they are no longer merged
with the literal value `"NA"` (`"NA, X"`) when calculating the VPC. Commas
and backslashes within values are escaped in the combined stratum, so e.g.
`("a, b", "c")` and `("a", "b, c")` are no longer merged.
- `vpc_cens()` with `stratify_color`: the color stratification is now
implemented. The observed fraction and simulated CI are calculated per
color stratum and drawn in separate colors (with legend), while facets are
determined by `stratify` only. Previously the color variable was added only
after the data were stratified, so it was ignored (color only) or
mislabeled as a facet (facet and color).

# vpc 1.3.5
- Consistent handling of censored and missing data (#80). Censored values are
now represented internally as `-Inf` (below `lloq`) or `Inf` (above `uloq`)
Expand Down
51 changes: 49 additions & 2 deletions R/add_stratification.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
#' When two stratification variables are supplied, the combined `strat` column
#' is a factor whose levels are ordered by the levels of the first variable,
#' then by the levels of the second variable. Factor level order of the
#' original columns is respected; non-factor columns are sorted.
#' original columns is respected; non-factor columns are sorted. Missing
#' values are labeled \code{"<NA>"} in the combined stratum, so that e.g.
#' \code{(NA, "x")} (\code{"<NA>, x"}) remains distinct from
#' \code{("NA", "x")} (\code{"NA, x"}). Commas and backslashes in values are
#' escaped (\code{"\\,"} and \code{"\\\\"}), so that e.g. \code{("a, b", "c")}
#' and \code{("a", "b, c")} remain distinct strata.
#'
#' @param dat An input data.frame or similar object
#' @param stratify character vector of stratification variables. Only 1 or 2 stratification variables can be supplied.
Expand All @@ -17,7 +22,7 @@ add_stratification <- function (dat, stratify, verbose = FALSE) {
dat$strat <- data.frame(dat)[,stratify]
} else {
strat_cols <- lapply(stratify, function(x) as.factor(dat[[x]]))
strat_label <- do.call(paste, c(lapply(strat_cols, as.character), sep = ", "))
strat_label <- do.call(paste, c(lapply(strat_cols, strat_value_label), sep = ", "))
# Order the combined levels by the first variable, then the second, etc.
level_order <- do.call(order, lapply(strat_cols, as.integer))
dat$strat <- factor(strat_label, levels = unique(strat_label[level_order]))
Expand All @@ -33,6 +38,31 @@ add_stratification <- function (dat, stratify, verbose = FALSE) {
dat
}

#' Label of the values of a stratification variable in a combined stratum
#'
#' The labels are combined with `", "` into the stratum, and are chosen such
#' that distinct combinations of values always give distinct strata. They are
#' independent of the data, so that observed and simulated data (which are
#' stratified separately) are labeled consistently:
#' - backslashes and commas in values are escaped (`\\` and `\,`), so the
#' separator is unambiguous, e.g. `("a, b", "c")` gives `"a\, b, c"` and
#' `("a", "b, c")` gives `"a, b\, c"`;
#' - missing values are labeled `"<NA>"`, and literal values of the form
#' `"<NA>"`, `"<<NA>>"`, etc. are wrapped in one more pair of angle brackets.
#' Other values are unchanged.
#' @param x vector of values
#' @return character vector of labels
#' @noRd
strat_value_label <- function(x) {
x <- as.character(x)
x <- gsub("\\", "\\\\", x, fixed = TRUE)
x <- gsub(",", "\\,", x, fixed = TRUE)
lit <- !is.na(x) & grepl("^<+NA>+$", x)
x[lit] <- paste0("<", x[lit], ">")
x[is.na(x)] <- "<NA>"
x
}

#' Add separate columns for each of two stratification variables
#'
#' Adds `strat1` and `strat2` columns to `dat` based on its combined `strat`
Expand Down Expand Up @@ -64,3 +94,20 @@ add_strat_columns <- function(dat, stratify, ...) {
}
dat
}

#' Add a column for each stratification variable, named by the variable
#'
#' Like [add_strat_columns()], but names the columns after the stratification
#' variables instead of `strat1`, `strat2`, ...
#' @inheritParams add_strat_columns
#' @param stratify character vector of stratification variables
#' @keywords internal
#' @noRd
add_strat_value_columns <- function(dat, stratify, ...) {
if (is.null(dat)) return(dat)
dat <- add_strat_columns(dat, stratify, ...)
for (i in seq_along(stratify)) {
colnames(dat)[match(paste0("strat", i), colnames(dat))] <- stratify[i]
}
dat
}
10 changes: 6 additions & 4 deletions R/calc_vpc_continuous.R
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,9 @@ calc_vpc_continuous <- function(sim, obs, loq, pi, ci, stratify, bins, bin_mid,
bin_mid = mean(.data$mean_idv, na.rm = TRUE)
)

vpc_dat$bin_min <- rep(bins[1:(length(bins)-1)], length(unique(vpc_dat$strat)))[vpc_dat$bin]
vpc_dat$bin_max <- rep(bins[2:length(bins)], length(unique(vpc_dat$strat)))[vpc_dat$bin]
bounds <- bin_boundaries(bins, vpc_dat$bin, vpc_dat$strat)
vpc_dat$bin_min <- bounds$bin_min
vpc_dat$bin_max <- bounds$bin_max
if(bin_mid == "middle") {
vpc_dat$bin_mid <- (vpc_dat$bin_min + vpc_dat$bin_max)/2
}
Expand All @@ -92,8 +93,9 @@ calc_vpc_continuous <- function(sim, obs, loq, pi, ci, stratify, bins, bin_mid,
obs95 = quantile_cens(x=dv, probs=pi[2], limit = cens_limit, cens = cens_type),
bin_mid = mean(idv)
)
aggr_obs$bin_min <- rep(bins[1:(length(bins)-1)], length(unique(aggr_obs$strat)) )[aggr_obs$bin]
aggr_obs$bin_max <- rep(bins[2:length(bins)], length(unique(aggr_obs$strat)) )[aggr_obs$bin]
bounds <- bin_boundaries(bins, aggr_obs$bin, aggr_obs$strat)
aggr_obs$bin_min <- bounds$bin_min
aggr_obs$bin_max <- bounds$bin_max
if(bin_mid == "middle") {
aggr_obs$bin_mid <- (aggr_obs$bin_min + aggr_obs$bin_max)/2
}
Expand Down
187 changes: 183 additions & 4 deletions R/define_bins.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,41 @@
#' @inheritParams read_vpc
#' @param bins either "density", "time", or "data", "none", or one of the
#' approaches available in classInterval() such as "jenks" (default) or
#' "pretty", or a numeric vector specifying the bin separators.
#' "pretty", or a numeric vector specifying the bin separators. For \code{vpc()}
#' and \code{vpc_cens()}, when binning
#' by stratum (see \code{bin_by_strata}), \code{bins} can also be a list
#' with one element (a binning method or numeric vector of bin separators)
#' per stratum. The list should be named by stratum (the value of the
#' stratification variable, or for two stratification variables the two
#' values separated by a comma and a space, e.g. \code{"1, female"}, with
#' missing values shown as \code{"<NA>"} and commas or backslashes within
#' values escaped by a backslash), or
#' be unnamed with one element per stratum in the order of the strata.
#' @param n_bins when using the "auto" binning method, what number of bins to
#' aim for
#' @return A list with named elements: "bins", the bin separator values;
#' aim for. When binning by stratum (\code{vpc()} and \code{vpc_cens()}),
#' this can also be a list or vector with
#' one value per stratum (named or ordered as for \code{bins}).
#' @param bin_by_strata Determine the bins separately for each stratum
#' (\code{TRUE}), or use the same bins for all strata (\code{FALSE},
#' default)? When \code{TRUE}, automatic binning methods are applied to the
#' data of each stratum separately. Specifying \code{bins} as a list
#' implies \code{bin_by_strata = TRUE}. Missing values of the
#' stratification variable form their own stratum (with an \code{NA} name
#' in the returned list of bins; for manual bins, use an \code{NA} name or,
#' when no stratum has the literal value \code{"NA"}, the name
#' \code{"NA"}).
#' Binning by stratum is available for all automatic binning methods except
#' \code{"percentiles"} (which labels the bins by their interval instead of
#' plotting them on the numeric scale of the independent variable).
#' @param verbose show debugging information (TRUE or FALSE)
#' @return A list with named elements: "bins", the bin separator values (a
#' named list with one numeric vector per stratum when binning by stratum);
#' "labeled", are the bins labeled?; "obs", binned observed data; "sim",
#' binned simulated data. Additionally, "tmp_bins" is added for tte data.
define_bins <- function(obs, sim, bins, n_bins, verbose=FALSE) {
define_bins <- function(obs, sim, bins, n_bins, bin_by_strata=FALSE, verbose=FALSE) {
if (is.list(bins) || isTRUE(bin_by_strata)) {
return(define_bins_by_strata(obs=obs, sim=sim, bins=bins, n_bins=n_bins, verbose=verbose))
}
labeled_bins <- bins[1] == "percentiles"
if (!inherits(bins, "numeric")) {
if (!is.null(obs)) {
Expand Down Expand Up @@ -37,6 +65,157 @@ define_bins <- function(obs, sim, bins, n_bins, verbose=FALSE) {
)
}

#' @describeIn define_bins Define bins separately for each stratum
define_bins_by_strata <- function(obs, sim, bins, n_bins, verbose=FALSE) {
ref <- if (!is.null(obs)) obs else sim
if (is.null(ref)) {
stop("No data available for binning.")
}
strata <- strata_levels(obs, sim)
bin_list <- list()
for (s in strata) {
bins_s <- select_strat_element(bins, s, strata, "bins")
n_bins_s <- select_strat_element(n_bins, s, strata, "n_bins")
if (!is.numeric(bins_s) && "percentiles" %in% bins_s) {
stop("`bins = \"percentiles\"` is not supported when binning by stratum.")
}
if (!is.numeric(bins_s)) {
dat_s <- NULL
if (!is.null(obs)) dat_s <- obs[strat_key(obs$strat) == s, , drop = FALSE]
if ((is.null(dat_s) || nrow(dat_s) == 0) && !is.null(sim)) {
dat_s <- sim[strat_key(sim$strat) == s, , drop = FALSE]
}
bins_s <- auto_bin(dat_s, bins_s, n_bins_s)
if (is.null(bins_s)) {
stop("Automatic binning unsuccessful for stratum `", strat_label(s), "`, try increasing the number of bins, or specify bin separators manually.")
}
}
bin_list[[s]] <- unique(as.numeric(bins_s))
msg(paste0("Binning (stratum ", strat_label(s), "): ", paste(bin_list[[s]], collapse=' ')), verbose=verbose)
}
obs <- bin_data_by_strata(obs, bin_list)
sim <- bin_data_by_strata(sim, bin_list)
# return the bins named by stratum value (NA for missing values)
names(bin_list) <- strat_name(names(bin_list))
list(
bins=bin_list,
labeled=FALSE,
obs=obs,
sim=sim
)
}

#' Internal stratum key used for per-stratum binning
#'
#' Stratum values are prefixed with "v:", and missing values of the
#' stratification variable form their own stratum with key "na". The keys can
#' therefore never collide, also not with a stratum with the literal value
#' "NA".
#' @param strat stratum values (or names of a per-stratum list of bins, in
#' which missing strata have an `NA` name)
#' @noRd
strat_key <- function(strat) {
strat <- as.character(strat)
ifelse(is.na(strat), "na", paste0("v:", strat))
}

#' Stratum value (NA for missing) from an internal stratum key
#' @noRd
strat_name <- function(key) {
ifelse(key == "na", NA_character_, sub("^v:", "", key))
}

#' Label for a stratum key in messages
#' @noRd
strat_label <- function(key) {
ifelse(key == "na", "<missing>", sub("^v:", "", key))
}

#' Keys of the strata across observed and simulated data
#' @noRd
strata_levels <- function(obs, sim) {
get_levels <- function(x) {
if (is.null(x)) return(character(0))
lev <- if (is.factor(x$strat)) levels(droplevels(x$strat)) else as.character(unique(stats::na.omit(x$strat)))
key <- strat_key(lev)
if (anyNA(x$strat)) key <- c(key, "na")
key
}
unique(c(get_levels(obs), get_levels(sim)))
}

#' Select the element of a per-stratum argument (bins or n_bins) for stratum
#' key `s`
#'
#' Elements are matched by name. The missing stratum is matched by an `NA`
#' name, or by the name "NA" when there is no stratum with the literal value
#' "NA".
#' @noRd
select_strat_element <- function(x, s, strata, name) {
per_strat <- is.list(x) || (name == "n_bins" && length(x) > 1)
if (!per_strat) return(x)
nms <- names(x)
if (!is.null(nms) && all(is.na(nms) | nms != "")) {
keys <- strat_key(nms)
if (!"v:NA" %in% strata) keys[keys == "v:NA"] <- "na"
if (!s %in% keys) {
stop("No `", name, "` specified for stratum `", strat_label(s), "`. Available strata: ",
paste(strat_label(strata), collapse = "; "))
}
return(x[[match(s, keys)]])
}
if (length(x) != length(strata)) {
stop("When `", name, "` is an unnamed list, it should have one element per stratum (",
length(strata), "): ", paste(strat_label(strata), collapse = "; "))
}
x[[match(s, strata)]]
}

#' Bin data using separate bin separators per stratum, retaining row order
#'
#' @param bins list of bin separators, named by stratum key
#' @noRd
bin_data_by_strata <- function(x, bins) {
if (is.null(x)) return(x)
bin <- rep(NA_integer_, nrow(x))
strat <- strat_key(x$strat)
for (s in names(bins)) {
idx <- which(strat == s)
if (length(idx) > 0) {
bin[idx] <- cut(x$idv[idx], bins[[s]], labels = FALSE, right = FALSE, include.lowest = TRUE)
}
}
x$bin <- bin
x
}

#' Lower and upper bin boundaries for a set of bins
#'
#' @param bins numeric vector of bin separators, or a named list of these (one
#' per stratum, with an `NA` name for missing strata)
#' @param bin bin number (or factor)
#' @param strat stratum for each bin (only used when `bins` is a list)
#' @return a list with `bin_min` and `bin_max`
#' @noRd
bin_boundaries <- function(bins, bin, strat = NULL) {
bin <- as.integer(bin)
if (is.list(bins)) {
strat <- strat_key(strat)
keys <- strat_key(names(bins))
bin_min <- bin_max <- rep(NA_real_, length(bin))
for (s in intersect(unique(strat), keys)) {
idx <- which(strat == s)
b <- bins[[match(s, keys)]]
bin_min[idx] <- b[bin[idx]]
bin_max[idx] <- b[bin[idx] + 1]
}
} else {
bin_min <- bins[bin]
bin_max <- bins[bin + 1]
}
list(bin_min = bin_min, bin_max = bin_max)
}

#' @describeIn define_bins Define bins for time-to-event data
#' @inheritParams vpc_tte
define_bins_tte <- function(obs, sim, bins, n_bins, kmmc, verbose=FALSE) {
Expand Down
Loading
Loading