From 708b909fb7adffa24640d00e0aa0d394c70d5a5d Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Sat, 14 Nov 2026 11:17:22 -0500 Subject: [PATCH 01/21] fix: a negative dose amount is an error PKNCAdose() refuses a negative dose amount with pknca_error_dose_negative, naming the first rows and their count, for a dose column, a one-row-per-group dose (dose ~ .), and a units column. pk.nca() checks again, because a mutate() or join on the dose object after PKNCAdose() can make one. A zero dose and a missing dose are allowed and give what they gave before (dose-normalized values Inf and NA); a row excluded with `exclude` is not checked, as for the dose times. NEWS lists it under breaking changes, since code that passed a negative dose now stops. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 6 +++ R/class-PKNCAdose.R | 41 ++++++++++++++++ R/pk.calc.all.R | 5 ++ man/PKNCAdose.Rd | 5 ++ tests/testthat/test-class-PKNCAdose.R | 69 +++++++++++++++++++++++++++ 5 files changed, 126 insertions(+) diff --git a/NEWS.md b/NEWS.md index 18b6f8941..d09cb45c6 100644 --- a/NEWS.md +++ b/NEWS.md @@ -8,6 +8,12 @@ the dosing including dose amount and route. ## Breaking changes +* A negative dose amount is an error (`pknca_error_dose_negative`, naming the + first rows and their count), in `PKNCAdose()` and again in `pk.nca()` for a + dose made negative later, for example by `mutate()` (@billdenney). Code + that passed a negative dose before now stops. A zero or missing dose amount + is allowed as before, and a dose row excluded with `exclude` is not checked. + * Parameter names and descriptions follow one style, so some column headers of `summary()` and some descriptions change (@billdenney): * Pretty names write lambda.z as math (`$\lambda_z$`), including "Number of diff --git a/R/class-PKNCAdose.R b/R/class-PKNCAdose.R index 4e5427e0a..f0bc333af 100644 --- a/R/class-PKNCAdose.R +++ b/R/class-PKNCAdose.R @@ -43,6 +43,11 @@ #' same dose is given in every interval. When given as a two-sided #' formula, both the dose amount and time are used directly from the #' data. +#' +#' A negative dose amount is an error (`pknca_error_dose_negative`, naming +#' the rows), here and again in [pk.nca()] for a dose made negative later +#' (for example by `mutate()`). A zero or missing amount is allowed, and a +#' row excluded with `exclude` is not checked. #' @family PKNCA objects #' @export PKNCAdose <- function(data, ...) @@ -152,6 +157,7 @@ PKNCAdose.data.frame <- function(data, formula, route, rate, duration, class = "pknca_error_partial_missing_indepvar" ) } + assert_dose_not_negative(ret) if (length(parsed_form$time) == 1 && inherits(data[[parsed_form$time]], "Date")) { pknca_warn_date_time(time_col = parsed_form$time, data_type = "dose") } @@ -293,6 +299,41 @@ getDepVar.PKNCAdose <- function(x, ...) { } } +#' Require that no dose amount is negative +#' +#' A negative dose amount is invalid input. A zero amount and a missing +#' amount are allowed, and an excluded row is not checked, as for the dose +#' times. +#' +#' @param object A PKNCAdose object +#' @returns `object`, invisibly, or the error `pknca_error_dose_negative` +#' naming the first rows of the dose data with a negative amount and their +#' count +#' @keywords Internal +#' @noRd +assert_dose_not_negative <- function(object) { + dose <- getDepVar.PKNCAdose(object) + if (!is.numeric(dose)) { + return(invisible(object)) + } + # The plain numbers, so that a units column needs no method + values <- as.numeric(dose) + rows <- which(!is.na(values) & values < 0 & is.na(normalize_exclude(object))) + if (length(rows) > 0) { + rlang::abort( + sprintf( + "Dose amounts (column '%s') must not be negative; %d row(s) of the dose data are: %s%s", + object$columns$dose, + length(rows), + paste(utils::head(rows, 5), collapse = ", "), + if (length(rows) > 5) ", ..." else "" + ), + class = "pknca_error_dose_negative" + ) + } + invisible(object) +} + #' @export getIndepVar.PKNCAdose <- function(x, ...) { time_col <- x$columns$time diff --git a/R/pk.calc.all.R b/R/pk.calc.all.R index 40e6b63ef..a438785df 100644 --- a/R/pk.calc.all.R +++ b/R/pk.calc.all.R @@ -29,6 +29,11 @@ #' @export pk.nca <- function(data, verbose=FALSE) { assert_PKNCAdata(data) + # PKNCAdose() refused a negative dose amount; a mutate() or join on the + # dose data afterwards may have made one + if (inherits(data$dose, "PKNCAdose")) { + assert_dose_not_negative(data$dose) + } # Date-time times and intervals and difftime durations become numbers here, # so that intervals can change after PKNCAdata(). The results keep the # converted data, which is the data the calculations used. diff --git a/man/PKNCAdose.Rd b/man/PKNCAdose.Rd index 453c2641b..5de47209f 100644 --- a/man/PKNCAdose.Rd +++ b/man/PKNCAdose.Rd @@ -88,6 +88,11 @@ per group. When the right side is missing, PKNCA assumes that the same dose is given in every interval. When given as a two-sided formula, both the dose amount and time are used directly from the data. + +A negative dose amount is an error (\code{pknca_error_dose_negative}, naming +the rows), here and again in \code{\link[=pk.nca]{pk.nca()}} for a dose made negative later +(for example by \code{mutate()}). A zero or missing amount is allowed, and a +row excluded with \code{exclude} is not checked. } \seealso{ Other PKNCA objects: diff --git a/tests/testthat/test-class-PKNCAdose.R b/tests/testthat/test-class-PKNCAdose.R index b960942b9..a0df6c2c6 100644 --- a/tests/testthat/test-class-PKNCAdose.R +++ b/tests/testthat/test-class-PKNCAdose.R @@ -584,3 +584,72 @@ test_that("PKNCAdose does not error for excluded, invalid times (#310)", { tmp.dose <- data.frame(time = c(1, 2), dose = c(1, 2)) expect_no_error(PKNCAdose(tmp.dose, formula = dose~time, exclude = NULL)) }) + +test_that("a negative dose amount is an error naming the rows", { + d_dose <- data.frame(id = 1:8, time = 0, dose = c(1, -1, 2, -2, -3, -4, -5, -6)) + expect_error( + PKNCAdose(d_dose, dose ~ time | id), + regexp = "Dose amounts (column 'dose') must not be negative; 6 row(s) of the dose data are: 2, 4, 5, 6, 7, ...", + fixed = TRUE, + class = "pknca_error_dose_negative" + ) + # One dose per group for every interval (`dose ~ .`) + expect_error( + PKNCAdose(data.frame(id = 1:2, dose = c(5, -5)), dose ~ . | id), + regexp = "Dose amounts (column 'dose') must not be negative; 1 row(s) of the dose data are: 2", + fixed = TRUE, + class = "pknca_error_dose_negative" + ) + # A units column + expect_error( + PKNCAdose(data.frame(id = 1, time = 0, dose = units::set_units(-5, "mg")), dose ~ time | id), + class = "pknca_error_dose_negative" + ) + # Through PKNCAdata() with a data.frame and formula.dose + expect_error( + PKNCAdata( + data.frame(id = 1, time = 0:2, conc = c(0, 2, 1)), data.frame(id = 1, time = 0, dose = -1), + formula.conc = conc ~ time | id, formula.dose = dose ~ time | id + ), + class = "pknca_error_dose_negative" + ) +}) + +test_that("an excluded negative dose, a zero dose, and a missing dose are allowed", { + d_dose <- data.frame(id = 1:2, time = 0, dose = c(1, -1), excl = c(NA, "bad dose")) + expect_no_error(PKNCAdose(d_dose, dose ~ time | id, exclude = "excl")) + # No dose amount at all + expect_no_error(PKNCAdose(data.frame(id = 1, time = 0), ~ time | id)) + # Zero and missing amounts give what they gave before negative amounts were + # refused: a zero dose divides to Inf, and a missing one gives NA + d_conc <- data.frame(id = 1, time = c(0, 1, 2, 4, 8), conc = c(0, 10, 8, 4, 2)) + intervals <- data.frame(start = 0, end = Inf, cl.last = TRUE, auclast.dn = TRUE, cmax.dn = TRUE, totdose = TRUE) + for (current in list(list(dose = 0, expected = c(cl.last = 0, auclast.dn = Inf, cmax.dn = Inf, totdose = 0)), + list(dose = NA_real_, expected = c(cl.last = NA_real_, auclast.dn = NA_real_, cmax.dn = NA_real_, totdose = NA_real_)))) { + o_data <- + PKNCAdata( + PKNCAconc(d_conc, conc ~ time | id), + PKNCAdose(data.frame(id = 1, time = 0, dose = current$dose), dose ~ time | id), + intervals = intervals + ) + res <- as.data.frame(suppressMessages(pk.nca(o_data))) + value <- stats::setNames(res$PPORRES, res$PPTESTCD) + expect_equal(value[names(current$expected)], current$expected, info = as.character(current$dose)) + } +}) + +test_that("pk.nca refuses a dose made negative after PKNCAdose", { + o_dose <- PKNCAdose(data.frame(id = 1, time = 0, dose = 1), dose ~ time | id) + o_data <- + PKNCAdata( + PKNCAconc(data.frame(id = 1, time = 0:2, conc = c(0, 2, 1)), conc ~ time | id), + dplyr::mutate(o_dose, dose = -dose), + intervals = data.frame(start = 0, end = Inf, cmax.dn = TRUE) + ) + expect_error( + pk.nca(o_data), + regexp = "Dose amounts (column 'dose') must not be negative; 1 row(s) of the dose data are: 1", + fixed = TRUE, + class = "pknca_error_dose_negative" + ) +}) From f3fec2e16887b9d97b4ddba1d216bd07837456ef Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Sun, 15 Nov 2026 10:33:13 -0500 Subject: [PATCH 02/21] fix: say "numeric" dose, and pin the five-row boundary and a character dose A dose column that is not numeric is not checked by assert_dose_not_negative(); the documentation and NEWS say so, and a test pins that a character dose does not raise pknca_error_dose_negative. A test pins the message with exactly five offending rows (no "..."). Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 12 +++++++----- R/class-PKNCAdose.R | 12 +++++++----- man/PKNCAdose.Rd | 9 +++++---- tests/testthat/test-class-PKNCAdose.R | 12 ++++++++++++ 4 files changed, 31 insertions(+), 14 deletions(-) diff --git a/NEWS.md b/NEWS.md index d09cb45c6..d10767d80 100644 --- a/NEWS.md +++ b/NEWS.md @@ -8,11 +8,13 @@ the dosing including dose amount and route. ## Breaking changes -* A negative dose amount is an error (`pknca_error_dose_negative`, naming the - first rows and their count), in `PKNCAdose()` and again in `pk.nca()` for a - dose made negative later, for example by `mutate()` (@billdenney). Code - that passed a negative dose before now stops. A zero or missing dose amount - is allowed as before, and a dose row excluded with `exclude` is not checked. +* A negative numeric dose amount is an error (`pknca_error_dose_negative`, + naming the first rows and their count), in `PKNCAdose()` and again in + `pk.nca()` for a dose made negative later, for example by `mutate()` + (@billdenney). Code that passed a negative dose before now stops. A zero + or missing dose amount is allowed as before, a dose row excluded with + `exclude` is not checked, and a dose column that is not numeric is not + checked here. * Parameter names and descriptions follow one style, so some column headers of `summary()` and some descriptions change (@billdenney): diff --git a/R/class-PKNCAdose.R b/R/class-PKNCAdose.R index f0bc333af..f67c309cf 100644 --- a/R/class-PKNCAdose.R +++ b/R/class-PKNCAdose.R @@ -44,10 +44,11 @@ #' formula, both the dose amount and time are used directly from the #' data. #' -#' A negative dose amount is an error (`pknca_error_dose_negative`, naming -#' the rows), here and again in [pk.nca()] for a dose made negative later -#' (for example by `mutate()`). A zero or missing amount is allowed, and a -#' row excluded with `exclude` is not checked. +#' A negative numeric dose amount is an error (`pknca_error_dose_negative`, +#' naming the rows), here and again in [pk.nca()] for a dose made negative +#' later (for example by `mutate()`). A zero or missing amount is allowed, +#' and a row excluded with `exclude` is not checked. A dose column that is +#' not numeric is not checked here. #' @family PKNCA objects #' @export PKNCAdose <- function(data, ...) @@ -303,7 +304,8 @@ getDepVar.PKNCAdose <- function(x, ...) { #' #' A negative dose amount is invalid input. A zero amount and a missing #' amount are allowed, and an excluded row is not checked, as for the dose -#' times. +#' times. A dose column that is not numeric (character, factor, difftime) is +#' not checked: it fails later, where it is used as a number. #' #' @param object A PKNCAdose object #' @returns `object`, invisibly, or the error `pknca_error_dose_negative` diff --git a/man/PKNCAdose.Rd b/man/PKNCAdose.Rd index 5de47209f..60c8023de 100644 --- a/man/PKNCAdose.Rd +++ b/man/PKNCAdose.Rd @@ -89,10 +89,11 @@ same dose is given in every interval. When given as a two-sided formula, both the dose amount and time are used directly from the data. -A negative dose amount is an error (\code{pknca_error_dose_negative}, naming -the rows), here and again in \code{\link[=pk.nca]{pk.nca()}} for a dose made negative later -(for example by \code{mutate()}). A zero or missing amount is allowed, and a -row excluded with \code{exclude} is not checked. +A negative numeric dose amount is an error (\code{pknca_error_dose_negative}, +naming the rows), here and again in \code{\link[=pk.nca]{pk.nca()}} for a dose made negative +later (for example by \code{mutate()}). A zero or missing amount is allowed, +and a row excluded with \code{exclude} is not checked. A dose column that is +not numeric is not checked here. } \seealso{ Other PKNCA objects: diff --git a/tests/testthat/test-class-PKNCAdose.R b/tests/testthat/test-class-PKNCAdose.R index a0df6c2c6..1dd39134e 100644 --- a/tests/testthat/test-class-PKNCAdose.R +++ b/tests/testthat/test-class-PKNCAdose.R @@ -593,6 +593,16 @@ test_that("a negative dose amount is an error naming the rows", { fixed = TRUE, class = "pknca_error_dose_negative" ) + # Exactly five rows are all named, with no "..." + cnd <- + expect_error( + PKNCAdose(data.frame(id = 1:6, time = 0, dose = c(1, -1, -2, -3, -4, -5)), dose ~ time | id), + class = "pknca_error_dose_negative" + ) + expect_equal( + conditionMessage(cnd), + "Dose amounts (column 'dose') must not be negative; 5 row(s) of the dose data are: 2, 3, 4, 5, 6" + ) # One dose per group for every interval (`dose ~ .`) expect_error( PKNCAdose(data.frame(id = 1:2, dose = c(5, -5)), dose ~ . | id), @@ -620,6 +630,8 @@ test_that("an excluded negative dose, a zero dose, and a missing dose are allowe expect_no_error(PKNCAdose(d_dose, dose ~ time | id, exclude = "excl")) # No dose amount at all expect_no_error(PKNCAdose(data.frame(id = 1, time = 0), ~ time | id)) + # A dose column that is not numeric is not checked here + expect_no_error(PKNCAdose(data.frame(id = 1:2, time = 0, dose = c("1", "-2")), dose ~ time | id)) # Zero and missing amounts give what they gave before negative amounts were # refused: a zero dose divides to Inf, and a missing one gives NA d_conc <- data.frame(id = 1, time = c(0, 1, 2, 4, 8), conc = c(0, 10, 8, 4, 2)) From aba3c974bf1aba1105a51d6a75bb2815a9ee9333 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Sun, 15 Nov 2026 19:45:21 -0500 Subject: [PATCH 03/21] fix: PKNCAdose() with a rate column works with more than one dose row PKNCAdose.data.frame() passed the dose amounts to setDuration.PKNCAdose(), which expects the name of the dose column, so `!is.na(dose)` had the length of the data and stopped with "'length = 2' in coercion to 'logical(1)'" from two rows on (one row worked by accident). The column name default now applies, and each dose's duration is its amount divided by its rate. A rate with no dose amount (a formula without a left side) is the typed error pknca_error_rate_without_dose. A missing rate, a rate of zero, or a missing dose amount give the existing pknca_error_dose_invalid_duration. Tests cover one, two, and three rows, a scalar rate, those three invalid cases, and the formula without a dose for one and two rows. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 8 +++++++ R/class-PKNCAdose.R | 22 +++++++++++++------ man/PKNCAdose.Rd | 9 +++++--- tests/testthat/test-class-PKNCAdose.R | 31 +++++++++++++++++++++++++++ 4 files changed, 61 insertions(+), 9 deletions(-) diff --git a/NEWS.md b/NEWS.md index d10767d80..1136d47ac 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1220,6 +1220,14 @@ the generated intervals: ## Bug fixes +* `PKNCAdose()` with a `rate` column now works with more than one dose row + (@billdenney; PR number to add). It stopped with "'length = 2' in coercion + to 'logical(1)'", because the dose amounts were passed where the name of the + dose column was expected; one row worked by accident. Each dose's duration + is its amount divided by its rate. A `rate` with no dose amount (a formula + without a left side) is now the error `pknca_error_rate_without_dose` in + place of an error without a class. + * Preferred units (`concu_pref`, `doseu_pref`, and the others) with unit columns whose units differ between groups no longer stop `PKNCAdata()` with "arguments imply differing number of rows: 1, 0" when some groups are diff --git a/R/class-PKNCAdose.R b/R/class-PKNCAdose.R index f67c309cf..2acd6896a 100644 --- a/R/class-PKNCAdose.R +++ b/R/class-PKNCAdose.R @@ -16,9 +16,12 @@ #' column from the `data`, and if given as a number, it is the value for all #' doses. Only one may be given, and if neither is given, then the dose is #' assumed to be a bolus (`duration=0`). If `rate` is given, then the dose -#' amount must be given (the left hand side of the `formula`). A numeric -#' duration is in the time unit of the analysis; a difftime duration is -#' converted to that unit in [PKNCAdata()]. +#' amount must be given (the left hand side of the `formula`; +#' `pknca_error_rate_without_dose` otherwise), and the duration of each dose +#' is its amount divided by its rate. A missing dose amount or rate, or a +#' rate of zero, gives no valid duration (`pknca_error_dose_invalid_duration`). +#' A numeric duration is in the time unit of the analysis; a difftime +#' duration is converted to that unit in [PKNCAdata()]. #' @param time.nominal (optional) The name of the nominal time column (if the #' main time variable is actual time. The `time.nominal` is not used during #' calculations; it is available to assist with data summary and checking. @@ -167,8 +170,8 @@ PKNCAdose.data.frame <- function(data, formula, route, rate, duration, } else { ret <- setRoute(ret, route) } - ret <- setDuration.PKNCAdose(ret, duration=duration, - rate=rate, dose=getDepVar.PKNCAdose(ret)) + # The dose is the column name, which setDuration.PKNCAdose() uses by default + ret <- setDuration.PKNCAdose(ret, duration=duration, rate=rate) if (!missing(time.nominal)) { ret <- setAttributeColumn(object=ret, @@ -252,7 +255,14 @@ setDuration.PKNCAdose <- function(object, duration, rate, dose, ...) { # requiring near-equal checks for floating point error. } else if (!missing(duration)) { object <- setAttributeColumn(object=object, attr_name="duration", col_or_value=duration) - } else if (!missing(rate) && !missing(dose) && !is.na(dose)) { + } else if (!missing(rate)) { + # `dose` is a column name (the default) or the dose amounts + if (length(dose) == 0 || all(is.na(dose))) { + rlang::abort( + "`rate` needs the dose amount (the left side of the formula) to calculate the duration; without a dose amount, give `duration` instead", + class = "pknca_error_rate_without_dose" + ) + } tmprate <- getColumnValueOrNot(object$data, rate, "rate") tmpdose <- getColumnValueOrNot(object$data, dose, "dose") duration <- tmpdose$data[[tmpdose$name]]/tmprate$data[[tmprate$name]] diff --git a/man/PKNCAdose.Rd b/man/PKNCAdose.Rd index 60c8023de..cf7ce40d0 100644 --- a/man/PKNCAdose.Rd +++ b/man/PKNCAdose.Rd @@ -48,9 +48,12 @@ duration of dosing. If given as a character string, it is the name of a column from the \code{data}, and if given as a number, it is the value for all doses. Only one may be given, and if neither is given, then the dose is assumed to be a bolus (\code{duration=0}). If \code{rate} is given, then the dose -amount must be given (the left hand side of the \code{formula}). A numeric -duration is in the time unit of the analysis; a difftime duration is -converted to that unit in \code{\link[=PKNCAdata]{PKNCAdata()}}.} +amount must be given (the left hand side of the \code{formula}; +\code{pknca_error_rate_without_dose} otherwise), and the duration of each dose +is its amount divided by its rate. A missing dose amount or rate, or a +rate of zero, gives no valid duration (\code{pknca_error_dose_invalid_duration}). +A numeric duration is in the time unit of the analysis; a difftime +duration is converted to that unit in \code{\link[=PKNCAdata]{PKNCAdata()}}.} \item{time.nominal}{(optional) The name of the nominal time column (if the main time variable is actual time. The \code{time.nominal} is not used during diff --git a/tests/testthat/test-class-PKNCAdose.R b/tests/testthat/test-class-PKNCAdose.R index 1dd39134e..4a9b1b0ec 100644 --- a/tests/testthat/test-class-PKNCAdose.R +++ b/tests/testthat/test-class-PKNCAdose.R @@ -665,3 +665,34 @@ test_that("pk.nca refuses a dose made negative after PKNCAdose", { class = "pknca_error_dose_negative" ) }) + +# The durations of the doses, from PKNCAdose(rate = ) on `d_dose` +rate_durations <- function(d_dose, formula = dose ~ time | id, rate = "rate") { + o_dose <- PKNCAdose(d_dose, formula, route = "intravascular", rate = rate) + as.data.frame(o_dose)[[o_dose$columns$duration]] +} + +test_that("a rate column gives each dose its own duration, with any number of rows", { + expect_equal(rate_durations(data.frame(id = 1, time = 0, dose = 10, rate = 5)), 2) + expect_equal(rate_durations(data.frame(id = 1:2, time = 0, dose = c(10, 20), rate = c(5, 4))), c(2, 5)) + expect_equal(rate_durations(data.frame(id = 1:3, time = 0, dose = c(10, 20, 30), rate = c(5, 4, 3))), c(2, 5, 10)) + # One rate for every dose + expect_equal(rate_durations(data.frame(id = 1:2, time = 0, dose = c(10, 20)), rate = 2), c(5, 10)) + # A missing rate, a rate of zero, or a missing dose amount gives no valid + # duration + for (d_dose in list( + data.frame(id = 1:2, time = 0, dose = c(10, 20), rate = c(5, NA)), + data.frame(id = 1:2, time = 0, dose = c(10, 20), rate = c(5, 0)), + data.frame(id = 1:2, time = 0, dose = c(10, NA), rate = c(5, 4)) + )) { + expect_error(rate_durations(d_dose), class = "pknca_error_dose_invalid_duration") + } + # Without a dose amount, a rate cannot give a duration + for (n in 1:2) { + expect_error( + rate_durations(data.frame(id = seq_len(n), time = 0, rate = 5), formula = ~ time | id), + regexp = "`rate` needs the dose amount", + class = "pknca_error_rate_without_dose" + ) + } +}) From e763a8e7d4ad1df825513fc32f66fa7d40174c59 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Sun, 15 Nov 2026 19:49:28 -0500 Subject: [PATCH 04/21] fix: pk.calc.tlag() skips missing concentrations, as its siblings do Bill's answer (2026-11-15) for a missing concentration in pk.calc.tlag(): "Same as its siblings". It gains check = TRUE (assert_conc_time()) and looks for the first increase among the measured concentrations, returning NA when none increases or every concentration is missing. Before, a missing value made the comparison of neighbours NA: tlag(c(NA, 40, 80, 10)) was NA by accident instead of 2, and tlag(c(NA, 40, 20, 10)) or an all-missing interval stopped with "missing value where TRUE/FALSE needed" (in pk.nca(), "Please report a bug"). pk.nca() gets no cleaning step. Tests: a missing value at the start, in the middle, at the end, and everywhere, directly (with and without check) and through pk.nca() at conc.na "drop" and at 0. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 9 +++++ R/pk.calc.simple.R | 15 +++++++-- man/pk.calc.tlag.Rd | 11 +++--- tests/testthat/test-pk.calc.simple.R | 50 ++++++++++++++++++++++++++++ 4 files changed, 79 insertions(+), 6 deletions(-) diff --git a/NEWS.md b/NEWS.md index 18b6f8941..e39773d2d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1212,6 +1212,15 @@ the generated intervals: ## Bug fixes +* `pk.calc.tlag()` skips missing concentrations, as `pk.calc.cmax()` and the + other simple parameters do, and gains a `check` argument like theirs + (@billdenney; PR number to add). Two results change: a missing value + before or between the measured ones gave `NA` (for example + `pk.calc.tlag(c(NA, 40, 80, 10), c(0, 2, 4, 8))`) and now gives the lag time + of the measured values (2); and a missing value with no increase after it, + or every value missing, stopped the calculation (in `pk.nca()`, "Please + report a bug ... missing value where TRUE/FALSE needed") and now gives `NA`. + * Preferred units (`concu_pref`, `doseu_pref`, and the others) with unit columns whose units differ between groups no longer stop `PKNCAdata()` with "arguments imply differing number of rows: 1, 0" when some groups are diff --git a/R/pk.calc.simple.R b/R/pk.calc.simple.R index 0252dafe2..4fa035ebf 100644 --- a/R/pk.calc.simple.R +++ b/R/pk.calc.simple.R @@ -2317,12 +2317,23 @@ add.interval.col("ptr", #' concentration above the limit of quantification or above the first #' concentration in the interval) #' +#' Missing concentrations are skipped, as in [pk.calc.cmax()] and the other +#' simple parameters: the increase is looked for among the measured +#' concentrations. `NA` is returned when no measured concentration increases +#' (including when every concentration is missing). +#' #' @inheritParams assert_conc_time +#' @param check Run [assert_conc_time()]? #' @returns The time associated with the first increasing concentration #' @family NCA time parameters #' @export -pk.calc.tlag <- function(conc, time) { - assert_conc_time(conc = conc, time = time) +pk.calc.tlag <- function(conc, time, check = TRUE) { + if (check) { + assert_conc_time(conc = conc, time = time) + } + mask_measured <- !is.na(conc) + conc <- conc[mask_measured] + time <- time[mask_measured] mask.increase <- c(conc[-1] > conc[-length(conc)], FALSE) if (any(mask.increase)) { time[mask.increase][1] diff --git a/man/pk.calc.tlag.Rd b/man/pk.calc.tlag.Rd index d41e97736..136ec3f87 100644 --- a/man/pk.calc.tlag.Rd +++ b/man/pk.calc.tlag.Rd @@ -6,20 +6,23 @@ concentration above the limit of quantification or above the first concentration in the interval)} \usage{ -pk.calc.tlag(conc, time) +pk.calc.tlag(conc, time, check = TRUE) } \arguments{ \item{conc}{Measured concentrations} \item{time}{Time of the measurement of the concentrations} + +\item{check}{Run \code{\link[=assert_conc_time]{assert_conc_time()}}?} } \value{ The time associated with the first increasing concentration } \description{ -Determine the observed lag time (time before the first -concentration above the limit of quantification or above the first -concentration in the interval) +Missing concentrations are skipped, as in \code{\link[=pk.calc.cmax]{pk.calc.cmax()}} and the other +simple parameters: the increase is looked for among the measured +concentrations. \code{NA} is returned when no measured concentration increases +(including when every concentration is missing). } \seealso{ Other NCA time parameters: diff --git a/tests/testthat/test-pk.calc.simple.R b/tests/testthat/test-pk.calc.simple.R index 98bb93ce8..e5843adde 100644 --- a/tests/testthat/test-pk.calc.simple.R +++ b/tests/testthat/test-pk.calc.simple.R @@ -515,6 +515,56 @@ test_that("pk.calc.tlag", { info="No increase gives NA") }) +test_that("pk.calc.tlag skips missing concentrations, as the other simple parameters do", { + # At the start: the first increase among the measured values is 40 to 80 + expect_equal(pk.calc.tlag(c(NA, 40, 80, 10), c(0, 2, 4, 8)), 2) + # At the start with no increase among the measured values + expect_equal(pk.calc.tlag(c(NA, 40, 20, 10), c(0, 2, 4, 8)), NA_real_) + # In the middle: 10 and 5 are not an increase, 5 to 8 is + expect_equal(pk.calc.tlag(c(10, NA, 5, 8), 0:3), 2) + # At the end + expect_equal(pk.calc.tlag(c(0, 5, 10, NA), 0:3), 0) + # Everywhere, with a warning from the check, and without it + expect_warning( + value_all_missing <- pk.calc.tlag(c(NA_real_, NA_real_, NA_real_), 0:2), + class = "pknca_warning_all_concentration_missing" + ) + expect_equal(value_all_missing, NA_real_) + expect_equal(pk.calc.tlag(c(NA_real_, NA_real_, NA_real_), 0:2, check = FALSE), NA_real_) + # check = FALSE skips the assertions, not the missing values + expect_equal(pk.calc.tlag(c(10, NA, 5, 8), 0:3, check = FALSE), 2) +}) + +# tlag from 0 to 8 of one profile with the conc.na option `conc_na` +tlag_test_nca <- function(conc, conc_na) { + o_data <- + PKNCAdata( + PKNCAconc(data.frame(id = 1, time = c(0, 2, 4, 8), conc = conc), conc ~ time | id), + PKNCAdose(data.frame(id = 1, time = 0, dose = 1), dose ~ time | id), + intervals = data.frame(start = 0, end = 8, tlag = TRUE), + options = list(conc.na = conc_na) + ) + res <- as.data.frame(suppressWarnings(suppressMessages(pk.nca(o_data)))) + res$PPORRES[res$PPTESTCD == "tlag"] +} + +test_that("tlag in pk.nca with missing concentrations", { + # The missing value is skipped at either conc.na, as for cmax + for (conc_na in list("drop", 0)) { + expect_equal(tlag_test_nca(c(NA, 40, 80, 10), conc_na), 2, info = as.character(conc_na)) + # No increase among the measured values: NA, where the interval stopped + # with "Please report a bug" + expect_equal(tlag_test_nca(c(NA, 40, 20, 10), conc_na), NA_real_, info = as.character(conc_na)) + } + # Every concentration missing: NA, where the interval stopped with "Please + # report a bug" (the data checks warn that every concentration is missing) + expect_warning( + value_all_missing <- tlag_test_nca(rep(NA_real_, 4), "drop"), + class = "pknca_warning_all_concentration_missing" + ) + expect_equal(value_all_missing, NA_real_) +}) + test_that("pk.calc.deg.fluc", { expect_equal(pk.calc.deg.fluc(cmax=100, cmin=10, cav=45), 200, info="Degree of fluctuation math works") From 5d34478c93d7d4b0f5cf8ab71f3f2f642e769cfa Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Sun, 15 Nov 2026 21:04:33 -0500 Subject: [PATCH 05/21] fix: the excretion rates are NA when a collection with a volume has no concentration Bill (2026-11-16): "Make them NA too". ertlst, ermax, ertmax, and erlst were calculated from the other collections, with the reason, when a collection with a volume had a missing concentration, while ae, fe, and erint were NA. The amount in that collection is unknown, so the rate of the interval is too: urine_rate_result() makes them NA, keeping the existing reasons and Bill's sentence. A collection missing both its concentration and its volume, or a known concentration with a missing volume, leaves the rates as they were. A comparison of every parameter against the base branch over seven imputation chains, both conc.na settings, and plasma, multiple-dose, and urine profiles changes only these four rates on the urine profile, from a number to NA, with no change to any exclusion text. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 10 ++++++++ R/pk.calc.urine.R | 38 ++++++++++++++--------------- tests/testthat/test-pk.calc.all.R | 5 ++-- tests/testthat/test-pk.calc.urine.R | 28 +++++++++++++++++++-- 4 files changed, 56 insertions(+), 25 deletions(-) diff --git a/NEWS.md b/NEWS.md index bdebef541..5db75d27c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -8,6 +8,16 @@ the dosing including dose amount and route. ## Breaking changes +* The excretion rates `ertlst`, `ermax`, `ertmax`, and `erlst` are now `NA` + when a collection with a volume has no concentration, as `ae`, `fe`, and + `erint` already were (@billdenney; PR number to add). They were calculated + from the other collections, with the reason "1 of 4 concentrations are + missing"; the amount in that collection is unknown, so the rate of the + interval is too. The reason is unchanged, with "At least one concentration + associated with a collection volume was missing" beside it. A collection + missing both its concentration and its volume, or a known concentration + with a missing volume, leaves the rates as they were. + * Parameter names and descriptions follow one style, so some column headers of `summary()` and some descriptions change (@billdenney): * Pretty names write lambda.z as math (`$\lambda_z$`), including "Number of diff --git a/R/pk.calc.urine.R b/R/pk.calc.urine.R index e2dd5cf19..0435531bb 100644 --- a/R/pk.calc.urine.R +++ b/R/pk.calc.urine.R @@ -247,11 +247,7 @@ pk.calc.ertlst <- function(conc, volume, time, duration.conc, check = TRUE) { ret <- max(midtime[!is.na(er) & er != 0]) } - if (length(message_all) != 0) { - message <- paste(message_all, collapse = "; ") - ret <- structure(ret, exclude = message) - } - ret + urine_rate_result(ret, conc = conc, volume = volume, message_all = message_all) } pknca_concept(pk.calc.ertlst) <- "excretion_rate" @@ -293,11 +289,7 @@ pk.calc.ermax <- function(conc, volume, time, duration.conc, check = TRUE) { } } - if (length(message_all) != 0) { - message <- paste(message_all, collapse = "; ") - ret <- structure(ret, exclude = message) - } - ret + urine_rate_result(ret, conc = conc, volume = volume, message_all = message_all) } pknca_concept(pk.calc.ermax) <- "excretion_rate" @@ -345,11 +337,7 @@ pk.calc.ertmax <- function(conc, volume, time, duration.conc, options = list(), } } - if (length(message_all) != 0) { - message <- paste(message_all, collapse = "; ") - ret <- structure(ret, exclude = message) - } - ret + urine_rate_result(ret, conc = conc, volume = volume, message_all = message_all) } pknca_concept(pk.calc.ertmax) <- "excretion_rate" @@ -437,11 +425,7 @@ pk.calc.erlst <- function(conc, volume, time, duration.conc, check = TRUE) { } } - if (length(message_all) != 0) { - message <- paste(message_all, collapse = "; ") - ret <- structure(ret, exclude = message) - } - ret + urine_rate_result(ret, conc = conc, volume = volume, message_all = message_all) } pknca_concept(pk.calc.erlst) <- "excretion_rate" @@ -524,3 +508,17 @@ urine_missing_messages <- function(conc, volume) { } ret } + +# The result of an excretion rate (ertlst, ermax, ertmax, erlst) with the +# reasons from urine_missing_messages(): a collection with a volume and no +# concentration has an unknown amount, so the rate of the interval is unknown +# too, as the amount excreted is +urine_rate_result <- function(ret, conc, volume, message_all) { + if (any(is.na(conc) & !is.na(volume))) { + ret <- NA_real_ + } + if (length(message_all) != 0) { + ret <- structure(ret, exclude = paste(message_all, collapse = "; ")) + } + ret +} diff --git a/tests/testthat/test-pk.calc.all.R b/tests/testthat/test-pk.calc.all.R index ba691e92a..b34dd3b8b 100644 --- a/tests/testthat/test-pk.calc.all.R +++ b/tests/testthat/test-pk.calc.all.R @@ -1390,9 +1390,8 @@ test_that("a collection with a missing concentration stays in the amount excrete res <- impute_test_urine(d_conc, current) expect_equal(unname(res$value[c("ae", "fe", "erint")]), rep(NA_real_, 3), info = current) expect_equal(unname(res$exclude[c("ae", "fe", "erint")]), rep(reason, 3), info = current) - # The excretion rate is calculated from the other collections, with the - # reason - expect_equal(unname(res$value["ermax"]), 20, info = current) + # The excretion rate of the interval is unknown too + expect_equal(unname(res$value["ermax"]), NA_real_, info = current) expect_equal(unname(res$exclude["ermax"]), reason, info = current) # The start row stays, so the start methods see a row there and impute # nothing diff --git a/tests/testthat/test-pk.calc.urine.R b/tests/testthat/test-pk.calc.urine.R index f196ec3ed..506577545 100644 --- a/tests/testthat/test-pk.calc.urine.R +++ b/tests/testthat/test-pk.calc.urine.R @@ -71,10 +71,16 @@ test_that("pk.calc.ertlst", { pk.calc.ertlst(conc = c(NA, NA), volume = c(NA, NA), time = c(0, 1), duration.conc = c(1, 1)), structure(NA_real_, exclude = "All concentrations and volumes are missing") ) - # All 0 or NA + # A collection with a volume and no concentration has an unknown amount, so + # the rate is unknown expect_equal( pk.calc.ertlst(conc = c(0, NA), volume = c(1, 1), time = c(0, 1), duration.conc = c(1, 1)), - structure(0, exclude = "1 of 2 concentrations are missing; At least one concentration associated with a collection volume was missing") + structure(NA_real_, exclude = "1 of 2 concentrations are missing; At least one concentration associated with a collection volume was missing") + ) + # All 0 with a missing volume: the concentration is known, so the rate is + expect_equal( + pk.calc.ertlst(conc = c(0, 0), volume = c(1, NA), time = c(0, 1), duration.conc = c(1, 1)), + structure(0, exclude = "1 of 2 volumes are missing") ) # Normal case expect_equal( @@ -269,3 +275,21 @@ test_that("erint and erlst are calculated by pk.nca()", { expect_equal(result$PPORRES[result$PPTESTCD == "erint"], ae / 24) expect_equal(result$PPORRES[result$PPTESTCD == "erlst"], 100 / 4) }) + +test_that("every excretion rate is NA when a collection with a volume has no concentration", { + reason <- "1 of 3 concentrations are missing; At least one concentration associated with a collection volume was missing" + args <- list(conc = c(40, NA, 10), volume = c(1, 2, 3), time = c(0, 2, 4), duration.conc = c(2, 2, 2)) + for (fun in c("pk.calc.ertlst", "pk.calc.ermax", "pk.calc.ertmax", "pk.calc.erlst")) { + expect_equal(do.call(fun, args), structure(NA_real_, exclude = reason), info = fun) + } + # A missing volume with a known concentration leaves the rates calculated + # from the other collections, with the reason, as before + args_volume <- list(conc = c(40, 5, 10), volume = c(1, NA, 3), time = c(0, 2, 4), duration.conc = c(2, 2, 2)) + expect_equal(pk.calc.ermax(conc = args_volume$conc, volume = args_volume$volume, time = args_volume$time, duration.conc = args_volume$duration.conc), structure(20, exclude = "1 of 3 volumes are missing")) + # A collection missing both its concentration and its volume is not one with + # a volume: the rates are calculated from the others, as before + expect_equal( + pk.calc.ermax(conc = c(40, NA, 10), volume = c(1, NA, 3), time = c(0, 2, 4), duration.conc = c(2, 2, 2)), + structure(20, exclude = "1 of 3 concentrations and volumes are missing") + ) +}) From 144474fa71be670f3ead40e8f44b931a68d6ce6a Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Mon, 16 Nov 2026 06:49:59 -0500 Subject: [PATCH 06/21] docs: the setDuration() dose argument and the previous errors, with a direct test - setDuration()'s @param dose says it is the name of the dose column by default, or the dose amounts. - NEWS says what a rate with no dose amount gave before (pknca_error_dose_invalid_duration with one row, an error without a class with more) and that a direct setDuration(object, rate = 5, dose = NA), which returned a duration of 0, is now pknca_error_rate_without_dose. - A test calls setDuration() directly with the default dose column, with dose amounts, and with a missing dose. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 6 ++++-- R/class-PKNCAdose.R | 4 +++- man/setDuration.Rd | 4 +++- tests/testthat/test-class-PKNCAdose.R | 13 +++++++++++++ 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/NEWS.md b/NEWS.md index 1136d47ac..0c0d10990 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1225,8 +1225,10 @@ the generated intervals: to 'logical(1)'", because the dose amounts were passed where the name of the dose column was expected; one row worked by accident. Each dose's duration is its amount divided by its rate. A `rate` with no dose amount (a formula - without a left side) is now the error `pknca_error_rate_without_dose` in - place of an error without a class. + without a left side) is now the error `pknca_error_rate_without_dose`; it + was `pknca_error_dose_invalid_duration` with one row and an error without a + class with more. A direct `setDuration(object, rate = 5, dose = NA)` + returned a duration of 0 and is now that error too. * Preferred units (`concu_pref`, `doseu_pref`, and the others) with unit columns whose units differ between groups no longer stop `PKNCAdata()` with diff --git a/R/class-PKNCAdose.R b/R/class-PKNCAdose.R index 2acd6896a..35913828a 100644 --- a/R/class-PKNCAdose.R +++ b/R/class-PKNCAdose.R @@ -234,7 +234,9 @@ setRoute.PKNCAdose <- function(object, route, ...) { #' @param duration The value to set for the duration or the name of the column #' in the data to use for the duration. #' @param rate (for PKNCAdose objects only) The rate of infusion -#' @param dose (for PKNCAdose objects only) The dose amount +#' @param dose (for PKNCAdose objects only) The name of the dose column (the +#' default, from the formula), or the dose amounts (a value, or one per +#' row); used with `rate` #' @param ... Arguments passed to another setDuration function #' @returns The object with duration set #' @export diff --git a/man/setDuration.Rd b/man/setDuration.Rd index bfab66b1a..3971fab6a 100644 --- a/man/setDuration.Rd +++ b/man/setDuration.Rd @@ -22,7 +22,9 @@ in the data to use for the duration.} \item{rate}{(for PKNCAdose objects only) The rate of infusion} -\item{dose}{(for PKNCAdose objects only) The dose amount} +\item{dose}{(for PKNCAdose objects only) The name of the dose column (the +default, from the formula), or the dose amounts (a value, or one per +row); used with \code{rate}} } \value{ The object with duration set diff --git a/tests/testthat/test-class-PKNCAdose.R b/tests/testthat/test-class-PKNCAdose.R index 4a9b1b0ec..7fa4d929e 100644 --- a/tests/testthat/test-class-PKNCAdose.R +++ b/tests/testthat/test-class-PKNCAdose.R @@ -696,3 +696,16 @@ test_that("a rate column gives each dose its own duration, with any number of ro ) } }) + +# The durations of the doses of a PKNCAdose object +dose_test_duration <- function(object) { + as.data.frame(object)[[object$columns$duration]] +} + +test_that("setDuration() with a rate takes the dose column by default, or the dose amounts", { + o_dose <- PKNCAdose(data.frame(id = 1:2, time = 0, dose = c(10, 20)), dose ~ time | id, route = "intravascular") + expect_equal(dose_test_duration(setDuration(o_dose, rate = 5)), c(2, 4)) + expect_equal(dose_test_duration(setDuration(o_dose, rate = 5, dose = c(20, 40))), c(4, 8)) + # A missing dose amount gives no duration + expect_error(setDuration(o_dose, rate = 5, dose = NA), class = "pknca_error_rate_without_dose") +}) From 37ad50f3d0bf3c12b6ca0595babbbc68df01053b Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Mon, 16 Nov 2026 06:51:47 -0500 Subject: [PATCH 07/21] docs: a missing sample before the first increase can move the lag time The lag is found among the measured samples only, so a missing sample between the last zero and the first increase moves it to the time of the last measured zero; the documentation says so and a test pins pk.calc.tlag(c(0, NA, 5, 8), c(0, 1, 2, 4)) at 0. Co-Authored-By: Claude Opus 5.5 --- R/pk.calc.simple.R | 5 ++++- man/pk.calc.tlag.Rd | 5 ++++- tests/testthat/test-pk.calc.simple.R | 3 +++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/R/pk.calc.simple.R b/R/pk.calc.simple.R index 4fa035ebf..335c54092 100644 --- a/R/pk.calc.simple.R +++ b/R/pk.calc.simple.R @@ -2320,7 +2320,10 @@ add.interval.col("ptr", #' Missing concentrations are skipped, as in [pk.calc.cmax()] and the other #' simple parameters: the increase is looked for among the measured #' concentrations. `NA` is returned when no measured concentration increases -#' (including when every concentration is missing). +#' (including when every concentration is missing). Because the lag is found +#' among the measured samples only, a missing sample between the last zero and +#' the first increase can move it: `pk.calc.tlag(c(0, NA, 5, 8), c(0, 1, 2, 4))` +#' is 0, the time of the last measured zero. #' #' @inheritParams assert_conc_time #' @param check Run [assert_conc_time()]? diff --git a/man/pk.calc.tlag.Rd b/man/pk.calc.tlag.Rd index 136ec3f87..832aa4c0a 100644 --- a/man/pk.calc.tlag.Rd +++ b/man/pk.calc.tlag.Rd @@ -22,7 +22,10 @@ The time associated with the first increasing concentration Missing concentrations are skipped, as in \code{\link[=pk.calc.cmax]{pk.calc.cmax()}} and the other simple parameters: the increase is looked for among the measured concentrations. \code{NA} is returned when no measured concentration increases -(including when every concentration is missing). +(including when every concentration is missing). Because the lag is found +among the measured samples only, a missing sample between the last zero and +the first increase can move it: \code{pk.calc.tlag(c(0, NA, 5, 8), c(0, 1, 2, 4))} +is 0, the time of the last measured zero. } \seealso{ Other NCA time parameters: diff --git a/tests/testthat/test-pk.calc.simple.R b/tests/testthat/test-pk.calc.simple.R index e5843adde..ed378ed9a 100644 --- a/tests/testthat/test-pk.calc.simple.R +++ b/tests/testthat/test-pk.calc.simple.R @@ -524,6 +524,9 @@ test_that("pk.calc.tlag skips missing concentrations, as the other simple parame expect_equal(pk.calc.tlag(c(10, NA, 5, 8), 0:3), 2) # At the end expect_equal(pk.calc.tlag(c(0, 5, 10, NA), 0:3), 0) + # Between the last zero and the first increase: the lag is the time of the + # last measured zero + expect_equal(pk.calc.tlag(c(0, NA, 5, 8), c(0, 1, 2, 4)), 0) # Everywhere, with a warning from the check, and without it expect_warning( value_all_missing <- pk.calc.tlag(c(NA_real_, NA_real_, NA_real_), 0:2), From d9dce1cf339c1e043c0cbb450e5d18b185ed482a Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Mon, 16 Nov 2026 06:53:12 -0500 Subject: [PATCH 08/21] refactor: one helper for a collection whose amount is unknown urine_missing_messages() and urine_rate_result() both tested whether a collection has a volume but no concentration; urine_collection_amount_missing() is that test, used by both. No result changes. Co-Authored-By: Claude Opus 5.5 --- R/pk.calc.urine.R | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/R/pk.calc.urine.R b/R/pk.calc.urine.R index 0435531bb..0ecf7c3fc 100644 --- a/R/pk.calc.urine.R +++ b/R/pk.calc.urine.R @@ -497,13 +497,19 @@ generate_missing_messages <- function(a, b, stats::na.omit(c(msg_both, msg_a, msg_b)) } +# Whether a collection has a volume but no concentration, so that its amount +# is unknown +urine_collection_amount_missing <- function(conc, volume) { + any(is.na(conc) & !is.na(volume)) +} + # The missing-data messages of a collection's concentrations and volumes (see # generate_missing_messages()), with one more when a collection has a volume # but its concentration is missing: the amount in that collection is # unknown, and this reason says so urine_missing_messages <- function(conc, volume) { ret <- generate_missing_messages(conc, volume, name_a = "concentrations", name_b = "volumes") - if (any(is.na(conc) & !is.na(volume))) { + if (urine_collection_amount_missing(conc = conc, volume = volume)) { ret <- c(ret, "At least one concentration associated with a collection volume was missing") } ret @@ -514,7 +520,7 @@ urine_missing_messages <- function(conc, volume) { # concentration has an unknown amount, so the rate of the interval is unknown # too, as the amount excreted is urine_rate_result <- function(ret, conc, volume, message_all) { - if (any(is.na(conc) & !is.na(volume))) { + if (urine_collection_amount_missing(conc = conc, volume = volume)) { ret <- NA_real_ } if (length(message_all) != 0) { From fc0d560a530f66b9e122bb6e52a1533ce29ffeb8 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Mon, 16 Nov 2026 07:01:06 -0500 Subject: [PATCH 09/21] fix: pk.calc.swing() gives NA for a missing cmin pk.calc.swing() tested cmin > 0 in an if, so a missing cmin stopped with "missing value where TRUE/FALSE needed"; in pk.nca() an interval whose concentrations are all missing stopped with "Please report a bug" when swing was requested. A missing cmin now gives NA (Bill, 2026-11-16). Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 5 +++++ R/pk.calc.simple.R | 6 ++++-- man/pk.calc.deg.fluc.Rd | 2 +- tests/testthat/test-pk.calc.simple.R | 18 ++++++++++++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/NEWS.md b/NEWS.md index 18b6f8941..e22645ace 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1212,6 +1212,11 @@ the generated intervals: ## Bug fixes +* `pk.calc.swing()` gives `NA` for a missing `cmin` instead of stopping with + "missing value where TRUE/FALSE needed" (@billdenney; PR number to add). + In `pk.nca()`, an interval whose concentrations are all missing stopped with + "Please report a bug" when `swing` was requested, and now gives `NA`. + * Preferred units (`concu_pref`, `doseu_pref`, and the others) with unit columns whose units differ between groups no longer stop `PKNCAdata()` with "arguments imply differing number of rows: 1, 0" when some groups are diff --git a/R/pk.calc.simple.R b/R/pk.calc.simple.R index 0252dafe2..55f9aab30 100644 --- a/R/pk.calc.simple.R +++ b/R/pk.calc.simple.R @@ -2384,10 +2384,12 @@ add.interval.col("deg.fluc", #' @details swing is `100*(cmax - cmin)/cmin`. #' #' @returns The swing above the minimum concentration. If `cmin` is zero, then -#' the result is infinity. +#' the result is infinity; if `cmin` is missing, it is `NA`. #' @export pk.calc.swing <- function(cmax, cmin) { - if (cmin > 0) { + if (is.na(cmin)) { + NA_real_ + } else if (cmin > 0) { 100*(cmax - cmin)/cmin } else { Inf diff --git a/man/pk.calc.deg.fluc.Rd b/man/pk.calc.deg.fluc.Rd index f240be7ca..13480ab51 100644 --- a/man/pk.calc.deg.fluc.Rd +++ b/man/pk.calc.deg.fluc.Rd @@ -20,7 +20,7 @@ pk.calc.swing(cmax, cmin) The degree of fluctuation around the average concentration. The swing above the minimum concentration. If \code{cmin} is zero, then -the result is infinity. +the result is infinity; if \code{cmin} is missing, it is \code{NA}. } \description{ Determine the degree of fluctuation diff --git a/tests/testthat/test-pk.calc.simple.R b/tests/testthat/test-pk.calc.simple.R index 98bb93ce8..b138c49d1 100644 --- a/tests/testthat/test-pk.calc.simple.R +++ b/tests/testthat/test-pk.calc.simple.R @@ -523,6 +523,9 @@ test_that("pk.calc.deg.fluc", { }) test_that("pk.calc.swing", { + # A missing cmin (or cmax) gives NA, not an error + expect_equal(pk.calc.swing(10, NA), NA_real_) + expect_equal(pk.calc.swing(NA, 2), NA_real_) expect_equal(pk.calc.swing(100, 10), 900, info="Swing math works") expect_equal(pk.calc.swing(100, 0), Inf, @@ -676,3 +679,18 @@ test_that("count.conc and count.conc.measured count imputed concentrations by va # by both even though it was not measured at that time expect_equal(counts("start_cmin"), c(conc = 7, measured = 7)) }) + +test_that("swing in pk.nca() with every concentration missing is NA", { + # The data checks warn that every concentration is missing; the interval + # used to stop with "Please report a bug" + res <- + suppressWarnings( + as.data.frame(pk.nca(PKNCAdata( + PKNCAconc(data.frame(id = 1, time = c(0, 2, 4), conc = NA_real_), conc ~ time | id), + PKNCAdose(data.frame(id = 1, time = 0, dose = 1), dose ~ time | id), + intervals = data.frame(start = 0, end = 4, swing = TRUE) + ))), + classes = "pknca_warning_all_concentration_missing" + ) + expect_equal(res$PPORRES[res$PPTESTCD == "swing"], NA_real_) +}) From 408f0751c2dd677504debb28d5a536473353413d Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 08:59:33 -0500 Subject: [PATCH 10/21] docs: regenerate pk.calc.mrt.Rd to match the functions' arguments The usage on main showed pk.calc.mrt.iv() and pk.calc.mrt.md.iv() with `dose` and `time.dose` required, while both arguments default to NULL in R/. This is the page roxygen2 writes for the code on main; no function changes. Co-Authored-By: Claude Fable 5.2 --- man/pk.calc.mrt.Rd | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/man/pk.calc.mrt.Rd b/man/pk.calc.mrt.Rd index b347d8ecf..2c89f9f60 100644 --- a/man/pk.calc.mrt.Rd +++ b/man/pk.calc.mrt.Rd @@ -10,11 +10,19 @@ multiple-dose data.} \usage{ pk.calc.mrt(auc, aumc) -pk.calc.mrt.iv(auc, aumc, duration.dose, dose, time.dose) +pk.calc.mrt.iv(auc, aumc, duration.dose, dose = NULL, time.dose = NULL) pk.calc.mrt.md(auctau, aumctau, aucinf, tau) -pk.calc.mrt.md.iv(auctau, aumctau, aucinf, tau, duration.dose, dose, time.dose) +pk.calc.mrt.md.iv( + auctau, + aumctau, + aucinf, + tau, + duration.dose, + dose = NULL, + time.dose = NULL +) } \arguments{ \item{auc}{the AUC from 0 to infinity or 0 to tau} From 09cacde525d25615dcaf20ba25cc7764d0f7c43c Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 08:59:34 -0500 Subject: [PATCH 11/21] fix: pk.calc.swing() gives NA for a missing cmax too, with the issue's cases as tests A missing cmax with a zero or negative cmin gave Inf; either input missing now gives NA_real_. The tests pin the three cases of GitHub issue 723 (reported by kawasakin) through pk.nca() at conc.na "drop" and 0: the profile with missing concentrations gets NA for tlag or swing, and the other subject's result is calculated. Co-Authored-By: Claude Fable 5.2 --- R/pk.calc.simple.R | 4 +- man/pk.calc.deg.fluc.Rd | 2 +- tests/testthat/test-pk.calc.simple.R | 69 ++++++++++++++++++++++++++-- 3 files changed, 67 insertions(+), 8 deletions(-) diff --git a/R/pk.calc.simple.R b/R/pk.calc.simple.R index b8f5c5c45..bd6be10c4 100644 --- a/R/pk.calc.simple.R +++ b/R/pk.calc.simple.R @@ -2465,10 +2465,10 @@ add.interval.col("deg.fluc", #' @details swing is `100*(cmax - cmin)/cmin`. #' #' @returns The swing above the minimum concentration. If `cmin` is zero, then -#' the result is infinity; if `cmin` is missing, it is `NA`. +#' the result is infinity; if `cmin` or `cmax` is missing, it is `NA`. #' @export pk.calc.swing <- function(cmax, cmin) { - if (is.na(cmin)) { + if (is.na(cmin) || is.na(cmax)) { NA_real_ } else if (cmin > 0) { 100*(cmax - cmin)/cmin diff --git a/man/pk.calc.deg.fluc.Rd b/man/pk.calc.deg.fluc.Rd index 13480ab51..cf6580408 100644 --- a/man/pk.calc.deg.fluc.Rd +++ b/man/pk.calc.deg.fluc.Rd @@ -20,7 +20,7 @@ pk.calc.swing(cmax, cmin) The degree of fluctuation around the average concentration. The swing above the minimum concentration. If \code{cmin} is zero, then -the result is infinity; if \code{cmin} is missing, it is \code{NA}. +the result is infinity; if \code{cmin} or \code{cmax} is missing, it is \code{NA}. } \description{ Determine the degree of fluctuation diff --git a/tests/testthat/test-pk.calc.simple.R b/tests/testthat/test-pk.calc.simple.R index 6d58a4a60..a3294b234 100644 --- a/tests/testthat/test-pk.calc.simple.R +++ b/tests/testthat/test-pk.calc.simple.R @@ -764,9 +764,13 @@ test_that("pk.calc.deg.fluc", { }) test_that("pk.calc.swing", { - # A missing cmin (or cmax) gives NA, not an error - expect_equal(pk.calc.swing(10, NA), NA_real_) - expect_equal(pk.calc.swing(NA, 2), NA_real_) + # A missing cmin or cmax gives NA_real_, not an error, and not the infinity + # of a zero cmin + expect_identical(pk.calc.swing(10, NA), NA_real_) + expect_identical(pk.calc.swing(NA, 2), NA_real_) + expect_identical(pk.calc.swing(NA, 0), NA_real_) + expect_identical(pk.calc.swing(NA, NA), NA_real_) + expect_identical(pk.calc.swing(10, NA_integer_), NA_real_) expect_equal(pk.calc.swing(100, 10), 900, info="Swing math works") expect_equal(pk.calc.swing(100, 0), Inf, @@ -922,8 +926,7 @@ test_that("count.conc and count.conc.measured count imputed concentrations by va }) test_that("swing in pk.nca() with every concentration missing is NA", { - # The data checks warn that every concentration is missing; the interval - # used to stop with "Please report a bug" + # The data checks warn that every concentration is missing res <- suppressWarnings( as.data.frame(pk.nca(PKNCAdata( @@ -935,3 +938,59 @@ test_that("swing in pk.nca() with every concentration missing is NA", { ) expect_equal(res$PPORRES[res$PPTESTCD == "swing"], NA_real_) }) + +# The tlag or swing results of pk.nca() for concentration data with the columns +# id, time, and conc, on one interval from 0 to `end`, in the order of id +tlag_swing_results <- function(d_conc, parameter, conc.na, end) { + d_interval <- data.frame(start = 0, end = end) + d_interval[[parameter]] <- TRUE + o_data <- + PKNCAdata( + PKNCAconc(d_conc, conc ~ time | id), + intervals = d_interval, + options = list(conc.na = conc.na) + ) + res <- + suppressWarnings( + as.data.frame(pk.nca(o_data)), + classes = "pknca_warning_all_concentration_missing" + ) + res <- res[res$PPTESTCD == parameter, ] + res$PPORRES[order(res$id)] +} + +test_that("a profile with missing concentrations does not stop tlag or swing for the other profiles (#723)", { + # The profile with missing concentrations gets NA, and the other subject's + # result is calculated, at any conc.na. + + # tlag: a falling profile, with one sample missing for the second subject + d_falling <- + data.frame( + id = rep(1:2, each = 5), + time = rep(c(0.25, 1, 2, 4, 8), 2), + conc = c(10, 8, 6, 4, 2, 10, 8, NA, 4, 2) + ) + expect_identical(tlag_swing_results(d_falling, "tlag", conc.na = "drop", end = Inf), c(NA_real_, NA_real_)) + expect_identical(tlag_swing_results(d_falling, "tlag", conc.na = 0, end = Inf), c(NA_real_, NA_real_)) + expect_identical(pk.calc.tlag(conc = c(10, 8, NA, 4, 2), time = c(0.25, 1, 2, 4, 8)), NA_real_) + + # tlag: no measurable concentration and one missing sample for the second + # subject + d_none_measurable <- + data.frame( + id = rep(1:2, each = 4), + time = rep(c(0, 1, 2, 4), 2), + conc = c(0, 5, 3, 1, 0, 0, NA, 0) + ) + expect_identical(tlag_swing_results(d_none_measurable, "tlag", conc.na = "drop", end = Inf), c(0, NA_real_)) + + # swing: every sample of the second subject's interval is missing + d_all_missing <- + data.frame( + id = rep(1:2, each = 4), + time = rep(c(0, 1, 2, 4), 2), + conc = c(1, 5, 3, 1, NA, NA, NA, NA) + ) + expect_identical(tlag_swing_results(d_all_missing, "swing", conc.na = "drop", end = 4), c(400, NA_real_)) + expect_identical(tlag_swing_results(d_all_missing, "swing", conc.na = 0, end = 4), c(400, NA_real_)) +}) From cf77608e3d95e5f3ac46fb641d4d1488f57a1688 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 10:35:47 -0500 Subject: [PATCH 12/21] docs: NEWS links the urine-rate entry to its pull request Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 31e7f51f5..783c7a49a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -10,7 +10,7 @@ the dosing including dose amount and route. * The excretion rates `ertlst`, `ermax`, `ertmax`, and `erlst` are now `NA` when a collection with a volume has no concentration, as `ae`, `fe`, and - `erint` already were (@billdenney; PR number to add). They were calculated + `erint` already were (@billdenney, #729). They were calculated from the other collections, with the reason "1 of 4 concentrations are missing"; the amount in that collection is unknown, so the rate of the interval is too. The reason is unchanged, with "At least one concentration From 564e19341c24bb0913c43225e0ce293a2467f5fa Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 10:35:51 -0500 Subject: [PATCH 13/21] docs: NEWS links the dose-rate entry to its pull request Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 0c0d10990..acaa3adea 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1221,7 +1221,7 @@ the generated intervals: ## Bug fixes * `PKNCAdose()` with a `rate` column now works with more than one dose row - (@billdenney; PR number to add). It stopped with "'length = 2' in coercion + (@billdenney, #728). It stopped with "'length = 2' in coercion to 'logical(1)'", because the dose amounts were passed where the name of the dose column was expected; one row worked by accident. Each dose's duration is its amount divided by its rate. A `rate` with no dose amount (a formula From efa14ca46e3725ac959fb4e5db756832ea487762 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 15:39:36 -0500 Subject: [PATCH 14/21] fix: a reason given by more than one input of a parameter is listed once in its exclude text combine_exclude_reasons() splits each input's text on "; " before joining, so a reason that reaches a parameter twice (cmax and cmin of an all-missing interval, both feeding swing) is listed once. Values are unchanged. Co-Authored-By: Claude Opus 5.5 --- R/pk.calc.all.R | 9 ++++++--- tests/testthat/test-secondary-parameters.R | 3 +++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/R/pk.calc.all.R b/R/pk.calc.all.R index 40e6b63ef..cd6906b10 100644 --- a/R/pk.calc.all.R +++ b/R/pk.calc.all.R @@ -947,10 +947,13 @@ bind_interval_result <- function(interval_cols, calculated) { # Combine exclusion reasons from a calculation's inputs with the exclusion the # calculation itself set (the "exclude" attribute). "DO NOT EXCLUDE" on the -# result wins and clears everything. Documented in -# vignettes/v80-writing-parameter-functions.Rmd. +# result wins and clears everything. Each input's exclusion may already be +# several reasons joined with "; ", so they are split before a reason given by +# more than one input (cmax and cmin of an all-missing profile) is listed once. +# Documented in vignettes/v80-writing-parameter-functions.Rmd. combine_exclude_reasons <- function(from_inputs, from_result) { - reasons <- stats::na.omit(c(from_inputs, from_result)) + reasons <- stats::na.omit(as.character(c(from_inputs, from_result))) + reasons <- unique(unlist(strsplit(reasons, split = "; ", fixed = TRUE))) if (identical(from_result, "DO NOT EXCLUDE")) { NA_character_ } else if (length(reasons) > 0) { diff --git a/tests/testthat/test-secondary-parameters.R b/tests/testthat/test-secondary-parameters.R index bc0965e27..23c4db624 100644 --- a/tests/testthat/test-secondary-parameters.R +++ b/tests/testthat/test-secondary-parameters.R @@ -1966,6 +1966,9 @@ test_that("combine_exclude_reasons() combines and clears exclusion reasons", { expect_equal(combine_exclude_reasons(c("a", NA, "b"), NULL), "a; b") expect_equal(combine_exclude_reasons(c("a", "b"), "DO NOT EXCLUDE"), NA_character_) expect_equal(combine_exclude_reasons(NULL, "DO NOT EXCLUDE"), NA_character_) + # A reason is listed once, also when it is one of several already joined + expect_equal(combine_exclude_reasons(c("a", "a"), "a"), "a") + expect_equal(combine_exclude_reasons(c("a; b", "b; c"), "a"), "a; b; c") }) # The automatic reference finder, group_ref, and ephemeral references --------- From 25b527c664f001becbd17133b54fe0ccda7a8eaa Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 15:39:39 -0500 Subject: [PATCH 15/21] feat: a simple parameter that is NA because of missing or unusable data says why The simple calculation functions (pk.calc.simple.R and pk.calc.dn()) return their NA with an exclude attribute naming the reason, which pk.nca() puts in the exclude column and carries into everything calculated from it. No value changes. Tests pin the reasons per function, through pk.nca() per condition, and iterate every registered parameter calculated by a simple function on all-missing, all-zero, missing-end, and missing-dose profiles so that a new NA without a reason fails. Co-Authored-By: Claude Opus 5.5 --- R/pk.calc.simple.R | 172 +++++++------ R/zzz-pk.calc.dn.R | 6 +- man/pk.calc.ceoi.Rd | 3 +- man/pk.calc.cmax.Rd | 2 +- man/pk.calc.ctrough.Rd | 4 +- man/pk.calc.dn.Rd | 3 +- man/pk.calc.ptr.Rd | 3 +- man/pk.calc.tlag.Rd | 4 +- man/pk.calc.tlast.Rd | 4 +- man/pk.calc.tmax.Rd | 3 +- man/pk.calc.tmin.Rd | 3 +- man/pk.calc.totdose.Rd | 3 +- tests/testthat/test-class-PKNCAresults.R | 27 +- tests/testthat/test-pk.calc.all.R | 3 +- tests/testthat/test-pk.calc.dn.R | 2 +- tests/testthat/test-pk.calc.simple.R | 242 ++++++++++++++---- vignettes/v80-writing-parameter-functions.Rmd | 2 +- 17 files changed, 338 insertions(+), 148 deletions(-) diff --git a/R/pk.calc.simple.R b/R/pk.calc.simple.R index bd6be10c4..0ae0a853a 100644 --- a/R/pk.calc.simple.R +++ b/R/pk.calc.simple.R @@ -16,12 +16,23 @@ adj.r.squared <- function(r.sq, n) { } } +# Set the values of `ret` selected by `mask` to `NA` and add `reason` to its +# "exclude" attribute, which pk.nca() puts in the exclude column (see +# combine_exclude_reasons()). `ret` is unchanged when `mask` selects nothing. +na_with_reason <- function(ret, mask, reason) { + if (any(mask)) { + ret[mask] <- NA_real_ + attr(ret, "exclude") <- paste(c(attr(ret, "exclude"), reason), collapse = "; ") + } + ret +} + #' Determine maximum observed PK concentration #' #' @inheritParams assert_conc_time #' @param check Run [assert_conc()]? #' @return a number for the maximum concentration or NA if all concentrations -#' are missing +#' are missing, with the reason in its "exclude" attribute #' @family NCA parameters for concentrations during the intervals #' @export pk.calc.cmax <- function(conc, check=TRUE) { @@ -29,7 +40,7 @@ pk.calc.cmax <- function(conc, check=TRUE) { assert_conc(conc = conc) } if (length(conc) == 0 || all(is.na(conc))) { - NA + structure(NA, exclude = "All concentrations are missing") } else { max(conc, na.rm=TRUE) } @@ -61,7 +72,7 @@ pk.calc.cmin <- function(conc, check=TRUE) { assert_conc(conc=conc) } if (length(conc) == 0 || all(is.na(conc))) { - NA + structure(NA, exclude = "All concentrations are missing") } else { min(conc, na.rm=TRUE) } @@ -99,7 +110,8 @@ add.interval.col("cmin", #' @param first.tmax If there is more than one time point with the maximum value (Cmax or ERmax), #' which time should be selected for Tmax/ERTmax? If 'TRUE', the first will be selected. If not, then the #' last is considered Tmax/ERTmax. -#' @returns The time of the maximum concentration +#' @returns The time of the maximum concentration, or `NA` with the reason in +#' its "exclude" attribute when no concentration is above zero #' @family NCA time parameters #' @examples #' conc_data <- Theoph[Theoph$Subject == 1,] @@ -113,8 +125,10 @@ pk.calc.tmax <- function(conc, time, if (check) { assert_conc_time(conc = conc, time = time) } - if (length(conc) == 0 || all(conc %in% c(NA, 0))) { - NA + if (length(conc) == 0 || all(is.na(conc))) { + structure(NA, exclude = "All concentrations are missing") + } else if (all(conc %in% c(NA, 0))) { + structure(NA, exclude = "No concentration is above zero") } else { ret <- time[conc %in% pk.calc.cmax(conc, check=FALSE)] if (first.tmax) { @@ -158,7 +172,8 @@ add.interval.col("tmax", #' @param first.tmin If there is more than one time point with the minimum value (Cmin), #' which time should be selected for Tmin? If 'TRUE', the first will be selected. If not, #' then the last is considered Tmin. -#' @returns The time of the minimum concentration +#' @returns The time of the minimum concentration, or `NA` with the reason in +#' its "exclude" attribute when all concentrations are missing #' @family NCA time parameters #' @examples #' conc_data <- Theoph[Theoph$Subject == 1,] @@ -173,7 +188,7 @@ pk.calc.tmin <- function(conc, time, assert_conc_time(conc = conc, time = time) } if (length(conc) == 0 || all(is.na(conc))) { - NA + structure(NA, exclude = "All concentrations are missing") } else { ret <- time[conc %in% pk.calc.cmin(conc, check=FALSE)] if (first.tmin) { @@ -204,15 +219,19 @@ add.interval.col("tmin", #' #' @inheritParams assert_conc_time #' @inheritParams clean.conc.blq -#' @returns The time of the last observed concentration measurement +#' @returns The time of the last observed concentration measurement, or `NA` +#' with the reason in its "exclude" attribute when no concentration is above +#' zero #' @family NCA time parameters #' @export pk.calc.tlast <- function(conc, time, check=TRUE) { if (check) { assert_conc_time(conc = conc, time = time) } - if (all(conc %in% c(NA, 0))) { - NA + if (all(is.na(conc))) { + structure(NA, exclude = "All concentrations are missing") + } else if (all(conc %in% c(NA, 0))) { + structure(NA, exclude = "No concentration is above zero") } else { max(time[!(conc %in% c(NA, 0))]) } @@ -238,8 +257,10 @@ pk.calc.tfirst <- function(conc, time, check=TRUE) { if (check) { assert_conc_time(conc, time) } - if (all(conc %in% c(NA, 0))) { - NA + if (all(is.na(conc))) { + structure(NA, exclude = "All concentrations are missing") + } else if (all(conc %in% c(NA, 0))) { + structure(NA, exclude = "No concentration is above zero") } else { min(time[!(conc %in% c(NA, 0))]) } @@ -276,7 +297,7 @@ pk.calc.clast.obs <- function(conc, time, check=TRUE) { assert_conc_time(conc = conc, time = time) } if (all(is.na(conc))) { - NA_real_ + structure(NA_real_, exclude = "All concentrations are missing") } else if (all(conc %in% c(0, NA))) { 0 } else { @@ -557,7 +578,7 @@ pk.calc.aucpext <- function(auclast, aucinf) { ) ret[mask_calc] <- 100*(1-auclast[mask_calc]/aucinf[mask_calc]) - ret + na_with_reason(ret, mask = !mask_na & aucinf %in% 0, reason = "AUCinf is zero") } pknca_concept(pk.calc.aucpext) <- "auc_extrapolation" @@ -823,17 +844,14 @@ add.interval.col("kel.sparse.last", pk.calc.cl <- function(dose, auc) { # sum() of nothing is 0, which would be a wrong answer, not a missing one if (length(dose) == 0) { - return(NA_real_) + return(structure(NA_real_, exclude = "No dose in the interval")) } if (length(auc) == 1) { dose <- sum(dose) } ret <- dose/auc - mask_zero <- !is.na(auc) & (auc <= 0) - if (any(mask_zero)) { - ret[mask_zero] <- NA_real_ - } - ret + ret <- na_with_reason(ret, mask = !is.na(auc) & is.na(dose), reason = "Dose is missing") + na_with_reason(ret, mask = !is.na(auc) & (auc <= 0), reason = "AUC is zero or negative") } pknca_concept(pk.calc.cl) <- "clearance" @@ -1064,14 +1082,11 @@ add.interval.col("cl.sparse.last", #' @export pk.calc.f <- function(dose1, auc1, dose2, auc2) { ret <- (auc2/dose2)/(auc1/dose1) - mask_zero <- - is.na(auc1) | (auc1 <= 0) | - is.na(dose2) | (dose2 <= 0) | - is.na(dose1) | (dose1 <= 0) - if (any(mask_zero)) { - ret[mask_zero] <- NA_real_ - } - ret + # A missing AUC carries its own reason from its calculation + ret[is.na(auc1)] <- NA_real_ + ret <- na_with_reason(ret, mask = is.na(dose1) | is.na(dose2), reason = "Dose is missing") + ret <- na_with_reason(ret, mask = (!is.na(dose1) & dose1 <= 0) | (!is.na(dose2) & dose2 <= 0), reason = "Dose is zero or negative") + na_with_reason(ret, mask = !is.na(auc1) & auc1 <= 0, reason = "AUC is zero or negative") } pknca_concept(pk.calc.f) <- "bioavailability" @@ -1354,11 +1369,11 @@ add.interval.col("mrt.sparse.last", #' @export pk.calc.mrt.iv <- function(auc, aumc, duration.dose, dose = NULL, time.dose = NULL) { mit <- pk_mean_input_time(dose, time.dose, duration.dose) - ret <- aumc/auc - mit - mask_zero <- is.na(auc) | auc <= 0 - if (any(mask_zero)) { - ret[mask_zero] <- NA_real_ - } + ret <- aumc/auc - as.numeric(mit) + # A missing AUC carries its own reason from its calculation + ret[is.na(auc)] <- NA_real_ + ret <- na_with_reason(ret, mask = !is.na(auc) & is.na(mit), reason = attr(mit, "exclude")) + ret <- na_with_reason(ret, mask = !is.na(auc) & auc <= 0, reason = "AUC is zero or negative") if (length(ret) != 1) { rlang::abort("MRT must be a single value per interval (auc and aumc must each be one value)", class = "pknca_error_mrt_not_scalar") } @@ -1380,12 +1395,13 @@ pk.calc.mrt.iv <- function(auc, aumc, duration.dose, dose = NULL, time.dose = NU # dose(s) are at the interval start. # @param duration.dose The dose durations # @returns A scalar mean input time, `NA_real_` when it cannot be determined +# (with the reason in its "exclude" attribute) # @noRd pk_mean_input_time <- function(dose = NULL, time.dose = NULL, duration.dose) { checkmate::assert_numeric(duration.dose, lower = 0, finite = TRUE) n_dose <- length(duration.dose) if (n_dose == 0) { - return(NA_real_) + return(structure(NA_real_, exclude = "No dose in the interval")) } if (is.null(time.dose)) { time.dose <- rep(0, n_dose) @@ -1395,13 +1411,15 @@ pk_mean_input_time <- function(dose = NULL, time.dose = NULL, duration.dose) { checkmate::assert_numeric(dose, len = n_dose, lower = 0, finite = TRUE, null.ok = n_dose == 1) midpoint <- time.dose + duration.dose/2 + if (anyNA(midpoint)) { + return(structure(NA_real_, exclude = "A dose time or duration is missing")) + } if (n_dose == 1) { # The weight does not matter for a single dose return(as.numeric(midpoint)) } - if (anyNA(dose) || anyNA(midpoint) || sum(dose) <= 0) { - # The weights or the input times are unknown - return(NA_real_) + if (anyNA(dose) || sum(dose) <= 0) { + return(structure(NA_real_, exclude = "A dose amount is missing, or the doses sum to zero")) } as.numeric(sum(dose*midpoint)/sum(dose)) } @@ -1578,11 +1596,12 @@ add.interval.col("mrt.md.inf.pred", #' @export pk.calc.mrt.md.iv <- function(auctau, aumctau, aucinf, tau, duration.dose, dose = NULL, time.dose = NULL) { mit <- pk_mean_input_time(dose, time.dose, duration.dose) - ret <- aumctau/auctau + tau*(aucinf-auctau)/auctau - mit - mask_zero <- is.na(auctau) | auctau <= 0 - if (any(mask_zero)) { - ret[mask_zero] <- NA_real_ - } + ret <- aumctau/auctau + tau*(aucinf-auctau)/auctau - as.numeric(mit) + # A missing AUC carries its own reason from its calculation + ret[is.na(auctau)] <- NA_real_ + ret <- na_with_reason(ret, mask = !is.na(auctau) & is.na(tau), reason = "The dosing interval (tau) is not known") + ret <- na_with_reason(ret, mask = !is.na(auctau) & is.na(mit), reason = attr(mit, "exclude")) + ret <- na_with_reason(ret, mask = !is.na(auctau) & auctau <= 0, reason = "AUC is zero or negative") if (length(ret) != 1) { rlang::abort("MRT must be a single value per interval (auctau, aumctau, and aucinf must each be one value)", class = "pknca_error_mrt.md_not_scalar") } @@ -2115,11 +2134,8 @@ add.interval.col("vss.sparse.last", #' @export pk.calc.cav <- function(auc, start, end) { ret <- auc/(end-start) - mask_zero <- is.na(end) | is.na(start) | end == start - if (any(mask_zero)) { - ret[mask_zero] <- NA_real_ - } - ret + ret <- na_with_reason(ret, mask = is.na(end) | is.na(start), reason = "The interval start or end is missing") + na_with_reason(ret, mask = !is.na(end) & !is.na(start) & end == start, reason = "The interval has zero duration") } pknca_concept(pk.calc.cav) <- "average_conc" @@ -2287,16 +2303,21 @@ add.interval.col( #' #' @inheritParams assert_conc_time #' @inheritParams assert_intervaltime_single -#' @returns The concentration when `time == end`. If none match, then `NA` +#' @returns The concentration when `time == end`. If none match, or that +#' concentration is missing, then `NA` with the reason in its "exclude" +#' attribute #' @family NCA parameters for concentrations during the intervals #' @export pk.calc.ctrough <- function(conc, time, end) { assert_conc_time(conc = conc, time = time) mask_end <- time %in% end - if (sum(mask_end) == 1) { + if (sum(mask_end) == 1 && !is.na(conc[mask_end])) { conc[mask_end] - } else if (sum(mask_end) == 0) { - NA_real_ + } else if (sum(mask_end) <= 1) { + structure( + if (sum(mask_end) == 1) conc[mask_end] else NA_real_, + exclude = "No non-missing concentration at the end of the interval" + ) } else { # This should be impossible as assert_conc_time should catch # duplicates. @@ -2327,10 +2348,13 @@ add.interval.col("ctrough", pk.calc.cstart <- function(conc, time, start) { assert_conc_time(conc = conc, time = time) mask_start <- time %in% start - if (sum(mask_start) == 1) { + if (sum(mask_start) == 1 && !is.na(conc[mask_start])) { conc[mask_start] - } else if (sum(mask_start) == 0) { - NA_real_ + } else if (sum(mask_start) <= 1) { + structure( + if (sum(mask_start) == 1) conc[mask_start] else NA_real_, + exclude = "No non-missing concentration at the start of the interval" + ) } else { # This should be impossible as assert_conc_time should catch # duplicates. @@ -2358,13 +2382,13 @@ add.interval.col("cstart", #' #' @param cmax The maximum observed concentration #' @param ctrough The last concentration in an interval -#' @return The ratio of cmax to ctrough (if ctrough == 0, NA) +#' @return The ratio of cmax to ctrough (if ctrough == 0, NA with the reason in +#' its "exclude" attribute) #' @family Multiple-dose PK parameters #' @export pk.calc.ptr <- function(cmax, ctrough) { ret <- cmax/ctrough - ret[ctrough %in% 0] <- NA_real_ - ret + na_with_reason(ret, mask = ctrough %in% 0, reason = "Ctrough is zero") } pknca_concept(pk.calc.ptr) <- "fluctuation" @@ -2394,7 +2418,9 @@ add.interval.col("ptr", #' #' @inheritParams assert_conc_time #' @param check Run [assert_conc_time()]? -#' @returns The time associated with the first increasing concentration +#' @returns The time associated with the first increasing concentration, or +#' `NA` with the reason in its "exclude" attribute when concentrations never +#' increase #' @family NCA time parameters #' @export pk.calc.tlag <- function(conc, time, check = TRUE) { @@ -2407,8 +2433,10 @@ pk.calc.tlag <- function(conc, time, check = TRUE) { mask.increase <- c(conc[-1] > conc[-length(conc)], FALSE) if (any(mask.increase)) { time[mask.increase][1] + } else if (length(conc) == 0) { + structure(NA_real_, exclude = "All concentrations are missing") } else { - NA_real_ + structure(NA_real_, exclude = "Concentrations never increase") } } @@ -2439,11 +2467,9 @@ add.interval.col("tlag", #' @export pk.calc.deg.fluc <- function(cmax, cmin, cav) { ret <- 100*(cmax - cmin)/cav - mask_zero <- is.na(cav) | cav == 0 - if (any(mask_zero)) { - ret[mask_zero] <- NA_real_ - } - ret + # A missing cav carries its own reason from its calculation + ret[is.na(cav)] <- NA_real_ + na_with_reason(ret, mask = cav %in% 0, reason = "Cav is zero") } pknca_concept(pk.calc.deg.fluc) <- "fluctuation" @@ -2497,7 +2523,8 @@ add.interval.col("swing", #' @param duration.dose The duration for the dosing administration (typically #' from IV infusion) #' @returns The concentration at the end of the infusion, `NA` if -#' `duration.dose` is `NA`, or `NA` if all `time != duration.dose` +#' `duration.dose` is `NA`, or `NA` if all `time != duration.dose` or that +#' concentration is missing; an `NA` has the reason in its "exclude" attribute #' @family NCA parameters for concentrations during the intervals #' @export pk.calc.ceoi <- function(conc, time, duration.dose=NA, check=TRUE) { @@ -2505,9 +2532,9 @@ pk.calc.ceoi <- function(conc, time, duration.dose=NA, check=TRUE) { assert_conc_time(conc = conc, time = time) } if (is.na(duration.dose)) { - NA_real_ - } else if (all(time != duration.dose)) { - NA_real_ + structure(NA_real_, exclude = "Dose duration is missing") + } else if (all(time != duration.dose) || is.na(conc[time == duration.dose][1])) { + structure(NA_real_, exclude = "No non-missing concentration at the end of the infusion") } else { conc[time == duration.dose][1] } @@ -2663,13 +2690,14 @@ add.interval.col( #' Extract the dose used for calculations #' #' @inheritParams pk.calc.cl -#' @returns The total dose for an interval +#' @returns The total dose for an interval, or `NA` with the reason in its +#' "exclude" attribute when there is no dose or a dose is missing #' @export pk.calc.totdose <- function(dose) { if (length(dose) == 0) { - return(NA_real_) + return(structure(NA_real_, exclude = "No dose in the interval")) } - sum(dose) + na_with_reason(sum(dose), mask = anyNA(dose), reason = "Dose is missing") } pknca_concept(pk.calc.totdose) <- "total_dose" diff --git a/R/zzz-pk.calc.dn.R b/R/zzz-pk.calc.dn.R index 1dcc62b76..28ebb7055 100644 --- a/R/zzz-pk.calc.dn.R +++ b/R/zzz-pk.calc.dn.R @@ -2,12 +2,14 @@ #' #' @param parameter Parameter to dose normalize #' @param dose Dose in units compatible with the area under the curve -#' @returns a number for dose normalized AUC +#' @returns a number for dose normalized AUC, or `NA` with the reason in its +#' "exclude" attribute when the dose is missing #' @examples #' pk.calc.dn(90, 10) #' @export pk.calc.dn <- function(parameter, dose) { - parameter/dose + # A missing parameter carries its own reason from its calculation + na_with_reason(parameter/dose, mask = !is.na(parameter) & is.na(dose), reason = "Dose is missing") } local({ diff --git a/man/pk.calc.ceoi.Rd b/man/pk.calc.ceoi.Rd index 80c0a2241..dc6e831d2 100644 --- a/man/pk.calc.ceoi.Rd +++ b/man/pk.calc.ceoi.Rd @@ -18,7 +18,8 @@ from IV infusion)} } \value{ The concentration at the end of the infusion, \code{NA} if -\code{duration.dose} is \code{NA}, or \code{NA} if all \code{time != duration.dose} +\code{duration.dose} is \code{NA}, or \code{NA} if all \code{time != duration.dose} or that +concentration is missing; an \code{NA} has the reason in its "exclude" attribute } \description{ Determine the concentration at the end of infusion diff --git a/man/pk.calc.cmax.Rd b/man/pk.calc.cmax.Rd index b23da96c8..53e4823a9 100644 --- a/man/pk.calc.cmax.Rd +++ b/man/pk.calc.cmax.Rd @@ -16,7 +16,7 @@ pk.calc.cmin(conc, check = TRUE) } \value{ a number for the maximum concentration or NA if all concentrations -are missing +are missing, with the reason in its "exclude" attribute } \description{ Determine maximum observed PK concentration diff --git a/man/pk.calc.ctrough.Rd b/man/pk.calc.ctrough.Rd index 4e910d6f7..954ee505f 100644 --- a/man/pk.calc.ctrough.Rd +++ b/man/pk.calc.ctrough.Rd @@ -19,7 +19,9 @@ pk.calc.cstart(conc, time, start) \item{start}{The start time of the interval} } \value{ -The concentration when \code{time == end}. If none match, then \code{NA} +The concentration when \code{time == end}. If none match, or that +concentration is missing, then \code{NA} with the reason in its "exclude" +attribute } \description{ Determine the trough (end of interval) concentration diff --git a/man/pk.calc.dn.Rd b/man/pk.calc.dn.Rd index a991a2866..01a61631e 100644 --- a/man/pk.calc.dn.Rd +++ b/man/pk.calc.dn.Rd @@ -12,7 +12,8 @@ pk.calc.dn(parameter, dose) \item{dose}{Dose in units compatible with the area under the curve} } \value{ -a number for dose normalized AUC +a number for dose normalized AUC, or \code{NA} with the reason in its +"exclude" attribute when the dose is missing } \description{ Determine dose normalized NCA parameter diff --git a/man/pk.calc.ptr.Rd b/man/pk.calc.ptr.Rd index 7fa4906b5..401736613 100644 --- a/man/pk.calc.ptr.Rd +++ b/man/pk.calc.ptr.Rd @@ -12,7 +12,8 @@ pk.calc.ptr(cmax, ctrough) \item{ctrough}{The last concentration in an interval} } \value{ -The ratio of cmax to ctrough (if ctrough == 0, NA) +The ratio of cmax to ctrough (if ctrough == 0, NA with the reason in +its "exclude" attribute) } \description{ Determine the peak-to-trough ratio diff --git a/man/pk.calc.tlag.Rd b/man/pk.calc.tlag.Rd index 832aa4c0a..548555f42 100644 --- a/man/pk.calc.tlag.Rd +++ b/man/pk.calc.tlag.Rd @@ -16,7 +16,9 @@ pk.calc.tlag(conc, time, check = TRUE) \item{check}{Run \code{\link[=assert_conc_time]{assert_conc_time()}}?} } \value{ -The time associated with the first increasing concentration +The time associated with the first increasing concentration, or +\code{NA} with the reason in its "exclude" attribute when concentrations never +increase } \description{ Missing concentrations are skipped, as in \code{\link[=pk.calc.cmax]{pk.calc.cmax()}} and the other diff --git a/man/pk.calc.tlast.Rd b/man/pk.calc.tlast.Rd index 0c27dcdb3..f752207ec 100644 --- a/man/pk.calc.tlast.Rd +++ b/man/pk.calc.tlast.Rd @@ -18,7 +18,9 @@ pk.calc.tfirst(conc, time, check = TRUE) \item{check}{Run \code{\link[=assert_conc_time]{assert_conc_time()}}?} } \value{ -The time of the last observed concentration measurement +The time of the last observed concentration measurement, or \code{NA} +with the reason in its "exclude" attribute when no concentration is above +zero } \description{ \code{NA} will be returned if all \code{conc} are \code{NA} or 0. diff --git a/man/pk.calc.tmax.Rd b/man/pk.calc.tmax.Rd index ef9bf0830..2af4e0df9 100644 --- a/man/pk.calc.tmax.Rd +++ b/man/pk.calc.tmax.Rd @@ -21,7 +21,8 @@ last is considered Tmax/ERTmax.} \item{check}{Run \code{\link[=assert_conc_time]{assert_conc_time()}}?} } \value{ -The time of the maximum concentration +The time of the maximum concentration, or \code{NA} with the reason in +its "exclude" attribute when no concentration is above zero } \description{ Input restrictions are: diff --git a/man/pk.calc.tmin.Rd b/man/pk.calc.tmin.Rd index 47e325f4a..11a2dfed4 100644 --- a/man/pk.calc.tmin.Rd +++ b/man/pk.calc.tmin.Rd @@ -21,7 +21,8 @@ then the last is considered Tmin.} \item{check}{Run \code{\link[=assert_conc_time]{assert_conc_time()}}?} } \value{ -The time of the minimum concentration +The time of the minimum concentration, or \code{NA} with the reason in +its "exclude" attribute when all concentrations are missing } \description{ Input restrictions are: diff --git a/man/pk.calc.totdose.Rd b/man/pk.calc.totdose.Rd index 76ec4195a..25cde15b2 100644 --- a/man/pk.calc.totdose.Rd +++ b/man/pk.calc.totdose.Rd @@ -10,7 +10,8 @@ pk.calc.totdose(dose) \item{dose}{the dose administered} } \value{ -The total dose for an interval +The total dose for an interval, or \code{NA} with the reason in its +"exclude" attribute when there is no dose or a dose is missing } \description{ Extract the dose used for calculations diff --git a/tests/testthat/test-class-PKNCAresults.R b/tests/testthat/test-class-PKNCAresults.R index 74b78803d..7a42c5e66 100644 --- a/tests/testthat/test-class-PKNCAresults.R +++ b/tests/testthat/test-class-PKNCAresults.R @@ -165,22 +165,29 @@ test_that("PKNCAresults has exclude, when applicable", { ) ] ), - "Too few points for half-life calculation (min.hl.points=3 with only 0 points)", + # half.life is calculated from tmax and tlast, which give their own reason + "No concentration is above zero; Too few points for half-life calculation (min.hl.points=3 with only 0 points)", info="exclusions are propagated to results" ) expect_equal( - unique( - o_result_df$exclude[ - !(o_result_df$ID == 2 & - o_result_df$PPTESTCD %in% - c("lambda.z", "r.squared", "adj.r.squared", "lambda.z.corrxy", "lambda.z.time.first", - "lambda.z.time.last", "lambda.z.n.points", "clast.pred", "half.life", "span.ratio") - ) - ] - ), + unique(o_result_df$exclude[o_result_df$ID == 1]), NA_character_, info="exclusions are propagated to results only when applicable" ) + # The other parameters of the all-zero profile say why they are NA + id2_other <- + o_result_df[ + o_result_df$ID == 2 & + o_result_df$PPTESTCD %in% c("tmax", "tlast", "tlag", "aucpext.inf.obs", "cl.inf.obs"), + ] + expect_equal( + id2_other$exclude[match(c("tmax", "tlast", "tlag", "aucpext.inf.obs", "cl.inf.obs"), id2_other$PPTESTCD)], + c( + "No concentration is above zero", "No concentration is above zero", + "Concentrations never increase", "AUCinf is zero", "AUC is zero or negative" + ) + ) + expect_true(all(is.na(id2_other$PPORRES))) }) test_that("ptr works as a parameter", { diff --git a/tests/testthat/test-pk.calc.all.R b/tests/testthat/test-pk.calc.all.R index edcaa4f17..ad0466770 100644 --- a/tests/testthat/test-pk.calc.all.R +++ b/tests/testthat/test-pk.calc.all.R @@ -353,7 +353,8 @@ test_that("Calculations when no dose info is given", { "AUC: lin up/log down", rep("", 2) ), - exclude=NA_character_ + # cl.last cannot be calculated without a dose, and says so + exclude=rep(c(NA_character_, NA_character_, "Dose is missing"), 2) ) ) }) diff --git a/tests/testthat/test-pk.calc.dn.R b/tests/testthat/test-pk.calc.dn.R index 4d2175fb8..cc9bd72cb 100644 --- a/tests/testthat/test-pk.calc.dn.R +++ b/tests/testthat/test-pk.calc.dn.R @@ -2,7 +2,7 @@ test_that("pk.calc.dn", { # Ensure correct calculation expect_equal(pk.calc.dn(1, 5), 0.2) expect_equal(pk.calc.dn(NA, 5), NA_real_) - expect_equal(pk.calc.dn(1, NA), NA_real_) + expect_equal(pk.calc.dn(1, NA), structure(NA_real_, exclude = "Dose is missing")) }) test_that("pk.calc.cmax", { diff --git a/tests/testthat/test-pk.calc.simple.R b/tests/testthat/test-pk.calc.simple.R index a3294b234..cf8ef28ff 100644 --- a/tests/testthat/test-pk.calc.simple.R +++ b/tests/testthat/test-pk.calc.simple.R @@ -16,9 +16,9 @@ test_that("adj.r.squared", { test_that("pk.calc.cmax", { # Confirm that all NAs give NA as an output expect_warning(v1 <- pk.calc.cmax(NA)) - expect_equal(v1, NA) + expect_equal(v1, structure(NA, exclude = "All concentrations are missing")) expect_warning(v2 <- pk.calc.cmax(c(NA, NA))) - expect_equal(v2, NA) + expect_equal(v2, structure(NA, exclude = "All concentrations are missing")) # Confirm that no NAs give the max value expect_equal(pk.calc.cmax(c(1, 2)), 2) @@ -32,15 +32,15 @@ test_that("pk.calc.cmax", { # Confirm that no data gives NA with a warning expect_warning(v3 <- pk.calc.cmax(numeric())) - expect_equal(v3, NA) + expect_equal(v3, structure(NA, exclude = "All concentrations are missing")) }) test_that("pk.calc.cmin", { # Confirm that all NAs give NA as an output expect_warning(v1 <- pk.calc.cmin(NA)) - expect_equal(v1, NA) + expect_equal(v1, structure(NA, exclude = "All concentrations are missing")) expect_warning(v2 <- pk.calc.cmin(c(NA, NA))) - expect_equal(v2, NA) + expect_equal(v2, structure(NA, exclude = "All concentrations are missing")) # Confirm that no NAs give the min value expect_equal(pk.calc.cmin(c(1, 2)), 1) @@ -54,7 +54,7 @@ test_that("pk.calc.cmin", { # Confirm that no data gives NA with a warning expect_warning(v3 <- pk.calc.cmin(numeric())) - expect_equal(v3, NA) + expect_equal(v3, structure(NA, exclude = "All concentrations are missing")) }) test_that("pk.calc.tmax", { @@ -64,7 +64,7 @@ test_that("pk.calc.tmax", { class = "pknca_warning_no_concentration"), class = "pknca_warning_no_time" ) - expect_equal(v1, NA) + expect_equal(v1, structure(NA, exclude = "All concentrations are missing")) # Either concentration or time is missing, give an error expect_error( @@ -94,7 +94,7 @@ test_that("pk.calc.tmin", { class = "pknca_warning_no_concentration"), class = "pknca_warning_no_time" ) - expect_equal(v1, NA) + expect_equal(v1, structure(NA, exclude = "All concentrations are missing")) # Either concentration or time is missing, give an error expect_error( @@ -108,7 +108,7 @@ test_that("pk.calc.tmin", { # All NA concentrations give NA expect_warning( - expect_equal(pk.calc.tmin(c(NA, NA), c(0, 1), first.tmin=TRUE), NA), + expect_equal(pk.calc.tmin(c(NA, NA), c(0, 1), first.tmin=TRUE), structure(NA, exclude = "All concentrations are missing")), class = "pknca_warning_all_concentration_missing" ) @@ -138,7 +138,7 @@ test_that("pk.calc.tlast", { expect_equal(pk.calc.tlast(c(1, 2), c(0, 1)), 1) expect_equal(pk.calc.tlast(c(0, 0), c(0, 1)), - NA) + structure(NA, exclude = "No concentration is above zero")) expect_equal(pk.calc.tlast(c(0, 1), c(0, 1)), 1) expect_equal(pk.calc.tlast(c(1, 0), c(0, 1)), @@ -188,7 +188,7 @@ test_that("pk.calc.clast.obs", { v1 <- pk.calc.clast.obs(c1, t1), class = "pknca_warning_all_concentration_missing" ) - expect_equal(v1, NA_real_) + expect_equal(v1, structure(NA_real_, exclude = "All concentrations are missing")) c1 <- rep(0, 4) t1 <- c(0, 1, 2, 3) @@ -253,26 +253,26 @@ test_that("pk.calc.cl", { c(NA_real_, 0.5), info="NA generation works with NA, including for a vector") expect_equal(pk.calc.cl(dose=c(50, 50), auc=c(0, 100)), - c(NA_real_, 0.5), + structure(c(NA_real_, 0.5), exclude = "AUC is zero or negative"), info="NA generation works with zero, including for a vector") }) test_that("pk.calc.f", { expect_equal(pk.calc.f(1, 1, 1, 2), 2, info="Standard bioavailability calculation") - expect_equal(pk.calc.f(NA, 1, 1, 1), NA_real_, + expect_equal(pk.calc.f(NA, 1, 1, 1), structure(NA_real_, exclude = "Dose is missing"), info="NA handling per parameter in bioavailability (1)") expect_equal(pk.calc.f(1, NA, 1, 1), NA_real_, info="NA handling per parameter in bioavailability (2)") - expect_equal(pk.calc.f(1, 1, NA, 1), NA_real_, + expect_equal(pk.calc.f(1, 1, NA, 1), structure(NA_real_, exclude = "Dose is missing"), info="NA handling per parameter in bioavailability (3)") expect_equal(pk.calc.f(1, 1, 1, NA), NA_real_, info="NA handling per parameter in bioavailability (4)") - expect_equal(pk.calc.f(0, 1, 1, 1), NA_real_, + expect_equal(pk.calc.f(0, 1, 1, 1), structure(NA_real_, exclude = "Dose is zero or negative"), info="Zero handling per parameter in bioavailability (1)") - expect_equal(pk.calc.f(1, 0, 1, 1), NA_real_, + expect_equal(pk.calc.f(1, 0, 1, 1), structure(NA_real_, exclude = "AUC is zero or negative"), info="Zero handling per parameter in bioavailability (2)") - expect_equal(pk.calc.f(1, 1, 0, 1), NA_real_, + expect_equal(pk.calc.f(1, 1, 0, 1), structure(NA_real_, exclude = "Dose is zero or negative"), info="Zero handling per parameter in bioavailability (3)") expect_equal(pk.calc.f(1, 1, 1, 0), 0, info="Zero handling per parameter in bioavailability (4)") @@ -289,7 +289,7 @@ test_that("pk.calc.aucpext", { class = "pknca_warning_aucpext_aucinf_le_auclast"), class = "pknca_warning_aucpext_aucinf_auclast_positive" ) - expect_equal(v2, NA_real_, + expect_equal(v2, structure(NA_real_, exclude = "AUCinf is zero"), info="aucinf<=0 gives NA_real_ (not infinity)") expect_equal(pk.calc.aucpext(NA, NA), NA_real_, @@ -328,10 +328,10 @@ test_that("pk.calc.mrt.iv", { 2, info="MRT.iv is calculated correctly when duration is 0") expect_equal(pk.calc.mrt.iv(auc=1, aumc=2, duration.dose=NA), - NA_real_, + structure(NA_real_, exclude = "A dose time or duration is missing"), info="MRT.iv is calculated correctly when duration is missing") expect_equal(pk.calc.mrt.iv(auc=0, aumc=2, duration.dose=NA), - NA_real_, + structure(NA_real_, exclude = "A dose time or duration is missing; AUC is zero or negative"), info="MRT.iv is calculated correctly when auc is zero") }) @@ -378,24 +378,24 @@ test_that("pk.calc.mrt.iv uses the dose-weighted mean input time for several dos test_that("pk.calc.mrt.iv returns NA when the mean input time is unknown for several doses", { expect_equal( pk.calc.mrt.iv(auc=1, aumc=6, duration.dose=c(1, NA), dose=c(10, 10), time.dose=c(0, 1)), - NA_real_ + structure(NA_real_, exclude = "A dose time or duration is missing") ) expect_equal( pk.calc.mrt.iv(auc=1, aumc=6, duration.dose=c(1, 2), dose=c(10, NA), time.dose=c(0, 1)), - NA_real_ + structure(NA_real_, exclude = "A dose amount is missing, or the doses sum to zero") ) expect_equal( pk.calc.mrt.iv(auc=1, aumc=6, duration.dose=c(1, 2), dose=c(0, 0), time.dose=c(0, 1)), - NA_real_ + structure(NA_real_, exclude = "A dose amount is missing, or the doses sum to zero") ) expect_equal( pk.calc.mrt.iv(auc=1, aumc=6, duration.dose=c(1, 2), dose=c(10, 10), time.dose=c(0, NA)), - NA_real_, + structure(NA_real_, exclude = "A dose time or duration is missing"), info="a missing dose time with several doses gives NA" ) expect_equal( pk.calc.mrt.iv(auc=0, aumc=6, duration.dose=c(1, 2), dose=c(10, 10), time.dose=c(0, 1)), - NA_real_ + structure(NA_real_, exclude = "AUC is zero or negative") ) # The weights are not guessed: with one dose missing, the result is NA rather than # the equal-weight value @@ -410,27 +410,27 @@ test_that("pk.calc.mrt.iv returns NA when the mean input time is unknown for sev 6 - (3 + 2/2) ) # A single dose with a missing time or duration is NA - expect_equal(pk.calc.mrt.iv(auc=1, aumc=6, duration.dose=2, dose=10, time.dose=NA_real_), NA_real_) - expect_equal(pk.calc.mrt.iv(auc=1, aumc=6, duration.dose=NA_real_, dose=10, time.dose=0), NA_real_) + expect_equal(pk.calc.mrt.iv(auc=1, aumc=6, duration.dose=2, dose=10, time.dose=NA_real_), structure(NA_real_, exclude = "A dose time or duration is missing")) + expect_equal(pk.calc.mrt.iv(auc=1, aumc=6, duration.dose=NA_real_, dose=10, time.dose=0), structure(NA_real_, exclude = "A dose time or duration is missing")) }) test_that("pk.calc.mrt.md.iv returns NA when the mean input time is unknown for several doses", { args <- list(auctau=10, aumctau=40, aucinf=12, tau=12) expect_equal( do.call(pk.calc.mrt.md.iv, c(args, list(duration.dose=c(1, NA), dose=c(10, 10), time.dose=c(0, 1)))), - NA_real_ + structure(NA_real_, exclude = "A dose time or duration is missing") ) expect_equal( do.call(pk.calc.mrt.md.iv, c(args, list(duration.dose=c(1, 2), dose=c(10, NA), time.dose=c(0, 1)))), - NA_real_ + structure(NA_real_, exclude = "A dose amount is missing, or the doses sum to zero") ) expect_equal( do.call(pk.calc.mrt.md.iv, c(args, list(duration.dose=c(1, 2), dose=c(0, 0), time.dose=c(0, 1)))), - NA_real_ + structure(NA_real_, exclude = "A dose amount is missing, or the doses sum to zero") ) expect_equal( do.call(pk.calc.mrt.md.iv, c(args, list(duration.dose=c(1, 2), dose=c(10, 10), time.dose=c(0, NA)))), - NA_real_ + structure(NA_real_, exclude = "A dose time or duration is missing") ) # A single dose row does not use dose expect_equal( @@ -494,7 +494,7 @@ test_that("pk.calc.mrt.iv requires one result and consistent dose inputs (#694)" test_that("pk.calc.mrt.md", { expect_equal(pk.calc.mrt.md(1, 2, 1.5, 24), 2 + 24*0.5) - expect_equal(pk.calc.mrt.md(0, 2, 1.5, 24), NA_real_, + expect_equal(pk.calc.mrt.md(0, 2, 1.5, 24), structure(NA_real_, exclude = "AUC is zero or negative"), info="auctau <= 0 becomes NA (not Inf)") }) @@ -503,9 +503,9 @@ test_that("pk.calc.mrt.md.iv", { expect_equal(pk.calc.mrt.md.iv(1, 2, 1.5, 24, duration.dose=0), pk.calc.mrt.md(1, 2, 1.5, 24), info="a zero infusion duration is the same as the non-IV form") - expect_equal(pk.calc.mrt.md.iv(0, 2, 1.5, 24, duration.dose=4), NA_real_, + expect_equal(pk.calc.mrt.md.iv(0, 2, 1.5, 24, duration.dose=4), structure(NA_real_, exclude = "AUC is zero or negative"), info="auctau <= 0 becomes NA (not Inf)") - expect_equal(pk.calc.mrt.md.iv(1, 2, 1.5, 24, duration.dose=NA), NA_real_, + expect_equal(pk.calc.mrt.md.iv(1, 2, 1.5, 24, duration.dose=NA), structure(NA_real_, exclude = "A dose time or duration is missing"), info="a missing infusion duration becomes NA") }) @@ -597,7 +597,7 @@ test_that("pk.calc.vss and its wrappers", { test_that("pk.calc.cav", { expect_equal(pk.calc.cav(2, 0, 1), 2) expect_equal(pk.calc.cav(NA, 0, 1), NA_real_) - expect_equal(pk.calc.cav(2, 1, 1), NA_real_, + expect_equal(pk.calc.cav(2, 1, 1), structure(NA_real_, exclude = "The interval has zero duration"), info="If end == start, return NA_real_") }) @@ -677,7 +677,7 @@ test_that("pk.calc.ctrough", { info="Found and it's the first time") expect_equal(pk.calc.ctrough(1:5, 0:4, 1), 2, info="Found and it's not the first time") - expect_equal(pk.calc.ctrough(1:5, 0:4, 1.5), NA_real_, + expect_equal(pk.calc.ctrough(1:5, 0:4, 1.5), structure(NA_real_, exclude = "No non-missing concentration at the end of the interval"), info="Not found") expect_error( pk.calc.ctrough(1:5, c(0, 0:3), 0), @@ -688,7 +688,7 @@ test_that("pk.calc.ctrough", { test_that("pk.calc.ptr", { expect_equal(pk.calc.ptr(cmax=2, ctrough=1), 2, info="Confirm that the ratio goes the right way") - expect_equal(pk.calc.ptr(2, 0), NA_real_, + expect_equal(pk.calc.ptr(2, 0), structure(NA_real_, exclude = "Ctrough is zero"), info="Division by zero returns NA") }) @@ -697,9 +697,9 @@ test_that("pk.calc.tlag", { info="find the first point") expect_equal(pk.calc.tlag(c(0, 0, 0, 0, 1), 0:4), 3, info="find the next to last point") - expect_equal(pk.calc.tlag(c(0, 0, 0, 0, 0), 0:4), NA_real_, + expect_equal(pk.calc.tlag(c(0, 0, 0, 0, 0), 0:4), structure(NA_real_, exclude = "Concentrations never increase"), info="No increase gives NA") - expect_equal(pk.calc.tlag(5:1, 0:4), NA_real_, + expect_equal(pk.calc.tlag(5:1, 0:4), structure(NA_real_, exclude = "Concentrations never increase"), info="No increase gives NA") }) @@ -707,7 +707,7 @@ test_that("pk.calc.tlag skips missing concentrations, as the other simple parame # At the start: the first increase among the measured values is 40 to 80 expect_equal(pk.calc.tlag(c(NA, 40, 80, 10), c(0, 2, 4, 8)), 2) # At the start with no increase among the measured values - expect_equal(pk.calc.tlag(c(NA, 40, 20, 10), c(0, 2, 4, 8)), NA_real_) + expect_equal(pk.calc.tlag(c(NA, 40, 20, 10), c(0, 2, 4, 8)), structure(NA_real_, exclude = "Concentrations never increase")) # In the middle: 10 and 5 are not an increase, 5 to 8 is expect_equal(pk.calc.tlag(c(10, NA, 5, 8), 0:3), 2) # At the end @@ -720,8 +720,8 @@ test_that("pk.calc.tlag skips missing concentrations, as the other simple parame value_all_missing <- pk.calc.tlag(c(NA_real_, NA_real_, NA_real_), 0:2), class = "pknca_warning_all_concentration_missing" ) - expect_equal(value_all_missing, NA_real_) - expect_equal(pk.calc.tlag(c(NA_real_, NA_real_, NA_real_), 0:2, check = FALSE), NA_real_) + expect_equal(value_all_missing, structure(NA_real_, exclude = "All concentrations are missing")) + expect_equal(pk.calc.tlag(c(NA_real_, NA_real_, NA_real_), 0:2, check = FALSE), structure(NA_real_, exclude = "All concentrations are missing")) # check = FALSE skips the assertions, not the missing values expect_equal(pk.calc.tlag(c(10, NA, 5, 8), 0:3, check = FALSE), 2) }) @@ -759,7 +759,7 @@ test_that("tlag in pk.nca with missing concentrations", { test_that("pk.calc.deg.fluc", { expect_equal(pk.calc.deg.fluc(cmax=100, cmin=10, cav=45), 200, info="Degree of fluctuation math works") - expect_equal(pk.calc.deg.fluc(cmax=100, cmin=10, cav=0), NA_real_, + expect_equal(pk.calc.deg.fluc(cmax=100, cmin=10, cav=0), structure(NA_real_, exclude = "Cav is zero"), info="Degree of fluctuation returns NA when cav=0") }) @@ -784,10 +784,10 @@ test_that("pk.calc.ceoi", { 1, info="Ceoi returns the concentration at the end of the dosing duration") expect_equal(pk.calc.ceoi(conc=0:5, time=0:5, duration.dose=1.5), - NA_real_, + structure(NA_real_, exclude = "No non-missing concentration at the end of the infusion"), info="Ceoi returns NA if there is no measurement at the end of the dosing duration") expect_equal(pk.calc.ceoi(conc=0:5, time=0:5, duration.dose=NA), - NA_real_, + structure(NA_real_, exclude = "Dose duration is missing"), info="Ceoi returns NA if there is no dosing duration") }) @@ -853,7 +853,7 @@ test_that("pk.calc.totdose", { test_that("pk.calc.cstart", { expect_equal(pk.calc.cstart(1:5, 0:4, 0), 1) expect_equal(pk.calc.cstart(1:5, 0:4, 1), 2) - expect_equal(pk.calc.cstart(1:5, 0:4, 1.5), NA_real_) + expect_equal(pk.calc.cstart(1:5, 0:4, 1.5), structure(NA_real_, exclude = "No non-missing concentration at the start of the interval")) expect_error( pk.calc.cstart(1:5, c(0, 0:3), 0), regexp = "Assertion on 'time' failed: Contains duplicated values, position 2." @@ -876,10 +876,11 @@ test_that("pk.calc.aucabove rejects non-finite conc_above", { }) test_that("zero-length input gives NA rather than zero (issue 601)", { - expect_equal(pk.calc.cl(dose = numeric(0), auc = 10), NA_real_) - expect_equal(pk.calc.cl(dose = NULL, auc = 10), NA_real_) - expect_equal(pk.calc.totdose(dose = numeric(0)), NA_real_) - expect_equal(pk.calc.totdose(dose = NULL), NA_real_) + no_dose <- structure(NA_real_, exclude = "No dose in the interval") + expect_equal(pk.calc.cl(dose = numeric(0), auc = 10), no_dose) + expect_equal(pk.calc.cl(dose = NULL, auc = 10), no_dose) + expect_equal(pk.calc.totdose(dose = numeric(0)), no_dose) + expect_equal(pk.calc.totdose(dose = NULL), no_dose) # Unchanged for real input, including multiple doses in one interval expect_equal(pk.calc.cl(dose = 100, auc = 10), 10) expect_equal(pk.calc.cl(dose = c(50, 50), auc = 10), 10) @@ -972,7 +973,7 @@ test_that("a profile with missing concentrations does not stop tlag or swing for ) expect_identical(tlag_swing_results(d_falling, "tlag", conc.na = "drop", end = Inf), c(NA_real_, NA_real_)) expect_identical(tlag_swing_results(d_falling, "tlag", conc.na = 0, end = Inf), c(NA_real_, NA_real_)) - expect_identical(pk.calc.tlag(conc = c(10, 8, NA, 4, 2), time = c(0.25, 1, 2, 4, 8)), NA_real_) + expect_identical(pk.calc.tlag(conc = c(10, 8, NA, 4, 2), time = c(0.25, 1, 2, 4, 8)), structure(NA_real_, exclude = "Concentrations never increase")) # tlag: no measurable concentration and one missing sample for the second # subject @@ -994,3 +995,142 @@ test_that("a profile with missing concentrations does not stop tlag or swing for expect_identical(tlag_swing_results(d_all_missing, "swing", conc.na = "drop", end = 4), c(400, NA_real_)) expect_identical(tlag_swing_results(d_all_missing, "swing", conc.na = 0, end = 4), c(400, NA_real_)) }) + +# Results of `parameters` from pk.nca() for one subject, dosed at time 0, over +# the interval 0 to 24. +simple_reason_results <- function(conc, parameters, dose = 100, duration = 0, + route = "extravascular", conc.na = "drop", + time = c(0, 1, 2, 4, 8, 24)) { + d_interval <- data.frame(start = 0, end = 24) + for (current_parameter in parameters) { + d_interval[[current_parameter]] <- TRUE + } + # The profiles are degenerate on purpose, so the warnings they give are + # expected + res <- + suppressWarnings( + { + o_data <- + PKNCAdata( + PKNCAconc(data.frame(id = 1, time = time, conc = conc), conc ~ time | id), + PKNCAdose( + data.frame(id = 1, time = 0, dose = dose, duration = duration), + dose ~ time | id, route = route, duration = "duration" + ), + intervals = d_interval, + options = list(conc.na = conc.na) + ) + as.data.frame(pk.nca(o_data)) + }, + classes = c( + "pknca_warning_all_concentration_missing", + "pknca_warning_deprecated_parameter", + "pknca_warning_interval_inconsistent_parameters", + "pknca_warning_auc_before_first", + "pknca_warning_tau_undetermined", + "pknca_warning_halflife_too_few_points", + "pknca_warning_aucpext_aucinf_le_auclast", + "pknca_warning_aucpext_aucinf_auclast_positive" + ) + ) + as.data.frame(res[res$PPTESTCD %in% parameters, c("PPTESTCD", "PPORRES", "exclude")]) +} + +test_that("a simple parameter that is NA because of missing or unusable data says why in pk.nca()", { + all_missing <- + simple_reason_results( + conc = rep(NA_real_, 6), + parameters = c("cmax", "cmin", "tmax", "tmin", "tlast", "tfirst", "clast.obs", "tlag", "swing", "cmax.dn") + ) + expect_true(all(is.na(all_missing$PPORRES))) + expect_equal(unique(all_missing$exclude), "All concentrations are missing") + + all_zero <- + simple_reason_results( + conc = rep(0, 6), + parameters = c("tmax", "tlast", "tfirst", "tlag", "cl.last", "mrt.last", "ptr", "deg.fluc", "aucpext.inf.obs", "mrt.md.inf.obs") + ) + expect_true(all(is.na(all_zero$PPORRES))) + expect_equal( + all_zero$exclude[match(c("tmax", "tlast", "tfirst", "tlag", "cl.last", "mrt.last", "ptr", "deg.fluc", "aucpext.inf.obs", "mrt.md.inf.obs"), all_zero$PPTESTCD)], + c( + rep("No concentration is above zero", 3), + "Concentrations never increase", + "AUC is zero or negative", "AUC is zero or negative", + "Ctrough is zero", + "Cav is zero", + "AUCinf is zero", + "The dosing interval (tau) is not known; AUC is zero or negative" + ) + ) + + missing_ends <- + simple_reason_results(conc = c(NA, 5, 8, 6, 3, NA), parameters = c("cstart", "ctrough", "ptr")) + expect_true(all(is.na(missing_ends$PPORRES))) + expect_equal( + missing_ends$exclude[match(c("cstart", "ctrough", "ptr"), missing_ends$PPTESTCD)], + c( + "No non-missing concentration at the start of the interval", + "No non-missing concentration at the end of the interval", + "No non-missing concentration at the end of the interval" + ) + ) + + dose_missing <- + simple_reason_results(conc = c(0, 5, 8, 6, 3, 1), parameters = c("cl.last", "cmax.dn", "totdose", "vss.last"), dose = NA) + expect_true(all(is.na(dose_missing$PPORRES))) + expect_equal(unique(dose_missing$exclude), "Dose is missing") + + infusion <- + simple_reason_results( + conc = c(0, 5, 8, 6, 3, 1), parameters = "ceoi", duration = 1.5, route = "intravascular" + ) + expect_equal(infusion$PPORRES, NA_real_) + expect_equal(infusion$exclude, "No non-missing concentration at the end of the infusion") +}) + +test_that("every parameter calculated by a simple function gives a reason with each NA in pk.nca()", { + simple_functions <- c( + "pk.calc.cmax", "pk.calc.cmin", "pk.calc.tmax", "pk.calc.tmin", "pk.calc.tlast", + "pk.calc.tfirst", "pk.calc.clast.obs", "pk.calc.thalf.eff", "pk.calc.aucpext", + "pk.calc.kel", "pk.calc.cl", "pk.calc.mrt", "pk.calc.mrt.iv", "pk.calc.mrt.md", + "pk.calc.mrt.md.iv", "pk.calc.vz", "pk.calc.vss", "pk.calc.cav", "pk.calc.ctrough", + "pk.calc.cstart", "pk.calc.ptr", "pk.calc.tlag", "pk.calc.deg.fluc", "pk.calc.swing", + "pk.calc.ceoi", "pk.calc.aucabove", "pk.calc.count_conc", "pk.calc.count_conc_measured", + "pk.calc.totdose", "pk.calc.dn" + ) + all_intervals <- get.interval.cols() + parameters <- + names(all_intervals)[vapply(all_intervals, function(x) isTRUE(x$FUN %in% simple_functions), logical(1))] + # Every simple function except pk.calc.f() (which needs a reference interval) + # is registered for at least one parameter + expect_setequal( + unique(vapply(all_intervals[parameters], function(x) x$FUN, character(1))), + simple_functions + ) + profiles <- list( + all_missing = rep(NA_real_, 6), + all_zero = rep(0, 6), + missing_ends = c(NA, 5, 8, 6, 3, NA) + ) + for (current_route in c("extravascular", "intravascular")) { + for (current_profile in names(profiles)) { + for (current_conc_na in list("drop", 0)) { + res <- + simple_reason_results( + conc = profiles[[current_profile]], parameters = parameters, + duration = if (current_route == "intravascular") 1.5 else 0, + route = current_route, conc.na = current_conc_na + ) + no_reason <- res$PPTESTCD[is.na(res$PPORRES) & is.na(res$exclude)] + expect_equal( + no_reason, character(0), + info = paste(current_route, current_profile, current_conc_na) + ) + } + } + } + res_dose_missing <- + simple_reason_results(conc = c(0, 5, 8, 6, 3, 1), parameters = parameters, dose = NA) + expect_equal(res_dose_missing$PPTESTCD[is.na(res_dose_missing$PPORRES) & is.na(res_dose_missing$exclude)], character(0)) +}) diff --git a/vignettes/v80-writing-parameter-functions.Rmd b/vignettes/v80-writing-parameter-functions.Rmd index 3c194e424..574ef025f 100644 --- a/vignettes/v80-writing-parameter-functions.Rmd +++ b/vignettes/v80-writing-parameter-functions.Rmd @@ -40,7 +40,7 @@ The interval's own times given to the function (`time` and `time.dose`) are rela The function should return either a scalar which is the value for the parameter (usually the case) or a data.frame with parameters named for each parameter calculated. For an example of returning a data.frame, see the `half.life` function. -The return value may have an attribute of `exclude` (set by `attr(return_value, "exclude") <- "reason"`). If the `exclude` attribute is set to a character string, then that string will be included in the `exclude` column for results. If any of the input parameters have an exclude attribute set, then those are also added to the `exclude` column. The exception to the setting of the `exclude` column is if the `exclude` attribute is `"DO NOT EXCLUDE"`, then the `exclude` column is set to `NA_character_`. +The return value may have an attribute of `exclude` (set by `attr(return_value, "exclude") <- "reason"`). If the `exclude` attribute is set to a character string, then that string will be included in the `exclude` column for results. If any of the input parameters have an exclude attribute set, then those are also added to the `exclude` column, each distinct reason once. When the function returns `NA` because of missing or unusable data, give the reason this way so that the `NA` is explained (for example, `structure(NA_real_, exclude = "Dose is missing")`). The exception to the setting of the `exclude` column is if the `exclude` attribute is `"DO NOT EXCLUDE"`, then the `exclude` column is set to `NA_character_`. ## Best Practices From b18960c069e9746ffbe4957f2ecbabfc8f22a977 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 15:39:41 -0500 Subject: [PATCH 16/21] docs: NEWS lists the reasons now given with NA simple parameters Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/NEWS.md b/NEWS.md index 992428914..b692a38f9 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1228,6 +1228,42 @@ the generated intervals: `swing` was requested, which stopped the calculation for every subject, and now gives `NA` for that interval. +* A simple parameter that is `NA` because of missing or unusable data now says + why in the `exclude` column of `pk.nca()` results, where the column was + empty (@billdenney, #727). No value changes; only the + `exclude` text of results that were already `NA`. The reasons, set by the + calculation functions as an `exclude` attribute on their `NA` return: + - "All concentrations are missing": `cmax`, `cmin`, `tmax`, `tmin`, `tlast`, + `tfirst`, `clast.obs`, `tlag`. + - "No concentration is above zero": `tmax`, `tlast`, `tfirst`. + - "Concentrations never increase": `tlag`. + - "No non-missing concentration at the start of the interval": `cstart`; + "... at the end of the interval": `ctrough`; "... at the end of the + infusion": `ceoi`. "Dose duration is missing": `ceoi`. + - "AUC is zero or negative": `cl.*`, `mrt.*` (all forms), and the reference + AUC of `f.*`; "AUCinf is zero": `aucpext.*`; "Cav is zero": `deg.fluc`; + "Ctrough is zero": `ptr`. + - "Dose is missing": `cl.*`, `f.*`, `totdose`, and the dose-normalized + parameters (`*.dn`); "Dose is zero or negative": `f.*`; "No dose in the + interval": `cl.*`, `totdose`, and `mrt.iv.*` and `mrt.ivmd.*`. + - "A dose time or duration is missing", or "A dose amount is missing, or the + doses sum to zero" (when several doses are weighted): `mrt.iv.*` and + `mrt.ivmd.*`; "The dosing interval (tau) is not known": `mrt.md.*` and + `mrt.ivmd.*`. + - "The interval start or end is missing", "The interval has zero duration": + `cav.*`. + + Everything calculated from one of these carries its reason, as for any + other reason (for example `swing`, `vss.*`, `vz.*`, `kel.*`, `thalf.eff.*`), + and a reason given by more than one input is now listed once (for example + `swing` of an all-missing interval, from both `cmax` and `cmin`). What + changes for code reading the results: `summary()` gives the same numbers + (it ignores an `NA` either way); `as.data.frame(filter_excluded = TRUE)` + now leaves out these `NA` rows, as it leaves out any row with a reason; and + `exclude()` adds its reason after the one already there. A direct call such + as `pk.calc.cmax(c(NA, NA))` still returns `NA`, now with the `exclude` + attribute, so `is.na()` is unchanged but `identical(x, NA)` is `FALSE`. + * `mrt.iv.*`, `mrt.ivint.*`, `mrt.ivmd.*`, and everything calculated from them (`vss.iv.*`, `vss.ivint.*`, `vss.ivmd.*`, `kel.iv.*`, `thalf.eff.iv.*`) are now correct, and one value per interval, when an interval has more than one From dcb5705b20471e72c19eaf9f69cd24aa49c02417 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 18:24:24 -0500 Subject: [PATCH 17/21] fix: reasons only on single values, 0/0 dose normalisation explained, clearer end texts An "exclude" attribute describes the whole vector, so na_with_reason() now sets it only on a result of length one; pk.nca() always calls with single values, and a vector from a direct call keeps no attribute that would also sit beside its valid values. pk.calc.dn(0, 0) stays NaN and now says "Dose is zero". pk.calc.ctrough() with an infinite interval end says "The interval has no finite end", and pk.calc.ceoi() says the dose duration may be missing because there is no dose in the interval. The @returns documentation names the reason attribute for every function that sets one. Co-Authored-By: Claude Opus 5.5 --- R/pk.calc.simple.R | 55 +++++++++++++++++++++++++++------------- R/zzz-pk.calc.dn.R | 12 ++++++--- man/pk.calc.aucpext.Rd | 7 ++--- man/pk.calc.cav.Rd | 3 ++- man/pk.calc.cl.Rd | 3 ++- man/pk.calc.clast.obs.Rd | 3 ++- man/pk.calc.ctrough.Rd | 3 ++- man/pk.calc.deg.fluc.Rd | 2 ++ man/pk.calc.dn.Rd | 5 ++-- man/pk.calc.f.Rd | 4 +++ man/pk.calc.mrt.Rd | 6 ++++- man/pk.calc.ptr.Rd | 4 +-- man/pk.calc.tlast.Rd | 6 ++--- 13 files changed, 77 insertions(+), 36 deletions(-) diff --git a/R/pk.calc.simple.R b/R/pk.calc.simple.R index 0ae0a853a..07d02b45b 100644 --- a/R/pk.calc.simple.R +++ b/R/pk.calc.simple.R @@ -16,13 +16,18 @@ adj.r.squared <- function(r.sq, n) { } } -# Set the values of `ret` selected by `mask` to `NA` and add `reason` to its -# "exclude" attribute, which pk.nca() puts in the exclude column (see -# combine_exclude_reasons()). `ret` is unchanged when `mask` selects nothing. +# Set the values of `ret` selected by `mask` to `NA` and, for a single value, +# add `reason` to its "exclude" attribute, which pk.nca() puts in the exclude +# column (see combine_exclude_reasons()). An attribute describes the whole +# vector, so a longer result gets none rather than one that would also sit +# beside its valid values; pk.nca() calls with single values. `ret` is +# unchanged when `mask` selects nothing. na_with_reason <- function(ret, mask, reason) { if (any(mask)) { ret[mask] <- NA_real_ - attr(ret, "exclude") <- paste(c(attr(ret, "exclude"), reason), collapse = "; ") + if (length(ret) == 1) { + attr(ret, "exclude") <- paste(c(attr(ret, "exclude"), reason), collapse = "; ") + } } ret } @@ -219,9 +224,9 @@ add.interval.col("tmin", #' #' @inheritParams assert_conc_time #' @inheritParams clean.conc.blq -#' @returns The time of the last observed concentration measurement, or `NA` -#' with the reason in its "exclude" attribute when no concentration is above -#' zero +#' @returns The time of the last (`pk.calc.tlast()`) or first +#' (`pk.calc.tfirst()`) observed concentration measurement, or `NA` with the +#' reason in its "exclude" attribute when no concentration is above zero #' @family NCA time parameters #' @export pk.calc.tlast <- function(conc, time, check=TRUE) { @@ -289,7 +294,8 @@ add.interval.col("tfirst", #' #' @inheritParams assert_conc_time #' @inheritParams clean.conc.blq -#' @returns The last observed concentration above the LOQ +#' @returns The last observed concentration above the LOQ, or `NA` with the +#' reason in its "exclude" attribute when all concentrations are missing #' @family NCA parameters for concentrations during the intervals #' @export pk.calc.clast.obs <- function(conc, time, check=TRUE) { @@ -537,9 +543,10 @@ add.interval.col("thalf.eff.iv.all", #' @param auclast the area under the curve from time 0 to the last measurement #' above the limit of quantification #' @param aucinf the area under the curve from time 0 to infinity -#' @returns The numeric value of the AUC percent extrapolated or `NA_real_` if -#' any of the following are true `is.na(aucinf)`, `is.na(auclast)`, -#' `aucinf <= 0`, or `auclast <= 0`. +#' @returns The numeric value of the AUC percent extrapolated, or `NA_real_` +#' if `aucinf` or `auclast` is `NA` or `aucinf` is zero (a negative value is +#' calculated, with a warning). A result of length one that is `NA` because of missing or unusable data +#' has the reason in its "exclude" attribute, which [pk.nca()] reports. #' @family Half-life and elimination #' @export pk.calc.aucpext <- function(auclast, aucinf) { @@ -829,7 +836,8 @@ add.interval.col("kel.sparse.last", #' @param dose the dose administered #' @param auc The area under the concentration-time curve. #' @returns the numeric value of the total (CL) or observed oral clearance -#' (CL/F) +#' (CL/F). A result of length one that is `NA` because of missing or unusable data +#' has the reason in its "exclude" attribute, which [pk.nca()] reports. #' @details If `dose` is the same length as the other inputs, then the output #' will be the same length as all of the inputs; the function assumes that you #' are calculating for multiple intervals simultaneously. If the inputs other @@ -1079,6 +1087,8 @@ add.interval.col("cl.sparse.last", #' method 1 #' @param auc2 The AUC from 0 to infinity or 0 to tau administered in route or #' method 2 +#' @returns The bioavailability. A result of length one that is `NA` because of missing or unusable data +#' has the reason in its "exclude" attribute, which [pk.nca()] reports. #' @export pk.calc.f <- function(dose1, auc1, dose2, auc2) { ret <- (auc2/dose2)/(auc1/dose1) @@ -1249,7 +1259,8 @@ add.interval.col("f.int.inf.pred", #' @param time.dose The time(s) of the dose(s) relative to the start of the #' interval (the same origin as `aumc`). When missing, the dose is assumed to #' be at the interval start (time 0). -#' @returns the numeric value of the mean residence time +#' @returns the numeric value of the mean residence time. A result of length one that is `NA` because of missing or unusable data +#' has the reason in its "exclude" attribute, which [pk.nca()] reports. #' @family Mean residence time #' @export pk.calc.mrt <- function(auc, aumc) { @@ -1549,6 +1560,8 @@ add.interval.col("mrt.ivint.inf.obs", #' @param aucinf the AUC from time 0 to infinity (typically using single-dose #' data) #' @inheritParams assert_dosetau +#' @returns The mean residence time. A result of length one that is `NA` because of missing or unusable data +#' has the reason in its "exclude" attribute, which [pk.nca()] reports. #' @export pk.calc.mrt.md <- function(auctau, aumctau, aucinf, tau) { pk.calc.mrt.md.iv( @@ -2129,7 +2142,8 @@ add.interval.col("vss.sparse.last", #' #' @param auc The area under the curve during the interval #' @inheritParams assert_intervaltime_single -#' @returns The Cav (average concentration during the interval) +#' @returns The Cav (average concentration during the interval). A result of length one that is `NA` because of missing or unusable data +#' has the reason in its "exclude" attribute, which [pk.nca()] reports. #' @family NCA parameters for concentrations during the intervals #' @export pk.calc.cav <- function(auc, start, end) { @@ -2303,7 +2317,8 @@ add.interval.col( #' #' @inheritParams assert_conc_time #' @inheritParams assert_intervaltime_single -#' @returns The concentration when `time == end`. If none match, or that +#' @returns The concentration when `time == end` (`pk.calc.ctrough()`) or +#' `time == start` (`pk.calc.cstart()`). If none match, or that #' concentration is missing, then `NA` with the reason in its "exclude" #' attribute #' @family NCA parameters for concentrations during the intervals @@ -2313,6 +2328,8 @@ pk.calc.ctrough <- function(conc, time, end) { mask_end <- time %in% end if (sum(mask_end) == 1 && !is.na(conc[mask_end])) { conc[mask_end] + } else if (sum(mask_end) == 0 && length(end) == 1 && is.infinite(end)) { + structure(NA_real_, exclude = "The interval has no finite end") } else if (sum(mask_end) <= 1) { structure( if (sum(mask_end) == 1) conc[mask_end] else NA_real_, @@ -2382,8 +2399,8 @@ add.interval.col("cstart", #' #' @param cmax The maximum observed concentration #' @param ctrough The last concentration in an interval -#' @return The ratio of cmax to ctrough (if ctrough == 0, NA with the reason in -#' its "exclude" attribute) +#' @return The ratio of cmax to ctrough (if ctrough == 0, NA). A result of length one that is `NA` because of missing or unusable data +#' has the reason in its "exclude" attribute, which [pk.nca()] reports. #' @family Multiple-dose PK parameters #' @export pk.calc.ptr <- function(cmax, ctrough) { @@ -2463,6 +2480,8 @@ add.interval.col("tlag", #' @param cmin The minimum observed concentration #' @param cav The average concentration in the interval #' @returns The degree of fluctuation around the average concentration. +#' A result of length one that is `NA` because of missing or unusable data +#' has the reason in its "exclude" attribute, which [pk.nca()] reports. #' @family Multiple-dose PK parameters #' @export pk.calc.deg.fluc <- function(cmax, cmin, cav) { @@ -2532,7 +2551,7 @@ pk.calc.ceoi <- function(conc, time, duration.dose=NA, check=TRUE) { assert_conc_time(conc = conc, time = time) } if (is.na(duration.dose)) { - structure(NA_real_, exclude = "Dose duration is missing") + structure(NA_real_, exclude = "Dose duration is missing (or there is no dose in the interval)") } else if (all(time != duration.dose) || is.na(conc[time == duration.dose][1])) { structure(NA_real_, exclude = "No non-missing concentration at the end of the infusion") } else { diff --git a/R/zzz-pk.calc.dn.R b/R/zzz-pk.calc.dn.R index 28ebb7055..d44cb9104 100644 --- a/R/zzz-pk.calc.dn.R +++ b/R/zzz-pk.calc.dn.R @@ -2,14 +2,20 @@ #' #' @param parameter Parameter to dose normalize #' @param dose Dose in units compatible with the area under the curve -#' @returns a number for dose normalized AUC, or `NA` with the reason in its -#' "exclude" attribute when the dose is missing +#' @returns a number for dose normalized AUC. A result of length one has the +#' reason in its "exclude" attribute when it is `NA` because the dose is +#' missing, or `NaN` because the parameter and the dose are both zero. #' @examples #' pk.calc.dn(90, 10) #' @export pk.calc.dn <- function(parameter, dose) { # A missing parameter carries its own reason from its calculation - na_with_reason(parameter/dose, mask = !is.na(parameter) & is.na(dose), reason = "Dose is missing") + ret <- na_with_reason(parameter/dose, mask = !is.na(parameter) & is.na(dose), reason = "Dose is missing") + # 0/0 stays NaN, as it was; its reason says why + if (length(ret) == 1 && is.nan(ret) && isTRUE(dose == 0)) { + attr(ret, "exclude") <- "Dose is zero" + } + ret } local({ diff --git a/man/pk.calc.aucpext.Rd b/man/pk.calc.aucpext.Rd index 247b83b01..b86a58d5d 100644 --- a/man/pk.calc.aucpext.Rd +++ b/man/pk.calc.aucpext.Rd @@ -13,9 +13,10 @@ above the limit of quantification} \item{aucinf}{the area under the curve from time 0 to infinity} } \value{ -The numeric value of the AUC percent extrapolated or \code{NA_real_} if -any of the following are true \code{is.na(aucinf)}, \code{is.na(auclast)}, -\code{aucinf <= 0}, or \code{auclast <= 0}. +The numeric value of the AUC percent extrapolated, or \code{NA_real_} +if \code{aucinf} or \code{auclast} is \code{NA} or \code{aucinf} is zero (a negative value is +calculated, with a warning). A result of length one that is \code{NA} because of missing or unusable data +has the reason in its "exclude" attribute, which \code{\link[=pk.nca]{pk.nca()}} reports. } \description{ Calculate the AUC percent extrapolated diff --git a/man/pk.calc.cav.Rd b/man/pk.calc.cav.Rd index f617435d9..322bd9377 100644 --- a/man/pk.calc.cav.Rd +++ b/man/pk.calc.cav.Rd @@ -14,7 +14,8 @@ pk.calc.cav(auc, start, end) \item{end}{The end time of the interval} } \value{ -The Cav (average concentration during the interval) +The Cav (average concentration during the interval). A result of length one that is \code{NA} because of missing or unusable data +has the reason in its "exclude" attribute, which \code{\link[=pk.nca]{pk.nca()}} reports. } \description{ Calculate the average concentration during an interval. diff --git a/man/pk.calc.cl.Rd b/man/pk.calc.cl.Rd index d0a970f91..c3ffff449 100644 --- a/man/pk.calc.cl.Rd +++ b/man/pk.calc.cl.Rd @@ -13,7 +13,8 @@ pk.calc.cl(dose, auc) } \value{ the numeric value of the total (CL) or observed oral clearance -(CL/F) +(CL/F). A result of length one that is \code{NA} because of missing or unusable data +has the reason in its "exclude" attribute, which \code{\link[=pk.nca]{pk.nca()}} reports. } \description{ Calculate the (observed oral) clearance diff --git a/man/pk.calc.clast.obs.Rd b/man/pk.calc.clast.obs.Rd index ca54a0a52..ead72509f 100644 --- a/man/pk.calc.clast.obs.Rd +++ b/man/pk.calc.clast.obs.Rd @@ -15,7 +15,8 @@ pk.calc.clast.obs(conc, time, check = TRUE) \item{check}{Run \code{\link[=assert_conc_time]{assert_conc_time()}}?} } \value{ -The last observed concentration above the LOQ +The last observed concentration above the LOQ, or \code{NA} with the +reason in its "exclude" attribute when all concentrations are missing } \description{ If all concentrations are missing, \code{NA_real_} is returned. If all diff --git a/man/pk.calc.ctrough.Rd b/man/pk.calc.ctrough.Rd index 954ee505f..046ed7301 100644 --- a/man/pk.calc.ctrough.Rd +++ b/man/pk.calc.ctrough.Rd @@ -19,7 +19,8 @@ pk.calc.cstart(conc, time, start) \item{start}{The start time of the interval} } \value{ -The concentration when \code{time == end}. If none match, or that +The concentration when \code{time == end} (\code{pk.calc.ctrough()}) or +\code{time == start} (\code{pk.calc.cstart()}). If none match, or that concentration is missing, then \code{NA} with the reason in its "exclude" attribute } diff --git a/man/pk.calc.deg.fluc.Rd b/man/pk.calc.deg.fluc.Rd index cf6580408..20fe33c87 100644 --- a/man/pk.calc.deg.fluc.Rd +++ b/man/pk.calc.deg.fluc.Rd @@ -18,6 +18,8 @@ pk.calc.swing(cmax, cmin) } \value{ The degree of fluctuation around the average concentration. +A result of length one that is \code{NA} because of missing or unusable data +has the reason in its "exclude" attribute, which \code{\link[=pk.nca]{pk.nca()}} reports. The swing above the minimum concentration. If \code{cmin} is zero, then the result is infinity; if \code{cmin} or \code{cmax} is missing, it is \code{NA}. diff --git a/man/pk.calc.dn.Rd b/man/pk.calc.dn.Rd index 01a61631e..cd5d0e4fb 100644 --- a/man/pk.calc.dn.Rd +++ b/man/pk.calc.dn.Rd @@ -12,8 +12,9 @@ pk.calc.dn(parameter, dose) \item{dose}{Dose in units compatible with the area under the curve} } \value{ -a number for dose normalized AUC, or \code{NA} with the reason in its -"exclude" attribute when the dose is missing +a number for dose normalized AUC. A result of length one has the +reason in its "exclude" attribute when it is \code{NA} because the dose is +missing, or \code{NaN} because the parameter and the dose are both zero. } \description{ Determine dose normalized NCA parameter diff --git a/man/pk.calc.f.Rd b/man/pk.calc.f.Rd index ae5875946..03a9ae389 100644 --- a/man/pk.calc.f.Rd +++ b/man/pk.calc.f.Rd @@ -17,6 +17,10 @@ method 1} \item{auc2}{The AUC from 0 to infinity or 0 to tau administered in route or method 2} } +\value{ +The bioavailability. A result of length one that is \code{NA} because of missing or unusable data +has the reason in its "exclude" attribute, which \code{\link[=pk.nca]{pk.nca()}} reports. +} \description{ Calculate the absolute (or relative) bioavailability } diff --git a/man/pk.calc.mrt.Rd b/man/pk.calc.mrt.Rd index 2c89f9f60..cac95cda5 100644 --- a/man/pk.calc.mrt.Rd +++ b/man/pk.calc.mrt.Rd @@ -52,7 +52,11 @@ data)} \item{tau}{The dosing interval} } \value{ -the numeric value of the mean residence time +the numeric value of the mean residence time. A result of length one that is \code{NA} because of missing or unusable data +has the reason in its "exclude" attribute, which \code{\link[=pk.nca]{pk.nca()}} reports. + +The mean residence time. A result of length one that is \code{NA} because of missing or unusable data +has the reason in its "exclude" attribute, which \code{\link[=pk.nca]{pk.nca()}} reports. } \description{ Calculate the mean residence time (MRT) for single-dose data or linear diff --git a/man/pk.calc.ptr.Rd b/man/pk.calc.ptr.Rd index 401736613..0784021e3 100644 --- a/man/pk.calc.ptr.Rd +++ b/man/pk.calc.ptr.Rd @@ -12,8 +12,8 @@ pk.calc.ptr(cmax, ctrough) \item{ctrough}{The last concentration in an interval} } \value{ -The ratio of cmax to ctrough (if ctrough == 0, NA with the reason in -its "exclude" attribute) +The ratio of cmax to ctrough (if ctrough == 0, NA). A result of length one that is \code{NA} because of missing or unusable data +has the reason in its "exclude" attribute, which \code{\link[=pk.nca]{pk.nca()}} reports. } \description{ Determine the peak-to-trough ratio diff --git a/man/pk.calc.tlast.Rd b/man/pk.calc.tlast.Rd index f752207ec..f37f1bc8c 100644 --- a/man/pk.calc.tlast.Rd +++ b/man/pk.calc.tlast.Rd @@ -18,9 +18,9 @@ pk.calc.tfirst(conc, time, check = TRUE) \item{check}{Run \code{\link[=assert_conc_time]{assert_conc_time()}}?} } \value{ -The time of the last observed concentration measurement, or \code{NA} -with the reason in its "exclude" attribute when no concentration is above -zero +The time of the last (\code{pk.calc.tlast()}) or first +(\code{pk.calc.tfirst()}) observed concentration measurement, or \code{NA} with the +reason in its "exclude" attribute when no concentration is above zero } \description{ \code{NA} will be returned if all \code{conc} are \code{NA} or 0. From 21a36d4690ef788108e7263b0134f4b76bc5dab8 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 18:24:24 -0500 Subject: [PATCH 18/21] test: every registered parameter gives a reason with each NA from pk.nca() The enumerating test runs every registered parameter on missing, zero and single-sample fixtures with and without a usable dose, and pins the set of parameters that still give NA without a reason (the auciv family). Vectors get no attribute, 0/0 dose normalisation says why, and ctrough with an infinite end gives its own text. Co-Authored-By: Claude Opus 5.5 --- tests/testthat/test-pk.calc.simple.R | 112 +++++++++++++++++++-------- 1 file changed, 78 insertions(+), 34 deletions(-) diff --git a/tests/testthat/test-pk.calc.simple.R b/tests/testthat/test-pk.calc.simple.R index cf8ef28ff..b4b5462f9 100644 --- a/tests/testthat/test-pk.calc.simple.R +++ b/tests/testthat/test-pk.calc.simple.R @@ -253,7 +253,7 @@ test_that("pk.calc.cl", { c(NA_real_, 0.5), info="NA generation works with NA, including for a vector") expect_equal(pk.calc.cl(dose=c(50, 50), auc=c(0, 100)), - structure(c(NA_real_, 0.5), exclude = "AUC is zero or negative"), + c(NA_real_, 0.5), info="NA generation works with zero, including for a vector") }) @@ -787,7 +787,7 @@ test_that("pk.calc.ceoi", { structure(NA_real_, exclude = "No non-missing concentration at the end of the infusion"), info="Ceoi returns NA if there is no measurement at the end of the dosing duration") expect_equal(pk.calc.ceoi(conc=0:5, time=0:5, duration.dose=NA), - structure(NA_real_, exclude = "Dose duration is missing"), + structure(NA_real_, exclude = "Dose duration is missing (or there is no dose in the interval)"), info="Ceoi returns NA if there is no dosing duration") }) @@ -1089,48 +1089,92 @@ test_that("a simple parameter that is NA because of missing or unusable data say expect_equal(infusion$exclude, "No non-missing concentration at the end of the infusion") }) -test_that("every parameter calculated by a simple function gives a reason with each NA in pk.nca()", { - simple_functions <- c( - "pk.calc.cmax", "pk.calc.cmin", "pk.calc.tmax", "pk.calc.tmin", "pk.calc.tlast", - "pk.calc.tfirst", "pk.calc.clast.obs", "pk.calc.thalf.eff", "pk.calc.aucpext", - "pk.calc.kel", "pk.calc.cl", "pk.calc.mrt", "pk.calc.mrt.iv", "pk.calc.mrt.md", - "pk.calc.mrt.md.iv", "pk.calc.vz", "pk.calc.vss", "pk.calc.cav", "pk.calc.ctrough", - "pk.calc.cstart", "pk.calc.ptr", "pk.calc.tlag", "pk.calc.deg.fluc", "pk.calc.swing", - "pk.calc.ceoi", "pk.calc.aucabove", "pk.calc.count_conc", "pk.calc.count_conc_measured", - "pk.calc.totdose", "pk.calc.dn" - ) +test_that("every registered parameter gives a reason with each NA in pk.nca()", { all_intervals <- get.interval.cols() parameters <- - names(all_intervals)[vapply(all_intervals, function(x) isTRUE(x$FUN %in% simple_functions), logical(1))] - # Every simple function except pk.calc.f() (which needs a reference interval) - # is registered for at least one parameter - expect_setequal( - unique(vapply(all_intervals[parameters], function(x) x$FUN, character(1))), - simple_functions - ) - profiles <- list( - all_missing = rep(NA_real_, 6), - all_zero = rep(0, 6), - missing_ends = c(NA, 5, 8, 6, 3, NA) - ) + names(all_intervals)[vapply(all_intervals, function(x) !is.null(x$FUN) && !is.na(x$FUN), logical(1))] + # Parameters these fixtures cannot calculate: they need a urine collection + # (volume), a reference interval, or a concentration threshold + not_exercised <- c( + "ae", "fe", "volpk", "ertlst", "ermax", "ertmax", "erint", "erlst", + grep("^clr[.]", parameters, value = TRUE), + grep("^(f|ratio)[.]", parameters, value = TRUE), + "time.above", "time_above" + ) + expect_true(all(not_exercised %in% parameters)) + parameters <- setdiff(parameters, not_exercised) + # Known to give NA without a reason in these fixtures, from the IV + # back-extrapolation functions (and cl.iv.* calculated from them). When they + # gain reasons, this test fails until they are removed from the list. + known_without_reason <- c( + "aucivinf.obs", "aucivinf.pred", "aumcivinf.obs", "aumcivinf.pred", + "cl.iv.inf.obs", "cl.iv.inf.pred", "cl.iv.obs", "cl.iv.pred", + "aucivpbext.last", "aucivpbext.all", "aucivpbext.inf.obs", "aucivpbext.inf.pred", + "aucivpbext.int.last", "aucivpbext.int.all", + "aucivpbextlast", "aucivpbextall", "aucivpbextinf.obs", "aucivpbextinf.pred", + "aucivpbextint.last", "aucivpbextint.all" + ) + fixtures <- list( + all_missing = list(conc = rep(NA_real_, 6), dose = 100), + all_zero = list(conc = rep(0, 6), dose = 100), + missing_ends = list(conc = c(NA, 5, 8, 6, 3, NA), dose = 100), + one_measured = list(conc = c(0, 0, 5, 0, 0, 0), dose = 100), + dose_zero = list(conc = c(0, 5, 8, 6, 3, 1), dose = 0), + dose_missing = list(conc = c(0, 5, 8, 6, 3, 1), dose = NA) + ) + found_without_reason <- character(0) for (current_route in c("extravascular", "intravascular")) { - for (current_profile in names(profiles)) { + for (current_fixture in names(fixtures)) { for (current_conc_na in list("drop", 0)) { + current_info <- paste(current_route, current_fixture, current_conc_na) res <- simple_reason_results( - conc = profiles[[current_profile]], parameters = parameters, + conc = fixtures[[current_fixture]]$conc, parameters = parameters, + dose = fixtures[[current_fixture]]$dose, duration = if (current_route == "intravascular") 1.5 else 0, route = current_route, conc.na = current_conc_na ) - no_reason <- res$PPTESTCD[is.na(res$PPORRES) & is.na(res$exclude)] - expect_equal( - no_reason, character(0), - info = paste(current_route, current_profile, current_conc_na) - ) + # The fixture calculates and has NA results to check + expect_gt(nrow(res), 0) + expect_true(any(is.na(res$PPORRES)), info = current_info) + no_reason <- unique(res$PPTESTCD[is.na(res$PPORRES) & is.na(res$exclude)]) + expect_equal(setdiff(no_reason, known_without_reason), character(0), info = current_info) + found_without_reason <- union(found_without_reason, no_reason) } } } - res_dose_missing <- - simple_reason_results(conc = c(0, 5, 8, 6, 3, 1), parameters = parameters, dose = NA) - expect_equal(res_dose_missing$PPTESTCD[is.na(res_dose_missing$PPORRES) & is.na(res_dose_missing$exclude)], character(0)) + expect_setequal(found_without_reason, known_without_reason) +}) + +test_that("a reason is given with a single value only, never beside a valid value", { + # One value: the reason is given + # A zero aucinf warns as well + aucpext_classes <- c("pknca_warning_aucpext_aucinf_le_auclast", "pknca_warning_aucpext_aucinf_auclast_positive") + expect_equal( + suppressWarnings(pk.calc.aucpext(1, 0), classes = aucpext_classes), + structure(NA_real_, exclude = "AUCinf is zero") + ) + expect_equal(pk.calc.cav(10, 5, 5), structure(NA_real_, exclude = "The interval has zero duration")) + expect_equal(pk.calc.dn(1, NA), structure(NA_real_, exclude = "Dose is missing")) + # Several values with one NA among them: no attribute + expect_equal( + suppressWarnings(pk.calc.aucpext(c(1, 1), c(2, 0)), classes = aucpext_classes), + c(50, NA_real_) + ) + expect_equal(pk.calc.cav(10, c(0, 5), 5), c(2, NA_real_)) + expect_equal(pk.calc.dn(c(1, 2), c(1, NA)), c(1, NA_real_)) + expect_equal(pk.calc.ptr(c(2, 2), c(1, 0)), c(2, NA_real_)) + expect_equal(pk.calc.deg.fluc(cmax = c(100, 100), cmin = 10, cav = c(45, 0)), c(200, NA_real_)) + expect_equal(pk.calc.f(c(1, 0), 1, 1, 1), c(1, NA_real_)) + expect_equal(pk.calc.totdose(c(1, 2)), 3) +}) + +test_that("a dose-normalized zero over a zero dose stays NaN and says why", { + expect_equal(pk.calc.dn(0, 0), structure(NaN, exclude = "Dose is zero")) + # A nonzero value over a zero dose is infinite, as before, with no reason + expect_identical(pk.calc.dn(1, 0), Inf) +}) + +test_that("ctrough for an interval with no finite end says so", { + expect_equal(pk.calc.ctrough(1:5, 0:4, Inf), structure(NA_real_, exclude = "The interval has no finite end")) }) From eccaa534e66a260e4ba0f33fc4b83b688afd663d Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Thu, 19 Nov 2026 18:24:25 -0500 Subject: [PATCH 19/21] docs: NEWS lists the reason attribute as a breaking change and the reworded texts Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 64 ++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 48 insertions(+), 16 deletions(-) diff --git a/NEWS.md b/NEWS.md index b692a38f9..2cc1f77a6 100644 --- a/NEWS.md +++ b/NEWS.md @@ -8,6 +8,27 @@ the dosing including dose amount and route. ## Breaking changes +* A calculation function that returns `NA` because of missing or unusable data + now returns it with an `exclude` attribute that gives the reason, as the AUC + functions already did, so that `pk.nca()` reports why (@billdenney, #727). + The value is unchanged. The functions are `pk.calc.cmax()`, `pk.calc.cmin()`, + `pk.calc.tmax()`, `pk.calc.tmin()`, `pk.calc.tlast()`, `pk.calc.tfirst()`, + `pk.calc.clast.obs()`, `pk.calc.aucpext()`, `pk.calc.cl()`, `pk.calc.f()`, + `pk.calc.mrt()`, `pk.calc.mrt.iv()`, `pk.calc.mrt.md()`, + `pk.calc.mrt.md.iv()`, `pk.calc.cav()`, `pk.calc.ctrough()`, + `pk.calc.cstart()`, `pk.calc.ptr()`, `pk.calc.tlag()`, `pk.calc.deg.fluc()`, + `pk.calc.ceoi()`, `pk.calc.totdose()`, and `pk.calc.dn()`; the vectorised + ones give the attribute only for a result of length one. For a result `x` + such as `pk.calc.cmax(c(NA, NA))`: + * these now fail: `identical(x, NA)`, `isTRUE(all.equal(x, NA))`, + `expect_equal(x, NA)`, `expect_identical(x, NA)`, and + `expect_equal(x, NA_real_)`; + * the attribute is carried by `x * 2` and by `data.frame(a = x)$a`; + * `is.na()`, `ifelse()`, `c()`, `sapply()`, `sum()`, `max()`, and `paste()` + are unaffected; + * `as.numeric(x)` drops the attribute (giving `NA_real_`, where `cmax`, + `cmin`, `tmax`, `tmin`, `tlast`, and `tfirst` gave a logical `NA`). + * Parameter names and descriptions follow one style, so some column headers of `summary()` and some descriptions change (@billdenney): * Pretty names write lambda.z as math (`$\lambda_z$`), including "Number of @@ -1230,22 +1251,25 @@ the generated intervals: * A simple parameter that is `NA` because of missing or unusable data now says why in the `exclude` column of `pk.nca()` results, where the column was - empty (@billdenney, #727). No value changes; only the - `exclude` text of results that were already `NA`. The reasons, set by the - calculation functions as an `exclude` attribute on their `NA` return: + empty (@billdenney, #727). No value changes; only the `exclude` text of + results that were already `NA`. The reasons, which the calculation functions + return as an `exclude` attribute (see "Breaking changes"): - "All concentrations are missing": `cmax`, `cmin`, `tmax`, `tmin`, `tlast`, `tfirst`, `clast.obs`, `tlag`. - "No concentration is above zero": `tmax`, `tlast`, `tfirst`. - "Concentrations never increase": `tlag`. - "No non-missing concentration at the start of the interval": `cstart`; - "... at the end of the interval": `ctrough`; "... at the end of the - infusion": `ceoi`. "Dose duration is missing": `ceoi`. + "No non-missing concentration at the end of the interval" and "The + interval has no finite end": `ctrough`; "No non-missing concentration at + the end of the infusion" and "Dose duration is missing (or there is no + dose in the interval)": `ceoi`. - "AUC is zero or negative": `cl.*`, `mrt.*` (all forms), and the reference AUC of `f.*`; "AUCinf is zero": `aucpext.*`; "Cav is zero": `deg.fluc`; "Ctrough is zero": `ptr`. - "Dose is missing": `cl.*`, `f.*`, `totdose`, and the dose-normalized - parameters (`*.dn`); "Dose is zero or negative": `f.*`; "No dose in the - interval": `cl.*`, `totdose`, and `mrt.iv.*` and `mrt.ivmd.*`. + parameters (`*.dn`); "Dose is zero": `*.dn` when the parameter is also + zero (the value stays `NaN`); "Dose is zero or negative": `f.*`; "No dose + in the interval": `cl.*`, `totdose`, `mrt.iv.*`, and `mrt.ivmd.*`. - "A dose time or duration is missing", or "A dose amount is missing, or the doses sum to zero" (when several doses are weighted): `mrt.iv.*` and `mrt.ivmd.*`; "The dosing interval (tau) is not known": `mrt.md.*` and @@ -1254,15 +1278,23 @@ the generated intervals: `cav.*`. Everything calculated from one of these carries its reason, as for any - other reason (for example `swing`, `vss.*`, `vz.*`, `kel.*`, `thalf.eff.*`), - and a reason given by more than one input is now listed once (for example - `swing` of an all-missing interval, from both `cmax` and `cmin`). What - changes for code reading the results: `summary()` gives the same numbers - (it ignores an `NA` either way); `as.data.frame(filter_excluded = TRUE)` - now leaves out these `NA` rows, as it leaves out any row with a reason; and - `exclude()` adds its reason after the one already there. A direct call such - as `pk.calc.cmax(c(NA, NA))` still returns `NA`, now with the `exclude` - attribute, so `is.na()` is unchanged but `identical(x, NA)` is `FALSE`. + other reason (for example `swing`, `vss.*`, `vz.*`, `kel.*`, `thalf.eff.*`). + What changes for code reading the results: `summary()` gives the same + numbers (it ignores an `NA` either way); `as.data.frame(filter_excluded = + TRUE)` now leaves out these `NA` rows, as it leaves out any row with a + reason; and `exclude()` adds its reason after the one already there. + +* The `exclude` text of a result that already had a reason now starts with the + root cause and lists each reason once (@billdenney, #727). For example, + the half-life results of an interval with every concentration missing read + "All concentrations are missing; Too few points for half-life calculation + (min.hl.points=3 with only 0 points)" instead of starting at "Too few + points"; `aucabove.trough.all` with no concentration at the end of the + interval reads "No non-missing concentration at the end of the interval; + Missing concentration to be above"; and a reason that reached a result from + two inputs ("X; X") is given once ("X"). Code that matches a reason by its + exact text must be updated. The values, and which results have a reason, + are unchanged. * `mrt.iv.*`, `mrt.ivint.*`, `mrt.ivmd.*`, and everything calculated from them (`vss.iv.*`, `vss.ivint.*`, `vss.ivmd.*`, `kel.iv.*`, `thalf.eff.iv.*`) are From 60689400b693f2023559dc245498d230e7abd602 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Fri, 20 Nov 2026 08:01:29 -0500 Subject: [PATCH 20/21] fix: pk.calc.swing() gives one value for each pair of cmax and cmin The missing-value fix on this branch tested the inputs with `||`, so a vector of cmax with one cmin, which gave one swing per cmax in the released version (`pk.calc.swing(cmax = c(10, 20), cmin = 1)` is 900 and 1900), stopped with "'length = 2' in coercion to 'logical(1)'". The function is now vectorized, as its sibling pk.calc.ptr() is: every value the released version returned is returned again, except that a vector of cmax with a cmin of zero or below gives one Inf for each cmax where it gave a single Inf. A missing cmin or cmax is still NA. Found by the review of the input-check branch; Bill's ruling of 2026-11-20: calls that returned a value keep working, and vectorized functions are preferred where the values need no consolidation. Co-Authored-By: Claude Fable 5.2 --- NEWS.md | 5 ++++- R/pk.calc.simple.R | 17 ++++++++--------- man/pk.calc.deg.fluc.Rd | 5 +++-- tests/testthat/test-pk.calc.simple.R | 8 ++++++++ 4 files changed, 23 insertions(+), 12 deletions(-) diff --git a/NEWS.md b/NEWS.md index 2cc1f77a6..21b82b658 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1247,7 +1247,10 @@ the generated intervals: @kawasakin, #723; @billdenney, #727). In `pk.nca()`, an interval whose concentrations are all missing stopped with "Please report a bug" when `swing` was requested, which stopped the calculation for every subject, and - now gives `NA` for that interval. + now gives `NA` for that interval. `pk.calc.swing()` gives one value for + each pair of `cmax` and `cmin`; a vector of `cmax` with one `cmin` gives the + values it gave before, except that with a `cmin` of zero or below the result + is one `Inf` for each `cmax` (before, a single `Inf`). * A simple parameter that is `NA` because of missing or unusable data now says why in the `exclude` column of `pk.nca()` results, where the column was diff --git a/R/pk.calc.simple.R b/R/pk.calc.simple.R index 07d02b45b..b8a00c813 100644 --- a/R/pk.calc.simple.R +++ b/R/pk.calc.simple.R @@ -2509,17 +2509,16 @@ add.interval.col("deg.fluc", #' #' @details swing is `100*(cmax - cmin)/cmin`. #' -#' @returns The swing above the minimum concentration. If `cmin` is zero, then -#' the result is infinity; if `cmin` or `cmax` is missing, it is `NA`. +#' @returns The swing above the minimum concentration, one value for each pair +#' of `cmax` and `cmin`. If `cmin` is zero, then the result is infinity; if +#' `cmin` or `cmax` is missing, it is `NA`. #' @export pk.calc.swing <- function(cmax, cmin) { - if (is.na(cmin) || is.na(cmax)) { - NA_real_ - } else if (cmin > 0) { - 100*(cmax - cmin)/cmin - } else { - Inf - } + ret <- 100*(cmax - cmin)/cmin + # A cmin at or below zero gives infinity, also where the division does not + # (a cmax of zero, or a negative cmin) + ret[!is.na(cmax) & !is.na(cmin) & cmin <= 0] <- Inf + ret } pknca_concept(pk.calc.swing) <- "fluctuation" diff --git a/man/pk.calc.deg.fluc.Rd b/man/pk.calc.deg.fluc.Rd index 20fe33c87..1f8bbb6af 100644 --- a/man/pk.calc.deg.fluc.Rd +++ b/man/pk.calc.deg.fluc.Rd @@ -21,8 +21,9 @@ The degree of fluctuation around the average concentration. A result of length one that is \code{NA} because of missing or unusable data has the reason in its "exclude" attribute, which \code{\link[=pk.nca]{pk.nca()}} reports. -The swing above the minimum concentration. If \code{cmin} is zero, then -the result is infinity; if \code{cmin} or \code{cmax} is missing, it is \code{NA}. +The swing above the minimum concentration, one value for each pair +of \code{cmax} and \code{cmin}. If \code{cmin} is zero, then the result is infinity; if +\code{cmin} or \code{cmax} is missing, it is \code{NA}. } \description{ Determine the degree of fluctuation diff --git a/tests/testthat/test-pk.calc.simple.R b/tests/testthat/test-pk.calc.simple.R index b4b5462f9..684c871bd 100644 --- a/tests/testthat/test-pk.calc.simple.R +++ b/tests/testthat/test-pk.calc.simple.R @@ -777,6 +777,14 @@ test_that("pk.calc.swing", { info="Swing handle Ctrough=0") expect_equal(pk.calc.swing(100, -1), Inf, info="Swing handle Ctrough<0") + expect_identical(pk.calc.swing(0, 0), Inf) + # One value for each pair, as the released version gave for a vector of cmax + expect_identical(pk.calc.swing(cmax = c(10, 20), cmin = 1), c(900, 1900)) + expect_identical(pk.calc.swing(cmax = numeric(0), cmin = 1), numeric(0)) + expect_identical( + pk.calc.swing(cmax = c(10, 20, NA, 5, 5, 0), cmin = c(1, 4, 1, NA, 0, 0)), + c(900, 400, NA, NA, Inf, Inf) + ) }) test_that("pk.calc.ceoi", { From a8cc14ebcc33a26b887cd718571961f443878bbe Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Sat, 21 Nov 2026 17:29:14 -0500 Subject: [PATCH 21/21] test: a missing start gives aucabove.predose.all cstart's reason first With PR 730's numeric conc.na, the start row's concentration is missing, so cstart is NA with "No non-missing concentration at the start of the interval", and aucabove.predose.all, which is above cstart, carries that root cause before its own reason, as this branch does for every result calculated from another (the aucabove.trough.all example in NEWS). Co-Authored-By: Claude Opus 5.5 --- tests/testthat/test-impute.R | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/testthat/test-impute.R b/tests/testthat/test-impute.R index 167bf00dc..9ab15e688 100644 --- a/tests/testthat/test-impute.R +++ b/tests/testthat/test-impute.R @@ -1601,7 +1601,13 @@ test_that("a numeric conc.na is the value of a missing start concentration, so t expect_equal(unname(res$value[c("count.conc", "cstart", "aucabove.predose.all")]), c(8, 0, 1836.33993274182), info = info) } else { expect_equal(unname(res$value[c("count.conc", "cstart", "aucabove.predose.all")]), c(7, NA, NA), info = info) - expect_equal(unname(res$exclude["aucabove.predose.all"]), "Missing concentration to be above", info = info) + # The predose concentration it is above is cstart, which is missing; + # its reason comes first, as for any result calculated from it + expect_equal( + unname(res$exclude["aucabove.predose.all"]), + "No non-missing concentration at the start of the interval; Missing concentration to be above", + info = info + ) } } }