diff --git a/DESCRIPTION b/DESCRIPTION index a304167..a15b95a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: vpc Title: Create Visual Predictive Checks -Version: 1.3.5 +Version: 1.3.6 Date: 2026-11-12 Authors@R: c( diff --git a/NEWS.md b/NEWS.md index 80ef554..43c059c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,27 @@ +# vpc 1.3.6 +- Bins can now be determined per stratum (#11). With `bin_by_strata = TRUE` in + `vpc()` and `vpc_cens()`, automatic binning methods are applied to the data + of each stratum separately. Manual bins can be specified per stratum by + passing a list to `bins` (named by stratum, or unnamed in the order of the + strata), e.g. `bins = list(A = c(0, 2, 6, 24), B = c(0, 4, 12, 48))`, which + can also mix binning methods and numeric separators. `n_bins` can likewise be + given per stratum. The bin separators shown in the plot are drawn per panel. + With per-stratum binning, `db$bins` in the vpcdb object is a named list. + Missing values of the stratification variable are binned as their own + stratum (with an `NA` name in `db$bins`; distinct from a stratum with the + literal value `"NA"`). Not available for `bins = "percentiles"`. +- With two stratification variables, missing values are now labeled `""` + in the combined stratum (e.g. `", X"`), so they are no longer merged + with the literal value `"NA"` (`"NA, X"`) when calculating the VPC. Commas + and backslashes within values are escaped in the combined stratum, so e.g. + `("a, b", "c")` and `("a", "b, c")` are no longer merged. +- `vpc_cens()` with `stratify_color`: the color stratification is now + implemented. The observed fraction and simulated CI are calculated per + color stratum and drawn in separate colors (with legend), while facets are + determined by `stratify` only. Previously the color variable was added only + after the data were stratified, so it was ignored (color only) or + mislabeled as a facet (facet and color). + # vpc 1.3.5 - Consistent handling of censored and missing data (#80). Censored values are now represented internally as `-Inf` (below `lloq`) or `Inf` (above `uloq`) diff --git a/R/add_stratification.R b/R/add_stratification.R index caef195..8e94707 100644 --- a/R/add_stratification.R +++ b/R/add_stratification.R @@ -3,7 +3,12 @@ #' When two stratification variables are supplied, the combined `strat` column #' is a factor whose levels are ordered by the levels of the first variable, #' then by the levels of the second variable. Factor level order of the -#' original columns is respected; non-factor columns are sorted. +#' original columns is respected; non-factor columns are sorted. Missing +#' values are labeled \code{""} in the combined stratum, so that e.g. +#' \code{(NA, "x")} (\code{", x"}) remains distinct from +#' \code{("NA", "x")} (\code{"NA, x"}). Commas and backslashes in values are +#' escaped (\code{"\\,"} and \code{"\\\\"}), so that e.g. \code{("a, b", "c")} +#' and \code{("a", "b, c")} remain distinct strata. #' #' @param dat An input data.frame or similar object #' @param stratify character vector of stratification variables. Only 1 or 2 stratification variables can be supplied. @@ -17,7 +22,7 @@ add_stratification <- function (dat, stratify, verbose = FALSE) { dat$strat <- data.frame(dat)[,stratify] } else { strat_cols <- lapply(stratify, function(x) as.factor(dat[[x]])) - strat_label <- do.call(paste, c(lapply(strat_cols, as.character), sep = ", ")) + strat_label <- do.call(paste, c(lapply(strat_cols, strat_value_label), sep = ", ")) # Order the combined levels by the first variable, then the second, etc. level_order <- do.call(order, lapply(strat_cols, as.integer)) dat$strat <- factor(strat_label, levels = unique(strat_label[level_order])) @@ -33,6 +38,31 @@ add_stratification <- function (dat, stratify, verbose = FALSE) { dat } +#' Label of the values of a stratification variable in a combined stratum +#' +#' The labels are combined with `", "` into the stratum, and are chosen such +#' that distinct combinations of values always give distinct strata. They are +#' independent of the data, so that observed and simulated data (which are +#' stratified separately) are labeled consistently: +#' - backslashes and commas in values are escaped (`\\` and `\,`), so the +#' separator is unambiguous, e.g. `("a, b", "c")` gives `"a\, b, c"` and +#' `("a", "b, c")` gives `"a, b\, c"`; +#' - missing values are labeled `""`, 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)] <- "" + x +} + #' Add separate columns for each of two stratification variables #' #' Adds `strat1` and `strat2` columns to `dat` based on its combined `strat` @@ -64,3 +94,20 @@ add_strat_columns <- function(dat, stratify, ...) { } dat } + +#' Add a column for each stratification variable, named by the variable +#' +#' Like [add_strat_columns()], but names the columns after the stratification +#' variables instead of `strat1`, `strat2`, ... +#' @inheritParams add_strat_columns +#' @param stratify character vector of stratification variables +#' @keywords internal +#' @noRd +add_strat_value_columns <- function(dat, stratify, ...) { + if (is.null(dat)) return(dat) + dat <- add_strat_columns(dat, stratify, ...) + for (i in seq_along(stratify)) { + colnames(dat)[match(paste0("strat", i), colnames(dat))] <- stratify[i] + } + dat +} diff --git a/R/calc_vpc_continuous.R b/R/calc_vpc_continuous.R index a574520..74cae4c 100644 --- a/R/calc_vpc_continuous.R +++ b/R/calc_vpc_continuous.R @@ -73,8 +73,9 @@ calc_vpc_continuous <- function(sim, obs, loq, pi, ci, stratify, bins, bin_mid, bin_mid = mean(.data$mean_idv, na.rm = TRUE) ) - vpc_dat$bin_min <- rep(bins[1:(length(bins)-1)], length(unique(vpc_dat$strat)))[vpc_dat$bin] - vpc_dat$bin_max <- rep(bins[2:length(bins)], length(unique(vpc_dat$strat)))[vpc_dat$bin] + bounds <- bin_boundaries(bins, vpc_dat$bin, vpc_dat$strat) + vpc_dat$bin_min <- bounds$bin_min + vpc_dat$bin_max <- bounds$bin_max if(bin_mid == "middle") { vpc_dat$bin_mid <- (vpc_dat$bin_min + vpc_dat$bin_max)/2 } @@ -92,8 +93,9 @@ calc_vpc_continuous <- function(sim, obs, loq, pi, ci, stratify, bins, bin_mid, obs95 = quantile_cens(x=dv, probs=pi[2], limit = cens_limit, cens = cens_type), bin_mid = mean(idv) ) - aggr_obs$bin_min <- rep(bins[1:(length(bins)-1)], length(unique(aggr_obs$strat)) )[aggr_obs$bin] - aggr_obs$bin_max <- rep(bins[2:length(bins)], length(unique(aggr_obs$strat)) )[aggr_obs$bin] + bounds <- bin_boundaries(bins, aggr_obs$bin, aggr_obs$strat) + aggr_obs$bin_min <- bounds$bin_min + aggr_obs$bin_max <- bounds$bin_max if(bin_mid == "middle") { aggr_obs$bin_mid <- (aggr_obs$bin_min + aggr_obs$bin_max)/2 } diff --git a/R/define_bins.R b/R/define_bins.R index 6fbb8e8..720f277 100644 --- a/R/define_bins.R +++ b/R/define_bins.R @@ -3,13 +3,41 @@ #' @inheritParams read_vpc #' @param bins either "density", "time", or "data", "none", or one of the #' approaches available in classInterval() such as "jenks" (default) or -#' "pretty", or a numeric vector specifying the bin separators. +#' "pretty", or a numeric vector specifying the bin separators. For \code{vpc()} +#' and \code{vpc_cens()}, when binning +#' by stratum (see \code{bin_by_strata}), \code{bins} can also be a list +#' with one element (a binning method or numeric vector of bin separators) +#' per stratum. The list should be named by stratum (the value of the +#' stratification variable, or for two stratification variables the two +#' values separated by a comma and a space, e.g. \code{"1, female"}, with +#' missing values shown as \code{""} and commas or backslashes within +#' values escaped by a backslash), or +#' be unnamed with one element per stratum in the order of the strata. #' @param n_bins when using the "auto" binning method, what number of bins to -#' aim for -#' @return A list with named elements: "bins", the bin separator values; +#' aim for. When binning by stratum (\code{vpc()} and \code{vpc_cens()}), +#' this can also be a list or vector with +#' one value per stratum (named or ordered as for \code{bins}). +#' @param bin_by_strata Determine the bins separately for each stratum +#' (\code{TRUE}), or use the same bins for all strata (\code{FALSE}, +#' default)? When \code{TRUE}, automatic binning methods are applied to the +#' data of each stratum separately. Specifying \code{bins} as a list +#' implies \code{bin_by_strata = TRUE}. Missing values of the +#' stratification variable form their own stratum (with an \code{NA} name +#' in the returned list of bins; for manual bins, use an \code{NA} name or, +#' when no stratum has the literal value \code{"NA"}, the name +#' \code{"NA"}). +#' Binning by stratum is available for all automatic binning methods except +#' \code{"percentiles"} (which labels the bins by their interval instead of +#' plotting them on the numeric scale of the independent variable). +#' @param verbose show debugging information (TRUE or FALSE) +#' @return A list with named elements: "bins", the bin separator values (a +#' named list with one numeric vector per stratum when binning by stratum); #' "labeled", are the bins labeled?; "obs", binned observed data; "sim", #' binned simulated data. Additionally, "tmp_bins" is added for tte data. -define_bins <- function(obs, sim, bins, n_bins, verbose=FALSE) { +define_bins <- function(obs, sim, bins, n_bins, bin_by_strata=FALSE, verbose=FALSE) { + if (is.list(bins) || isTRUE(bin_by_strata)) { + return(define_bins_by_strata(obs=obs, sim=sim, bins=bins, n_bins=n_bins, verbose=verbose)) + } labeled_bins <- bins[1] == "percentiles" if (!inherits(bins, "numeric")) { if (!is.null(obs)) { @@ -37,6 +65,157 @@ define_bins <- function(obs, sim, bins, n_bins, verbose=FALSE) { ) } +#' @describeIn define_bins Define bins separately for each stratum +define_bins_by_strata <- function(obs, sim, bins, n_bins, verbose=FALSE) { + ref <- if (!is.null(obs)) obs else sim + if (is.null(ref)) { + stop("No data available for binning.") + } + strata <- strata_levels(obs, sim) + bin_list <- list() + for (s in strata) { + bins_s <- select_strat_element(bins, s, strata, "bins") + n_bins_s <- select_strat_element(n_bins, s, strata, "n_bins") + if (!is.numeric(bins_s) && "percentiles" %in% bins_s) { + stop("`bins = \"percentiles\"` is not supported when binning by stratum.") + } + if (!is.numeric(bins_s)) { + dat_s <- NULL + if (!is.null(obs)) dat_s <- obs[strat_key(obs$strat) == s, , drop = FALSE] + if ((is.null(dat_s) || nrow(dat_s) == 0) && !is.null(sim)) { + dat_s <- sim[strat_key(sim$strat) == s, , drop = FALSE] + } + bins_s <- auto_bin(dat_s, bins_s, n_bins_s) + if (is.null(bins_s)) { + stop("Automatic binning unsuccessful for stratum `", strat_label(s), "`, try increasing the number of bins, or specify bin separators manually.") + } + } + bin_list[[s]] <- unique(as.numeric(bins_s)) + msg(paste0("Binning (stratum ", strat_label(s), "): ", paste(bin_list[[s]], collapse=' ')), verbose=verbose) + } + obs <- bin_data_by_strata(obs, bin_list) + sim <- bin_data_by_strata(sim, bin_list) + # return the bins named by stratum value (NA for missing values) + names(bin_list) <- strat_name(names(bin_list)) + list( + bins=bin_list, + labeled=FALSE, + obs=obs, + sim=sim + ) +} + +#' Internal stratum key used for per-stratum binning +#' +#' Stratum values are prefixed with "v:", and missing values of the +#' stratification variable form their own stratum with key "na". The keys can +#' therefore never collide, also not with a stratum with the literal value +#' "NA". +#' @param strat stratum values (or names of a per-stratum list of bins, in +#' which missing strata have an `NA` name) +#' @noRd +strat_key <- function(strat) { + strat <- as.character(strat) + ifelse(is.na(strat), "na", paste0("v:", strat)) +} + +#' Stratum value (NA for missing) from an internal stratum key +#' @noRd +strat_name <- function(key) { + ifelse(key == "na", NA_character_, sub("^v:", "", key)) +} + +#' Label for a stratum key in messages +#' @noRd +strat_label <- function(key) { + ifelse(key == "na", "", sub("^v:", "", key)) +} + +#' Keys of the strata across observed and simulated data +#' @noRd +strata_levels <- function(obs, sim) { + get_levels <- function(x) { + if (is.null(x)) return(character(0)) + lev <- if (is.factor(x$strat)) levels(droplevels(x$strat)) else as.character(unique(stats::na.omit(x$strat))) + key <- strat_key(lev) + if (anyNA(x$strat)) key <- c(key, "na") + key + } + unique(c(get_levels(obs), get_levels(sim))) +} + +#' Select the element of a per-stratum argument (bins or n_bins) for stratum +#' key `s` +#' +#' Elements are matched by name. The missing stratum is matched by an `NA` +#' name, or by the name "NA" when there is no stratum with the literal value +#' "NA". +#' @noRd +select_strat_element <- function(x, s, strata, name) { + per_strat <- is.list(x) || (name == "n_bins" && length(x) > 1) + if (!per_strat) return(x) + nms <- names(x) + if (!is.null(nms) && all(is.na(nms) | nms != "")) { + keys <- strat_key(nms) + if (!"v:NA" %in% strata) keys[keys == "v:NA"] <- "na" + if (!s %in% keys) { + stop("No `", name, "` specified for stratum `", strat_label(s), "`. Available strata: ", + paste(strat_label(strata), collapse = "; ")) + } + return(x[[match(s, keys)]]) + } + if (length(x) != length(strata)) { + stop("When `", name, "` is an unnamed list, it should have one element per stratum (", + length(strata), "): ", paste(strat_label(strata), collapse = "; ")) + } + x[[match(s, strata)]] +} + +#' Bin data using separate bin separators per stratum, retaining row order +#' +#' @param bins list of bin separators, named by stratum key +#' @noRd +bin_data_by_strata <- function(x, bins) { + if (is.null(x)) return(x) + bin <- rep(NA_integer_, nrow(x)) + strat <- strat_key(x$strat) + for (s in names(bins)) { + idx <- which(strat == s) + if (length(idx) > 0) { + bin[idx] <- cut(x$idv[idx], bins[[s]], labels = FALSE, right = FALSE, include.lowest = TRUE) + } + } + x$bin <- bin + x +} + +#' Lower and upper bin boundaries for a set of bins +#' +#' @param bins numeric vector of bin separators, or a named list of these (one +#' per stratum, with an `NA` name for missing strata) +#' @param bin bin number (or factor) +#' @param strat stratum for each bin (only used when `bins` is a list) +#' @return a list with `bin_min` and `bin_max` +#' @noRd +bin_boundaries <- function(bins, bin, strat = NULL) { + bin <- as.integer(bin) + if (is.list(bins)) { + strat <- strat_key(strat) + keys <- strat_key(names(bins)) + bin_min <- bin_max <- rep(NA_real_, length(bin)) + for (s in intersect(unique(strat), keys)) { + idx <- which(strat == s) + b <- bins[[match(s, keys)]] + bin_min[idx] <- b[bin[idx]] + bin_max[idx] <- b[bin[idx] + 1] + } + } else { + bin_min <- bins[bin] + bin_max <- bins[bin + 1] + } + list(bin_min = bin_min, bin_max = bin_max) +} + #' @describeIn define_bins Define bins for time-to-event data #' @inheritParams vpc_tte define_bins_tte <- function(obs, sim, bins, n_bins, kmmc, verbose=FALSE) { diff --git a/R/plot_vpc.R b/R/plot_vpc.R index 52383c8..56b9845 100644 --- a/R/plot_vpc.R +++ b/R/plot_vpc.R @@ -102,21 +102,20 @@ 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]) } } } + 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 } @@ -164,7 +163,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=db$bins, 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. @@ -259,7 +259,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) } @@ -308,12 +312,29 @@ NULL #' @describeIn vpc_ggplot Show rug plot of bin separators #' @param bins Numeric vector of bin separators (if logical value, geom_blank is -#' returned) -geom_bin_sep <- function(bins, show, vpc_theme) { +#' returned), or a data.frame with the bin separators in column \code{x} and +#' the stratification columns (for bins that differ by stratum) +#' @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) ) { - 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)) + } + 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, @@ -326,6 +347,53 @@ 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) + strat <- rep(strata, lengths(db$bins)) + 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) @@ -442,7 +510,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), @@ -503,7 +579,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.R b/R/vpc.R index 37693d2..7b14915 100644 --- a/R/vpc.R +++ b/R/vpc.R @@ -118,7 +118,8 @@ vpc_vpc <- function(sim = NULL, vpcdb = FALSE, verbose = FALSE, sim_ref = NULL, - ...) { + ..., + bin_by_strata = FALSE) { msg("Configuring and initializing...", verbose=verbose) vpc_data <- read_vpc( @@ -256,7 +257,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..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) @@ -46,7 +49,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, @@ -77,6 +81,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 <- @@ -105,22 +125,8 @@ 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, 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 +144,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,19 +160,25 @@ 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) } } 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/add_stratification.Rd b/man/add_stratification.Rd index 1d23a52..0eaabce 100644 --- a/man/add_stratification.Rd +++ b/man/add_stratification.Rd @@ -17,5 +17,10 @@ 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"}). 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 5307803..16d127d 100644 --- a/man/calc_vpc_continuous.Rd +++ b/man/calc_vpc_continuous.Rd @@ -32,7 +32,16 @@ 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"}, with +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 08c8bb5..d401dd1 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,42 @@ 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"}, with +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 -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}. 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{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 +63,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 188878b..bbf0da1 100644 --- a/man/vpc.Rd +++ b/man/vpc.Rd @@ -43,7 +43,8 @@ vpc_vpc( vpcdb = FALSE, verbose = FALSE, sim_ref = NULL, - ... + ..., + bin_by_strata = FALSE ) } \arguments{ @@ -57,10 +58,21 @@ 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"}, with +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 -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.} @@ -159,6 +171,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/man/vpc_cat.Rd b/man/vpc_cat.Rd index 8972874..e8a41b6 100644 --- a/man/vpc_cat.Rd +++ b/man/vpc_cat.Rd @@ -38,10 +38,21 @@ 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"}, with +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 -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 7e29301..b1122b7 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,21 @@ 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"}, with +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 -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.} @@ -65,7 +77,10 @@ category) compared to the CI of the simulated fraction. Styled with the \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)} @@ -90,6 +105,19 @@ category) compared to the CI of the simulated fraction. Styled with the \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}. 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/man/vpc_ggplot.Rd b/man/vpc_ggplot.Rd index 4d7cbab..98aabe4 100644 --- a/man/vpc_ggplot.Rd +++ b/man/vpc_ggplot.Rd @@ -26,7 +26,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) @@ -79,12 +79,15 @@ 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)} \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/man/vpc_tte.Rd b/man/vpc_tte.Rd index 57cbfcf..5b31e30 100644 --- a/man/vpc_tte.Rd +++ b/man/vpc_tte.Rd @@ -57,10 +57,21 @@ 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"}, with +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 -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-add_stratification.R b/tests/testthat/test-add_stratification.R index 1f8ed6e..e452634 100644 --- a/tests/testthat/test-add_stratification.R +++ b/tests/testthat/test-add_stratification.R @@ -51,3 +51,36 @@ 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) +}) + +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 c177469..9589897 100644 --- a/tests/testthat/test-binning.R +++ b/tests/testthat/test-binning.R @@ -133,3 +133,300 @@ 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") +}) + +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: 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_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$SEX), "M") + expect_equal(unique(v$GRP), "B") + expect_equal(v$bin_max, db$bins[["M, B"]][v$bin + 1]) + 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", { + 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_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))) + 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) +}) + +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") +}) + +test_that("outlier areas work with per-stratum bins and color stratification", { + d <- strat_test_data() + for (smooth in c(TRUE, FALSE)) { + db <- vpc(sim = d$sim, obs = d$obs, stratify = "GRP", bins = "time", n_bins = 4, + bin_by_strata = TRUE, vpcdb = TRUE) + areas <- calc_outlier_areas(db$vpc_dat, db$aggr_obs, smooth = smooth) + if (!smooth && !is.null(areas)) { + # rectangles follow the bins of their own stratum + for (s in unique(as.character(areas$strat))) { + expect_true(all(areas$xmin[areas$strat == s] %in% db$bins[[s]])) + } + } + pl <- plot_vpc(db, show = list(outlier_areas = TRUE), smooth = smooth) + expect_s3_class(ggplot2::ggplot_build(pl), "ggplot_built") + 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) + areas <- calc_outlier_areas(db$vpc_dat, db$aggr_obs, smooth = smooth) + if (!is.null(areas)) expect_true("GRP" %in% names(areas)) + pl <- plot_vpc(db, show = list(outlier_areas = TRUE), smooth = smooth) + 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") +}) + +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") +}) diff --git a/tests/testthat/test-ref_corr.R b/tests/testthat/test-ref_corr.R index 31746f9..5189b76 100644 --- a/tests/testthat/test-ref_corr.R +++ b/tests/testthat/test-ref_corr.R @@ -263,8 +263,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)", {