From bf1aacad4ed0e6c580dc31aea79d0ced175c07fd Mon Sep 17 00:00:00 2001 From: roninsightrx Date: Thu, 12 Nov 2026 12:59:22 -0800 Subject: [PATCH 1/6] Add per-stratum binning (bin_by_strata) (#11) vpc() and vpc_cens() gain a `bin_by_strata` argument. When TRUE, automatic binning methods are applied to each stratum's data separately. Manual per-stratum bins can be given as a list in `bins` (named by stratum or in stratum order, mixing methods and separators), which implies binning by stratum; `n_bins` can also be given per stratum. Bin boundaries are now looked up through a shared bin_boundaries() helper, and the bin separator rug is drawn per facet when bins differ by stratum. Per-stratum bins are rejected for vpc_cat() and for "percentiles" bins. Co-Authored-By: Claude Opus 5.5 --- DESCRIPTION | 2 +- NEWS.md | 10 +++ R/calc_vpc_continuous.R | 10 ++- R/define_bins.R | 134 +++++++++++++++++++++++++++++++++- R/plot_vpc.R | 37 +++++++++- R/vpc.R | 3 +- R/vpc_cat.R | 13 +++- R/vpc_cens.R | 15 ++-- man/calc_vpc_continuous.Rd | 9 ++- man/define_bins.Rd | 29 +++++++- man/vpc.Rd | 20 ++++- man/vpc_cat.Rd | 13 +++- man/vpc_cens.Rd | 22 +++++- man/vpc_ggplot.Rd | 3 +- man/vpc_tte.Rd | 13 +++- tests/testthat/test-binning.R | 116 +++++++++++++++++++++++++++++ 16 files changed, 411 insertions(+), 38 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index db61f76..f781f1a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: vpc Title: Create Visual Predictive Checks -Version: 1.3.2 +Version: 1.3.3 Date: 2026-11-12 Authors@R: c( diff --git a/NEWS.md b/NEWS.md index 2250367..ec6d839 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,13 @@ +# vpc 1.3.3 +- 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. + # vpc 1.3.2 - Added visual regression tests (#9): `tests/testthat/test-plots.R` uses `vdiffr` to snapshot the VPC plots (continuous, pcVPC, LLOQ/log-y, diff --git a/R/calc_vpc_continuous.R b/R/calc_vpc_continuous.R index 7af692e..16ef439 100644 --- a/R/calc_vpc_continuous.R +++ b/R/calc_vpc_continuous.R @@ -68,8 +68,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 } @@ -87,8 +88,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 } diff --git a/R/define_bins.R b/R/define_bins.R index 6fbb8e8..071431b 100644 --- a/R/define_bins.R +++ b/R/define_bins.R @@ -3,13 +3,32 @@ #' @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"}), 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}. +#' @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)) { @@ -37,6 +56,113 @@ 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[as.character(obs$strat) == s, , drop = FALSE] + if ((is.null(dat_s) || nrow(dat_s) == 0) && !is.null(sim)) { + dat_s <- sim[as.character(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 `", s, "`, try increasing the number of bins, or specify bin separators manually.") + } + } + bin_list[[s]] <- unique(as.numeric(bins_s)) + msg(paste0("Binning (stratum ", s, "): ", paste(bin_list[[s]], collapse=' ')), verbose=verbose) + } + list( + bins=bin_list, + labeled=FALSE, + obs=bin_data_by_strata(obs, bin_list), + sim=bin_data_by_strata(sim, bin_list) + ) +} + +#' Levels of the stratification column across observed and simulated data +#' @noRd +strata_levels <- function(obs, sim) { + get_levels <- function(x) { + if (is.null(x)) return(character(0)) + if (is.factor(x$strat)) levels(droplevels(x$strat)) else as.character(unique(x$strat)) + } + unique(c(get_levels(obs), get_levels(sim))) +} + +#' Select the element of a per-stratum argument (bins or n_bins) for stratum `s` +#' @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) + if (!is.null(names(x)) && all(names(x) != "")) { + if (!s %in% names(x)) { + stop("No `", name, "` specified for stratum `", s, "`. Available strata: ", + paste(strata, collapse = "; ")) + } + return(x[[s]]) + } + if (length(x) != length(strata)) { + stop("When `", name, "` is an unnamed list, it should have one element per stratum (", + length(strata), "): ", paste(strata, collapse = "; ")) + } + x[[match(s, strata)]] +} + +#' Bin data using separate bin separators per stratum, retaining row order +#' @noRd +bin_data_by_strata <- function(x, bins) { + if (is.null(x)) return(x) + bin <- rep(NA_integer_, nrow(x)) + strat <- as.character(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) +#' @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 <- as.character(strat) + bin_min <- bin_max <- rep(NA_real_, length(bin)) + for (s in intersect(unique(strat), names(bins))) { + idx <- which(strat == s) + b <- bins[[s]] + 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) { diff --git a/R/plot_vpc.R b/R/plot_vpc.R index a80d5dc..1367395 100644 --- a/R/plot_vpc.R +++ b/R/plot_vpc.R @@ -109,6 +109,7 @@ plot_vpc_helper.vpcdb_continuous <- function(db, ..., } } } + bin_sep <- bin_separators_data(db) if (!is.null(db$sim) && is.factor(db$vpc_dat$bin)) { db$vpc_dat$bin_mid <- db$vpc_dat$bin } @@ -148,7 +149,7 @@ plot_vpc_helper.vpcdb_continuous <- function(db, ..., geom_obs_median_continuous(data=db, show=show$obs_median, vpc_theme=vpc_theme) + geom_obs_ci_continuous(data=db, show=show$obs_ci, vpc_theme=vpc_theme) + geom_obs_dv_continuous(data=db, show=show$obs_dv, vpc_theme=vpc_theme) + - geom_bin_sep(bins=db$bins, show=show$bin_sep, vpc_theme=vpc_theme) + + geom_bin_sep(bins=bin_sep, show=show$bin_sep, vpc_theme=vpc_theme) + ggplot2::labs( # While title is not always used, it defaults to NULL which causes no # title to display. @@ -292,12 +293,18 @@ NULL #' @describeIn vpc_ggplot Show rug plot of bin separators #' @param bins Numeric vector of bin separators (if logical value, geom_blank is -#' returned) +#' returned), or a data.frame with the bin separators in column \code{x} and +#' the stratification columns (for bins that differ by stratum) geom_bin_sep <- function(bins, show, vpc_theme) { ret <- ggplot2::geom_blank() if (show) { if(! (inherits(bins, "logical") && !bins) ) { - bdat <- data.frame(cbind(x = bins, y = NA)) + if (is.data.frame(bins)) { + bdat <- bins + bdat$y <- NA + } else { + bdat <- data.frame(cbind(x = bins, y = NA)) + } ret <- ggplot2::geom_rug( data=bdat, @@ -310,6 +317,30 @@ geom_bin_sep <- function(bins, show, vpc_theme) { ret } +#' Bin separators for plotting +#' +#' When bins are defined per stratum (\code{db$bins} is a list), returns a +#' data.frame with the bin separators (\code{x}) and the stratification +#' columns named as used for faceting. Otherwise returns \code{db$bins}. +#' @param db vpcdb object +#' @noRd +bin_separators_data <- function(db) { + if (!is.list(db$bins)) return(db$bins) + strata <- names(db$bins) + bdat <- data.frame( + strat = factor(rep(strata, lengths(db$bins)), levels = strata), + x = unlist(db$bins, use.names = FALSE) + ) + if (length(db$stratify) == 1) { + colnames(bdat)[1] <- db$stratify[1] + } else if (length(db$stratify) == 2) { + bdat <- add_strat_columns(bdat, db$stratify, db$obs, db$sim) + bdat$strat <- NULL + colnames(bdat)[match(c("strat1", "strat2"), colnames(bdat))] <- db$stratify + } + bdat +} + #' @describeIn vpc_ggplot Generate hlines for the lloq/uloq geom_hline_loq <- function(data, vpc_theme) { loq_values <- c(data$lloq, data$uloq) diff --git a/R/vpc.R b/R/vpc.R index 6042acf..dc1e3a3 100644 --- a/R/vpc.R +++ b/R/vpc.R @@ -117,6 +117,7 @@ vpc_vpc <- function(sim = NULL, labeller = NULL, vpcdb = FALSE, verbose = FALSE, + bin_by_strata = FALSE, sim_ref = NULL, ...) { msg("Configuring and initializing...", verbose=verbose) @@ -239,7 +240,7 @@ vpc_vpc <- function(sim = NULL, } # Binning #### - bins_data <- define_bins(obs=vpc_data$obs, sim=vpc_data$sim, bins=bins, n_bins=n_bins, verbose=verbose) + bins_data <- define_bins(obs=vpc_data$obs, sim=vpc_data$sim, bins=bins, n_bins=n_bins, bin_by_strata=bin_by_strata, verbose=verbose) bins <- bins_data$bins labeled_bins <- bins_data$labeled obs <- bins_data$obs diff --git a/R/vpc_cat.R b/R/vpc_cat.R index a7e03e0..3b0a381 100644 --- a/R/vpc_cat.R +++ b/R/vpc_cat.R @@ -100,6 +100,9 @@ vpc_cat <- function(sim = NULL, } # Binning #### + if (is.list(bins)) { + stop("Per-stratum bins (a list for `bins`) are not supported for `vpc_cat()`.") + } bins_data <- define_bins(obs=vpc_data$obs, sim=vpc_data$sim, bins=bins, n_bins=n_bins, verbose=verbose) bins <- bins_data$bins obs <- bins_data$obs @@ -140,8 +143,9 @@ vpc_cat <- function(sim = NULL, q50.up = quantile(value, ci[2]), bin_mid = mean(mn_idv)) %>% dplyr::ungroup() - 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, NULL) + vpc_dat$bin_min <- bounds$bin_min + vpc_dat$bin_max <- bounds$bin_max if(bin_mid == "middle") { vpc_dat$bin_mid <- apply(cbind(vpc_dat$bin_min, vpc_dat$bin_max), 1, mean) } @@ -169,8 +173,9 @@ vpc_cat <- function(sim = NULL, tmp2 <- tidyr::pivot_longer(tmp1, names_to = "strat", cols = paste0("fact_", lev)) %>% dplyr::arrange(strat, bin) %>% dplyr::mutate(strat = stringr::str_replace(strat, "fact_", "")) - tmp2$bin_min <- rep(bins[1:(length(bins)-1)], length(unique(tmp2$strat)) )[tmp2$bin] - tmp2$bin_max <- rep(bins[2:length(bins)], length(unique(tmp2$strat)) )[tmp2$bin] + bounds <- bin_boundaries(bins, tmp2$bin, NULL) + tmp2$bin_min <- bounds$bin_min + tmp2$bin_max <- bounds$bin_max if(bin_mid == "middle") { tmp2$bin_mid <- apply(dplyr::bind_cols(tmp2$bin_min, tmp2$bin_max), 1, mean) } diff --git a/R/vpc_cens.R b/R/vpc_cens.R index 64422b6..47a4644 100644 --- a/R/vpc_cens.R +++ b/R/vpc_cens.R @@ -46,7 +46,8 @@ vpc_cens <- function(sim = NULL, facet = "wrap", labeller = NULL, vpcdb = FALSE, - verbose = FALSE) { + verbose = FALSE, + bin_by_strata = FALSE) { vpc_data <- read_vpc( sim=sim, obs=obs, psn_folder=psn_folder, @@ -120,7 +121,7 @@ vpc_cens <- function(sim = NULL, } # Binning #### - bins_data <- define_bins(obs=obs, sim=vpc_data$sim, bins=bins, n_bins=n_bins, verbose=verbose) + bins_data <- define_bins(obs=obs, sim=vpc_data$sim, bins=bins, n_bins=n_bins, bin_by_strata=bin_by_strata, verbose=verbose) bins <- bins_data$bins obs <- bins_data$obs sim <- bins_data$sim @@ -138,8 +139,9 @@ vpc_cens <- function(sim = NULL, q50.up = quantile(ploq, ci[2]), bin_mid = mean(mn_idv)) %>% dplyr::ungroup() - 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 <- apply(dplyr::bind_cols(vpc_dat$bin_min, vpc_dat$bin_max), 1, mean) } @@ -153,8 +155,9 @@ vpc_cens <- function(sim = NULL, dplyr::summarise(obs50 = loq_frac(dv, limit = cens_limit, cens = cens_type), bin_mid = mean(idv)) %>% dplyr::ungroup() - 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 <- apply(dplyr::bind_cols(aggr_obs$bin_min, aggr_obs$bin_max), 1, mean) } diff --git a/man/calc_vpc_continuous.Rd b/man/calc_vpc_continuous.Rd index 5c6272f..8b2fbd2 100644 --- a/man/calc_vpc_continuous.Rd +++ b/man/calc_vpc_continuous.Rd @@ -32,7 +32,14 @@ calc_vpc_continuous( \item{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"}), or +be unnamed with one element per stratum in the order of the strata.} \item{bin_mid}{either "mean" for the mean of all timepoints (default) or "middle" to use the average of the bin boundaries.} diff --git a/man/define_bins.Rd b/man/define_bins.Rd index 08c8bb5..fcaea8c 100644 --- a/man/define_bins.Rd +++ b/man/define_bins.Rd @@ -2,10 +2,13 @@ % Please edit documentation in R/define_bins.R \name{define_bins} \alias{define_bins} +\alias{define_bins_by_strata} \alias{define_bins_tte} \title{Define bins for many types of data} \usage{ -define_bins(obs, sim, bins, n_bins, verbose = FALSE) +define_bins(obs, sim, bins, n_bins, bin_by_strata = FALSE, verbose = FALSE) + +define_bins_by_strata(obs, sim, bins, n_bins, verbose = FALSE) define_bins_tte(obs, sim, bins, n_bins, kmmc, verbose = FALSE) } @@ -16,17 +19,33 @@ define_bins_tte(obs, sim, bins, n_bins, kmmc, verbose = FALSE) \item{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"}), or +be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to -aim for} +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}).} + +\item{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}.} \item{verbose}{show debugging information (TRUE or FALSE)} \item{kmmc}{either NULL (for regular TTE vpc, default), or a variable name for a KMMC plot (e.g. "WT")} } \value{ -A list with named elements: "bins", the bin separator values; +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. } @@ -35,6 +54,8 @@ Define bins for many types of data } \section{Functions}{ \itemize{ +\item \code{define_bins_by_strata()}: Define bins separately for each stratum + \item \code{define_bins_tte()}: Define bins for time-to-event data }} diff --git a/man/vpc.Rd b/man/vpc.Rd index 3b99492..7d9c468 100644 --- a/man/vpc.Rd +++ b/man/vpc.Rd @@ -42,6 +42,7 @@ vpc_vpc( labeller = NULL, vpcdb = FALSE, verbose = FALSE, + bin_by_strata = FALSE, sim_ref = NULL, ... ) @@ -57,10 +58,19 @@ vpc_vpc( \item{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"}), or +be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to -aim for} +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}).} \item{bin_mid}{either "mean" for the mean of all timepoints (default) or "middle" to use the average of the bin boundaries.} @@ -134,6 +144,12 @@ columns (\code{"free_y"}), or both rows and columns (\code{"free"})?} \item{verbose}{show debugging information (TRUE or FALSE)} +\item{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}.} + \item{sim_ref}{simulations of a reference dataset, for a reference-corrected VPC (rcVPC). Same format, columns and record order as \code{sim}, but simulated from a dataset in which selected independent variables (dose, diff --git a/man/vpc_cat.Rd b/man/vpc_cat.Rd index 75f427c..967eb8b 100644 --- a/man/vpc_cat.Rd +++ b/man/vpc_cat.Rd @@ -38,10 +38,19 @@ vpc_cat( \item{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"}), or +be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to -aim for} +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}).} \item{bin_mid}{either "mean" for the mean of all timepoints (default) or "middle" to use the average of the bin boundaries.} diff --git a/man/vpc_cens.Rd b/man/vpc_cens.Rd index 52114e3..95f3308 100644 --- a/man/vpc_cens.Rd +++ b/man/vpc_cens.Rd @@ -28,7 +28,8 @@ vpc_cens( facet = "wrap", labeller = NULL, vpcdb = FALSE, - verbose = FALSE + verbose = FALSE, + bin_by_strata = FALSE ) } \arguments{ @@ -40,10 +41,19 @@ vpc_cens( \item{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"}), or +be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to -aim for} +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}).} \item{bin_mid}{either "mean" for the mean of all timepoints (default) or "middle" to use the average of the bin boundaries.} @@ -82,6 +92,12 @@ aim for} \item{vpcdb}{boolean whether to return the underlying vpcdb rather than the plot} \item{verbose}{show debugging information (TRUE or FALSE)} + +\item{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}.} } \value{ a list containing calculated VPC information (when vpcdb=TRUE), or a ggplot2 object (default) diff --git a/man/vpc_ggplot.Rd b/man/vpc_ggplot.Rd index 0b213c2..b2a259f 100644 --- a/man/vpc_ggplot.Rd +++ b/man/vpc_ggplot.Rd @@ -69,7 +69,8 @@ scale_y_log10_vpc(show) } \arguments{ \item{bins}{Numeric vector of bin separators (if logical value, geom_blank is -returned)} +returned), or a data.frame with the bin separators in column \code{x} and +the stratification columns (for bins that differ by stratum)} \item{show}{Should the geom be shown? (TRUE/FALSE)} diff --git a/man/vpc_tte.Rd b/man/vpc_tte.Rd index 1c609d5..405e4e2 100644 --- a/man/vpc_tte.Rd +++ b/man/vpc_tte.Rd @@ -57,10 +57,19 @@ and specify that as independent variable to the vpc_tte() function.} \item{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"}), or +be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to -aim for} +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}).} \item{software}{name of software platform using (e.g. nonmem, phoenix)} diff --git a/tests/testthat/test-binning.R b/tests/testthat/test-binning.R index c177469..9335822 100644 --- a/tests/testthat/test-binning.R +++ b/tests/testthat/test-binning.R @@ -133,3 +133,119 @@ test_that("vpc() with bins = 'data' keeps all observations in the VPC", { expect_false(any(is.na(db$obs$bin))) expect_equal(length(unique(db$obs$bin)), 5) }) + +# Binning by stratum (#11) #### + +strat_test_data <- function() { + obs <- simple_data$obs + sim <- simple_data$sim + obs$GRP <- ifelse(obs$ID %% 2 == 0, "A", "B") + sim$GRP <- ifelse(sim$ID %% 2 == 0, "A", "B") + # stratum B has twice the time range of stratum A + obs$TIME[obs$GRP == "B"] <- obs$TIME[obs$GRP == "B"] * 2 + sim$TIME[sim$GRP == "B"] <- sim$TIME[sim$GRP == "B"] * 2 + list(obs = obs, sim = sim) +} + +test_that("bin_by_strata = TRUE determines automatic bins per stratum", { + d <- strat_test_data() + db <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = "time", + n_bins = 4, bin_by_strata = TRUE, vpcdb = TRUE) + expect_type(db$bins, "list") + expect_named(db$bins, c("A", "B")) + obs_a <- d$obs$TIME[d$obs$GRP == "A" & d$obs$MDV == 0] + obs_b <- d$obs$TIME[d$obs$GRP == "B" & d$obs$MDV == 0] + expect_equal(db$bins$A, auto_bin(obs_a, type = "time", n_bins = 4)) + expect_equal(db$bins$B, auto_bin(obs_b, type = "time", n_bins = 4)) + # all data binned, bin boundaries taken from the stratum's own bins + expect_false(any(is.na(db$obs$bin))) + expect_false(any(is.na(db$sim$bin))) + for (s in c("A", "B")) { + v <- db$vpc_dat[db$vpc_dat$strat == s, ] + expect_equal(v$bin_min, db$bins[[s]][v$bin]) + expect_equal(v$bin_max, db$bins[[s]][v$bin + 1]) + o <- db$aggr_obs[db$aggr_obs$strat == s, ] + expect_equal(o$bin_min, db$bins[[s]][o$bin]) + } + # row order of the data is retained + expect_equal(db$obs$idv, d$obs$TIME[d$obs$MDV == 0]) +}) + +test_that("default (bin_by_strata = FALSE) uses the same bins for all strata", { + d <- strat_test_data() + db <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = "time", + n_bins = 4, vpcdb = TRUE) + expect_type(db$bins, "double") + expect_length(db$bins, 5) +}) + +test_that("manual bins can be specified per stratum as a list", { + d <- strat_test_data() + bins <- list(A = c(0, 2, 5, 10, 30), B = c(0, 4, 10, 60)) + db <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = bins, vpcdb = TRUE) + expect_equal(db$bins, bins) + expect_equal(sort(unique(db$obs$bin[db$obs$strat == "A"])), 1:4) + expect_equal(sort(unique(db$obs$bin[db$obs$strat == "B"])), 1:3) + expect_equal(db$aggr_obs$bin_max[db$aggr_obs$strat == "B"], c(4, 10, 60)) + # unnamed list, in order of the strata + db2 <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = unname(bins), vpcdb = TRUE) + expect_equal(db2$aggr_obs, db$aggr_obs) + # mixing methods and separators, and per-stratum n_bins + db3 <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", + bins = list(A = "time", B = c(0, 4, 10, 60)), + n_bins = list(A = 3, B = 8), vpcdb = TRUE) + expect_length(db3$bins$A, 4) + expect_equal(db3$bins$B, c(0, 4, 10, 60)) +}) + +test_that("per-stratum bins give informative errors", { + d <- strat_test_data() + expect_error( + vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = list(A = c(0, 10, 30)), vpcdb = TRUE), + "No `bins` specified for stratum `B`" + ) + expect_error( + vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = list(c(0, 10, 30)), vpcdb = TRUE), + "one element per stratum" + ) + expect_error( + vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = "percentiles", + bin_by_strata = TRUE, vpcdb = TRUE), + "not supported when binning by stratum" + ) +}) + +test_that("bin_by_strata works with two stratification variables, pred_corr and plotting", { + d <- strat_test_data() + d$obs$SEX <- ifelse(d$obs$ID %% 3 == 0, "M", "F") + d$sim$SEX <- ifelse(d$sim$ID %% 3 == 0, "M", "F") + db <- vpc(sim = d$sim, obs = d$obs, stratify = c("GRP", "SEX"), + bin_by_strata = TRUE, pred_corr = TRUE, vpcdb = TRUE) + expect_named(db$bins, c("A, F", "A, M", "B, F", "B, M")) + expect_false(any(is.na(db$vpc_dat$bin_min))) + bsep <- bin_separators_data(db) + expect_true(all(c("x", "GRP", "SEX") %in% names(bsep))) + expect_equal(nrow(bsep), length(unlist(db$bins))) + pl <- plot_vpc(db) + expect_s3_class(pl, "ggplot") + expect_silent(ggplot2::ggplot_build(pl)) +}) + +test_that("bin_by_strata works for vpc_cens()", { + d <- strat_test_data() + db <- vpc_cens(sim = d$sim, obs = d$obs, lloq = 30, stratify = "GRP", + bins = "time", n_bins = 5, bin_by_strata = TRUE, vpcdb = TRUE) + expect_named(db$bins, c("A", "B")) + expect_false(isTRUE(all.equal(db$bins$A, db$bins$B))) + v <- db$vpc_dat[db$vpc_dat$strat == "B", ] + expect_equal(v$bin_max, db$bins$B[v$bin + 1]) + expect_s3_class(plot_vpc(db), "ggplot") +}) + +test_that("vpc_cat() does not accept per-stratum bins", { + tmp <- simple_data + tmp$obs$DV <- as.integer(tmp$obs$DV > 40) + tmp$sim$DV <- as.integer(tmp$sim$DV > 40) + expect_error(vpc_cat(sim = tmp$sim, obs = tmp$obs, bins = list(c(0, 3, 30)), vpcdb = TRUE), + "not supported") +}) From 983ceb8f7a9cb8c24c2b3926387061ec09fa8dfd Mon Sep 17 00:00:00 2001 From: roninsightrx Date: Thu, 12 Nov 2026 13:05:28 -0800 Subject: [PATCH 2/6] Fix per-stratum binning for vpc_cens color strata and missing strata - vpc_cens(): combine `stratify_color` into the stratification before the data are formatted, so the internal `strat` column (used for binning and the calculations) includes the color variable. Previously it was ignored for color-only stratification and mislabeled for facet + color. - Missing values of the stratification variable are binned as their own stratum ("NA") instead of yielding NA rows / unbinned records, and the bin separator rug is drawn in the NA panel. - Document that bins = "percentiles" is not available with bin_by_strata. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 6 +++++ R/define_bins.R | 29 ++++++++++++++++----- R/plot_vpc.R | 6 ++++- R/vpc_cens.R | 30 +++++++++++----------- man/define_bins.Rd | 6 ++++- man/vpc.Rd | 6 ++++- man/vpc_cens.Rd | 6 ++++- tests/testthat/test-binning.R | 47 +++++++++++++++++++++++++++++++++++ 8 files changed, 112 insertions(+), 24 deletions(-) diff --git a/NEWS.md b/NEWS.md index ec6d839..8e5a28e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -7,6 +7,12 @@ 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 (`"NA"`). Not available for `bins = "percentiles"`. +- `vpc_cens()` with `stratify_color`: the color stratification variable is now + included in the stratification used for the calculations. Previously it was + added only after the data were stratified, so it was ignored (color only) + or mislabeled (facet and color). # vpc 1.3.2 - Added visual regression tests (#9): `tests/testthat/test-plots.R` uses diff --git a/R/define_bins.R b/R/define_bins.R index 071431b..3673e98 100644 --- a/R/define_bins.R +++ b/R/define_bins.R @@ -19,7 +19,11 @@ #' (\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}. +#' implies \code{bin_by_strata = TRUE}. Missing values of the +#' stratification variable form their own stratum, named \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); @@ -72,9 +76,9 @@ define_bins_by_strata <- function(obs, sim, bins, n_bins, verbose=FALSE) { } if (!is.numeric(bins_s)) { dat_s <- NULL - if (!is.null(obs)) dat_s <- obs[as.character(obs$strat) == s, , drop = FALSE] + 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[as.character(sim$strat) == s, , drop = FALSE] + 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)) { @@ -92,12 +96,25 @@ define_bins_by_strata <- function(obs, sim, bins, n_bins, verbose=FALSE) { ) } +#' Stratum identifier used for per-stratum binning +#' +#' The stratum as character, with missing values of the stratification +#' variable as their own stratum, named "NA". +#' @noRd +strat_key <- function(strat) { + key <- as.character(strat) + key[is.na(key)] <- "NA" + key +} + #' Levels of the stratification column across observed and simulated data #' @noRd strata_levels <- function(obs, sim) { get_levels <- function(x) { if (is.null(x)) return(character(0)) - if (is.factor(x$strat)) levels(droplevels(x$strat)) else as.character(unique(x$strat)) + lev <- if (is.factor(x$strat)) levels(droplevels(x$strat)) else as.character(unique(stats::na.omit(x$strat))) + if (anyNA(x$strat)) lev <- c(lev, "NA") + lev } unique(c(get_levels(obs), get_levels(sim))) } @@ -126,7 +143,7 @@ select_strat_element <- function(x, s, strata, name) { bin_data_by_strata <- function(x, bins) { if (is.null(x)) return(x) bin <- rep(NA_integer_, nrow(x)) - strat <- as.character(x$strat) + strat <- strat_key(x$strat) for (s in names(bins)) { idx <- which(strat == s) if (length(idx) > 0) { @@ -148,7 +165,7 @@ bin_data_by_strata <- function(x, bins) { bin_boundaries <- function(bins, bin, strat = NULL) { bin <- as.integer(bin) if (is.list(bins)) { - strat <- as.character(strat) + strat <- strat_key(strat) bin_min <- bin_max <- rep(NA_real_, length(bin)) for (s in intersect(unique(strat), names(bins))) { idx <- which(strat == s) diff --git a/R/plot_vpc.R b/R/plot_vpc.R index 1367395..dadc26d 100644 --- a/R/plot_vpc.R +++ b/R/plot_vpc.R @@ -327,8 +327,12 @@ geom_bin_sep <- function(bins, show, vpc_theme) { bin_separators_data <- function(db) { if (!is.list(db$bins)) return(db$bins) strata <- names(db$bins) + strat <- rep(strata, lengths(db$bins)) + # missing values of the stratification variable are binned as stratum "NA" + has_na <- anyNA(db$obs$strat) || anyNA(db$sim$strat) + if (has_na) strat[strat == "NA"] <- NA bdat <- data.frame( - strat = factor(rep(strata, lengths(db$bins)), levels = strata), + strat = factor(strat, levels = setdiff(strata, if (has_na) "NA")), x = unlist(db$bins, use.names = FALSE) ) if (length(db$stratify) == 1) { diff --git a/R/vpc_cens.R b/R/vpc_cens.R index 47a4644..1a36a41 100644 --- a/R/vpc_cens.R +++ b/R/vpc_cens.R @@ -78,6 +78,22 @@ vpc_cens <- function(sim = NULL, check_stratification_columns_available(data=obs, stratify=stratify_color, type="observation") check_stratification_columns_available(data=vpc_data$sim, stratify=stratify_color, type="simulation") + ## the color stratification variable is part of the stratification used for + ## the calculations (and binning), so combine before formatting the data + stratify_original <- stratify + if(!is.null(stratify_color)) { + if (is.null(stratify)) { + stratify <- stratify_color + } + if (length(stratify_color) > 1) { + stop("Error: please specify only 1 stratification variable for color!") + } + if (!stratify_color %in% stratify) { + stratify_original <- stratify + stratify <- c(stratify, stratify_color) + } + } + ## parse data into specific format if(!is.null(obs)) { obs <- @@ -106,20 +122,6 @@ vpc_cens <- function(sim = NULL, vpc_data$sim$sim <- add_sim_index_number(vpc_data$sim) } - stratify_original <- stratify - if(!is.null(stratify_color)) { - if (is.null(stratify)) { - stratify <- stratify_color - } - if (length(stratify_color) > 1) { - stop("Error: please specify only 1 stratification variable for color!") - } - if (!stratify_color %in% stratify) { - stratify_original <- stratify - stratify <- c(stratify, stratify_color) - } - } - # Binning #### bins_data <- define_bins(obs=obs, sim=vpc_data$sim, bins=bins, n_bins=n_bins, bin_by_strata=bin_by_strata, verbose=verbose) bins <- bins_data$bins diff --git a/man/define_bins.Rd b/man/define_bins.Rd index fcaea8c..797c3ad 100644 --- a/man/define_bins.Rd +++ b/man/define_bins.Rd @@ -37,7 +37,11 @@ one value per stratum (named or ordered as for \code{bins}).} (\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}.} +implies \code{bin_by_strata = TRUE}. Missing values of the +stratification variable form their own stratum, named \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).} \item{verbose}{show debugging information (TRUE or FALSE)} diff --git a/man/vpc.Rd b/man/vpc.Rd index 7d9c468..6fbc5a9 100644 --- a/man/vpc.Rd +++ b/man/vpc.Rd @@ -148,7 +148,11 @@ columns (\code{"free_y"}), or both rows and columns (\code{"free"})?} (\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}.} +implies \code{bin_by_strata = TRUE}. Missing values of the +stratification variable form their own stratum, named \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).} \item{sim_ref}{simulations of a reference dataset, for a reference-corrected VPC (rcVPC). Same format, columns and record order as \code{sim}, but diff --git a/man/vpc_cens.Rd b/man/vpc_cens.Rd index 95f3308..95a251a 100644 --- a/man/vpc_cens.Rd +++ b/man/vpc_cens.Rd @@ -97,7 +97,11 @@ one value per stratum (named or ordered as for \code{bins}).} (\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}.} +implies \code{bin_by_strata = TRUE}. Missing values of the +stratification variable form their own stratum, named \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).} } \value{ a list containing calculated VPC information (when vpcdb=TRUE), or a ggplot2 object (default) diff --git a/tests/testthat/test-binning.R b/tests/testthat/test-binning.R index 9335822..8ae3c88 100644 --- a/tests/testthat/test-binning.R +++ b/tests/testthat/test-binning.R @@ -249,3 +249,50 @@ test_that("vpc_cat() does not accept per-stratum bins", { expect_error(vpc_cat(sim = tmp$sim, obs = tmp$obs, bins = list(c(0, 3, 30)), vpcdb = TRUE), "not supported") }) + +test_that("bin_by_strata in vpc_cens() includes the color stratification", { + d <- strat_test_data() + d$obs$SEX <- ifelse(d$obs$ID %% 3 == 0, "M", "F") + d$sim$SEX <- ifelse(d$sim$ID %% 3 == 0, "M", "F") + # color stratification only + db <- vpc_cens(sim = d$sim, obs = d$obs, lloq = 30, stratify_color = "GRP", + bins = "time", n_bins = 4, bin_by_strata = TRUE, vpcdb = TRUE) + expect_named(db$bins, c("A", "B")) + expect_false(isTRUE(all.equal(db$bins$A, db$bins$B))) + expect_setequal(as.character(unique(db$vpc_dat$strat)), c("A", "B")) + expect_s3_class(ggplot2::ggplot_build(plot_vpc(db)), "ggplot_built") + # facet and color stratification + db <- vpc_cens(sim = d$sim, obs = d$obs, lloq = 30, stratify = "SEX", + stratify_color = "GRP", bins = "time", n_bins = 4, + bin_by_strata = TRUE, vpcdb = TRUE) + expect_named(db$bins, c("F, A", "F, B", "M, A", "M, B")) + expect_equal(db$bins[["M, B"]][5], max(d$obs$TIME[d$obs$MDV == 0 & d$obs$SEX == "M" & d$obs$GRP == "B"]) * 1.001) + v <- db$vpc_dat[db$vpc_dat$strat == "M, B", ] + expect_equal(unique(v$strat1), "M") + expect_equal(unique(v$strat2), "B") + expect_equal(v$bin_max, db$bins[["M, B"]][v$bin + 1]) + expect_s3_class(ggplot2::ggplot_build(plot_vpc(db)), "ggplot_built") +}) + +test_that("missing values of the stratification variable are binned as their own stratum", { + d <- strat_test_data() + d$obs$GRP[d$obs$ID %in% c(1, 2)] <- NA + d$sim$GRP[d$sim$ID %in% c(1, 2)] <- NA + db <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = "time", + n_bins = 3, bin_by_strata = TRUE, vpcdb = TRUE) + expect_named(db$bins, c("A", "B", "NA")) + expect_true(all(is.finite(unlist(db$bins)))) + expect_false(any(is.na(db$obs$bin))) + expect_false(any(is.na(db$sim$bin))) + expect_false(any(is.na(db$vpc_dat$bin_min))) + expect_false(any(is.na(db$aggr_obs$bin_max))) + bsep <- bin_separators_data(db) + expect_true(anyNA(bsep$GRP)) + expect_s3_class(ggplot2::ggplot_build(plot_vpc(db)), "ggplot_built") + # manual bins, with the missing stratum named "NA" + db2 <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", + bins = list(A = c(0, 5, 30), B = c(0, 10, 60), "NA" = c(0, 30)), + vpcdb = TRUE) + expect_false(any(is.na(db2$obs$bin))) + expect_equal(db2$aggr_obs$bin_max[is.na(db2$aggr_obs$strat)], 30) +}) From 1031c4f5028d67117de7ec827c53e68912555d7b Mon Sep 17 00:00:00 2001 From: roninsightrx Date: Thu, 12 Nov 2026 13:12:55 -0800 Subject: [PATCH 3/6] Color stratification for vpc_cens(); collision-free missing-stratum key - vpc_cens(): `stratify_color` now behaves as documented. Statistics are computed per color stratum, the observed line and simulated CI are mapped to colour/fill (grouped by the color variable, with legend), and facets use only `stratify`. Per-stratum bin separators are colored per color stratum. - Per-stratum binning uses internal keys ("v:", "na" for missing), so a missing stratum no longer collides with a literal "NA" stratum. In `db$bins` the missing stratum has an NA name; manual bins for it can be given with an NA name (or "NA" when no literal "NA" stratum exists). Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 13 +++-- R/add_stratification.R | 17 ++++++ R/define_bins.R | 82 +++++++++++++++++++-------- R/plot_vpc.R | 102 +++++++++++++++++++++++++--------- R/vpc_cens.R | 20 +++++-- man/define_bins.Rd | 5 +- man/vpc.Rd | 5 +- man/vpc_cens.Rd | 10 +++- man/vpc_ggplot.Rd | 4 +- tests/testthat/test-binning.R | 79 +++++++++++++++++++++++--- 10 files changed, 262 insertions(+), 75 deletions(-) diff --git a/NEWS.md b/NEWS.md index 8e5a28e..bf509c1 100644 --- a/NEWS.md +++ b/NEWS.md @@ -8,11 +8,14 @@ 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 (`"NA"`). Not available for `bins = "percentiles"`. -- `vpc_cens()` with `stratify_color`: the color stratification variable is now - included in the stratification used for the calculations. Previously it was - added only after the data were stratified, so it was ignored (color only) - or mislabeled (facet and color). + stratum (with an `NA` name in `db$bins`; distinct from a stratum with the + literal value `"NA"`). Not available for `bins = "percentiles"`. +- `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.2 - Added visual regression tests (#9): `tests/testthat/test-plots.R` uses diff --git a/R/add_stratification.R b/R/add_stratification.R index caef195..6b9c4d3 100644 --- a/R/add_stratification.R +++ b/R/add_stratification.R @@ -64,3 +64,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 +} diff --git a/R/define_bins.R b/R/define_bins.R index 3673e98..efc4c26 100644 --- a/R/define_bins.R +++ b/R/define_bins.R @@ -20,7 +20,10 @@ #' 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, named \code{"NA"}. +#' 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). @@ -82,63 +85,93 @@ define_bins_by_strata <- function(obs, sim, bins, n_bins, verbose=FALSE) { } bins_s <- auto_bin(dat_s, bins_s, n_bins_s) if (is.null(bins_s)) { - stop("Automatic binning unsuccessful for stratum `", s, "`, try increasing the number of bins, or specify bin separators manually.") + 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 ", s, "): ", paste(bin_list[[s]], collapse=' ')), verbose=verbose) + 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=bin_data_by_strata(obs, bin_list), - sim=bin_data_by_strata(sim, bin_list) + obs=obs, + sim=sim ) } -#' Stratum identifier used for per-stratum binning +#' Internal stratum key used for per-stratum binning #' -#' The stratum as character, with missing values of the stratification -#' variable as their own stratum, named "NA". +#' 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) { - key <- as.character(strat) - key[is.na(key)] <- "NA" - key + 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)) } -#' Levels of the stratification column across observed and simulated data +#' Label for a stratum key in messages +#' @noRd +strat_label <- function(key) { + ifelse(key == "na", "", 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))) - if (anyNA(x$strat)) lev <- c(lev, "NA") - lev + 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 `s` +#' 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) - if (!is.null(names(x)) && all(names(x) != "")) { - if (!s %in% names(x)) { - stop("No `", name, "` specified for stratum `", s, "`. Available strata: ", - paste(strata, collapse = "; ")) + 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[[s]]) + 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(strata, collapse = "; ")) + 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) @@ -157,7 +190,7 @@ bin_data_by_strata <- function(x, bins) { #' 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) +#' 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` @@ -166,10 +199,11 @@ 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), names(bins))) { + for (s in intersect(unique(strat), keys)) { idx <- which(strat == s) - b <- bins[[s]] + b <- bins[[match(s, keys)]] bin_min[idx] <- b[bin[idx]] bin_max[idx] <- b[bin[idx] + 1] } diff --git a/R/plot_vpc.R b/R/plot_vpc.R index dadc26d..5ec9469 100644 --- a/R/plot_vpc.R +++ b/R/plot_vpc.R @@ -94,18 +94,16 @@ plot_vpc_helper.vpcdb_continuous <- function(db, ..., verbose = FALSE) { if(!is.null(db$stratify)) { ## rename "strat" to original stratification variable names + ## (unless the data already have columns with these names, e.g. for + ## color stratification in `vpc_cens()`) if(length(db$stratify) == 1) { - if(!is.null(db$aggr_obs)) colnames(db$aggr_obs)[match("strat", colnames(db$aggr_obs))] <- db$stratify[1] - if(!is.null(db$vpc_dat)) colnames(db$vpc_dat)[match("strat", colnames(db$vpc_dat))] <- db$stratify[1] + db$aggr_obs <- rename_strat_column(db$aggr_obs, "strat", db$stratify[1]) + db$vpc_dat <- rename_strat_column(db$vpc_dat, "strat", db$stratify[1]) } if(length(db$stratify) == 2) { - if(!is.null(db$aggr_obs)) { - colnames(db$aggr_obs)[match("strat1", colnames(db$aggr_obs))] <- db$stratify[1] - colnames(db$aggr_obs)[match("strat2", colnames(db$aggr_obs))] <- db$stratify[2] - } - if(!is.null(db$vpc_dat)) { - colnames(db$vpc_dat)[match("strat1", colnames(db$vpc_dat))] <- db$stratify[1] - colnames(db$vpc_dat)[match("strat2", colnames(db$vpc_dat))] <- db$stratify[2] + for (i in 1:2) { + db$aggr_obs <- rename_strat_column(db$aggr_obs, paste0("strat", i), db$stratify[i]) + db$vpc_dat <- rename_strat_column(db$vpc_dat, paste0("strat", i), db$stratify[i]) } } } @@ -149,7 +147,8 @@ plot_vpc_helper.vpcdb_continuous <- function(db, ..., geom_obs_median_continuous(data=db, show=show$obs_median, vpc_theme=vpc_theme) + geom_obs_ci_continuous(data=db, show=show$obs_ci, vpc_theme=vpc_theme) + geom_obs_dv_continuous(data=db, show=show$obs_dv, vpc_theme=vpc_theme) + - geom_bin_sep(bins=bin_sep, show=show$bin_sep, vpc_theme=vpc_theme) + + geom_bin_sep(bins=bin_sep, show=show$bin_sep, vpc_theme=vpc_theme, color=db$stratify_color[1]) + + guides_stratify_color(data=db) + ggplot2::labs( # While title is not always used, it defaults to NULL which causes no # title to display. @@ -244,7 +243,11 @@ plot_vpc_helper.vpcdb_time_to_event <- function(db, ..., #' @export ggplot.vpcdb_continuous <- function(data = NULL, mapping = NULL, ..., environment = parent.frame()) { if (!is.null(data$sim)) { - pl <- ggplot2::ggplot(data$vpc_dat, ggplot2::aes(x=bin_mid, group=1)) + if (is.null(data$stratify_color)) { + pl <- ggplot2::ggplot(data$vpc_dat, ggplot2::aes(x=bin_mid, group=1)) + } else { + pl <- ggplot2::ggplot(data$vpc_dat, ggplot2::aes(x=bin_mid, group=.data[[data$stratify_color[1]]])) + } } else { pl <- ggplot2::ggplot(data$aggr_obs) } @@ -295,7 +298,8 @@ NULL #' @param bins Numeric vector of bin separators (if logical value, geom_blank is #' returned), or a data.frame with the bin separators in column \code{x} and #' the stratification columns (for bins that differ by stratum) -geom_bin_sep <- function(bins, show, vpc_theme) { +#' @param color name of the color stratification variable (or \code{NULL}) +geom_bin_sep <- function(bins, show, vpc_theme, color = NULL) { ret <- ggplot2::geom_blank() if (show) { if(! (inherits(bins, "logical") && !bins) ) { @@ -305,6 +309,16 @@ geom_bin_sep <- function(bins, show, vpc_theme) { } else { bdat <- data.frame(cbind(x = bins, y = NA)) } + if (!is.null(color) && color %in% names(bdat)) { + # bins differ by color stratum: color the separators accordingly + return( + ggplot2::geom_rug( + data=bdat, + sides = "t", + ggplot2::aes(x = x, y = y, group=NA, colour = .data[[color]]) + ) + ) + } ret <- ggplot2::geom_rug( data=bdat, @@ -328,23 +342,42 @@ bin_separators_data <- function(db) { if (!is.list(db$bins)) return(db$bins) strata <- names(db$bins) strat <- rep(strata, lengths(db$bins)) - # missing values of the stratification variable are binned as stratum "NA" - has_na <- anyNA(db$obs$strat) || anyNA(db$sim$strat) - if (has_na) strat[strat == "NA"] <- NA - bdat <- data.frame( - strat = factor(strat, levels = setdiff(strata, if (has_na) "NA")), - x = unlist(db$bins, use.names = FALSE) - ) - if (length(db$stratify) == 1) { - colnames(bdat)[1] <- db$stratify[1] - } else if (length(db$stratify) == 2) { - bdat <- add_strat_columns(bdat, db$stratify, db$obs, db$sim) - bdat$strat <- NULL - colnames(bdat)[match(c("strat1", "strat2"), colnames(bdat))] <- db$stratify + x <- unlist(db$bins, use.names = FALSE) + vars <- unique(c(db$stratify, db$stratify_color)) + if (length(vars) == 0) { + return(data.frame(x = x)) + } + if (length(vars) == 1 && is.null(db$stratify_color)) { + # facet column is the (factor) `strat` column, renamed + bdat <- data.frame(strat = factor(strat, levels = strata[!is.na(strata)]), x = x) + colnames(bdat)[1] <- vars + return(bdat) } + # look up the values of the stratification variables for each stratum + refs <- Filter(function(d) !is.null(d) && all(c("strat", vars) %in% names(d)), list(db$obs, db$sim)) + if (length(refs) == 0) return(sort(unique(x))) + lookup <- do.call(rbind, lapply(refs, function(d) { + d <- as.data.frame(d)[, c("strat", vars), drop = FALSE] + d$key <- strat_key(d$strat) + d$strat <- NULL + unique(d) + })) + lookup <- lookup[!duplicated(lookup$key), , drop = FALSE] + idx <- match(strat_key(strat), lookup$key) + bdat <- data.frame(x = x) + for (v in vars) bdat[[v]] <- lookup[[v]][idx] bdat } +#' Rename a stratification column, unless the target name already exists +#' @noRd +rename_strat_column <- function(dat, from, to) { + if (!is.null(dat) && from %in% colnames(dat) && !to %in% colnames(dat)) { + colnames(dat)[match(from, colnames(dat))] <- to + } + dat +} + #' @describeIn vpc_ggplot Generate hlines for the lloq/uloq geom_hline_loq <- function(data, vpc_theme) { loq_values <- c(data$lloq, data$uloq) @@ -455,7 +488,15 @@ geom_obs_km <- function(data) { #' @describeIn vpc_ggplot Show observed median line for continuous data geom_obs_median_continuous <- function(data, show, vpc_theme) { - if (show & !is.null(data$aggr_obs)) { + if (show & !is.null(data$aggr_obs) & !is.null(data$stratify_color)) { + color <- data$stratify_color[1] + ggplot2::geom_line( + data=data$aggr_obs, + ggplot2::aes(x=bin_mid, y=obs50, colour=.data[[color]], group=.data[[color]]), + linetype=vpc_theme$obs_median_linetype, + linewidth=vpc_theme$obs_median_linewidth + ) + } else if (show & !is.null(data$aggr_obs)) { ggplot2::geom_line( data=data$aggr_obs, ggplot2::aes(x=bin_mid, y=obs50), @@ -516,7 +557,14 @@ geom_sim_median_tte <- function(data, show, smooth) { #' @describeIn vpc_ggplot Show simulated median confidence interval for #' continuous data geom_sim_median_ci_continuous <- function(data, show, smooth, vpc_theme) { - if (show & !is.null(data$sim)) { + if (show & !is.null(data$sim) & !is.null(data$stratify_color)) { + color <- data$stratify_color[1] + if (smooth) { + ggplot2::geom_ribbon(ggplot2::aes(x=bin_mid, ymin=q50.low, ymax=q50.up, fill=.data[[color]]), alpha=vpc_theme$sim_median_alpha) + } else { + ggplot2::geom_rect(ggplot2::aes(xmin=bin_min, xmax=bin_max, ymin=q50.low, ymax=q50.up, fill=.data[[color]]), alpha=vpc_theme$sim_median_alpha) + } + } else if (show & !is.null(data$sim)) { if (smooth) { ggplot2::geom_ribbon(ggplot2::aes(x=bin_mid, ymin=q50.low, ymax=q50.up), alpha=vpc_theme$sim_median_alpha, fill = vpc_theme$sim_median_fill) } else { diff --git a/R/vpc_cens.R b/R/vpc_cens.R index 1a36a41..49ef9a1 100644 --- a/R/vpc_cens.R +++ b/R/vpc_cens.R @@ -8,7 +8,10 @@ #' @inheritParams as_vpcdb #' @inheritParams define_bins #' @param bin_mid either "mean" for the mean of all timepoints (default) or "middle" to use the average of the bin boundaries. -#' @param stratify_color variable to stratify and color lines for observed data. Only 1 stratification variables can be supplied. +#' @param stratify_color variable to stratify by color: the observed +#' fraction (line) and simulated confidence interval (area) are calculated +#' and colored per value of this variable, while \code{stratify} determines +#' the facets. Only 1 stratification variable can be supplied. #' @param ci confidence interval to plot. Default is (0.05, 0.95) #' @param vpcdb boolean whether to return the underlying vpcdb rather than the plot #' @param verbose show debugging information (TRUE or FALSE) @@ -166,11 +169,16 @@ vpc_cens <- function(sim = NULL, } else { aggr_obs <- NULL } - if (!is.null(stratify_original)) { - if (length(stratify) == 2) { - vpc_dat <- add_strat_columns(vpc_dat, stratify, obs, sim) - aggr_obs <- add_strat_columns(aggr_obs, stratify, obs, sim) - } + if (!is.null(stratify_color)) { + ## stratification by color: add a column for each stratification variable + ## (named by the variable), facet only by the `stratify` variables, and + ## color by `stratify_color` + vpc_dat <- add_strat_value_columns(vpc_dat, stratify, obs, sim) + aggr_obs <- add_strat_value_columns(aggr_obs, stratify, obs, sim) + stratify <- stratify_original + } else if (length(stratify) == 2) { + vpc_dat <- add_strat_columns(vpc_dat, stratify, obs, sim) + aggr_obs <- add_strat_columns(aggr_obs, stratify, obs, sim) } ## plotting starts here diff --git a/man/define_bins.Rd b/man/define_bins.Rd index 797c3ad..75f7af1 100644 --- a/man/define_bins.Rd +++ b/man/define_bins.Rd @@ -38,7 +38,10 @@ one value per stratum (named or ordered as for \code{bins}).} 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, named \code{"NA"}. +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).} diff --git a/man/vpc.Rd b/man/vpc.Rd index 6fbc5a9..4623d16 100644 --- a/man/vpc.Rd +++ b/man/vpc.Rd @@ -149,7 +149,10 @@ columns (\code{"free_y"}), or both rows and columns (\code{"free"})?} 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, named \code{"NA"}. +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).} diff --git a/man/vpc_cens.Rd b/man/vpc_cens.Rd index 95a251a..57dc09e 100644 --- a/man/vpc_cens.Rd +++ b/man/vpc_cens.Rd @@ -67,7 +67,10 @@ one value per stratum (named or ordered as for \code{bins}).} \item{stratify}{character vector of stratification variables. Only 1 or 2 stratification variables can be supplied.} -\item{stratify_color}{variable to stratify and color lines for observed data. Only 1 stratification variables can be supplied.} +\item{stratify_color}{variable to stratify by color: the observed +fraction (line) and simulated confidence interval (area) are calculated +and colored per value of this variable, while \code{stratify} determines +the facets. Only 1 stratification variable can be supplied.} \item{ci}{confidence interval to plot. Default is (0.05, 0.95)} @@ -98,7 +101,10 @@ one value per stratum (named or ordered as for \code{bins}).} 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, named \code{"NA"}. +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).} diff --git a/man/vpc_ggplot.Rd b/man/vpc_ggplot.Rd index b2a259f..0935fcc 100644 --- a/man/vpc_ggplot.Rd +++ b/man/vpc_ggplot.Rd @@ -25,7 +25,7 @@ \alias{scale_y_log10_vpc} \title{A collection of internal ggplot helpers for VPC plotting} \usage{ -geom_bin_sep(bins, show, vpc_theme) +geom_bin_sep(bins, show, vpc_theme, color = NULL) geom_hline_loq(data, vpc_theme) @@ -76,6 +76,8 @@ the stratification columns (for bins that differ by stratum)} \item{vpc_theme}{The theme to use} +\item{color}{name of the color stratification variable (or \code{NULL})} + \item{data}{The vpcdb object} \item{smooth}{"smooth" the VPC (connect bin midpoints) or show bins as rectangular boxes. Default is TRUE.} diff --git a/tests/testthat/test-binning.R b/tests/testthat/test-binning.R index 8ae3c88..0529298 100644 --- a/tests/testthat/test-binning.R +++ b/tests/testthat/test-binning.R @@ -254,24 +254,58 @@ test_that("bin_by_strata in vpc_cens() includes the color stratification", { d <- strat_test_data() d$obs$SEX <- ifelse(d$obs$ID %% 3 == 0, "M", "F") d$sim$SEX <- ifelse(d$sim$ID %% 3 == 0, "M", "F") - # color stratification only + # color stratification only: single panel, colored by GRP db <- vpc_cens(sim = d$sim, obs = d$obs, lloq = 30, stratify_color = "GRP", bins = "time", n_bins = 4, bin_by_strata = TRUE, vpcdb = TRUE) expect_named(db$bins, c("A", "B")) expect_false(isTRUE(all.equal(db$bins$A, db$bins$B))) - expect_setequal(as.character(unique(db$vpc_dat$strat)), c("A", "B")) - expect_s3_class(ggplot2::ggplot_build(plot_vpc(db)), "ggplot_built") - # facet and color stratification + expect_null(db$stratify) + expect_equal(db$stratify_color, "GRP") + expect_setequal(db$vpc_dat$GRP, c("A", "B")) + expect_equal(db$vpc_dat$bin_max[db$vpc_dat$GRP == "B"], + db$bins$B[db$vpc_dat$bin[db$vpc_dat$GRP == "B"] + 1]) + pl <- plot_vpc(db) + expect_s3_class(pl$facet, "FacetNull") + built <- ggplot2::ggplot_build(pl) + obs_layer <- which(vapply(pl$layers, function(l) inherits(l$geom, "GeomLine"), logical(1))) + expect_length(unique(built$data[[obs_layer]]$colour), 2) + ribbon_layer <- which(vapply(pl$layers, function(l) inherits(l$geom, "GeomRibbon"), logical(1))) + expect_length(unique(built$data[[ribbon_layer]]$fill), 2) + expect_equal(length(unique(built$data[[obs_layer]]$group)), 2) + # facet (SEX) and color (GRP) stratification db <- vpc_cens(sim = d$sim, obs = d$obs, lloq = 30, stratify = "SEX", stratify_color = "GRP", bins = "time", n_bins = 4, bin_by_strata = TRUE, vpcdb = TRUE) expect_named(db$bins, c("F, A", "F, B", "M, A", "M, B")) expect_equal(db$bins[["M, B"]][5], max(d$obs$TIME[d$obs$MDV == 0 & d$obs$SEX == "M" & d$obs$GRP == "B"]) * 1.001) + expect_equal(db$stratify, "SEX") v <- db$vpc_dat[db$vpc_dat$strat == "M, B", ] - expect_equal(unique(v$strat1), "M") - expect_equal(unique(v$strat2), "B") + expect_equal(unique(v$SEX), "M") + expect_equal(unique(v$GRP), "B") expect_equal(v$bin_max, db$bins[["M, B"]][v$bin + 1]) - expect_s3_class(ggplot2::ggplot_build(plot_vpc(db)), "ggplot_built") + pl <- plot_vpc(db) + expect_s3_class(pl$facet, "FacetWrap") + expect_equal(names(pl$facet$params$facets), "SEX") + built <- ggplot2::ggplot_build(pl) + expect_equal(nrow(built$layout$layout), 2) + obs_layer <- which(vapply(pl$layers, function(l) inherits(l$geom, "GeomLine"), logical(1))) + expect_length(unique(built$data[[obs_layer]]$colour), 2) + # bin separators are drawn per facet and colored per color stratum + rug_layer <- which(vapply(pl$layers, function(l) inherits(l$geom, "GeomRug"), logical(1))) + rug <- built$data[[rug_layer]] + expect_equal(nrow(rug), length(unlist(db$bins))) + expect_length(unique(rug$colour), 2) +}) + +test_that("vpc_cens() color stratification without per-stratum binning", { + d <- strat_test_data() + db <- vpc_cens(sim = d$sim, obs = d$obs, lloq = 30, stratify_color = "GRP", + bins = "time", n_bins = 4, vpcdb = TRUE) + expect_type(db$bins, "double") + expect_setequal(db$aggr_obs$GRP, c("A", "B")) + pl <- plot_vpc(db) + expect_s3_class(pl$facet, "FacetNull") + expect_s3_class(ggplot2::ggplot_build(pl), "ggplot_built") }) test_that("missing values of the stratification variable are binned as their own stratum", { @@ -280,7 +314,7 @@ test_that("missing values of the stratification variable are binned as their own d$sim$GRP[d$sim$ID %in% c(1, 2)] <- NA db <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = "time", n_bins = 3, bin_by_strata = TRUE, vpcdb = TRUE) - expect_named(db$bins, c("A", "B", "NA")) + expect_equal(names(db$bins), c("A", "B", NA)) expect_true(all(is.finite(unlist(db$bins)))) expect_false(any(is.na(db$obs$bin))) expect_false(any(is.na(db$sim$bin))) @@ -296,3 +330,32 @@ test_that("missing values of the stratification variable are binned as their own expect_false(any(is.na(db2$obs$bin))) expect_equal(db2$aggr_obs$bin_max[is.na(db2$aggr_obs$strat)], 30) }) + +test_that("missing strata do not collide with a stratum with the literal value \"NA\"", { + d <- strat_test_data() + d$obs$GRP[d$obs$ID %in% c(1, 2)] <- NA + d$sim$GRP[d$sim$ID %in% c(1, 2)] <- NA + d$obs$GRP[d$obs$ID %in% c(3, 4)] <- "NA" + d$sim$GRP[d$sim$ID %in% c(3, 4)] <- "NA" + # literal "NA" stratum has a 2x longer time range than the missing stratum + d$obs$TIME[d$obs$GRP %in% "NA"] <- d$obs$TIME[d$obs$GRP %in% "NA"] * 2 + d$sim$TIME[d$sim$GRP %in% "NA"] <- d$sim$TIME[d$sim$GRP %in% "NA"] * 2 + db <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = "time", + n_bins = 3, bin_by_strata = TRUE, vpcdb = TRUE) + expect_length(db$bins, 4) + expect_true("NA" %in% names(db$bins)) + expect_true(anyNA(names(db$bins))) + lit <- db$bins[[which(names(db$bins) %in% "NA")]] + mis <- db$bins[[which(is.na(names(db$bins)))]] + expect_equal(max(lit), max(d$obs$TIME[d$obs$MDV == 0 & d$obs$GRP %in% "NA"]) * 1.001) + expect_equal(max(mis), max(d$obs$TIME[d$obs$MDV == 0 & is.na(d$obs$GRP)]) * 1.001) + expect_false(any(is.na(db$obs$bin))) + # manual bins: separate definitions for the literal "NA" and missing strata + bins <- list(A = c(0, 30), B = c(0, 60), "NA" = c(0, 10, 50), c(0, 5, 30)) + names(bins)[4] <- NA + db2 <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = bins, vpcdb = TRUE) + expect_false(any(is.na(db2$obs$bin))) + expect_equal(db2$aggr_obs$bin_max[is.na(db2$aggr_obs$strat)], c(5, 30)) + expect_equal(db2$aggr_obs$bin_max[db2$aggr_obs$strat %in% "NA"], c(10, 50)) + expect_s3_class(ggplot2::ggplot_build(plot_vpc(db2)), "ggplot_built") +}) From 3b44f6aa5eb2f7c85d26dc41b62cb6a2cc29a2ad Mon Sep 17 00:00:00 2001 From: roninsightrx Date: Thu, 12 Nov 2026 13:26:39 -0800 Subject: [PATCH 4/6] Keep missing values distinct in combined two-variable strata add_stratification() pasted the values of both stratification variables, so a tuple (NA, "X") became "NA, X" and collided with the literal ("NA", "X"); both were then binned and aggregated as one stratum. Missing values are now labeled "" via strat_value_label(), and literal values of the form "", "<>", ... get one more pair of brackets, which keeps the labels injective. The mapping does not depend on the data, so observed and simulated data (stratified separately) are labeled consistently. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 3 +++ R/add_stratification.R | 24 +++++++++++++++++++++-- R/define_bins.R | 3 ++- man/add_stratification.Rd | 5 ++++- man/calc_vpc_continuous.Rd | 3 ++- man/define_bins.Rd | 3 ++- man/vpc.Rd | 3 ++- man/vpc_cat.Rd | 3 ++- man/vpc_cens.Rd | 3 ++- man/vpc_tte.Rd | 3 ++- tests/testthat/test-add_stratification.R | 17 ++++++++++++++++ tests/testthat/test-binning.R | 25 ++++++++++++++++++++++++ 12 files changed, 85 insertions(+), 10 deletions(-) diff --git a/NEWS.md b/NEWS.md index c712831..e2e025b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -10,6 +10,9 @@ 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 `""` + in the combined stratum (e.g. `", X"`), so they are no longer merged + with the literal value `"NA"` (`"NA, X"`) when calculating the VPC. - `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 diff --git a/R/add_stratification.R b/R/add_stratification.R index 6b9c4d3..81cf420 100644 --- a/R/add_stratification.R +++ b/R/add_stratification.R @@ -3,7 +3,10 @@ #' 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{""} in the combined stratum, so that e.g. +#' \code{(NA, "x")} (\code{", x"}) remains distinct from +#' \code{("NA", "x")} (\code{"NA, x"}); see \code{strat_value_label()}. #' #' @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. @@ -17,7 +20,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])) @@ -33,6 +36,23 @@ add_stratification <- function (dat, stratify, verbose = FALSE) { dat } +#' Label of the values of a stratification variable in a combined stratum +#' +#' Missing values are labeled `""`. To keep the labels unique (and +#' independent of the data, so that observed and simulated data are labeled +#' consistently), literal values of the form `""`, `"<>"`, 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) + lit <- !is.na(x) & grepl("^<+NA>+$", x) + x[lit] <- paste0("<", x[lit], ">") + x[is.na(x)] <- "" + x +} + #' Add separate columns for each of two stratification variables #' #' Adds `strat1` and `strat2` columns to `dat` based on its combined `strat` diff --git a/R/define_bins.R b/R/define_bins.R index efc4c26..6368581 100644 --- a/R/define_bins.R +++ b/R/define_bins.R @@ -9,7 +9,8 @@ #' 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"}), or +#' values separated by a comma and a space, e.g. \code{"1, female"}, with +#' missing values shown as \code{""}), 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. When binning by stratum (\code{vpc()} and \code{vpc_cens()}), diff --git a/man/add_stratification.Rd b/man/add_stratification.Rd index 1d23a52..4d82514 100644 --- a/man/add_stratification.Rd +++ b/man/add_stratification.Rd @@ -17,5 +17,8 @@ add_stratification(dat, stratify, verbose = FALSE) 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{""} in the combined stratum, so that e.g. +\code{(NA, "x")} (\code{", x"}) remains distinct from +\code{("NA", "x")} (\code{"NA, x"}); see \code{strat_value_label()}. } diff --git a/man/calc_vpc_continuous.Rd b/man/calc_vpc_continuous.Rd index 8b2fbd2..a6851ac 100644 --- a/man/calc_vpc_continuous.Rd +++ b/man/calc_vpc_continuous.Rd @@ -38,7 +38,8 @@ 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"}), or +values separated by a comma and a space, e.g. \code{"1, female"}, with +missing values shown as \code{""}), or be unnamed with one element per stratum in the order of the strata.} \item{bin_mid}{either "mean" for the mean of all timepoints (default) or "middle" to use the average of the bin boundaries.} diff --git a/man/define_bins.Rd b/man/define_bins.Rd index 75f7af1..b392946 100644 --- a/man/define_bins.Rd +++ b/man/define_bins.Rd @@ -25,7 +25,8 @@ 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"}), or +values separated by a comma and a space, e.g. \code{"1, female"}, with +missing values shown as \code{""}), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/man/vpc.Rd b/man/vpc.Rd index d0d86b7..da6086e 100644 --- a/man/vpc.Rd +++ b/man/vpc.Rd @@ -64,7 +64,8 @@ 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"}), or +values separated by a comma and a space, e.g. \code{"1, female"}, with +missing values shown as \code{""}), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/man/vpc_cat.Rd b/man/vpc_cat.Rd index f1bf3ec..ab2b7e8 100644 --- a/man/vpc_cat.Rd +++ b/man/vpc_cat.Rd @@ -44,7 +44,8 @@ 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"}), or +values separated by a comma and a space, e.g. \code{"1, female"}, with +missing values shown as \code{""}), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/man/vpc_cens.Rd b/man/vpc_cens.Rd index 1e73e87..6ab7bc3 100644 --- a/man/vpc_cens.Rd +++ b/man/vpc_cens.Rd @@ -47,7 +47,8 @@ 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"}), or +values separated by a comma and a space, e.g. \code{"1, female"}, with +missing values shown as \code{""}), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/man/vpc_tte.Rd b/man/vpc_tte.Rd index 75109b8..62b02ae 100644 --- a/man/vpc_tte.Rd +++ b/man/vpc_tte.Rd @@ -63,7 +63,8 @@ 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"}), or +values separated by a comma and a space, e.g. \code{"1, female"}, with +missing values shown as \code{""}), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/tests/testthat/test-add_stratification.R b/tests/testthat/test-add_stratification.R index 1f8ed6e..1697d56 100644 --- a/tests/testthat/test-add_stratification.R +++ b/tests/testthat/test-add_stratification.R @@ -51,3 +51,20 @@ test_that("vpc with 2 stratification variables respects factor order (#101)", { expect_equal(levels(built$layout$layout$xfac), c("b", "a", "c")) expect_equal(levels(built$layout$layout$yfac), c("e", "d", "f")) }) + +test_that("add_stratification keeps missing values distinct from literal \"NA\" in combined strata", { + dat <- data.frame( + x = c(NA, "NA", "", NA, "a"), + y = c("X", "X", "X", NA, "X") + ) + out <- add_stratification(dat, c("x", "y")) + expect_equal(as.character(out$strat), c(", X", "NA, X", "<>, X", ", ", "a, X")) + expect_equal(nlevels(out$strat), 5) + # labels do not depend on the other values in the data (obs vs sim) + expect_equal(as.character(add_stratification(dat[1, ], c("x", "y"))$strat), ", X") + # original values are recovered per stratum + summ <- data.frame(strat = out$strat) + cols <- add_strat_columns(summ, c("x", "y"), out) + expect_equal(cols$strat1, dat$x) + expect_equal(cols$strat2, dat$y) +}) diff --git a/tests/testthat/test-binning.R b/tests/testthat/test-binning.R index 9e217ed..00e9b51 100644 --- a/tests/testthat/test-binning.R +++ b/tests/testthat/test-binning.R @@ -382,3 +382,28 @@ test_that("outlier areas work with per-stratum bins and color stratification", { expect_s3_class(ggplot2::ggplot_build(pl), "ggplot_built") } }) + +test_that("bin_by_strata keeps missing and literal \"NA\" values distinct with two stratification variables", { + d <- strat_test_data() + d$obs$SEX <- "X" + d$sim$SEX <- "X" + d$obs$GRP[d$obs$ID %in% c(1, 2)] <- NA + d$sim$GRP[d$sim$ID %in% c(1, 2)] <- NA + d$obs$GRP[d$obs$ID %in% c(3, 4)] <- "NA" + d$sim$GRP[d$sim$ID %in% c(3, 4)] <- "NA" + d$obs$TIME[d$obs$GRP %in% "NA"] <- d$obs$TIME[d$obs$GRP %in% "NA"] * 2 + d$sim$TIME[d$sim$GRP %in% "NA"] <- d$sim$TIME[d$sim$GRP %in% "NA"] * 2 + db <- vpc(sim = d$sim, obs = d$obs, stratify = c("GRP", "SEX"), bins = "time", + n_bins = 3, bin_by_strata = TRUE, vpcdb = TRUE) + expect_setequal(names(db$bins), c("A, X", "B, X", "NA, X", ", X")) + expect_equal(max(db$bins[["NA, X"]]), max(d$obs$TIME[d$obs$MDV == 0 & d$obs$GRP %in% "NA"]) * 1.001) + expect_equal(max(db$bins[[", X"]]), max(d$obs$TIME[d$obs$MDV == 0 & is.na(d$obs$GRP)]) * 1.001) + # aggregated per stratum, with the original values recovered + mis <- db$aggr_obs[db$aggr_obs$strat == ", X", ] + lit <- db$aggr_obs[db$aggr_obs$strat == "NA, X", ] + expect_true(all(is.na(mis$strat1))) + expect_true(all(lit$strat1 == "NA")) + expect_equal(nrow(db$obs[db$obs$strat == ", X", ]), sum(d$obs$MDV == 0 & is.na(d$obs$GRP))) + expect_false(any(is.na(db$obs$bin))) + expect_s3_class(ggplot2::ggplot_build(plot_vpc(db)), "ggplot_built") +}) From f62376c30aee2f3e4a00a4516e794f1a8cff56df Mon Sep 17 00:00:00 2001 From: roninsightrx Date: Thu, 12 Nov 2026 13:40:43 -0800 Subject: [PATCH 5/6] Keep vpc_vpc() positional arguments compatible `bin_by_strata` was inserted before `sim_ref`, so a positional `sim_ref` bound to `bin_by_strata` and silently produced an uncorrected VPC. Move it after `...` so it can only be passed by name, and add a regression test that a positional `sim_ref` still yields the reference-corrected VPC. Co-Authored-By: Claude Opus 5.5 --- R/vpc.R | 4 ++-- man/vpc.Rd | 30 +++++++++++++++--------------- tests/testthat/test-ref_corr.R | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 50 insertions(+), 18 deletions(-) diff --git a/R/vpc.R b/R/vpc.R index dc1e3a3..c43dcac 100644 --- a/R/vpc.R +++ b/R/vpc.R @@ -117,9 +117,9 @@ vpc_vpc <- function(sim = NULL, labeller = NULL, vpcdb = FALSE, verbose = FALSE, - bin_by_strata = FALSE, sim_ref = NULL, - ...) { + ..., + bin_by_strata = FALSE) { msg("Configuring and initializing...", verbose=verbose) vpc_data <- read_vpc( diff --git a/man/vpc.Rd b/man/vpc.Rd index da6086e..04392fd 100644 --- a/man/vpc.Rd +++ b/man/vpc.Rd @@ -42,9 +42,9 @@ vpc_vpc( labeller = NULL, vpcdb = FALSE, verbose = FALSE, - bin_by_strata = FALSE, sim_ref = NULL, - ... + ..., + bin_by_strata = FALSE ) } \arguments{ @@ -153,19 +153,6 @@ columns (\code{"free_y"}), or both rows and columns (\code{"free"})?} \item{verbose}{show debugging information (TRUE or FALSE)} -\item{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).} - \item{sim_ref}{simulations of a reference dataset, for a reference-corrected VPC (rcVPC). Same format, columns and record order as \code{sim}, but simulated from a dataset in which selected independent variables (dose, @@ -183,6 +170,19 @@ default bound of 0); such records are excluded with a warning, also when variability component (Eq. 1 only) can be done manually by multiplying DV in \code{obs} and \code{sim} by \code{PRED_REF / PRED} before calling \code{vpc()}.} + +\item{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).} } \value{ a list containing calculated VPC information (when vpcdb=TRUE), or a ggplot2 object (default) diff --git a/tests/testthat/test-ref_corr.R b/tests/testthat/test-ref_corr.R index 773cd72..ea9356f 100644 --- a/tests/testthat/test-ref_corr.R +++ b/tests/testthat/test-ref_corr.R @@ -260,8 +260,40 @@ test_that("corrected observations are not re-censored against raw LLOQ", { test_that("new vpc_vpc() arguments do not shift positional arguments", { f <- names(formals(vpc_vpc)) - expect_equal(f[(length(f) - 1):length(f)], c("sim_ref", "...")) expect_equal(which(f == "pi"), 16) + expect_equal(which(f == "sim_ref"), 32) + expect_equal(which(f == "..."), 33) + # arguments added later (e.g. `bin_by_strata`, #11) come after `...`, so + # they can only be supplied by name + expect_equal(f[length(f)], "bin_by_strata") +}) + +test_that("sim_ref supplied by position still gives a reference-corrected VPC", { + fx <- refcorr_vpc_data() + named <- vpc_vpc( + sim = fx$sim, obs = fx$obs, sim_ref = fx$ref, + obs_cols = fx$obs_cols, sim_cols = fx$sim_cols, + software = "nonmem", vpcdb = TRUE + ) + # all arguments up to and including `sim_ref` by position + f <- formals(vpc_vpc) + pos <- lapply(f[seq_len(which(names(f) == "sim_ref") - 1)], eval) + pos$sim <- fx$sim + pos$obs <- fx$obs + pos["psn_folder"] <- list(NULL) + pos$obs_cols <- fx$obs_cols + pos$sim_cols <- fx$sim_cols + pos$software <- "nonmem" + pos$vpcdb <- TRUE + positional <- do.call(vpc_vpc, c(unname(pos), list(fx$ref))) + expect_equal(positional$vpc_dat, named$vpc_dat) + expect_equal(positional$aggr_obs, named$aggr_obs) + uncorrected <- vpc_vpc( + sim = fx$sim, obs = fx$obs, + obs_cols = fx$obs_cols, sim_cols = fx$sim_cols, + software = "nonmem", vpcdb = TRUE + ) + expect_false(isTRUE(all.equal(positional$vpc_dat, uncorrected$vpc_dat))) }) test_that("obs PRED fallback warns on record mismatch (pcVPC)", { From 017322218bb3fb581e21d7c06c567b81eba512e5 Mon Sep 17 00:00:00 2001 From: roninsightrx Date: Thu, 12 Nov 2026 13:45:39 -0800 Subject: [PATCH 6/6] Escape separator in combined two-variable strata The combined stratum was formed with paste(sep = ", "), so e.g. ("a, b", "c") and ("a", "b, c") both became "a, b, c" and were binned and summarised as one stratum. strat_value_label() now escapes backslashes and commas in values ("\\" and "\,"), which makes the label injective while leaving labels of ordinary values unchanged and staying independent of the data (obs and sim are stratified separately). Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 4 +++- R/add_stratification.R | 20 +++++++++++++++----- R/define_bins.R | 3 ++- man/add_stratification.Rd | 4 +++- man/calc_vpc_continuous.Rd | 3 ++- man/define_bins.Rd | 3 ++- man/vpc.Rd | 3 ++- man/vpc_cat.Rd | 3 ++- man/vpc_cens.Rd | 3 ++- man/vpc_tte.Rd | 3 ++- tests/testthat/test-add_stratification.R | 16 ++++++++++++++++ tests/testthat/test-binning.R | 23 +++++++++++++++++++++++ 12 files changed, 74 insertions(+), 14 deletions(-) diff --git a/NEWS.md b/NEWS.md index e2e025b..1cca7ef 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,7 +12,9 @@ literal value `"NA"`). Not available for `bins = "percentiles"`. - With two stratification variables, missing values are now labeled `""` in the combined stratum (e.g. `", X"`), so they are no longer merged - with the literal value `"NA"` (`"NA, X"`) when calculating the VPC. + 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 diff --git a/R/add_stratification.R b/R/add_stratification.R index 81cf420..8e94707 100644 --- a/R/add_stratification.R +++ b/R/add_stratification.R @@ -6,7 +6,9 @@ #' original columns is respected; non-factor columns are sorted. Missing #' values are labeled \code{""} in the combined stratum, so that e.g. #' \code{(NA, "x")} (\code{", x"}) remains distinct from -#' \code{("NA", "x")} (\code{"NA, x"}); see \code{strat_value_label()}. +#' \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. @@ -38,15 +40,23 @@ add_stratification <- function (dat, stratify, verbose = FALSE) { #' Label of the values of a stratification variable in a combined stratum #' -#' Missing values are labeled `""`. To keep the labels unique (and -#' independent of the data, so that observed and simulated data are labeled -#' consistently), literal values of the form `""`, `"<>"`, etc. are -#' wrapped in one more pair of angle brackets. Other values are unchanged. +#' 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 `""`, and literal values of the form +#' `""`, `"<>"`, 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)] <- "" diff --git a/R/define_bins.R b/R/define_bins.R index 6368581..720f277 100644 --- a/R/define_bins.R +++ b/R/define_bins.R @@ -10,7 +10,8 @@ #' 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{""}), or +#' missing values shown as \code{""} 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. When binning by stratum (\code{vpc()} and \code{vpc_cens()}), diff --git a/man/add_stratification.Rd b/man/add_stratification.Rd index 4d82514..0eaabce 100644 --- a/man/add_stratification.Rd +++ b/man/add_stratification.Rd @@ -20,5 +20,7 @@ then by the levels of the second variable. Factor level order of the original columns is respected; non-factor columns are sorted. Missing values are labeled \code{""} in the combined stratum, so that e.g. \code{(NA, "x")} (\code{", x"}) remains distinct from -\code{("NA", "x")} (\code{"NA, x"}); see \code{strat_value_label()}. +\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. } diff --git a/man/calc_vpc_continuous.Rd b/man/calc_vpc_continuous.Rd index a6851ac..bd3cd0a 100644 --- a/man/calc_vpc_continuous.Rd +++ b/man/calc_vpc_continuous.Rd @@ -39,7 +39,8 @@ 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{""}), or +missing values shown as \code{""} and commas or backslashes within +values escaped by a backslash), or be unnamed with one element per stratum in the order of the strata.} \item{bin_mid}{either "mean" for the mean of all timepoints (default) or "middle" to use the average of the bin boundaries.} diff --git a/man/define_bins.Rd b/man/define_bins.Rd index b392946..d401dd1 100644 --- a/man/define_bins.Rd +++ b/man/define_bins.Rd @@ -26,7 +26,8 @@ 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{""}), or +missing values shown as \code{""} and commas or backslashes within +values escaped by a backslash), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/man/vpc.Rd b/man/vpc.Rd index 04392fd..bbf0da1 100644 --- a/man/vpc.Rd +++ b/man/vpc.Rd @@ -65,7 +65,8 @@ 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{""}), or +missing values shown as \code{""} and commas or backslashes within +values escaped by a backslash), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/man/vpc_cat.Rd b/man/vpc_cat.Rd index ab2b7e8..e8a41b6 100644 --- a/man/vpc_cat.Rd +++ b/man/vpc_cat.Rd @@ -45,7 +45,8 @@ 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{""}), or +missing values shown as \code{""} and commas or backslashes within +values escaped by a backslash), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/man/vpc_cens.Rd b/man/vpc_cens.Rd index 6ab7bc3..b1122b7 100644 --- a/man/vpc_cens.Rd +++ b/man/vpc_cens.Rd @@ -48,7 +48,8 @@ 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{""}), or +missing values shown as \code{""} and commas or backslashes within +values escaped by a backslash), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/man/vpc_tte.Rd b/man/vpc_tte.Rd index 62b02ae..5b31e30 100644 --- a/man/vpc_tte.Rd +++ b/man/vpc_tte.Rd @@ -64,7 +64,8 @@ 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{""}), or +missing values shown as \code{""} and commas or backslashes within +values escaped by a backslash), or be unnamed with one element per stratum in the order of the strata.} \item{n_bins}{when using the "auto" binning method, what number of bins to diff --git a/tests/testthat/test-add_stratification.R b/tests/testthat/test-add_stratification.R index 1697d56..e452634 100644 --- a/tests/testthat/test-add_stratification.R +++ b/tests/testthat/test-add_stratification.R @@ -68,3 +68,19 @@ test_that("add_stratification keeps missing values distinct from literal \"NA\" expect_equal(cols$strat1, dat$x) expect_equal(cols$strat2, dat$y) }) + +test_that("add_stratification keeps strata distinct when values contain the separator", { + dat <- data.frame( + x = c("a, b", "a", "a\\", "a"), + y = c("c", "b, c", ", c", "\\, c") + ) + out <- add_stratification(dat, c("x", "y")) + expect_equal(nlevels(out$strat), 4) + expect_equal(as.character(out$strat)[1:2], c("a\\, b, c", "a, b\\, c")) + # labels of values without commas or backslashes are unchanged + expect_equal(as.character(add_stratification(data.frame(x = "a b", y = 1), c("x", "y"))$strat), "a b, 1") + # original values are recovered per stratum + cols <- add_strat_columns(data.frame(strat = out$strat), c("x", "y"), out) + expect_equal(cols$strat1, dat$x) + expect_equal(cols$strat2, dat$y) +}) diff --git a/tests/testthat/test-binning.R b/tests/testthat/test-binning.R index 00e9b51..9589897 100644 --- a/tests/testthat/test-binning.R +++ b/tests/testthat/test-binning.R @@ -407,3 +407,26 @@ test_that("bin_by_strata keeps missing and literal \"NA\" values distinct with t expect_false(any(is.na(db$obs$bin))) expect_s3_class(ggplot2::ggplot_build(plot_vpc(db)), "ggplot_built") }) + +test_that("bin_by_strata keeps strata distinct when values contain the separator", { + d <- strat_test_data() + # ("a, b", "c") for even IDs vs ("a", "b, c") for odd IDs + d$obs$V1 <- ifelse(d$obs$GRP == "A", "a, b", "a") + d$sim$V1 <- ifelse(d$sim$GRP == "A", "a, b", "a") + d$obs$V2 <- ifelse(d$obs$GRP == "A", "c", "b, c") + d$sim$V2 <- ifelse(d$sim$GRP == "A", "c", "b, c") + db <- vpc(sim = d$sim, obs = d$obs, stratify = c("V1", "V2"), bins = "time", + n_bins = 3, bin_by_strata = TRUE, vpcdb = TRUE) + expect_length(db$bins, 2) + expect_setequal(names(db$bins), c("a\\, b, c", "a, b\\, c")) + # stratum ("a", "b, c") (GRP B) has twice the time range of ("a, b", "c") + expect_equal(max(db$bins[["a, b\\, c"]]), max(d$obs$TIME[d$obs$MDV == 0 & d$obs$GRP == "B"]) * 1.001) + expect_equal(max(db$bins[["a\\, b, c"]]), max(d$obs$TIME[d$obs$MDV == 0 & d$obs$GRP == "A"]) * 1.001) + expect_setequal(paste(db$aggr_obs$strat1, db$aggr_obs$strat2, sep = "|"), c("a, b|c", "a|b, c")) + # manual bins addressed by the stratum names + bins <- list(c(0, 30), c(0, 10, 60)) + names(bins) <- c("a\\, b, c", "a, b\\, c") + db2 <- vpc(sim = d$sim, obs = d$obs, stratify = c("V1", "V2"), bins = bins, vpcdb = TRUE) + expect_equal(db2$aggr_obs$bin_max[db2$aggr_obs$strat1 == "a"], c(10, 60)) + expect_s3_class(ggplot2::ggplot_build(plot_vpc(db2)), "ggplot_built") +})