Skip to content

Add bivariate covariate pair outlier checks to gross cleaning - #5

Open
JordanBrooks33 wants to merge 1 commit into
mainfrom
RXR-3352
Open

JordanBrooks33 wants to merge 1 commit into
mainfrom
RXR-3352

Conversation

@JordanBrooks33

Copy link
Copy Markdown
Collaborator

Summary

  • Adds covariate_pairs parameter to assess_data_quality() for bivariate covariate outlier detection
  • Continuous x continuous pairs (e.g., WT ~ AGE): robust loess residual + IQR flagging
  • Categorical x continuous pairs (e.g., SEX ~ WT): within-group IQR flagging
  • covariate_pairs = "all" shorthand auto-generates all valid pairs from covariate_cols and categorical_cols (skips cat x cat)
  • pair_method = "reference" stub for future CDC/WHO growth chart support
  • Plot method produces scatter + loess panels for continuous pairs, boxplot + jitter for grouped pairs
  • 25 new tests (66 total for gross_cleaning), all passing
  • R CMD check: 0 errors, 0 notes (2 pre-existing vignette warnings)

Usage

qc <- assess_data_quality(
  dat,
  covariate_cols   = c("AGE", "WT", "HT"),
  categorical_cols = "SEX",
  covariate_pairs  = "all",
  iqr_multiplier   = 3
)
print(qc)
plot(qc)

Test plan

  • devtools::test(filter = "gross_cleaning") -- 66 tests pass
  • devtools::check() -- 0 errors, 0 notes
  • Manual smoke test with busulfan_sim dataset
  • Review plot output for continuous and grouped pair panels

🤖 Generated with Claude Code

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-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 323 lines in your changes missing coverage. Please review.
✅ Project coverage is 0.00%. Comparing base (515e6a5) to head (9b05d9a).

Files with missing lines Patch % Lines
R/gross_cleaning.R 0.00% 323 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dominic-irx dominic-irx left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. covariate_pairs = "all" regresses in whatever direction column order dictates (e.g. AGE ~ WT instead of WT ~ AGE), and misses the planted outlier.
  2. A character/factor categorical column coerces X_VALUE to character for all pairs after rbind, 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

  • @return docs omit PAIR_TYPE, and describe covariate_pair_scatter as loess-fitted values (grouped pairs hold group means).
  • Local variable sd shadows stats::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.

Comment thread R/gross_cleaning.R
)
}
# Generate all 2-combinations, then drop categorical x categorical
combos <- utils::combn(all_cols, 2, simplify = FALSE)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread R/gross_cleaning.R
}

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread R/gross_cleaning.R
alpha = 0.4,
size = 1.5
) +
ggplot2::stat_smooth(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread R/gross_cleaning.R
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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread R/gross_cleaning.R
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread R/gross_cleaning.R
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]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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).

Comment thread R/gross_cleaning.R
#' 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread R/gross_cleaning.R
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]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@dominic-irx

Copy link
Copy Markdown

Reprex for the two Must fix items in the review above (run from the repo root with RXR-3352 checked out; ggplot not rendered here).

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 draw

Created on 2026-11-25 with reprex v2.1.1

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants