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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Package: irxforge
Title: Forging data for pharmacometric analyses
Version: 0.0.0.9049
Version: 0.0.0.9052
Authors@R: c(
person("Ron", "Keizer", email = "ron@insight-rx.com", role = c("cre", "aut")),
person("Michael", "McCarthy", email = "michael.mccarthy@insight-rx.com", role = "ctb"),
Expand Down
17 changes: 17 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
# irxforge (development version)

* `anonymize_dataset()`: a numeric covariate with exactly two distinct values
(e.g. a 0/1 flag), however few records carry it, that is not listed in
`cat_covs` is no longer resampled as continuous, which could silently drop
one of its levels. With `method = "mice"` it is now treated as categorical
(with a message naming it); with `"lme"` or `"copulas"` it is rejected with
an error naming it. After resampling, the record-level share of each level
of every discrete covariate (categorical covariates, two-level numeric
covariates, and whole-number covariates with at most 3 distinct values) is
compared with the source, and a warning (`irxforge_anonymize_level_warning`)
lists covariates where a source level is absent from the output (including
an all-missing output), values absent from the source appear, or a level's
share changes more than 3-fold. The check runs on the returned dataset,
after below-LOQ records are removed (with `loq` and
`blq_method = "remove"`) and after `sigdig` rounding, which no longer
applies to categorical covariates
(so numeric codes such as `10000` and `10001` are not merged) (#46).

* `anonymize_dataset()`: a covariate that the model references under a spelling
that differs only by case from its data column (e.g. `CONC0` for a `conc0`
column) is now bridged with an added `[data]` rename (`CONC0 = conc0`) in the
Expand Down
169 changes: 167 additions & 2 deletions R/anonymize_dataset.R
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@
#' returned with their original numeric codes. With `method = "mice"`, a
#' warning is raised for numeric covariates that look like categorical codes
#' (whole numbers with at most 3 distinct values) but are not listed here.
#' A numeric covariate with exactly two distinct values (e.g. a 0/1 flag)
#' has no continuous
#' distribution to preserve and could lose a level if resampled as
#' continuous: with `method = "mice"` it is treated as categorical (with a
#' message) even when not listed here, and with `"lme"` or `"copulas"` it is
#' rejected with an error naming it. After resampling, the level shares of
#' each discrete covariate (categorical covariates, and covariates with at
#' least 10 whole-number values and at most 3 distinct values) in the
#' returned dataset (after `sigdig` rounding and below-`loq` removal) are
#' compared, record by record, with the source, and a warning is raised when
#' a source level is absent from the output, values absent from the source
#' appear, or a level's share changes more than 3-fold.
#' Categorical covariates (including factor and character columns) with
#' more than 20 distinct values are rejected with an error reporting the
#' level count of each categorical covariate: such a column is almost always
Expand All @@ -68,7 +80,8 @@
#' @param sigdig number of significant digits to round the sampled covariates
#' and simulated concentrations (`DV`) to, via [signif()], to further obscure
#' the values. Default `4`. `NULL` disables rounding. Rounding is applied
#' before the `loq` comparison.
#' before the `loq` comparison. Categorical covariates (see `cat_covs`) are
#' never rounded, so distinct numeric codes are not merged.
#' @param n_candidates number of independent candidates to draw and score against
#' the observed data, keeping the closest match. Default `1` (no scoring; a
#' single candidate is used). When greater than 1, the candidate with the
Expand Down Expand Up @@ -219,6 +232,30 @@ anonymize_dataset <- function(
is.factor(x) || is.character(x)
}, logical(1))
])
# a numeric covariate with exactly two distinct values (e.g. a 0/1 flag) has
# no continuous distribution to preserve: resampling it as continuous can
# silently drop one of its levels, so treat it as categorical (MICE) or
# refuse it (LME / copulas, which support only continuous covariates)
binary_covs <- find_anonymize_binary_covariates(sample_data, covariates, cat_covs)
if (length(binary_covs) > 0) {
if (method != "mice") {
stop(
"`method = \"", method, "\"` supports only continuous covariates, but ",
"these numeric covariates take exactly two distinct values and cannot ",
"be resampled as continuous: ",
paste0("`", binary_covs, "`", collapse = ", "),
". Use `method = \"mice\"` (they are then sampled as categorical), or ",
"remove them from `covariates`.",
call. = FALSE
)
}
message(
"Treating two-level numeric covariate(s) as categorical: ",
paste0("`", binary_covs, "`", collapse = ", "),
". Add them to `cat_covs` to silence this message."
)
cat_covs <- union(cat_covs, binary_covs)
}
if (method != "mice" && length(cat_covs) > 0) {
stop(
"`method = \"", method, "\"` supports only continuous covariates, but these ",
Expand Down Expand Up @@ -254,9 +291,11 @@ anonymize_dataset <- function(
...
)

# categorical codes are labels, not measurements: rounding them could merge
# distinct levels (e.g. 10000 and 10001 with `sigdig = 4`)
anonymized <- apply_anonymize_sigdig(
data = selected$data,
covariates = covariates,
covariates = setdiff(covariates, cat_covs),
sigdig = sigdig
)
result <- apply_anonymize_blq(
Expand All @@ -265,6 +304,15 @@ anonymize_dataset <- function(
blq_method = blq_method
)
result <- recompute_anonymized_mdv(result)
# compare the level set and level shares of discrete covariates between the
# source and the returned data (after rounding and below-LOQ removal), so a
# lost or collapsed level is reported instead of silently changing the design
check_anonymize_covariate_levels(
source = data,
resampled = result,
covariates = covariates,
cat_covs = cat_covs
)
attr(result, "design_map") <- attr(selected$data, "design_map")
attr(result, "similarity_score") <- selected$score
result
Expand Down Expand Up @@ -345,6 +393,123 @@ check_anonymize_dots <- function(dot_names, n_dots, method) {
invisible(NULL)
}

#' Find numeric covariates that take exactly two distinct values
#'
#' Such a column (typically a 0/1 flag) has no continuous distribution to
#' preserve, regardless of how many records carry it.
#'
#' @param data data.frame holding the covariates.
#' @param covariates names of the covariates to check.
#' @param cat_covs names of the covariates already treated as categorical.
#' @returns character vector of the two-level numeric covariates not in
#' `cat_covs`.
#'
#' @noRd
find_anonymize_binary_covariates <- function(data, covariates, cat_covs = NULL) {
covs <- setdiff(covariates, cat_covs)
covs[vapply(covs, function(cov) {
x <- data[[cov]]
if (!is.numeric(x)) return(FALSE)
length(unique(x[!is.na(x)])) == 2
}, logical(1))]
}

#' Warn when anonymization loses or distorts a level of a discrete covariate
#'
#' For every discrete covariate (the categorical covariates, numeric
#' covariates with exactly two distinct source values, and numeric covariates
#' with at least 10 non-missing source values, all whole numbers with at most
#' 3 distinct values), compares the record-level share of each level in `source` with
#' that in `resampled`. A single warning lists every covariate where a level
#' present in the source is absent from the resampled data, where values absent
#' from the source appear, or where a level's share changes by more than
#' `max_ratio`-fold.
#'
#' @param source the original data.
#' @param resampled the returned anonymized data (after rounding and BLQ
#' handling).
#' @param covariates names of the resampled covariates.
#' @param cat_covs names of the categorical covariates.
#' @param max_ratio largest accepted fold change of a level's share.
#' @returns a character vector with one problem description per affected
#' covariate, invisibly.
#'
#' @noRd
check_anonymize_covariate_levels <- function(source, resampled, covariates,
cat_covs = NULL, max_ratio = 3) {
covs <- intersect(covariates, names(resampled))
discrete <- covs[vapply(covs, function(cov) {
if (cov %in% cat_covs) return(TRUE)
x <- source[[cov]]
if (!is.numeric(x)) return(FALSE)
x <- x[!is.na(x)]
ux <- unique(x)
length(ux) == 2 ||
(length(x) >= 10 && length(ux) == 3 && all(ux == round(ux)))
}, logical(1))]
level_shares <- function(x) {
x <- as.character(x[!is.na(x)])
if (length(x) == 0) return(numeric(0))
tab <- table(x)
stats::setNames(as.numeric(tab) / length(x), names(tab))
}
fmt <- function(p) formatC(p, digits = 3, format = "f")
problems <- character(0)
for (cov in discrete) {
src <- level_shares(source[[cov]])
out <- level_shares(resampled[[cov]])
# nothing to preserve when the source has no values; an all-missing output
# loses every source level and is reported as such below
if (length(src) == 0) next
issues <- character(0)
lost <- setdiff(names(src), names(out))
if (length(lost) > 0) {
issues <- c(issues, paste0(
"level(s) ", paste0("`", lost, "`", collapse = ", "),
" (source share ", paste(fmt(src[lost]), collapse = ", "),
") absent from the output"
))
}
new <- setdiff(names(out), names(src))
if (length(new) > 0) {
shown <- utils::head(new, 5)
issues <- c(issues, paste0(
length(new), " value(s) absent from the source (e.g. ",
paste0("`", shown, "`", collapse = ", "), ")"
))
}
common <- intersect(names(src), names(out))
ratio <- out[common] / src[common]
shifted <- common[ratio > max_ratio | ratio < 1 / max_ratio]
if (length(shifted) > 0) {
issues <- c(issues, paste0(
"share of level(s) ",
paste0("`", shifted, "` ", fmt(src[shifted]), " -> ", fmt(out[shifted]),
collapse = ", ")
))
}
if (length(issues) > 0) {
problems <- c(problems, paste0("`", cov, "`: ", paste(issues, collapse = "; ")))
}
}
if (length(problems) > 0) {
warning(warningCondition(
paste0(
"Anonymization changed the level distribution of discrete covariate(s) ",
"(record-level shares, source -> output):\n",
paste0(" * ", problems, collapse = "\n"),
"\nThe anonymized dataset may not reflect the source design. Declare ",
"categorical codes in `cat_covs`, or pass study-design columns that ",
"must not be resampled in `design_cols`. With `loq`, removing ",
"below-LOQ records (`blq_method = \"remove\"`) can also drop levels; ",
"`blq_method = \"cens\"` keeps them."
),
class = "irxforge_anonymize_level_warning"
))
}
invisible(problems)
}

#' Draw one time-varying covariate candidate with the chosen sampler
#'
#' Dispatches to the MICE, LME or copula time-varying sampler, in all cases
Expand Down
15 changes: 14 additions & 1 deletion man/anonymize_dataset.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading