Repository navigation
Add bivariate covariate pair outlier checks to gross cleaning - #5
JordanBrooks33 wants to merge 1 commit into
Conversation
Add covariate_pairs parameter supporting continuous-continuous (loess residual flagging) and categorical-continuous (within-group IQR) pair checks. Includes "all" shorthand to auto-generate pairs from covariate_cols and categorical_cols, scatter/boxplot plot panels, and a "reference" method stub for future CDC/WHO growth charts. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #5 +/- ##
======================================
Coverage 0.00% 0.00%
======================================
Files 11 11
Lines 2584 2907 +323
======================================
- Misses 2584 2907 +323 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
DT: had CC review and write this up. I did check that these things need doing.
Thanks for this — the feature is a useful addition and the tests pass locally (devtools::test(filter = "gross_cleaning")). I probed it with a simulated dataset (60 subjects, one planted outlier: subject 5, AGE = 5, WT = 150) and found two bugs that affect the usage example in the PR description, plus a few smaller items. Details are inline; summary:
Must fix
covariate_pairs = "all"regresses in whatever direction column order dictates (e.g. AGE ~ WT instead of WT ~ AGE), and misses the planted outlier.- A character/factor categorical column coerces
X_VALUEto character for all pairs afterrbind, breaking the continuous-pair plots.
Should fix
3. Plotted smoother (stat_smooth) is not the fit used for flagging.
4. LOWER_BOUND/UPPER_BOUND are on the residual scale for continuous pairs but the raw scale for grouped pairs, in the same column.
5. Grouped flagging runs with as few as 3 subjects per group (univariate check requires 8); groups below 3 are skipped silently.
Minor
@returndocs omitPAIR_TYPE, and describecovariate_pair_scatteras loess-fitted values (grouped pairs hold group means).- Local variable
sdshadowsstats::sd(imported by the package). - Pre-existing, not a regression: one-row-per-subject uses the first row, so a covariate that is NA on the dose row but populated later drops the subject. In my test with WT NA on dose rows, every subject was dropped and the pair skipped.
| ) | ||
| } | ||
| # Generate all 2-combinations, then drop categorical x categorical | ||
| combos <- utils::combn(all_cols, 2, simplify = FALSE) |
There was a problem hiding this comment.
[Must fix] "all" picks regression direction from column order.
combn(c("AGE","WT"), 2) yields c("AGE","WT"), and element 1 is treated as Y, so this fits AGE ~ WT — the reverse of the WT ~ AGE example in the docs/PR description. Because the residual check is one-directional, the direction matters:
# 60 subjects, subject 5 has AGE = 5, WT = 150
qc <- assess_data_quality(dat, covariate_cols = c("AGE","WT"),
covariate_pairs = "all", iqr_multiplier = 3)
# AGE ~ WT: subject 5 NOT flagged
qc <- assess_data_quality(dat, covariate_cols = c("AGE","WT"),
covariate_pairs = list(c("WT","AGE")), iqr_multiplier = 3)
# WT ~ AGE: subject 5 flagged, residual 130, bounds [-12.4, 12.2]Options: fit both directions for continuous pairs, use a symmetric criterion, or restrict "all" and document that explicit pairs are interpreted as Y ~ X.
| } | ||
|
|
||
| flagged_df <- if (length(flagged_all) > 0) do.call(rbind, flagged_all) else NULL | ||
| scatter_df <- if (length(scatter_all) > 0) do.call(rbind, scatter_all) else NULL |
There was a problem hiding this comment.
[Must fix] Mixed types in X_VALUE after rbind.
When a categorical column is character (e.g. SEX = "M"/"F") or factor, rbinding grouped and continuous results coerces X_VALUE to character for every row, including continuous pairs. Same for flagged_df (covariate_pair_outliers$X_VALUE).
Effect: the continuous-pair plot gets a discrete x-axis with one tick per value and the smoother disappears. All tests use numeric 0/1 SEX, so this isn't covered.
Suggest keeping X_VALUE numeric with a separate X_LEVEL character column for grouped pairs (or returning continuous and grouped results separately), plus a test with a character categorical.
| alpha = 0.4, | ||
| size = 1.5 | ||
| ) + | ||
| ggplot2::stat_smooth( |
There was a problem hiding this comment.
[Should fix] Plotted smoother differs from the flagging fit.
stat_smooth(method = "loess") refits with ggplot defaults (gaussian family, span 0.75), ignoring loess_span and family = "symmetric". A non-robust fit gets pulled toward outliers, so the drawn line can disagree with which points are red. Suggest drawing the stored PREDICTED values (geom_line on data ordered by X_VALUE) instead.
| X_VALUE = out_sd[[cat_col]], | ||
| PREDICTED = group_means[as.character(g)], | ||
| RESIDUAL = out_sd[[cont_col]] - group_means[as.character(g)], | ||
| LOWER_BOUND = as.numeric(lo), |
There was a problem hiding this comment.
[Should fix] Bound columns have different meanings by pair type.
Here LOWER_BOUND/UPPER_BOUND are quantile bounds on the raw values, while PREDICTED/RESIDUAL are relative to the group mean. In .fit_loess_pair the bounds are on the residual scale. Both end up in the same columns of covariate_pair_outliers, so a reader comparing RESIDUAL to the bounds will get the wrong answer for grouped rows. Suggest making them consistent (e.g. bounds on residuals from group median) or naming them distinctly.
| for (g in groups) { | ||
| idx <- sd[[cat_col]] == g | ||
| vals <- sd[[cont_col]][idx] | ||
| if (sum(!is.na(vals)) < 3L) next # too few in group |
There was a problem hiding this comment.
[Should fix] Minimum group size.
Groups are screened with as few as 3 non-missing values; .flag_covariate_outliers requires 8 before computing IQR bounds. Quartiles from 3–7 values are unstable. Groups below the threshold are also skipped without a warning, so the user can't tell they weren't checked. Suggest aligning the threshold with the univariate check (or exposing it) and warning on skipped groups.
| iqr_mult, loess_span, min_subjects_pair) { | ||
| # Subset to complete cases for this pair | ||
| cc <- stats::complete.cases(subj_data[[y_col]], subj_data[[x_col]]) | ||
| sd <- subj_data[cc, , drop = FALSE] |
There was a problem hiding this comment.
[Minor] sd shadows stats::sd, which the package imports (same at L1042). Not a bug today, but easy to trip on later — suggest renaming (e.g. pair_df).
| #' bivariate covariate checks, or \code{NULL} if none detected / not | ||
| #' requested. Columns: ID, Y_COL, X_COL, Y_VALUE, X_VALUE, PREDICTED, | ||
| #' RESIDUAL, LOWER_BOUND, UPPER_BOUND.} | ||
| #' \item{covariate_pair_scatter}{Data frame of per-subject loess-fitted |
There was a problem hiding this comment.
[Minor] Docs. The column list for covariate_pair_outliers (L90–92) omits PAIR_TYPE, and covariate_pair_scatter is described as loess-fitted values, but for grouped pairs PREDICTED holds group means. Remember to re-run devtools::document() after updating.
| all_cov_cols <- unique(unlist(covariate_pairs)) | ||
| present_cols <- intersect(all_cov_cols, names(data)) | ||
| keep_cols <- unique(c(id_col, present_cols)) | ||
| subj_data <- data[!duplicated(data[[id_col]]), keep_cols, drop = FALSE] |
There was a problem hiding this comment.
[Minor / pre-existing] Taking the first row per subject (same approach as .flag_covariate_outliers) drops subjects whose covariate is NA on that row but populated later, e.g. NA on dose records. In my test with WT set to NA on dose rows, 0 subjects remained and the pair was skipped with a warning. Not introduced by this PR, but worth considering taking the first non-missing value per subject per column.
|
Reprex for the two Must fix items in the review above (run from the repo root with devtools::load_all(".", quiet = TRUE) # on branch RXR-3352
# 60 subjects, WT ~ linear in AGE, one planted outlier (ID 5: AGE 5, WT 150)
set.seed(1)
n <- 60
subj <- data.frame(
ID = 1:n,
AGE = round(runif(n, 2, 18)),
SEX = sample(c("M", "F"), n, replace = TRUE)
)
subj$WT <- 5 + 3 * subj$AGE + rnorm(n, 0, 3)
subj$WT[5] <- 150
rec <- data.frame(
ID = rep(1:n, each = 3), TIME = rep(0:2, n), DV = rep(c(NA, 10, 5), n),
EVID = rep(c(1, 0, 0), n), MDV = rep(c(1, 0, 0), n), AMT = rep(c(100, 0, 0), n)
)
dat <- merge(rec, subj, by = "ID")
# --- Bug 1: "all" fits AGE ~ WT and misses ID 5 -------------------------------
qc_all <- suppressMessages(assess_data_quality(
dat, covariate_cols = c("AGE", "WT"),
covariate_pairs = "all", iqr_multiplier = 3, verbose = FALSE
))
qc_all$covariate_pairs
#> [[1]]
#> [1] "AGE" "WT"
qc_all$covariate_pair_outliers
#> NULL
# Same data, explicit WT ~ AGE: ID 5 is flagged
qc_exp <- suppressMessages(assess_data_quality(
dat, covariate_cols = c("AGE", "WT"),
covariate_pairs = list(c("WT", "AGE")), iqr_multiplier = 3, verbose = FALSE
))
qc_exp$covariate_pair_outliers[, c("ID", "Y_COL", "X_COL", "RESIDUAL", "LOWER_BOUND", "UPPER_BOUND")]
#> ID Y_COL X_COL RESIDUAL LOWER_BOUND UPPER_BOUND
#> 1 5 WT AGE 129.9683 -12.38199 12.23471
# --- Bug 2: character categorical coerces X_VALUE for continuous pairs --------
qc_chr <- suppressMessages(assess_data_quality(
dat, covariate_cols = c("AGE", "WT"), categorical_cols = "SEX",
covariate_pairs = list(c("WT", "AGE"), c("WT", "SEX")),
iqr_multiplier = 3, verbose = FALSE
))
sc <- qc_chr$covariate_pair_scatter
class(sc$X_VALUE)
#> [1] "character"
head(sc$X_VALUE[sc$X_COL == "AGE"])
#> [1] "6" "8" "11" "17" "5" "16"
# plot(qc_chr)$pair_WT_AGE -> discrete x-axis, smoother fails to drawCreated on 2026-11-25 with reprex v2.1.1 |
Summary
covariate_pairsparameter toassess_data_quality()for bivariate covariate outlier detectioncovariate_pairs = "all"shorthand auto-generates all valid pairs fromcovariate_colsandcategorical_cols(skips cat x cat)pair_method = "reference"stub for future CDC/WHO growth chart supportUsage
Test plan
devtools::test(filter = "gross_cleaning")-- 66 tests passdevtools::check()-- 0 errors, 0 notesbusulfan_simdataset🤖 Generated with Claude Code