From 5127333c0137e33231f3f2a17c78e7d9e5a6eda5 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Mon, 9 Nov 2026 18:42:14 +0000 Subject: [PATCH 1/2] fix(be): classify the bioequivalence design from each endpoint's rows be_fit_models() passed the rows of every endpoint to be_design(), so long data with several PPTESTCD values had several rows per subject and period: a 2x2 crossover with Cmax and AUC read as a full replicate (making the EMA and FDA frameworks look feasible), and a parallel study with two endpoints read as repeated measures, so lme4 refused the per-endpoint mixed model. The design is now classified from each endpoint's rows, and endpoints whose designs differ stop with pknca_error_be_design_endpoints_differ. be_design() and be_within_var(), which take one endpoint's rows, stop when a subject has more than one row in a period instead of reading the rows as replicates. The covariate-missing check of be_dataset() looks only at the rows of the requested endpoints, like its design-column check. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 13 ++++ R/bioequivalence.R | 86 +++++++++++++++++---- man/be_assess.Rd | 5 +- man/be_compare.Rd | 5 +- man/be_design.Rd | 4 +- man/be_fit_models.Rd | 12 +-- tests/testthat/test-bioequivalence-assess.R | 41 ++++++++++ tests/testthat/test-bioequivalence.R | 72 +++++++++++++++++ 8 files changed, 214 insertions(+), 24 deletions(-) diff --git a/NEWS.md b/NEWS.md index a58102da1..43a8e37b6 100644 --- a/NEWS.md +++ b/NEWS.md @@ -613,6 +613,19 @@ the generated intervals: sequence, so no model drops such rows while the subject count includes them. (@billdenney) +* `be_assess()`, `be_compare()`, and `be_fit_models()` classify the design from + the rows of each endpoint, so long data with several `PPTESTCD` values give + the design of one endpoint: a 2x2 crossover with Cmax and AUC rows is + `"2x2x2"`, where reference scaling is not feasible, and a parallel study with + two endpoints is `"parallel"` and uses the fixed-effects ANOVA. Endpoints + with different designs stop with `pknca_error_be_design_endpoints_differ`. + `be_design()` and `be_within_var()` stop with + `pknca_error_be_design_duplicate_period` and + `pknca_error_be_within_var_duplicate_period` when a subject has more than one + row in a period, which is what the rows of several endpoints look like. A + covariate missing only in rows of an endpoint that is not assessed is not an + error. (@billdenney) + * The expanding-limits frameworks of `be_assess()` widen only the endpoints their guidances allow (@billdenney). The EMA and the GCC widen Cmax and keep AUC at 80.00-125.00%; Health Canada widens AUC and judges Cmax by its point diff --git a/R/bioequivalence.R b/R/bioequivalence.R index 910fb198b..5eea7c2ab 100644 --- a/R/bioequivalence.R +++ b/R/bioequivalence.R @@ -394,6 +394,24 @@ be_expand_limits <- function(swR, regulator) { paste(trt[idx], collapse = "") } +# Stop when a subject has more than one row in a period. The design and the +# within-subject variances are defined for one endpoint, with one row per +# subject and period; the long data of several endpoints (several `PPTESTCD` +# values) would otherwise read as replicated administrations. `subj` and `per` +# are the subject and period of each row (a missing period counts as a period). +.be_check_one_row_per_period <- function(subj, per, class) { + dup <- duplicated(data.frame(subj = subj, per = as.character(per))) + if (any(dup)) { + rlang::abort( + sprintf( + "Subject(s) %s have more than one row in a period; give one row per subject and period, such as the rows of one endpoint (`PPTESTCD`) and one interval.", + paste(utils::head(unique(subj[dup]), 5), collapse = ", ") + ), + class = class + ) + } +} + #' Classify a bioequivalence crossover design #' #' `be_design()` inspects the treatment-by-period pattern of a crossover study @@ -402,8 +420,8 @@ be_expand_limits <- function(swR, regulator) { #' scaling (EMA/HC/GCC/FDA) requires the reference to be replicated; the narrow #' therapeutic index frameworks additionally require the test to be replicated. #' -#' @param data A long data.frame with one row per concentration-derived -#' observation (subject, period, treatment). +#' @param data A long data.frame with one row per subject and period for a +#' single endpoint (filter long NCA results to one `PPTESTCD` first). #' @param subject,sequence,period,treatment Column names (length-1 character) #' identifying the subject, randomization sequence, period, and treatment. #' `sequence` may be `NA` to derive it from the treatment-by-period pattern. @@ -454,6 +472,7 @@ be_design <- function(data, subject, sequence, period, treatment, reference_valu subj <- as.character(data[[subject]]) trt <- as.character(data[[treatment]]) per <- data[[period]] + .be_check_one_row_per_period(subj, per, "pknca_error_be_design_duplicate_period") # Per-subject treatment pattern, ordered by period -- the realized sequence. patterns <- tapply(seq_len(nrow(data)), subj, .be_subject_pattern, per = per, trt = trt) # Per-subject replication counts of the reference. @@ -675,6 +694,9 @@ be_within_var <- function(data, value, subject, period, treatment, reference_val } assert_numeric_between(alpha, lower = 0, upper = 1) reference_value <- as.character(reference_value) + .be_check_one_row_per_period( + as.character(data[[subject]]), data[[period]], "pknca_error_be_within_var_duplicate_period" + ) work <- data.frame( .subject = factor(as.character(data[[subject]])), @@ -1492,11 +1514,12 @@ be_dataset.default <- function(object, reference_col, reference_value, } data <- data[!is.na(data[[value_col]]) & data[[value_col]] > 0, , drop = FALSE] + analyzed <- data[data$PPTESTCD %in% endpoints, , drop = FALSE] .be_check_design_cols( - data[data$PPTESTCD %in% endpoints, , drop = FALSE], + analyzed, subject = subject, sequence = sequence, period = period, treatment = reference_col ) - missing_cov <- covariates[vapply(data[covariates], anyNA, logical(1))] + missing_cov <- covariates[vapply(analyzed[covariates], anyNA, logical(1))] if (length(missing_cov) > 0) { rlang::abort( sprintf( @@ -2348,9 +2371,10 @@ be_table <- function(params, regulator, alpha = 0.10, design = NA_character_, mo #' #' `be_fit_models()` runs the single bioequivalence calculation path and returns #' the regulatory pass/fail table. It coordinates the stages in order: -#' [be_dataset()] to prepare the data, [be_design()] to classify the design and -#' choose the model, [be_fit_model_single()] to fit, [be_extract_param()] to -#' extract the parameters, and [be_table()] to apply the regulatory decision. +#' [be_dataset()] to prepare the data, [be_design()] to classify the design +#' (from the rows of each endpoint) and choose the model, +#' [be_fit_model_single()] to fit, [be_extract_param()] to extract the +#' parameters, and [be_table()] to apply the regulatory decision. #' [be_assess()] and [be_compare()] are thin verbs over it. #' #' @inheritParams be_assess @@ -2372,10 +2396,7 @@ be_fit_models <- function(object, reference_col, reference_value, covariates = covariates ) if (is.null(design)) { - design <- be_design( - ds$data, ds$columns$subject, ds$columns$sequence, ds$columns$period, - ds$columns$treatment, ds$reference_value - ) + design <- .be_design_endpoints(ds) } else if (!inherits(design, "be_design")) { rlang::abort( "`design` must be a `be_design` object from `be_design()`.", @@ -2418,6 +2439,44 @@ be_fit_models <- function(object, reference_col, reference_value, .be_table_finish(tbl, ds, caption = caption) } +# The design of a be_dataset(), classified from the rows of each endpoint (the +# long data hold one row per subject, period, and endpoint). One framework +# and one model type apply to every endpoint, so the endpoints must agree on +# the design, on the replication of each formulation, and on whether subjects +# have repeated measures. +.be_design_endpoints <- function(ds) { + designs <- list() + for (ep in ds$endpoints) { + ds_ep <- ds$data[!is.na(ds$data$PPTESTCD) & ds$data$PPTESTCD == ep, , drop = FALSE] + designs[[ep]] <- be_design( + ds_ep, ds$columns$subject, ds$columns$sequence, ds$columns$period, + ds$columns$treatment, ds$reference_value + ) + } + descriptions <- vapply(designs, .be_design_description, character(1)) + if (length(unique(descriptions)) > 1) { + rlang::abort( + sprintf( + "The endpoints have different designs (%s); assess them separately or give `design`.", + paste(names(descriptions), descriptions, sep = ": ", collapse = "; ") + ), + class = "pknca_error_be_design_endpoints_differ" + ) + } + designs[[1]] +} + +# The parts of a be_design() that choose the model and the feasible frameworks +.be_design_description <- function(design) { + sprintf( + "%s of %s, reference %s, test %s, %s", + design$design, paste(design$treatments, collapse = "/"), + if (design$replicate_reference) "replicated" else "not replicated", + if (design$replicate_test) "replicated" else "not replicated", + if (identical(design$recommended_model_type, "anova")) "one measurement per subject" else "repeated measures" + ) +} + # Order the table from be_table() by endpoint (in the requested order) then by # test formulation (in the reference-first treatment factor order), omit the # units column (with a warning) when units are unavailable, and add the caption @@ -2709,8 +2768,9 @@ be_fit_models <- function(object, reference_col, reference_value, #' @param subject,sequence,period Column names for the subject, randomization #' sequence, and period. When `NULL` they are taken from the `PKNCAresults` #' object or detected from common column names. `sequence` may be absent. -#' @param design An optional [be_design()] object; computed from the data when -#' `NULL`. +#' @param design An optional [be_design()] object. When `NULL`, the design is +#' classified from the rows of each endpoint, and the endpoints must all have +#' the same design. #' @param covariates An optional character vector of column names added to #' every model as additive fixed effects (numeric columns as linear terms, #' character or factor columns as factors). They must not be missing in any diff --git a/man/be_assess.Rd b/man/be_assess.Rd index 8daa81ca7..3641b3601 100644 --- a/man/be_assess.Rd +++ b/man/be_assess.Rd @@ -84,8 +84,9 @@ the regulator, and \code{heteroscedastic}.} sequence, and period. When \code{NULL} they are taken from the \code{PKNCAresults} object or detected from common column names. \code{sequence} may be absent.} -\item{design}{An optional \code{\link[=be_design]{be_design()}} object; computed from the data when -\code{NULL}.} +\item{design}{An optional \code{\link[=be_design]{be_design()}} object. When \code{NULL}, the design is +classified from the rows of each endpoint, and the endpoints must all have +the same design.} \item{covariates}{An optional character vector of column names added to every model as additive fixed effects (numeric columns as linear terms, diff --git a/man/be_compare.Rd b/man/be_compare.Rd index 99ab19e54..f0a6c3499 100644 --- a/man/be_compare.Rd +++ b/man/be_compare.Rd @@ -57,8 +57,9 @@ the regulator, and \code{heteroscedastic}.} sequence, and period. When \code{NULL} they are taken from the \code{PKNCAresults} object or detected from common column names. \code{sequence} may be absent.} -\item{design}{An optional \code{\link[=be_design]{be_design()}} object; computed from the data when -\code{NULL}.} +\item{design}{An optional \code{\link[=be_design]{be_design()}} object. When \code{NULL}, the design is +classified from the rows of each endpoint, and the endpoints must all have +the same design.} \item{covariates}{An optional character vector of column names added to every model as additive fixed effects (numeric columns as linear terms, diff --git a/man/be_design.Rd b/man/be_design.Rd index 929b43499..3fc818859 100644 --- a/man/be_design.Rd +++ b/man/be_design.Rd @@ -7,8 +7,8 @@ be_design(data, subject, sequence, period, treatment, reference_value) } \arguments{ -\item{data}{A long data.frame with one row per concentration-derived -observation (subject, period, treatment).} +\item{data}{A long data.frame with one row per subject and period for a +single endpoint (filter long NCA results to one \code{PPTESTCD} first).} \item{subject, sequence, period, treatment}{Column names (length-1 character) identifying the subject, randomization sequence, period, and treatment. diff --git a/man/be_fit_models.Rd b/man/be_fit_models.Rd index 3a11cbbee..c6a21a72f 100644 --- a/man/be_fit_models.Rd +++ b/man/be_fit_models.Rd @@ -58,8 +58,9 @@ the regulator, and \code{heteroscedastic}.} sequence, and period. When \code{NULL} they are taken from the \code{PKNCAresults} object or detected from common column names. \code{sequence} may be absent.} -\item{design}{An optional \code{\link[=be_design]{be_design()}} object; computed from the data when -\code{NULL}.} +\item{design}{An optional \code{\link[=be_design]{be_design()}} object. When \code{NULL}, the design is +classified from the rows of each endpoint, and the endpoints must all have +the same design.} \item{covariates}{An optional character vector of column names added to every model as additive fixed effects (numeric columns as linear terms, @@ -96,9 +97,10 @@ columns described in \code{\link[=be_assess]{be_assess()}}). \description{ \code{be_fit_models()} runs the single bioequivalence calculation path and returns the regulatory pass/fail table. It coordinates the stages in order: -\code{\link[=be_dataset]{be_dataset()}} to prepare the data, \code{\link[=be_design]{be_design()}} to classify the design and -choose the model, \code{\link[=be_fit_model_single]{be_fit_model_single()}} to fit, \code{\link[=be_extract_param]{be_extract_param()}} to -extract the parameters, and \code{\link[=be_table]{be_table()}} to apply the regulatory decision. +\code{\link[=be_dataset]{be_dataset()}} to prepare the data, \code{\link[=be_design]{be_design()}} to classify the design +(from the rows of each endpoint) and choose the model, +\code{\link[=be_fit_model_single]{be_fit_model_single()}} to fit, \code{\link[=be_extract_param]{be_extract_param()}} to extract the +parameters, and \code{\link[=be_table]{be_table()}} to apply the regulatory decision. \code{\link[=be_assess]{be_assess()}} and \code{\link[=be_compare]{be_compare()}} are thin verbs over it. } \seealso{ diff --git a/tests/testthat/test-bioequivalence-assess.R b/tests/testthat/test-bioequivalence-assess.R index 5ace7e988..a2dd9546e 100644 --- a/tests/testthat/test-bioequivalence-assess.R +++ b/tests/testthat/test-bioequivalence-assess.R @@ -131,8 +131,49 @@ test_that("be_design errors on an unknown reference value", { ) }) +test_that("be_design needs one row per subject and period", { + # The long data of two endpoints give each subject two rows per period, which + # would otherwise read as a replicated reference and test. + d <- generate_be_replicate(16, 3, "2x2") + expect_error( + be_design(rbind(d, d), "subject", "sequence", "period", "treatment", "R"), + regexp = "Subject(s) 1, 2, 3, 4, 5 have more than one row in a period", + fixed = TRUE, + class = "pknca_error_be_design_duplicate_period" + ) + par <- data.frame(subject = 1:8, period = 1L, treatment = rep(c("R", "T"), each = 4)) + expect_error( + be_design(rbind(par, par), "subject", NA, "period", "treatment", "R"), + class = "pknca_error_be_design_duplicate_period" + ) + # A missing period is one period: one row per subject is still parallel. + par$period <- NA + expect_identical(be_design(par, "subject", NA, "period", "treatment", "R")$design, "parallel") + par2 <- rbind(par, par[1, ]) + expect_error( + be_design(par2, "subject", NA, "period", "treatment", "R"), + regexp = "Subject(s) 1 have", + fixed = TRUE, + class = "pknca_error_be_design_duplicate_period" + ) +}) + # be_within_var ------------------------------------------------------------- +test_that("be_within_var needs one row per subject and period", { + # Two endpoints of a 2x2 crossover would otherwise give a "replicated" + # reference and a within-subject variance between the endpoints. + d <- generate_be_replicate(16, 3, "2x2") + expect_error( + be_within_var(rbind(d, d), "PK", "subject", "period", "treatment", "R"), + class = "pknca_error_be_within_var_duplicate_period" + ) + expect_error( + be_within_var(rbind(d, d), "PK", "subject", "period", "treatment", "R", model_type = "isc"), + class = "pknca_error_be_within_var_duplicate_period" + ) +}) + test_that("be_within_var (anova) matches the ANOVA within-subject variances", { # Pinned to the reference implementation's CV.calc on the high-variability # full replicate: swR = 0.446... here is dataset-specific. diff --git a/tests/testthat/test-bioequivalence.R b/tests/testthat/test-bioequivalence.R index 14399d9dd..c2d1ebbe9 100644 --- a/tests/testthat/test-bioequivalence.R +++ b/tests/testthat/test-bioequivalence.R @@ -211,6 +211,70 @@ test_that("be_fit_models is the engine and matches be_assess values", { expect_equal(as.data.frame(res), tbl) }) +test_that("be_assess classifies the design from each endpoint's rows", { + skip_if_not_installed("lme4") + skip_if_not_installed("lmerTest") + skip_if_not_installed("emmeans") + # Two endpoints of a 2x2 crossover: each subject has two rows per period in + # the long data, but each endpoint has one. + d <- rbind(make_be_df(endpoint = "auclast"), make_be_df(seed = 124, endpoint = "cmax")) + res <- be_assess(d, reference_col = "form", reference_value = "R", + endpoints = "auclast", regulator = "ABE") + expect_identical(attr(res, "design"), "2x2x2") + expect_identical(res$design, "2x2x2") + expect_equal( + res, + be_assess(d[d$PPTESTCD == "auclast", ], reference_col = "form", reference_value = "R", + endpoints = "auclast", regulator = "ABE") + ) + both <- be_assess(d, reference_col = "form", reference_value = "R", + endpoints = c("auclast", "cmax"), regulator = "ABE") + expect_identical(both$design, c("2x2x2", "2x2x2")) + # The reference is not replicated, so reference scaling is infeasible. + expect_error( + be_assess(d, reference_col = "form", reference_value = "R", + endpoints = "auclast", regulator = "EMA"), + class = "pknca_error_be_infeasible_design" + ) +}) + +test_that("be_assess classifies a parallel design with several endpoints as parallel", { + skip_if_not_installed("emmeans") + d <- generate_be_parallel(effect = c(R = 0, T = log(1.10)), sd = c(R = 0.20, T = 0.30)) + d_cmax <- d + d_cmax$PPTESTCD <- "cmax" + d_cmax$PPORRESU <- "ng/mL" + res <- be_assess(rbind(d, d_cmax), "treatment", "R", "auclast") + expect_identical(attr(res, "design"), "parallel") + expect_identical(res$model_type, "anova") + expect_equal(res, be_assess(d, "treatment", "R", "auclast")) +}) + +test_that("be_assess stops when the endpoints have different designs", { + skip_if_not_installed("lme4") + skip_if_not_installed("lmerTest") + skip_if_not_installed("emmeans") + # Cmax only in period 1: a parallel comparison beside the auclast crossover. + d_cmax <- make_be_df(seed = 124, endpoint = "cmax") + d <- rbind(make_be_df(endpoint = "auclast"), d_cmax[d_cmax$period == 1, ]) + expect_error( + be_assess(d, reference_col = "form", reference_value = "R", + endpoints = c("auclast", "cmax"), regulator = "ABE"), + regexp = paste( + "auclast: 2x2x2 of R/T, reference not replicated, test not replicated, repeated measures;", + "cmax: parallel of R/T, reference not replicated, test not replicated, one measurement per subject" + ), + fixed = TRUE, + class = "pknca_error_be_design_endpoints_differ" + ) + # Only the requested endpoints are classified. + expect_identical( + attr(be_assess(d, reference_col = "form", reference_value = "R", + endpoints = "auclast", regulator = "ABE"), "design"), + "2x2x2" + ) +}) + test_that("be_assess confidence interval widens with smaller alpha", { skip_if_not_installed("lme4") skip_if_not_installed("lmerTest") @@ -346,6 +410,14 @@ test_that("be_dataset validates covariates", { # a missing covariate on a row that is dropped (missing value) is not an error d$PPORRES[3] <- NA expect_s3_class(be_dataset(d, "treatment", "R", "auclast", covariates = "WT"), "be_dataset") + # nor is one on a row of an endpoint that is not analyzed + d_cmax <- generate_be_parallel() + d_cmax$PPTESTCD <- "cmax" + d_cmax$WT[5] <- NA + expect_s3_class( + be_dataset(rbind(generate_be_parallel(), d_cmax), "treatment", "R", "auclast", covariates = "WT"), + "be_dataset" + ) }) test_that("a covariate with a single value is an error", { From 5d244350e99592196195a418c1f13e8a74e229e8 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Mon, 9 Nov 2026 19:33:46 +0000 Subject: [PATCH 2/2] fix(be): classify the design from the study rows, not each endpoint's values Review of the per-endpoint classification: classifying each endpoint after the missing values were dropped let routine missingness (aucinf.obs without an estimable lambda.z) change one endpoint's design and stop a valid assessment. be_dataset() now keeps design_rows, the distinct subject, sequence, period, and treatment rows of the requested endpoints, including administrations whose value is missing, and be_fit_models() classifies the study from them. be_dataset() stops with pknca_error_be_dataset_duplicate_period when an endpoint has more than one value for a subject and period (results with several intervals), saying to filter to one interval, and with pknca_error_be_dataset_design_conflict when endpoints disagree on a subject's treatment or sequence in a period. be_compare() calls be_dataset() before its per-framework loop, so both are raised once there rather than as skipped frameworks. An endpoint left with one value per subject stops lmer and nlme with pknca_error_be_endpoint_not_repeated instead of an lme4 error. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 21 +++-- R/bioequivalence.R | 124 ++++++++++++++++----------- man/be_assess.Rd | 4 +- man/be_compare.Rd | 4 +- man/be_dataset.Rd | 7 +- man/be_fit_models.Rd | 10 +-- tests/testthat/test-bioequivalence.R | 89 ++++++++++++++++--- 7 files changed, 178 insertions(+), 81 deletions(-) diff --git a/NEWS.md b/NEWS.md index 9e3bd8f20..2f1c9d7f0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -614,13 +614,20 @@ the generated intervals: (@billdenney) * `be_assess()`, `be_compare()`, and `be_fit_models()` classify the design from - the rows of each endpoint, so long data with several `PPTESTCD` values give - the design of one endpoint: a 2x2 crossover with Cmax and AUC rows is - `"2x2x2"`, where reference scaling is not feasible, and a parallel study with - two endpoints is `"parallel"` and uses the fixed-effects ANOVA. Endpoints - with different designs stop with `pknca_error_be_design_endpoints_differ`. - `be_design()` and `be_within_var()` stop with - `pknca_error_be_design_duplicate_period` and + the subjects, periods, and treatments of the requested endpoints, one row per + subject and period, so long data with several `PPTESTCD` values give the + study design: a 2x2 crossover with Cmax and AUC rows is `"2x2x2"`, where + reference scaling is not feasible, and a parallel study with two endpoints is + `"parallel"` and uses the fixed-effects ANOVA. An administration whose value + is missing (an `aucinf.obs` without an estimable lambda.z) still counts, so + missing values do not change the design. `be_dataset()` stops with + `pknca_error_be_dataset_duplicate_period` when an endpoint has more than one + value for a subject and period (results with several intervals), and with + `pknca_error_be_dataset_design_conflict` when endpoints disagree on a + subject's treatment or sequence in a period; `be_compare()` raises both once. + An endpoint left with one value per subject stops a mixed model with + `pknca_error_be_endpoint_not_repeated`. `be_design()` and `be_within_var()` + stop with `pknca_error_be_design_duplicate_period` and `pknca_error_be_within_var_duplicate_period` when a subject has more than one row in a period, which is what the rows of several endpoints look like. A covariate missing only in rows of an endpoint that is not assessed is not an diff --git a/R/bioequivalence.R b/R/bioequivalence.R index 5eea7c2ab..b876e6716 100644 --- a/R/bioequivalence.R +++ b/R/bioequivalence.R @@ -398,20 +398,24 @@ be_expand_limits <- function(swR, regulator) { # within-subject variances are defined for one endpoint, with one row per # subject and period; the long data of several endpoints (several `PPTESTCD` # values) would otherwise read as replicated administrations. `subj` and `per` -# are the subject and period of each row (a missing period counts as a period). -.be_check_one_row_per_period <- function(subj, per, class) { +# are the subject and period of each row (a missing period counts as a period), +# and `msg` is a sprintf() format whose one `%s` receives the subjects (the +# first five). +.be_check_one_row_per_period <- function(subj, per, class, msg) { dup <- duplicated(data.frame(subj = subj, per = as.character(per))) if (any(dup)) { rlang::abort( - sprintf( - "Subject(s) %s have more than one row in a period; give one row per subject and period, such as the rows of one endpoint (`PPTESTCD`) and one interval.", - paste(utils::head(unique(subj[dup]), 5), collapse = ", ") - ), + sprintf(msg, paste(utils::head(unique(subj[dup]), 5), collapse = ", ")), class = class ) } } +# The message of .be_check_one_row_per_period() for a function given the rows +# of one endpoint +.be_one_endpoint_msg <- + "Subject(s) %s have more than one row in a period; give one row per subject and period, such as the rows of one endpoint (`PPTESTCD`) and one interval." + #' Classify a bioequivalence crossover design #' #' `be_design()` inspects the treatment-by-period pattern of a crossover study @@ -472,7 +476,7 @@ be_design <- function(data, subject, sequence, period, treatment, reference_valu subj <- as.character(data[[subject]]) trt <- as.character(data[[treatment]]) per <- data[[period]] - .be_check_one_row_per_period(subj, per, "pknca_error_be_design_duplicate_period") + .be_check_one_row_per_period(subj, per, "pknca_error_be_design_duplicate_period", .be_one_endpoint_msg) # Per-subject treatment pattern, ordered by period -- the realized sequence. patterns <- tapply(seq_len(nrow(data)), subj, .be_subject_pattern, per = per, trt = trt) # Per-subject replication counts of the reference. @@ -695,7 +699,8 @@ be_within_var <- function(data, value, subject, period, treatment, reference_val assert_numeric_between(alpha, lower = 0, upper = 1) reference_value <- as.character(reference_value) .be_check_one_row_per_period( - as.character(data[[subject]]), data[[period]], "pknca_error_be_within_var_duplicate_period" + as.character(data[[subject]]), data[[period]], "pknca_error_be_within_var_duplicate_period", + .be_one_endpoint_msg ) work <- data.frame( @@ -1455,8 +1460,11 @@ print.be_within_var <- function(x, ...) { #' @returns An object of class `be_dataset`: a list with `data` (the #' standardized long frame, including a `.units` column and one `.cov_` #' column per covariate), `columns` (the resolved column names, including -#' `units` and `covariates`), `reference_value`, `test_levels`, and -#' `endpoints` (those present). For the results of a sparse bootstrap (see +#' `units` and `covariates`), `reference_value`, `test_levels`, `endpoints` +#' (those present), and `design_rows` (the distinct subject, sequence, period, +#' and treatment combinations of the requested endpoints, including those +#' whose value is missing, from which [be_design()] classifies the study). +#' For the results of a sparse bootstrap (see #' [sparse_bootstrap()]), `data` has one row per bootstrap replicate, group, #' and endpoint instead of one per subject and period. #' @family Bioequivalence @@ -1513,12 +1521,30 @@ be_dataset.default <- function(object, reference_col, reference_value, ) } - data <- data[!is.na(data[[value_col]]) & data[[value_col]] > 0, , drop = FALSE] + has_value <- !is.na(data[[value_col]]) & data[[value_col]] > 0 + design_rows <- .be_design_rows( + data[data$PPTESTCD %in% endpoints, , drop = FALSE], + has_value = has_value[data$PPTESTCD %in% endpoints], + cols = c(subject, if (!is.na(sequence)) sequence, period, reference_col) + ) + data <- data[has_value, , drop = FALSE] analyzed <- data[data$PPTESTCD %in% endpoints, , drop = FALSE] .be_check_design_cols( analyzed, subject = subject, sequence = sequence, period = period, treatment = reference_col ) + .be_check_one_row_per_period( + sprintf("%s for %s", analyzed[[subject]], analyzed$PPTESTCD), analyzed[[period]], + "pknca_error_be_dataset_duplicate_period", + paste( + "Subject(s) %s have more than one value in a period; the results may hold several intervals for an endpoint.", + "Filter them to one interval per endpoint before the bioequivalence assessment." + ) + ) + .be_check_one_row_per_period( + design_rows[[subject]], design_rows[[period]], "pknca_error_be_dataset_design_conflict", + "Subject(s) %s have a period whose treatment or sequence differs between endpoints." + ) missing_cov <- covariates[vapply(analyzed[covariates], anyNA, logical(1))] if (length(missing_cov) > 0) { rlang::abort( @@ -1554,12 +1580,25 @@ be_dataset.default <- function(object, reference_col, reference_value, ), reference_value = reference_value, test_levels = setdiff(levels(data$.trt), reference_value), - endpoints = present + endpoints = present, + design_rows = design_rows ), class = "be_dataset" ) } +# The rows that define the study design: the distinct subject, sequence, +# period, and treatment combinations (`cols`) of the requested endpoints' +# rows, `data`. Rows whose value is missing (`has_value` is FALSE) still +# count when their design columns are complete, so an endpoint that could not +# be calculated for an administration does not change the design. +.be_design_rows <- function(data, has_value, cols) { + keep <- has_value | stats::complete.cases(data[cols]) + rows <- unique(data[keep, cols, drop = FALSE]) + rownames(rows) <- NULL + rows +} + # Stop when a design column (subject, sequence, period, or treatment) is # missing in a row that would be analyzed, or when a subject has more than one # sequence. The model fits would otherwise drop those rows while the subject @@ -2372,9 +2411,9 @@ be_table <- function(params, regulator, alpha = 0.10, design = NA_character_, mo #' `be_fit_models()` runs the single bioequivalence calculation path and returns #' the regulatory pass/fail table. It coordinates the stages in order: #' [be_dataset()] to prepare the data, [be_design()] to classify the design -#' (from the rows of each endpoint) and choose the model, -#' [be_fit_model_single()] to fit, [be_extract_param()] to extract the -#' parameters, and [be_table()] to apply the regulatory decision. +#' (from the subjects, periods, and treatments of the requested endpoints) and +#' choose the model, [be_fit_model_single()] to fit, [be_extract_param()] to +#' extract the parameters, and [be_table()] to apply the regulatory decision. #' [be_assess()] and [be_compare()] are thin verbs over it. #' #' @inheritParams be_assess @@ -2396,7 +2435,7 @@ be_fit_models <- function(object, reference_col, reference_value, covariates = covariates ) if (is.null(design)) { - design <- .be_design_endpoints(ds) + design <- .be_design_dataset(ds) } else if (!inherits(design, "be_design")) { rlang::abort( "`design` must be a `be_design` object from `be_design()`.", @@ -2423,6 +2462,7 @@ be_fit_models <- function(object, reference_col, reference_value, params <- list() for (ep in ds$endpoints) { ds_ep <- ds$data[!is.na(ds$data$PPTESTCD) & ds$data$PPTESTCD == ep, , drop = FALSE] + .be_check_endpoint_repeated(ds_ep, model_type, ep) fit <- be_fit_model_single(ds_ep, model_type, scaling = reg$scaling != "none") p <- be_extract_param(fit, ds_ep, alpha) p$endpoint <- ep @@ -2439,42 +2479,28 @@ be_fit_models <- function(object, reference_col, reference_value, .be_table_finish(tbl, ds, caption = caption) } -# The design of a be_dataset(), classified from the rows of each endpoint (the -# long data hold one row per subject, period, and endpoint). One framework -# and one model type apply to every endpoint, so the endpoints must agree on -# the design, on the replication of each formulation, and on whether subjects -# have repeated measures. -.be_design_endpoints <- function(ds) { - designs <- list() - for (ep in ds$endpoints) { - ds_ep <- ds$data[!is.na(ds$data$PPTESTCD) & ds$data$PPTESTCD == ep, , drop = FALSE] - designs[[ep]] <- be_design( - ds_ep, ds$columns$subject, ds$columns$sequence, ds$columns$period, - ds$columns$treatment, ds$reference_value - ) - } - descriptions <- vapply(designs, .be_design_description, character(1)) - if (length(unique(descriptions)) > 1) { +# The design of a be_dataset(), classified from its design rows (see +# .be_design_rows()): one row per subject and period, whichever endpoints +# have a value there. +.be_design_dataset <- function(ds) { + be_design( + ds$design_rows, ds$columns$subject, ds$columns$sequence, ds$columns$period, + ds$columns$treatment, ds$reference_value + ) +} + +# Stop when an endpoint has one measurement per subject but `model_type` needs +# repeated measures (the endpoint is missing in the other periods) +.be_check_endpoint_repeated <- function(ds_ep, model_type, endpoint) { + if (model_type %in% c("lmer", "nlme") && .be_is_parallel(ds_ep)) { rlang::abort( sprintf( - "The endpoints have different designs (%s); assess them separately or give `design`.", - paste(names(descriptions), descriptions, sep = ": ", collapse = "; ") + "Endpoint %s has one value per subject, so model_type = '%s', which needs repeated measures, cannot be fit; assess it separately.", + endpoint, model_type ), - class = "pknca_error_be_design_endpoints_differ" + class = c("pknca_error_be_endpoint_not_repeated", "pknca_error_be_not_estimable") ) } - designs[[1]] -} - -# The parts of a be_design() that choose the model and the feasible frameworks -.be_design_description <- function(design) { - sprintf( - "%s of %s, reference %s, test %s, %s", - design$design, paste(design$treatments, collapse = "/"), - if (design$replicate_reference) "replicated" else "not replicated", - if (design$replicate_test) "replicated" else "not replicated", - if (identical(design$recommended_model_type, "anova")) "one measurement per subject" else "repeated measures" - ) } # Order the table from be_table() by endpoint (in the requested order) then by @@ -2769,8 +2795,8 @@ be_fit_models <- function(object, reference_col, reference_value, #' sequence, and period. When `NULL` they are taken from the `PKNCAresults` #' object or detected from common column names. `sequence` may be absent. #' @param design An optional [be_design()] object. When `NULL`, the design is -#' classified from the rows of each endpoint, and the endpoints must all have -#' the same design. +#' classified from the subjects, periods, and treatments of the requested +#' endpoints, including administrations where an endpoint's value is missing. #' @param covariates An optional character vector of column names added to #' every model as additive fixed effects (numeric columns as linear terms, #' character or factor columns as factors). They must not be missing in any diff --git a/man/be_assess.Rd b/man/be_assess.Rd index 3641b3601..4205d10aa 100644 --- a/man/be_assess.Rd +++ b/man/be_assess.Rd @@ -85,8 +85,8 @@ sequence, and period. When \code{NULL} they are taken from the \code{PKNCAresul object or detected from common column names. \code{sequence} may be absent.} \item{design}{An optional \code{\link[=be_design]{be_design()}} object. When \code{NULL}, the design is -classified from the rows of each endpoint, and the endpoints must all have -the same design.} +classified from the subjects, periods, and treatments of the requested +endpoints, including administrations where an endpoint's value is missing.} \item{covariates}{An optional character vector of column names added to every model as additive fixed effects (numeric columns as linear terms, diff --git a/man/be_compare.Rd b/man/be_compare.Rd index f0a6c3499..ec3e42f9b 100644 --- a/man/be_compare.Rd +++ b/man/be_compare.Rd @@ -58,8 +58,8 @@ sequence, and period. When \code{NULL} they are taken from the \code{PKNCAresul object or detected from common column names. \code{sequence} may be absent.} \item{design}{An optional \code{\link[=be_design]{be_design()}} object. When \code{NULL}, the design is -classified from the rows of each endpoint, and the endpoints must all have -the same design.} +classified from the subjects, periods, and treatments of the requested +endpoints, including administrations where an endpoint's value is missing.} \item{covariates}{An optional character vector of column names added to every model as additive fixed effects (numeric columns as linear terms, diff --git a/man/be_dataset.Rd b/man/be_dataset.Rd index a5ca96633..8d4599c2b 100644 --- a/man/be_dataset.Rd +++ b/man/be_dataset.Rd @@ -66,8 +66,11 @@ use covariates.} An object of class \code{be_dataset}: a list with \code{data} (the standardized long frame, including a \code{.units} column and one \verb{.cov_} column per covariate), \code{columns} (the resolved column names, including -\code{units} and \code{covariates}), \code{reference_value}, \code{test_levels}, and -\code{endpoints} (those present). For the results of a sparse bootstrap (see +\code{units} and \code{covariates}), \code{reference_value}, \code{test_levels}, \code{endpoints} +(those present), and \code{design_rows} (the distinct subject, sequence, period, +and treatment combinations of the requested endpoints, including those +whose value is missing, from which \code{\link[=be_design]{be_design()}} classifies the study). +For the results of a sparse bootstrap (see \code{\link[=sparse_bootstrap]{sparse_bootstrap()}}), \code{data} has one row per bootstrap replicate, group, and endpoint instead of one per subject and period. } diff --git a/man/be_fit_models.Rd b/man/be_fit_models.Rd index c6a21a72f..7317b85c7 100644 --- a/man/be_fit_models.Rd +++ b/man/be_fit_models.Rd @@ -59,8 +59,8 @@ sequence, and period. When \code{NULL} they are taken from the \code{PKNCAresul object or detected from common column names. \code{sequence} may be absent.} \item{design}{An optional \code{\link[=be_design]{be_design()}} object. When \code{NULL}, the design is -classified from the rows of each endpoint, and the endpoints must all have -the same design.} +classified from the subjects, periods, and treatments of the requested +endpoints, including administrations where an endpoint's value is missing.} \item{covariates}{An optional character vector of column names added to every model as additive fixed effects (numeric columns as linear terms, @@ -98,9 +98,9 @@ columns described in \code{\link[=be_assess]{be_assess()}}). \code{be_fit_models()} runs the single bioequivalence calculation path and returns the regulatory pass/fail table. It coordinates the stages in order: \code{\link[=be_dataset]{be_dataset()}} to prepare the data, \code{\link[=be_design]{be_design()}} to classify the design -(from the rows of each endpoint) and choose the model, -\code{\link[=be_fit_model_single]{be_fit_model_single()}} to fit, \code{\link[=be_extract_param]{be_extract_param()}} to extract the -parameters, and \code{\link[=be_table]{be_table()}} to apply the regulatory decision. +(from the subjects, periods, and treatments of the requested endpoints) and +choose the model, \code{\link[=be_fit_model_single]{be_fit_model_single()}} to fit, \code{\link[=be_extract_param]{be_extract_param()}} to +extract the parameters, and \code{\link[=be_table]{be_table()}} to apply the regulatory decision. \code{\link[=be_assess]{be_assess()}} and \code{\link[=be_compare]{be_compare()}} are thin verbs over it. } \seealso{ diff --git a/tests/testthat/test-bioequivalence.R b/tests/testthat/test-bioequivalence.R index c2d1ebbe9..188ea5c93 100644 --- a/tests/testthat/test-bioequivalence.R +++ b/tests/testthat/test-bioequivalence.R @@ -250,28 +250,89 @@ test_that("be_assess classifies a parallel design with several endpoints as para expect_equal(res, be_assess(d, "treatment", "R", "auclast")) }) -test_that("be_assess stops when the endpoints have different designs", { +test_that("a missing endpoint value does not change the design", { skip_if_not_installed("lme4") skip_if_not_installed("lmerTest") skip_if_not_installed("emmeans") - # Cmax only in period 1: a parallel comparison beside the auclast crossover. + # A full replicate where aucinf.obs could not be calculated for most + # administrations (for example, lambda.z was not estimable). + full <- generate_be_replicate(24, 20240501, "full") + d_inf <- be_replicate_long(full, endpoint = "aucinf.obs") + set.seed(5) + d_inf$PPORRES[sample(nrow(d_inf), 55)] <- NA + d <- rbind(be_replicate_long(full, endpoint = "auclast"), d_inf) + res <- be_assess(d, "treatment", "R", c("auclast", "aucinf.obs"), regulator = "ABE") + expect_identical(res$design, c("full_replicate", "full_replicate")) + expect_identical(res$endpoint, c("auclast", "aucinf.obs")) + expect_equal( + as.data.frame(res)[2, ], + as.data.frame(be_assess(d_inf, "treatment", "R", "aucinf.obs", regulator = "ABE")), + ignore_attr = TRUE + ) + + # A 2x2 crossover where Cmax is missing for every subject in period 2 is + # still a 2x2 crossover; Cmax alone cannot be fit by the crossover model. d_cmax <- make_be_df(seed = 124, endpoint = "cmax") - d <- rbind(make_be_df(endpoint = "auclast"), d_cmax[d_cmax$period == 1, ]) + d_cmax$PPORRES[d_cmax$period == 2] <- NA + d2 <- rbind(make_be_df(endpoint = "auclast"), d_cmax) + expect_identical( + be_assess(d2, reference_col = "form", reference_value = "R", + endpoints = "auclast", regulator = "ABE")$design, + "2x2x2" + ) expect_error( - be_assess(d, reference_col = "form", reference_value = "R", + be_assess(d2, reference_col = "form", reference_value = "R", endpoints = c("auclast", "cmax"), regulator = "ABE"), - regexp = paste( - "auclast: 2x2x2 of R/T, reference not replicated, test not replicated, repeated measures;", - "cmax: parallel of R/T, reference not replicated, test not replicated, one measurement per subject" - ), + regexp = "Endpoint cmax has one value per subject, so model_type = 'lmer', which needs repeated measures, cannot be fit", fixed = TRUE, - class = "pknca_error_be_design_endpoints_differ" + class = "pknca_error_be_endpoint_not_repeated" ) - # Only the requested endpoints are classified. - expect_identical( - attr(be_assess(d, reference_col = "form", reference_value = "R", - endpoints = "auclast", regulator = "ABE"), "design"), - "2x2x2" +}) + +test_that("be_assess stops when an endpoint has two values for a subject and period", { + # Two intervals of the results give auclast twice for subject 1, period 1. + d <- make_be_df() + d_dup <- rbind(d, d[1, ]) + expect_error( + be_assess(d_dup, reference_col = "form", reference_value = "R", endpoints = "auclast"), + regexp = "Subject(s) 1 for auclast have more than one value in a period; the results may hold several intervals for an endpoint. Filter them to one interval per endpoint before the bioequivalence assessment.", + fixed = TRUE, + class = "pknca_error_be_dataset_duplicate_period" + ) + # Rows of an endpoint that is not assessed do not matter. + d_other <- d[1, ] + d_other$PPTESTCD <- "cmax" + expect_s3_class( + be_dataset(rbind(d, d_other, d_other), reference_col = "form", reference_value = "R", endpoints = "auclast"), + "be_dataset" + ) +}) + +test_that("be_assess stops when endpoints disagree on a subject's treatment in a period", { + d_cmax <- make_be_df(endpoint = "cmax") + d_cmax$form[1] <- setdiff(c("R", "T"), d_cmax$form[1]) + d <- rbind(make_be_df(endpoint = "auclast"), d_cmax) + expect_error( + be_assess(d, reference_col = "form", reference_value = "R", endpoints = c("auclast", "cmax")), + regexp = "Subject(s) 1 have a period whose treatment or sequence differs between endpoints.", + fixed = TRUE, + class = "pknca_error_be_dataset_design_conflict" + ) +}) + +test_that("be_compare raises the design errors of the data once", { + d <- make_be_df() + expect_error( + be_compare(rbind(d, d[1, ]), reference_col = "form", reference_value = "R", + endpoints = "auclast", regulators = c("ABE", "EMA")), + class = "pknca_error_be_dataset_duplicate_period" + ) + d_cmax <- make_be_df(endpoint = "cmax") + d_cmax$form[1] <- setdiff(c("R", "T"), d_cmax$form[1]) + expect_error( + be_compare(rbind(d, d_cmax), reference_col = "form", reference_value = "R", + endpoints = c("auclast", "cmax"), regulators = c("ABE", "EMA")), + class = "pknca_error_be_dataset_design_conflict" ) })