From f73cde60ce2ac04c4693da1549d64ec30c4a24e3 Mon Sep 17 00:00:00 2001 From: MadDERt <2129882365@qq.com> Date: Wed, 28 Oct 2026 16:23:03 +0800 Subject: [PATCH 1/3] feat: add faers_restrict and .role_cod exposure restriction --- DESCRIPTION | 1 + NAMESPACE | 1 + NEWS.md | 19 ++ R/restrict.R | 353 +++++++++++++++++++++++++++++++ R/scan-db.R | 35 ++- R/scan-strata-db.R | 13 +- R/scan-strata.R | 26 ++- R/scan.R | 30 ++- man/faers_phv_scan.Rd | 10 + man/faers_phv_scan_stratified.Rd | 8 + man/faers_restrict.Rd | 98 +++++++++ tests/testthat/test_restrict.R | 233 ++++++++++++++++++++ tests/testthat/test_scan.R | 74 +++++++ 13 files changed, 883 insertions(+), 18 deletions(-) create mode 100644 R/restrict.R create mode 100644 man/faers_restrict.Rd create mode 100644 tests/testthat/test_restrict.R diff --git a/DESCRIPTION b/DESCRIPTION index 09d06ba..c887e86 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -74,6 +74,7 @@ Collate: 'period.R' 'phv_.R' 'phv_ebgm.R' + 'restrict.R' 'rxnorm.R' 'sample.R' 'scan-db.R' diff --git a/NAMESPACE b/NAMESPACE index 1b77aa4..927e391 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -31,6 +31,7 @@ export(faers_phv_signal_composite) export(faers_phv_table) export(faers_primaryid) export(faers_quarter) +export(faers_restrict) export(faers_standardize) export(faers_year) export(fda_drugs) diff --git a/NEWS.md b/NEWS.md index 67dffa3..2324462 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,24 @@ # faers 1.5.6 +* Added `faers_restrict()`, a report-level restriction helper that narrows a + standardized FAERS object to a sub-population by reporting period + (`.period`), date window (`.date_range` on `.date_field`, with partial + dates like year-only `1999` excluded and counted by default, or kept with + `.date_partial = "keep"`), sex, age interval (on the standardized + `age_in_years`), age group and occurrence country. All enabled conditions + are intersected; excluded reports (including missing or unparseable values) + are counted per condition and reported in a single aggregated warning. The + implementation converges onto `primaryid` and reuses `faers_keep()`, so + both the memory and duckdb backends work and the + `@standardization` / `@deduplication` flags are preserved. + +* Added `.role_cod` to `faers_phv_scan()` and `faers_phv_scan_stratified()`: + restrict the exposure definition to specific drug role codes (`PS` primary + suspect, `SS` secondary suspect, `C` concomitant, `I` interacting) before + counting. `NULL` (default) keeps every role, matching previous behaviour; + the background `n` / `n_stratum` is unchanged either way. Implemented on + both backends (memory pre-filter and SQL `role_cod IN (...)` pushdown). + * Added `faers_phv_scan()`, a whole-database signal scanner that enumerates all drug x event pairs, builds a contingency table for every pair and runs the requested disproportionality methods in one vectorized pass. It ships diff --git a/R/restrict.R b/R/restrict.R new file mode 100644 index 0000000..56d3962 --- /dev/null +++ b/R/restrict.R @@ -0,0 +1,353 @@ +# Period / population restriction of FAERS objects. +# +# `faers_restrict()` narrows a standardized (and optionally de-duplicated) +# FAERS object to a sub-population defined by report-level conditions: +# reporting period, date window, sex, age range, age group and country. +# All conditions are combined by intersection: a report must satisfy every +# enabled condition to survive. The implementation converges every condition +# onto the demo table's `primaryid` and delegates the actual row filtering to +# `faers_keep()`, so both backends (in-memory data.tables and duckdb) are +# supported for free and the `@standardization` / `@deduplication` flags are +# preserved untouched. + +# Human-readable labels for the aggregated drop warning. +RESTRICT_LABELS <- c( + period = "period", + date_range = "date range", + sex = "sex", + age = "age range", + age_grp = "age group", + country = "country" +) + +#' Restrict a FAERS object to a sub-population +#' +#' @description `faers_restrict()` narrows a standardized FAERS object to +#' reports matching period, date-window and demographic conditions. All +#' enabled conditions are intersected: a report survives only if it satisfies +#' every one of them. Reports excluded by any enabled condition — including +#' those dropped because their value is missing or unparseable (e.g. partial +#' dates) — are counted per condition and reported in a single aggregated +#' warning, mirroring the package's philosophy of never silently truncating +#' data. +#' +#' @param .object A [FAERSascii] object. Should be standardized (and +#' de-duplicated for downstream signal scans). +#' @param .period Character vector of period keys, e.g. `c("2019q4", +#' "2020q1")`. Case-insensitive. `NULL` (default) keeps all periods present +#' in the object. +#' @param .date_range Length-2 vector `c(start, end)` of dates. Accepts +#' `Date` objects or strings in `YYYY-MM-DD` or `YYYYMMDD` form; both ends +#' are inclusive. `NULL` (default) applies no date window. +#' @param .date_field The demo date column to compare against `.date_range`. +#' `"fda_dt"` (FDA receipt date, essentially complete) is the default +#' because it is the most complete; `"event_dt"` and `"rept_dt"` are +#' available. Rows whose date is missing or partial (e.g. year-only `1999`) +#' cannot be placed in the window and are excluded (counted in the +#' aggregated warning) unless `.date_partial = "keep"`. +#' @param .sex Character vector of sexes to keep, e.g. `c("Female", "Male")`. +#' Valid values are `Female` and `Male`; unmatched non-NA values are an +#' error. Reports with missing sex are excluded whenever `.sex` is enabled. +#' @param .age Length-2 numeric `c(lower, upper)` closed interval on +#' `age_in_years` (the standardized age in years; all age codes are +#' converted during standardization). `NULL` applies no age filter. Reports +#' with missing age are excluded whenever `.age` is enabled. +#' @param .age_grp Character vector of age-group codes to keep. The recoded +#' `age_grp` column ("A" adult, "E" elderly, "I" infant, "N" neonate) is +#' missing for older quarters, so this filter is only reliable for recent +#' periods; missing values are excluded whenever enabled. `NULL` applies no +#' age-group filter. +#' @param .country Character vector of occurrence countries to keep +#' (`occr_country`). `NULL` applies no country filter; missing countries are +#' excluded whenever enabled. +#' @param .invert If `TRUE`, the semantics invert: reports matching **all** +#' enabled conditions are removed instead of kept. +#' @param .date_partial How to handle reports whose date cannot be parsed +#' (missing or partial dates like `1999` or `200301`) when a date window is +#' enabled: `"exclude"` (default) removes them and counts them in the +#' aggregated warning; `"keep"` retains them unfiltered. +#' +#' @return A [FAERSascii] object of the same backend (in-memory or duckdb) +#' with the same `@standardization` / `@deduplication` flags as the input, +#' restricted to reports satisfying all enabled conditions. The input +#' object is never modified. +#' @seealso [faers_keep()], [faers_filter()] +#' @examples +#' \donttest{ +#' # The bundled sample is already standardized. +#' data <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) +#' +#' # keep female reports aged 18-85 +#' sub <- faers_restrict(data, .sex = "Female", .age = c(18, 85)) +#' +#' # period keys +#' sub2 <- faers_restrict(data, .period = c("2004q1", "2017q2")) +#' +#' # date window on the FDA receipt date +#' sub3 <- faers_restrict(data, .date_range = c("2004-01-01", "2004-12-31")) +#' } +#' @export +faers_restrict <- function( + .object, .period = NULL, .date_range = NULL, + .date_field = c("fda_dt", "event_dt", "rept_dt"), .sex = NULL, + .age = NULL, .age_grp = NULL, .country = NULL, .invert = FALSE, + .date_partial = c("exclude", "keep")) { + .date_field <- match.arg(.date_field) + .date_partial <- match.arg(.date_partial) + .period <- restrict_check_period(.period) + .date_range <- restrict_check_dates(.date_range) + .sex <- restrict_check_values(.sex, c("Female", "Male"), ".sex") + .age <- restrict_check_age(.age) + .age_grp <- restrict_check_values( + .age_grp, c("A", "E", "I", "N"), ".age_grp" + ) + .country <- restrict_check_values_free(.country, ".country") + + demo <- faers_get(.object, "demo") + enabled <- restrict_enabled_conditions( + .period, .date_range, .sex, .age, .age_grp, .country + ) + if (!length(enabled)) { + cli::cli_warn( + "No restriction condition is enabled: object returned unchanged" + ) + return(.object) + } + + # ---- per-condition keep masks on demo rows (TRUE = keep) ---- + masks <- vector("list", length(enabled)) + names(masks) <- enabled + n_missing <- integer(length(enabled)) + names(n_missing) <- enabled + for (cond in enabled) { + res <- switch(cond, + period = restrict_mask_period(demo, .period), + date_range = restrict_mask_date( + demo, .date_range, .date_field, .date_partial + ), + sex = restrict_mask_values(demo$sex, .sex), + age = restrict_mask_age(demo$age_in_years, .age), + age_grp = restrict_mask_values(demo$age_grp, .age_grp), + country = restrict_mask_values(demo$occr_country, .country) + ) + masks[[cond]] <- res$mask + n_missing[[cond]] <- res$n_missing + } + + keep_mask <- Reduce(`&`, masks) + if (isTRUE(.invert)) { + keep_mask <- !keep_mask + } + ids <- unique(as.character(demo$primaryid[keep_mask])) + + # ---- aggregated drop report (never silently truncate) ---- + n_removed <- sum(!keep_mask) + if (n_removed > 0L && !isTRUE(.invert)) { + msgs <- vapply(enabled, function(cond) { + sprintf( + "%s: %d removed (%d missing/unparseable)", + RESTRICT_LABELS[[cond]], sum(!masks[[cond]]), n_missing[[cond]] + ) + }, character(1L), USE.NAMES = FALSE) + cli::cli_warn(c( + "{.fn faers_restrict} removed {n_removed} report{?s} to build the requested sub-population", # nolint + stats::setNames(msgs, rep("x", length(msgs))) + )) + } else if (n_removed > 0L) { + cli::cli_warn( + "{.fn faers_restrict} removed {n_removed} report{?s} matching all enabled conditions" # nolint + ) + } + + # delegate to faers_keep so both backends + flags are handled identically + faers_keep(.object, ids, invert = FALSE) +} + +# ---------- validation helpers ---------- + +restrict_check_period <- function(period) { + if (is.null(period)) { + return(NULL) + } + if (!is.character(period) || !length(period)) { + cli::cli_abort( + "{.arg .period} must be a character vector like {.val {c(\"2019q4\", \"2020q1\")}}" + ) + } + period <- tolower(trimws(period)) + bad <- !grepl("^[0-9]{4}q[1-4]$", period) + if (any(bad)) { + cli::cli_abort(c( + "{.arg .period} entries must look like {.val YYYYqN} with N in 1-4", + x = "Invalid: {.val {period[bad]}}", + i = "Examples: {.val {c(\"2020q1\", \"2020q2\")}}" + )) + } + unique(period) +} + +restrict_check_dates <- function(x) { + if (is.null(x)) { + return(NULL) + } + if (!is.atomic(x) || length(x) != 2L || anyNA(x)) { + cli::cli_abort( + "{.arg .date_range} must be a length-2 vector c(start, end)" + ) + } + d <- vapply(x, restrict_parse_one_date, numeric(1L)) + d <- as.Date(d, origin = "1970-01-01") + if (anyNA(d)) { + cli::cli_abort(c( + "{.arg .date_range} must be two parseable dates", + i = "Accepted forms: `Date`, {.val YYYY-MM-DD} or {.val YYYYMMDD}" + )) + } + if (d[[1L]] > d[[2L]]) { + cli::cli_abort("{.arg .date_range} start must not be after the end") + } + d +} + +restrict_check_values <- function(x, allowed, arg) { + if (is.null(x)) { + return(NULL) + } + if (!is.character(x) || !length(x)) { + cli::cli_abort("{.arg {arg}} must be a non-empty character vector") + } + x <- trimws(x) + bad <- unique(x[!x %chin% allowed]) + if (length(bad)) { + cli::cli_abort(c( + "{.arg {arg}} only accepts {.val {allowed}}", + x = "Invalid value{?s}: {.val {bad}}" + )) + } + unique(x) +} + +# Free-form values (country): only shape is validated. +restrict_check_values_free <- function(x, arg) { + if (is.null(x)) { + return(NULL) + } + if (!is.character(x) || !length(x)) { + cli::cli_abort("{.arg {arg}} must be `NULL` or a non-empty character vector") + } + unique(trimws(x)) +} + +restrict_check_age <- function(x) { + if (is.null(x)) { + return(NULL) + } + ok <- is.numeric(x) && length(x) == 2L && !anyNA(x) && + all(is.finite(x)) && x[[1L]] <= x[[2L]] + if (!ok) { + cli::cli_abort(c( + "{.arg .age} must be `NULL` or a length-2 numeric c(lower, upper) with lower <= upper", # nolint + i = "Ages are compared in years against the standardized {.field age_in_years} column" # nolint + )) + } + as.numeric(x) +} + +# ---------- mask builders ---------- +# Each returns list(mask = logical, n_missing = integer). Reports whose +# condition value is missing/unparseable get FALSE when the condition is +# enabled (dates: kept when .date_partial = "keep"). + +restrict_mask_values <- function(v, keep_vals) { + v <- as.character(v) + v_trim <- trimws(v) + keep <- !is.na(v) & v_trim %chin% keep_vals + list(mask = keep, n_missing = sum(is.na(v) | (!is.na(v) & v_trim == ""))) +} + +restrict_mask_age <- function(v, range) { + keep <- !is.na(v) & v >= range[[1L]] & v <= range[[2L]] + list(mask = keep, n_missing = sum(is.na(v))) +} + +restrict_mask_period <- function(demo, period) { + keys <- restrict_period_keys(demo$year, demo$quarter) + list(mask = keys %chin% period, n_missing = 0L) +} + +restrict_period_keys <- function(year, quarter) { + q <- tolower(trimws(as.character(quarter))) + q <- sub("^q", "", q) # tolerate both "q1" and "1" forms + paste(as.character(year), q, sep = "q") +} + +restrict_mask_date <- function(demo, date_range, date_field, date_partial) { + raw <- demo[[date_field]] + dates <- restrict_parse_dates(raw) + ok <- !is.na(dates) + keep <- ok & dates >= date_range[[1L]] & dates <= date_range[[2L]] + if (identical(date_partial, "keep")) { + keep[!ok] <- TRUE + } + list(mask = keep, n_missing = sum(!ok)) +} + +# Parse demo date columns (YYYYMMDD numerics, or character forms) into Date; +# partial dates (year-only or year-month) stay NA so they never match a +# window silently. +restrict_parse_dates <- function(x) { + if (inherits(x, "Date")) { + return(x) + } + if (is.numeric(x)) { + s <- sprintf("%08.0f", x) + } else { + s <- trimws(as.character(x)) + } + out <- as.Date(rep(NA_character_, length(s))) + ok <- !is.na(s) & nchar(s) == 8L & !grepl("[^0-9]", s) + if (any(ok)) { + out[ok] <- as.Date(s[ok], format = "%Y%m%d") + } + # also accept ISO strings if a user hand-edited a table + rest <- which(!ok & !is.na(s) & nchar(s) == 10L) + if (length(rest)) { + iso <- restrict_parse_one_date(s[rest]) + hit <- !is.na(iso) + out[rest[hit]] <- as.Date(iso[hit], origin = "1970-01-01") + } + out +} + +# Parse a single date value -> days since epoch (numeric) or NA_real_. +restrict_parse_one_date <- function(x) { + if (inherits(x, "Date")) { + return(as.numeric(x)) + } + if (is.numeric(x)) { + x <- sprintf("%08.0f", x) + } else { + x <- trimws(as.character(x)) + } + d <- suppressWarnings(as.Date(x, format = "%Y%m%d")) + if (is.na(d)) { + d <- tryCatch( + suppressWarnings(as.Date(x)), # ISO YYYY-MM-DD + error = function(e) as.Date(NA) + ) + } + if (is.na(d)) { + NA_real_ + } else { + as.numeric(d) + } +} + +restrict_enabled_conditions <- function( + period, date_range, sex, age, age_grp, country) { + args <- list( + period = period, date_range = date_range, sex = sex, + age = age, age_grp = age_grp, country = country + ) + names(args)[!vapply(args, is.null, logical(1L))] +} diff --git a/R/scan-db.R b/R/scan-db.R index da62be2..b7f9558 100644 --- a/R/scan-db.R +++ b/R/scan-db.R @@ -13,6 +13,9 @@ # SQL string literal for the drug names that are dropped before counting. DB_SCAN_UNKNOWN_DRUGS <- c("", "unknown", "?") +# Valid drug role codes in FAERS ascii data. +DB_SCAN_ROLE_CODES <- c("PS", "SS", "C", "I") + # SQL fragment filtering garbage drug names (must stay in sync with # SCAN_UNKNOWN_DRUGS in scan.R, which the memory path applies in R). db_scan_drug_filter_sql <- function(drug_col_q) { @@ -27,8 +30,25 @@ db_scan_drug_filter_sql <- function(drug_col_q) { ) } +# SQL fragment restricting drug rows to the requested role_cod whitelist. +# Returns "" when `role_cod` is NULL (no role restriction), so callers can +# append it unconditionally. +db_scan_role_filter_sql <- function(role_cod) { + if (is.null(role_cod)) { + return("") + } + vals <- paste( + vapply(role_cod, function(x) + sprintf("'%s'", gsub("'", "''", x)), character(1L) + ), + collapse = ", " + ) + sprintf(" AND role_cod IN (%s)", vals) +} + # Build the full SQL string for the scan aggregation. -db_scan_query <- function(drug_col, event_col, meddra, min_a) { +db_scan_query <- function(drug_col, event_col, meddra, min_a, + role_cod = NULL) { drug_tbl <- db_field_table("drug") reac_tbl <- db_field_table("reac") demo_tbl <- db_field_table("demo") @@ -38,9 +58,11 @@ db_scan_query <- function(drug_col, event_col, meddra, min_a) { paste( "SELECT DISTINCT primaryid, lower(trim(%s)) AS drugname", "FROM %s", - "WHERE %s IS NOT NULL AND %s" + "WHERE %s IS NOT NULL AND %s%s" ), - drug_col_q, drug_tbl, drug_col_q, db_scan_drug_filter_sql(drug_col_q) + drug_col_q, drug_tbl, drug_col_q, + db_scan_drug_filter_sql(drug_col_q), + db_scan_role_filter_sql(role_cod) ) if (isTRUE(meddra)) { reac_sel <- sprintf( @@ -94,14 +116,17 @@ CROSS JOIN (SELECT COUNT(DISTINCT primaryid) AS n FROM %s) AS x # Run the scan aggregation on a db-backed object and return a data.table with # columns: drug, event, a, n_drug, n_event, n. -scan_counts_db <- function(object, drug_col, event_col, min_a) { +scan_counts_db <- function(object, drug_col, event_col, min_a, + role_cod = NULL) { con <- object@db@con meddra <- event_col %chin% names(object@meddra@hierarchy) if (meddra && !DB_MEDDRA_TABLE %in% DBI::dbListTables(con)) { db_ingest_meddra(con, object) } out <- DBI::dbGetQuery( - con, db_scan_query(drug_col, event_col, meddra, min_a) + con, db_scan_query(drug_col, event_col, meddra, min_a, + role_cod = role_cod + ) ) out <- data.table::as.data.table(out) # COUNT(DISTINCT ...) comes back as BIGINT/double -> coerce to integer, diff --git a/R/scan-strata-db.R b/R/scan-strata-db.R index 58c204b..552845b 100644 --- a/R/scan-strata-db.R +++ b/R/scan-strata-db.R @@ -15,7 +15,7 @@ # Build the full SQL string for the stratified scan aggregation. db_scan_strata_query <- function(strata_cols, drug_col, event_col, meddra, - min_a, na_stratum) { + min_a, na_stratum, role_cod = NULL) { drug_tbl <- db_field_table("drug") reac_tbl <- db_field_table("reac") demo_tbl <- db_field_table("demo") @@ -52,9 +52,11 @@ db_scan_strata_query <- function(strata_cols, drug_col, event_col, meddra, paste( "SELECT DISTINCT primaryid, lower(trim(%s)) AS drugname", "FROM %s", - "WHERE %s IS NOT NULL AND %s" + "WHERE %s IS NOT NULL AND %s%s" ), - drug_col_q, drug_tbl, drug_col_q, db_scan_drug_filter_sql(drug_col_q) + drug_col_q, drug_tbl, drug_col_q, + db_scan_drug_filter_sql(drug_col_q), + db_scan_role_filter_sql(role_cod) ) if (isTRUE(meddra)) { reac_sel <- sprintf( @@ -142,7 +144,7 @@ db_scan_strata_query <- function(strata_cols, drug_col, event_col, meddra, # data.table with columns: , drug, event, a, n_drug, n_event, # n_stratum. scan_strata_counts_db <- function(object, strata_cols, drug_col, event_col, - min_a, na_stratum) { + min_a, na_stratum, role_cod = NULL) { con <- object@db@con meddra <- event_col %chin% names(object@meddra@hierarchy) if (meddra && !DB_MEDDRA_TABLE %in% DBI::dbListTables(con)) { @@ -151,7 +153,8 @@ scan_strata_counts_db <- function(object, strata_cols, drug_col, event_col, out <- DBI::dbGetQuery( con, db_scan_strata_query( - strata_cols, drug_col, event_col, meddra, min_a, na_stratum + strata_cols, drug_col, event_col, meddra, min_a, na_stratum, + role_cod = role_cod ) ) out <- data.table::as.data.table(out) diff --git a/R/scan-strata.R b/R/scan-strata.R index 0130bba..d8bd740 100644 --- a/R/scan-strata.R +++ b/R/scan-strata.R @@ -82,6 +82,12 @@ STRATA_RESERVED <- c( #' which excludes them from the stratified scan. #' @param .methods An atomic character, the disproportionality methods passed #' to [phv_signal]. Defaults to `c("ror", "prr")`. +#' @param .role_cod An optional character vector of drug role codes to keep +#' before counting: `"PS"` primary suspect, `"SS"` secondary suspect, +#' `"C"` concomitant, `"I"` interacting. `NULL` (default) keeps every role. +#' Restricting roles changes the exposure definition within every stratum; +#' the per-stratum background `n_stratum` is unchanged either way. See +#' [faers_phv_scan()] for details. #' @param .chunk_size A single integer, the number of unique `primaryid`s #' processed per chunk by the memory backend. Only relevant for #' `database = "memory"`. @@ -129,7 +135,8 @@ methods::setGeneric("faers_phv_scan_stratified", function(.object, ...) { methods::setMethod("faers_phv_scan_stratified", "FAERSascii", function( .object, .strata = "sex", .events = "pt", .drug_field = "drugname", .drug_pattern = NULL, .min_a = 3L, .methods = c("ror", "prr"), - .na_stratum = c("keep", "drop"), .chunk_size = 1e6L, + .role_cod = NULL, .na_stratum = c("keep", "drop"), + .chunk_size = 1e6L, .phv_signal_params = list(), BPPARAM = BiocParallel::SerialParam() ) { .na_stratum <- match.arg(.na_stratum) @@ -139,6 +146,9 @@ methods::setMethod("faers_phv_scan_stratified", "FAERSascii", function( assert_number_whole(.min_a, min = 1) assert_number_whole(.chunk_size, min = 1) assert_(.phv_signal_params, is.list, "a list") + .role_cod <- restrict_check_values( + .role_cod, SCAN_ROLE_CODES, ".role_cod" + ) if (!is.character(.strata) || !length(.strata) || anyDuplicated(.strata)) { cli::cli_abort(c( "{.arg .strata} must be a non-empty character vector of distinct column names", @@ -219,13 +229,14 @@ methods::setMethod("faers_phv_scan_stratified", "FAERSascii", function( if (!is.null(.object@db)) { counts <- scan_strata_counts_db( .object, strata_cols = .strata, drug_col = .drug_field, - event_col = .events, min_a = .min_a, na_stratum = .na_stratum + event_col = .events, min_a = .min_a, na_stratum = .na_stratum, + role_cod = .role_cod ) } else { counts <- scan_strata_counts_memory( .object, strata_cols = .strata, drug_col = .drug_field, event_col = .events, min_a = .min_a, chunk_size = .chunk_size, - na_stratum = .na_stratum + na_stratum = .na_stratum, role_cod = .role_cod ) } @@ -368,7 +379,8 @@ methods::setMethod("faers_phv_scan_stratified", "FAERSascii", function( # every step. Reports are atomic in their stratum (one demo row per # primaryid), so per-chunk counts sum to the exact database-wide counts. scan_strata_counts_memory <- function(object, strata_cols, drug_col, event_col, - min_a, chunk_size, na_stratum) { + min_a, chunk_size, na_stratum, + role_cod = NULL) { demo <- faers_get(object, "demo") strata_dt <- unique( demo[, c("primaryid", strata_cols), with = FALSE], @@ -403,6 +415,12 @@ scan_strata_counts_memory <- function(object, strata_cols, drug_col, event_col, drug <- faers_get(object, "drug") reac <- faers_get(object, "reac") + # ---- optional drug-role restriction (identical to the plain scan) ---- + if (!is.null(role_cod)) { + keep_roles <- role_cod + drug <- drug[role_cod %chin% keep_roles] + } + # ---- normalize + deduplicate both sides (identical to the scan) ---- drug_u <- drug[, .(primaryid, drug = tolower(trimws(get(drug_col))))] drug_u <- drug_u[!is.na(drug) & !drug %chin% SCAN_UNKNOWN_DRUGS] diff --git a/R/scan.R b/R/scan.R index 929ac40..4569971 100644 --- a/R/scan.R +++ b/R/scan.R @@ -50,6 +50,14 @@ #' drug-event pair for it to be kept. Defaults to `3L`. #' @param .methods An atomic character, the disproportionality methods passed #' to [phv_signal]. Defaults to `c("ror", "prr")`. +#' @param .role_cod An optional character vector of drug role codes to keep +#' before counting: `"PS"` primary suspect, `"SS"` secondary suspect, +#' `"C"` concomitant, `"I"` interacting. `NULL` (default) keeps every role, +#' matching the behaviour of previous package versions. Restricting roles +#' changes the exposure definition (e.g. `.role_cod = "PS"` counts only drugs +#' the reporter listed as the primary suspect), so results are **not** +#' directly comparable with unrestricted scans; the total background `n` +#' is unchanged either way. #' @param .chunk_size A single integer, the number of unique `primaryid`s #' processed per chunk by the memory backend. Only relevant for #' `database = "memory"`; smaller values trade speed for peak memory. @@ -93,7 +101,8 @@ methods::setGeneric("faers_phv_scan", function(.object, ...) { #' @method faers_phv_scan FAERSascii methods::setMethod("faers_phv_scan", "FAERSascii", function( .object, .events = "pt", .drug_field = "drugname", .drug_pattern = NULL, - .min_a = 3L, .methods = c("ror", "prr"), .chunk_size = 1e6L, + .min_a = 3L, .methods = c("ror", "prr"), .role_cod = NULL, + .chunk_size = 1e6L, .phv_signal_params = list(), BPPARAM = BiocParallel::SerialParam() ) { assert_string(.drug_field, allow_empty = FALSE) @@ -102,6 +111,9 @@ methods::setMethod("faers_phv_scan", "FAERSascii", function( assert_number_whole(.min_a, min = 1) assert_number_whole(.chunk_size, min = 1) assert_(.phv_signal_params, is.list, "a list") + .role_cod <- restrict_check_values( + .role_cod, SCAN_ROLE_CODES, ".role_cod" + ) if (!.object@standardization) { cli::cli_abort("{.arg .object} must be standardized using {.fn faers_standardize}") } @@ -140,12 +152,13 @@ methods::setMethod("faers_phv_scan", "FAERSascii", function( # ---- count all drug x event pairs ---- if (!is.null(.object@db)) { counts <- scan_counts_db( - .object, drug_col = .drug_field, event_col = .events, min_a = .min_a + .object, drug_col = .drug_field, event_col = .events, + min_a = .min_a, role_cod = .role_cod ) } else { counts <- scan_counts_memory( .object, drug_col = .drug_field, event_col = .events, - min_a = .min_a, chunk_size = .chunk_size + min_a = .min_a, chunk_size = .chunk_size, role_cod = .role_cod ) } @@ -213,6 +226,8 @@ SCAN_EXPENSIVE_THRESHOLD <- 1e5L # Drug names dropped before counting (keep in sync with # DB_SCAN_UNKNOWN_DRUGS in scan-db.R). SCAN_UNKNOWN_DRUGS <- c("", "unknown", "?") +# Valid drug role codes (keep in sync with DB_SCAN_ROLE_CODES in scan-db.R). +SCAN_ROLE_CODES <- c("PS", "SS", "C", "I") #' Shared assembly of the per-pair 2x2 contingency table. #' `counts` must provide `drug`, `event`, `a`, `n_drug`, `n_event`, `n` @@ -233,10 +248,17 @@ scan_build_contingency <- function(counts) { # Chunking is exact because every report's rows share the same `primaryid`, so # a report never spans two chunks: summing per-chunk COUNT(DISTINCT primaryid) # yields the database-wide distinct counts. -scan_counts_memory <- function(object, drug_col, event_col, min_a, chunk_size) { +scan_counts_memory <- function(object, drug_col, event_col, min_a, chunk_size, + role_cod = NULL) { drug <- faers_get(object, "drug") reac <- faers_get(object, "reac") + # ---- optional drug-role restriction (exposure definition) ---- + if (!is.null(role_cod)) { + keep_roles <- role_cod + drug <- drug[role_cod %chin% keep_roles] + } + # ---- normalize + deduplicate both sides ---- drug_u <- drug[, .(primaryid, drug = tolower(trimws(get(drug_col))))] drug_u <- drug_u[!is.na(drug) & !drug %chin% SCAN_UNKNOWN_DRUGS] diff --git a/man/faers_phv_scan.Rd b/man/faers_phv_scan.Rd index 57b1413..618ec92 100644 --- a/man/faers_phv_scan.Rd +++ b/man/faers_phv_scan.Rd @@ -14,6 +14,7 @@ faers_phv_scan(.object, ...) .drug_pattern = NULL, .min_a = 3L, .methods = c("ror", "prr"), + .role_cod = NULL, .chunk_size = 1000000L, .phv_signal_params = list(), BPPARAM = BiocParallel::SerialParam() @@ -44,6 +45,15 @@ drug-event pair for it to be kept. Defaults to \code{3L}.} \item{.methods}{An atomic character, the disproportionality methods passed to \link{phv_signal}. Defaults to \code{c("ror", "prr")}.} +\item{.role_cod}{An optional character vector of drug role codes to keep +before counting: \code{"PS"} primary suspect, \code{"SS"} secondary suspect, +\code{"C"} concomitant, \code{"I"} interacting. \code{NULL} (default) keeps every role, +matching the behaviour of previous package versions. Restricting roles +changes the exposure definition (e.g. \code{.role_cod = "PS"} counts only drugs +the reporter listed as the primary suspect), so results are \strong{not} +directly comparable with unrestricted scans; the total background \code{n} +is unchanged either way.} + \item{.chunk_size}{A single integer, the number of unique \code{primaryid}s processed per chunk by the memory backend. Only relevant for \code{database = "memory"}; smaller values trade speed for peak memory.} diff --git a/man/faers_phv_scan_stratified.Rd b/man/faers_phv_scan_stratified.Rd index 2227743..558831b 100644 --- a/man/faers_phv_scan_stratified.Rd +++ b/man/faers_phv_scan_stratified.Rd @@ -15,6 +15,7 @@ faers_phv_scan_stratified(.object, ...) .drug_pattern = NULL, .min_a = 3L, .methods = c("ror", "prr"), + .role_cod = NULL, .na_stratum = c("keep", "drop"), .chunk_size = 1000000L, .phv_signal_params = list(), @@ -50,6 +51,13 @@ drug-event pair \strong{within a stratum} for it to be kept. Defaults to \code{3 \item{.methods}{An atomic character, the disproportionality methods passed to \link{phv_signal}. Defaults to \code{c("ror", "prr")}.} +\item{.role_cod}{An optional character vector of drug role codes to keep +before counting: \code{"PS"} primary suspect, \code{"SS"} secondary suspect, +\code{"C"} concomitant, \code{"I"} interacting. \code{NULL} (default) keeps every role. +Restricting roles changes the exposure definition within every stratum; +the per-stratum background \code{n_stratum} is unchanged either way. See +\code{\link[=faers_phv_scan]{faers_phv_scan()}} for details.} + \item{.na_stratum}{Either \code{"keep"} (default), which groups reports with missing strata values into an explicit \code{"Missing"} stratum, or \code{"drop"}, which excludes them from the stratified scan.} diff --git a/man/faers_restrict.Rd b/man/faers_restrict.Rd new file mode 100644 index 0000000..fa8c60f --- /dev/null +++ b/man/faers_restrict.Rd @@ -0,0 +1,98 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/restrict.R +\name{faers_restrict} +\alias{faers_restrict} +\title{Restrict a FAERS object to a sub-population} +\usage{ +faers_restrict( + .object, + .period = NULL, + .date_range = NULL, + .date_field = c("fda_dt", "event_dt", "rept_dt"), + .sex = NULL, + .age = NULL, + .age_grp = NULL, + .country = NULL, + .invert = FALSE, + .date_partial = c("exclude", "keep") +) +} +\arguments{ +\item{.object}{A \link{FAERSascii} object. Should be standardized (and +de-duplicated for downstream signal scans).} + +\item{.period}{Character vector of period keys, e.g. \code{c("2019q4", "2020q1")}. Case-insensitive. \code{NULL} (default) keeps all periods present +in the object.} + +\item{.date_range}{Length-2 vector \code{c(start, end)} of dates. Accepts +\code{Date} objects or strings in \code{YYYY-MM-DD} or \code{YYYYMMDD} form; both ends +are inclusive. \code{NULL} (default) applies no date window.} + +\item{.date_field}{The demo date column to compare against \code{.date_range}. +\code{"fda_dt"} (FDA receipt date, essentially complete) is the default +because it is the most complete; \code{"event_dt"} and \code{"rept_dt"} are +available. Rows whose date is missing or partial (e.g. year-only \code{1999}) +cannot be placed in the window and are excluded (counted in the +aggregated warning) unless \code{.date_partial = "keep"}.} + +\item{.sex}{Character vector of sexes to keep, e.g. \code{c("Female", "Male")}. +Valid values are \code{Female} and \code{Male}; unmatched non-NA values are an +error. Reports with missing sex are excluded whenever \code{.sex} is enabled.} + +\item{.age}{Length-2 numeric \code{c(lower, upper)} closed interval on +\code{age_in_years} (the standardized age in years; all age codes are +converted during standardization). \code{NULL} applies no age filter. Reports +with missing age are excluded whenever \code{.age} is enabled.} + +\item{.age_grp}{Character vector of age-group codes to keep. The recoded +\code{age_grp} column ("A" adult, "E" elderly, "I" infant, "N" neonate) is +missing for older quarters, so this filter is only reliable for recent +periods; missing values are excluded whenever enabled. \code{NULL} applies no +age-group filter.} + +\item{.country}{Character vector of occurrence countries to keep +(\code{occr_country}). \code{NULL} applies no country filter; missing countries are +excluded whenever enabled.} + +\item{.invert}{If \code{TRUE}, the semantics invert: reports matching \strong{all} +enabled conditions are removed instead of kept.} + +\item{.date_partial}{How to handle reports whose date cannot be parsed +(missing or partial dates like \code{1999} or \code{200301}) when a date window is +enabled: \code{"exclude"} (default) removes them and counts them in the +aggregated warning; \code{"keep"} retains them unfiltered.} +} +\value{ +A \link{FAERSascii} object of the same backend (in-memory or duckdb) +with the same \verb{@standardization} / \verb{@deduplication} flags as the input, +restricted to reports satisfying all enabled conditions. The input +object is never modified. +} +\description{ +\code{faers_restrict()} narrows a standardized FAERS object to +reports matching period, date-window and demographic conditions. All +enabled conditions are intersected: a report survives only if it satisfies +every one of them. Reports excluded by any enabled condition — including +those dropped because their value is missing or unparseable (e.g. partial +dates) — are counted per condition and reported in a single aggregated +warning, mirroring the package's philosophy of never silently truncating +data. +} +\examples{ +\donttest{ +# The bundled sample is already standardized. +data <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) + +# keep female reports aged 18-85 +sub <- faers_restrict(data, .sex = "Female", .age = c(18, 85)) + +# period keys +sub2 <- faers_restrict(data, .period = c("2004q1", "2017q2")) + +# date window on the FDA receipt date +sub3 <- faers_restrict(data, .date_range = c("2004-01-01", "2004-12-31")) +} +} +\seealso{ +\code{\link[=faers_keep]{faers_keep()}}, \code{\link[=faers_filter]{faers_filter()}} +} diff --git a/tests/testthat/test_restrict.R b/tests/testthat/test_restrict.R new file mode 100644 index 0000000..11728be --- /dev/null +++ b/tests/testthat/test_restrict.R @@ -0,0 +1,233 @@ +# Tests for faers_restrict (period / population restriction). +# +# Mirrors test_scan-strata.R: the bundled standardized sample is not +# de-duplicated, so helpers flip the `deduplication` flag; duckdb parity tests +# build an in-memory twin database and are skipped when duckdb is missing. + +has_duckdb <- requireNamespace("duckdb", quietly = TRUE) && + requireNamespace("DBI", quietly = TRUE) + +restrict_sample_object <- function() { + rds <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) + sl <- list() + for (sn in methods::slotNames("FAERSascii")) { + sl[[sn]] <- tryCatch(methods::slot(rds, sn), error = function(e) NULL) + } + sl <- Filter(Negate(is.null), sl) + obj <- do.call(methods::new, c(list(Class = "FAERSascii"), sl)) + obj@deduplication <- TRUE + obj +} + +# in-memory duckdb twin builder (same pattern as test_scan-strata.R) +restrict_db_twin <- function(mem_obj) { + ns <- asNamespace("faers") + con <- ns$db_connect(":memory:") + tables <- ns$db_field_tables() + for (f in names(mem_obj@data)) ns$db_ingest(con, f, mem_obj@data[[f]]) + proxies <- stats::setNames( + lapply(names(mem_obj@data), function(f) { + methods::new("FAERSdbTbl", con = con, table = tables[[f]]) + }), + names(mem_obj@data) + ) + methods::new("FAERSascii", + data = proxies, + deletedCases = methods::slot(mem_obj, "deletedCases"), + year = mem_obj@year, quarter = mem_obj@quarter, + standardization = mem_obj@standardization, + deduplication = mem_obj@deduplication, + format = mem_obj@format, meddra = mem_obj@meddra, + db = methods::new("FAERSdb", con = con, path = ":memory:", + version = as.character(packageVersion("duckdb")), + tables = tables + ) + ) +} + +testthat::test_that("faers_restrict with no conditions warns and returns input unchanged", { + obj <- restrict_sample_object() + testthat::expect_warning(res <- faers_restrict(obj), "No restriction condition") + testthat::expect_identical(res, obj) +}) + +testthat::test_that("faers_restrict filters by sex and reports drops in one aggregated warning", { + obj <- restrict_sample_object() + demo <- obj@data$demo + expect_n <- sum(demo$sex == "Female", na.rm = TRUE) + w <- NULL + res <- withCallingHandlers( + faers_restrict(obj, .sex = "Female"), + warning = function(cnd) { + w <<- c(w, conditionMessage(cnd)) + invokeRestart("muffleWarning") + } + ) + testthat::expect_equal(nrow(res@data$demo), expect_n) + testthat::expect_length(w, 1L) + testthat::expect_match(w[[1L]], "removed", fixed = TRUE) + testthat::expect_match(w[[1L]], "sex", fixed = TRUE) + testthat::expect_match(w[[1L]], "missing", fixed = TRUE) + # combined intersection: sex Female AND age 0-120 + res2 <- suppressWarnings(faers_restrict(obj, .sex = "Female", .age = c(0, 120))) + testthat::expect_lte(nrow(res2@data$demo), expect_n) +}) + +testthat::test_that("faers_restrict filters by age interval on age_in_years", { + obj <- restrict_sample_object() + demo <- obj@data$demo + expect_n <- sum( + !is.na(demo$age_in_years) & + demo$age_in_years >= 18 & demo$age_in_years <= 85 + ) + res <- suppressWarnings(faers_restrict(obj, .age = c(18, 85))) + testthat::expect_equal(nrow(res@data$demo), expect_n) + testthat::expect_error(faers_restrict(obj, .age = c(85, 18)), "age") + testthat::expect_error(faers_restrict(obj, .age = c(18)), "age") + testthat::expect_error(faers_restrict(obj, .age = c("a", "b")), "age") +}) + +testthat::test_that("faers_restrict filters by period key", { + obj <- restrict_sample_object() + demo <- obj@data$demo + res <- suppressWarnings(faers_restrict(obj, .period = "2004q1")) + testthat::expect_equal(nrow(res@data$demo), sum(demo$year == 2004)) + # case-insensitive + whitespace tolerated + res2 <- suppressWarnings(faers_restrict(obj, .period = " 2004Q1 ")) + testthat::expect_equal( + sort(faers_primaryid(res)), sort(faers_primaryid(res2)) + ) + testthat::expect_error(faers_restrict(obj, .period = "2020_Q1"), "YYYYqN") + testthat::expect_error(faers_restrict(obj, .period = "2020q9"), "1-4") + testthat::expect_error(faers_restrict(obj, .period = 2004), "character") +}) + +testthat::test_that("faers_restrict applies date windows on the chosen field", { + obj <- restrict_sample_object() + demo <- obj@data$demo + # fda_dt: numeric YYYYMMDD, complete in the sample + res <- suppressWarnings( + faers_restrict(obj, .date_range = c("2004-01-01", "2004-12-31")) + ) + ok <- !is.na(demo$fda_dt) + d <- as.Date(sprintf("%08.0f", demo$fda_dt[ok]), format = "%Y%m%d") + testthat::expect_equal( + nrow(res@data$demo), + sum(ok & d >= as.Date("2004-01-01") & d <= as.Date("2004-12-31")) + ) + # numeric YYYYMMDD form is accepted too + res_num <- suppressWarnings(faers_restrict( + obj, .date_range = c(20040101, 20040630) + )) + expect_num <- sum( + ok & d >= as.Date("2004-01-01") & d <= as.Date("2004-06-30") + ) + testthat::expect_equal(nrow(res_num@data$demo), expect_num) + # event_dt: NA/partial rows (year-only 1999, year-month 201610, etc.) + # cannot be placed in a window -> excluded by default, kept with + # .date_partial = "keep". Window is wide; only parseable full dates pass. + full_ok <- !is.na(demo$event_dt) & nchar(as.character(demo$event_dt)) == 8L + res_e <- suppressWarnings(faers_restrict( + obj, .date_range = c("1900-01-01", "2100-01-01"), .date_field = "event_dt" + )) + testthat::expect_equal( + nrow(res_e@data$demo), sum(full_ok) + ) + res_k <- suppressWarnings(faers_restrict( + obj, .date_range = c("1900-01-01", "2100-01-01"), + .date_field = "event_dt", .date_partial = "keep" + )) + testthat::expect_equal(nrow(res_k@data$demo), nrow(demo)) + # bad inputs + testthat::expect_error( + faers_restrict(obj, .date_range = c("2020-01-01")), "length-2" + ) + testthat::expect_error( + faers_restrict(obj, .date_range = c("not-a-date", "2020-01-01")), + "parseable" + ) + testthat::expect_error( + faers_restrict(obj, .date_range = c("2020-12-31", "2020-01-01")), + "start must not be after" + ) +}) + +testthat::test_that("faers_restrict combines conditions by intersection", { + obj <- restrict_sample_object() + demo <- obj@data$demo + res <- suppressWarnings(faers_restrict( + obj, .period = "2004q1", .sex = "Female" + )) + expected_ids <- demo[year == 2004 & sex == "Female", unique(primaryid)] + testthat::expect_setequal(faers_primaryid(res), expected_ids) + # every downstream field is filtered to the same reports + testthat::expect_true(all(res@data$drug$primaryid %in% expected_ids)) +}) + +testthat::test_that("faers_restrict keeps missing values of disabled conditions", { + obj <- restrict_sample_object() + # age has ~42% NA; a sex-only filter must keep all ages + res <- suppressWarnings(faers_restrict(obj, .sex = "Female")) + testthat::expect_true(any(is.na(res@data$demo$age_in_years))) +}) + +testthat::test_that("faers_restrict .invert removes matching reports", { + obj <- restrict_sample_object() + demo <- obj@data$demo + res <- suppressWarnings(faers_restrict(obj, .sex = "Female", .invert = TRUE)) + testthat::expect_equal( + nrow(res@data$demo), + sum(demo$sex != "Female" | is.na(demo$sex)) + ) +}) + +testthat::test_that("faers_restrict preserves flags and never mutates the input", { + obj <- restrict_sample_object() + snapshot <- lapply(obj@data, function(x) data.table::copy(x)) + res <- suppressWarnings(faers_restrict(obj, .sex = "Female")) + testthat::expect_true(res@standardization) + testthat::expect_true(res@deduplication == obj@deduplication) + # row contents of the input are untouched (identical() may be FALSE due + # to data.table's internal selfref pointer, so compare values) + testthat::expect_true(isTRUE(all.equal( + obj@data$demo, snapshot$demo, check.attributes = FALSE + ))) + testthat::expect_true(isTRUE(all.equal( + obj@data$drug, snapshot$drug, check.attributes = FALSE + ))) +}) + +testthat::test_that("faers_restrict validates value whitelists", { + obj <- restrict_sample_object() + testthat::expect_error(faers_restrict(obj, .sex = "femal"), "Female") + testthat::expect_error(faers_restrict(obj, .age_grp = "X"), "age group|A|E") + testthat::expect_error(faers_restrict(obj, .country = 123), "character") + testthat::expect_error(faers_restrict(obj, .sex = character(0)), "non-empty") +}) + +testthat::test_that("faers_restrict produces identical id sets on memory and duckdb backends", { + testthat::skip_if_not(has_duckdb) + conds <- list( + list(.sex = "Female"), + list(.age = c(18, 85)), + list(.sex = "Female", .age = c(18, 85)), + list(.period = "2004q1"), + list(.date_range = c("2004-01-01", "2004-12-31")), + list(.country = "US") + ) + for (i in seq_along(conds)) { + # each condition gets a FRESH pair because the db backend filters by + # physically deleting rows (faers_keep_db semantics) + mem2 <- restrict_sample_object() + db2 <- restrict_db_twin(mem2) + mem_res <- do.call(faers_restrict, c(list(.object = mem2), conds[[i]])) + db_res <- suppressWarnings(do.call( + faers_restrict, c(list(.object = db2), conds[[i]]) + )) + testthat::expect_identical( + sort(faers_primaryid(mem_res)), + sort(faers_primaryid(db_res)), + label = sprintf("condition %d", i) + ) + } +}) diff --git a/tests/testthat/test_scan.R b/tests/testthat/test_scan.R index e8dc7b2..a8837d2 100644 --- a/tests/testthat/test_scan.R +++ b/tests/testthat/test_scan.R @@ -213,3 +213,77 @@ testthat::test_that("db_scan_query builds SQL with the right filters", { testthat::expect_match(q_meddra, "faers_meddra", fixed = TRUE) testthat::expect_match(q_meddra, "meddra_hierarchy_idx", fixed = TRUE) }) + +testthat::test_that("faers_phv_scan .role_cod restricts the exposure definition", { + obj <- scan_sample_object() + r_all <- suppressMessages(suppressWarnings( + faers_phv_scan(obj, .min_a = 1L) + )) + r_ps <- suppressMessages(suppressWarnings( + faers_phv_scan(obj, .min_a = 1L, .role_cod = "PS") + )) + testthat::expect_gt(nrow(r_all), nrow(r_ps)) + # every PS pair's a is a subset count of the all-roles pair + m <- merge( + r_all[, .(drugname, pt, a_all = a)], + r_ps[, .(drugname, pt, a_ps = a)], + by = c("drugname", "pt"), all = TRUE + ) + m[is.na(a_ps), a_ps := 0L] + testthat::expect_true(all(m$a_ps <= m$a_all)) + # background n is unchanged by the role filter + # (reconstruct n from one row: n = a + b + c + d) + if (nrow(r_all) && nrow(r_ps)) { + n_all <- r_all[1, a + b + c + d] + n_ps <- r_ps[1, a + b + c + d] + testthat::expect_equal(n_all, n_ps) + } + # multiple roles accepted + r_pss <- suppressMessages(suppressWarnings( + faers_phv_scan(obj, .min_a = 1L, .role_cod = c("PS", "SS")) + )) + testthat::expect_gte(nrow(r_pss), nrow(r_ps)) + # invalid role code errors with the valid list + testthat::expect_error( + suppressMessages(faers_phv_scan(obj, .min_a = 1L, .role_cod = "XX")), + "PS" + ) + # NULL keeps everything (default; identical to previous versions) + r_null <- suppressMessages(faers_phv_scan(obj, .min_a = 1L, .role_cod = NULL)) + testthat::expect_equal(nrow(r_null <- r_all), nrow(r_null)) +}) + +testthat::test_that("faers_phv_scan_stratified .role_cod filters within strata", { + obj <- scan_sample_object() + s_all <- suppressMessages(faers_phv_scan_stratified( + obj, .strata = "sex", .min_a = 1L + )) + s_ps <- suppressMessages(suppressWarnings( + faers_phv_scan_stratified( + obj, .strata = "sex", .min_a = 1L, .role_cod = "PS" + ) + )) + testthat::expect_gte(nrow(s_all), nrow(s_ps)) + testthat::expect_equal( + sort(unique(s_all$n_stratum)), sort(unique(s_ps$n_stratum)) + ) + m <- merge( + s_all[, .(sex, drugname, pt, a_all = a)], + s_ps[, .(sex, drugname, pt, a_ps = a)], + by = c("sex", "drugname", "pt"), all = TRUE + ) + m[is.na(a_ps), a_ps := 0L] + testthat::expect_true(all(m$a_ps <= m$a_all)) +}) + +testthat::test_that("db_scan_role_filter_sql emits correct SQL", { + ns <- asNamespace("faers") + testthat::expect_identical(ns$db_scan_role_filter_sql(NULL), "") + q <- ns$db_scan_role_filter_sql(c("PS", "SS")) + testthat::expect_match(q, "role_cod IN ('PS', 'SS')", fixed = TRUE) + # full query embeds the fragment + q2 <- asNamespace("faers")$db_scan_query( + "drugname", "pt", meddra = FALSE, min_a = 3L, role_cod = "PS" + ) + testthat::expect_match(q2, "role_cod IN ('PS')", fixed = TRUE) +}) From d9b3e92be939bdeff35ab9c2522df495e2176fc8 Mon Sep 17 00:00:00 2001 From: MadDERt <2129882365@qq.com> Date: Wed, 28 Oct 2026 16:36:02 +0800 Subject: [PATCH 2/3] fix: runnable example for faers_restrict, avoid suppressWarnings in date parsing --- R/restrict.R | 22 +++++++++++++--------- man/faers_restrict.Rd | 21 ++++++++++++--------- tests/testthat/test_restrict.R | 4 +++- 3 files changed, 28 insertions(+), 19 deletions(-) diff --git a/R/restrict.R b/R/restrict.R index 56d3962..a3de4bc 100644 --- a/R/restrict.R +++ b/R/restrict.R @@ -73,19 +73,23 @@ RESTRICT_LABELS <- c( #' object is never modified. #' @seealso [faers_keep()], [faers_filter()] #' @examples -#' \donttest{ -#' # The bundled sample is already standardized. +#' # The bundled sample must be de-duplicated before scanning; `faers_dedup()` +#' # also standardizes the age column used by `.age`. #' data <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) +#' data <- faers_dedup(data) #' -#' # keep female reports aged 18-85 -#' sub <- faers_restrict(data, .sex = "Female", .age = c(18, 85)) -#' -#' # period keys -#' sub2 <- faers_restrict(data, .period = c("2004q1", "2017q2")) +#' # keep female reports aged 18-85 (missing ages are excluded and counted) +#' sub <- suppressWarnings(faers_restrict(data, .sex = "Female", .age = c(18, 85))) +#' nrow(faers_get(sub, "demo")) #' #' # date window on the FDA receipt date -#' sub3 <- faers_restrict(data, .date_range = c("2004-01-01", "2004-12-31")) -#' } +#' sub2 <- faers_restrict(data, .date_range = c("2004-01-01", "2004-12-31")) +#' nrow(faers_get(sub2, "demo")) +#' +#' # combine with a signal scan on primary-suspect drugs only +#' res <- faers_phv_scan(sub2, .min_a = 2L, .role_cod = "PS") +#' res[order(-ror), list(drugname, pt, a, ror, ror_ci_low)] +#' @export #' @export faers_restrict <- function( .object, .period = NULL, .date_range = NULL, diff --git a/man/faers_restrict.Rd b/man/faers_restrict.Rd index fa8c60f..0fd766b 100644 --- a/man/faers_restrict.Rd +++ b/man/faers_restrict.Rd @@ -79,19 +79,22 @@ warning, mirroring the package's philosophy of never silently truncating data. } \examples{ -\donttest{ -# The bundled sample is already standardized. +# The bundled sample must be de-duplicated before scanning; `faers_dedup()` +# also standardizes the age column used by `.age`. data <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) +data <- faers_dedup(data) -# keep female reports aged 18-85 -sub <- faers_restrict(data, .sex = "Female", .age = c(18, 85)) - -# period keys -sub2 <- faers_restrict(data, .period = c("2004q1", "2017q2")) +# keep female reports aged 18-85 (missing ages are excluded and counted) +sub <- suppressWarnings(faers_restrict(data, .sex = "Female", .age = c(18, 85))) +nrow(faers_get(sub, "demo")) # date window on the FDA receipt date -sub3 <- faers_restrict(data, .date_range = c("2004-01-01", "2004-12-31")) -} +sub2 <- faers_restrict(data, .date_range = c("2004-01-01", "2004-12-31")) +nrow(faers_get(sub2, "demo")) + +# combine with a signal scan on primary-suspect drugs only +res <- faers_phv_scan(sub2, .min_a = 2L, .role_cod = "PS") +res[order(-ror), list(drugname, pt, a, ror, ror_ci_low)] } \seealso{ \code{\link[=faers_keep]{faers_keep()}}, \code{\link[=faers_filter]{faers_filter()}} diff --git a/tests/testthat/test_restrict.R b/tests/testthat/test_restrict.R index 11728be..3067ab9 100644 --- a/tests/testthat/test_restrict.R +++ b/tests/testthat/test_restrict.R @@ -220,7 +220,9 @@ testthat::test_that("faers_restrict produces identical id sets on memory and duc # physically deleting rows (faers_keep_db semantics) mem2 <- restrict_sample_object() db2 <- restrict_db_twin(mem2) - mem_res <- do.call(faers_restrict, c(list(.object = mem2), conds[[i]])) + mem_res <- suppressWarnings(do.call( + faers_restrict, c(list(.object = mem2), conds[[i]]) + )) db_res <- suppressWarnings(do.call( faers_restrict, c(list(.object = db2), conds[[i]]) )) From 5dd2c1cccf44b9ad11a7e3135b5ed3d264e1ead3 Mon Sep 17 00:00:00 2001 From: MadDERt <2129882365@qq.com> Date: Wed, 28 Oct 2026 17:12:54 +0800 Subject: [PATCH 3/3] fix: harden faers_restrict (private db copy, missing-column guard, ISO date parsing); fix vacuous role_cod test --- R/restrict.R | 73 +++++++++++++++++++++++++++++++++++--- tests/testthat/test_scan.R | 6 ++-- 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/R/restrict.R b/R/restrict.R index a3de4bc..f2b1e05 100644 --- a/R/restrict.R +++ b/R/restrict.R @@ -90,7 +90,6 @@ RESTRICT_LABELS <- c( #' res <- faers_phv_scan(sub2, .min_a = 2L, .role_cod = "PS") #' res[order(-ror), list(drugname, pt, a, ror, ror_ci_low)] #' @export -#' @export faers_restrict <- function( .object, .period = NULL, .date_range = NULL, .date_field = c("fda_dt", "event_dt", "rept_dt"), .sex = NULL, @@ -108,6 +107,10 @@ faers_restrict <- function( .country <- restrict_check_values_free(.country, ".country") demo <- faers_get(.object, "demo") + # Fail loudly when a requested condition column does not exist (older + # quarters lack `age_grp`; some builds may lack `occr_country`), instead + # of silently excluding every report. + restrict_check_demo_cols(demo, .age_grp, .country) enabled <- restrict_enabled_conditions( .period, .date_range, .sex, .age, .age_grp, .country ) @@ -163,12 +166,72 @@ faers_restrict <- function( ) } - # delegate to faers_keep so both backends + flags are handled identically + # delegate to faers_keep so both backends + flags are handled identically. + # duckdb objects share the source db connection, and `faers_keep_db()` + # physically DELETEs rows, so keep a private copy: without it, restricting + # Female would wipe the source db and a later Male restriction (or the + # original object, or previously returned results) would see empty data. + if (!is.null(.object@db)) { + .object <- restrict_private_db_copy(.object) + } faers_keep(.object, ids, invert = FALSE) } +# Deep-copy the duckdb tables of an object into a fresh temporary database so +# that the physical DELETE performed by `faers_keep_db()` cannot touch the +# user's original database. Returns a db-backed FAERSascii whose @db points at +# the private copy (proxies rebuilt against the new connection); the source +# connection and every previously created object stay untouched. +restrict_private_db_copy <- function(.object) { + fields <- names(.object@db@tables) + con_src <- .object@db@con + tmp_db <- db_new_path() + con <- db_connect(tmp_db) + # copy every physical field table into the fresh database + for (field in fields) { + tbl <- db_collect(con_src, field) + db_ingest(con, field, tbl) + } + # the meddra hierarchy lookup is re-ingested so SQL joins keep working + if (!is.null(.object@meddra)) { + db_ingest_meddra(con, .object) + } + db_store <- methods::new( + "FAERSdb", con = con, path = tmp_db, + version = .object@db@version, tables = .object@db@tables + ) + data <- stats::setNames(lapply(fields, function(f) { + methods::new("FAERSdbTbl", con = con, table = db_field_table(f)) + }), fields) + methods::new( + "FAERSascii", data = data, + deletedCases = methods::slot(.object, "deletedCases"), + year = .object@year, quarter = .object@quarter, + standardization = .object@standardization, + deduplication = .object@deduplication, + format = .object@format, meddra = .object@meddra, db = db_store + ) +} + # ---------- validation helpers ---------- +# A requested `.age_grp` / `.country` filter is meaningless when the demo +# table lacks the column entirely (older FAERS quarters) — abort instead of +# silently returning an empty object. +restrict_check_demo_cols <- function(demo, .age_grp, .country) { + missing_cols <- c( + age_grp = if (!is.null(.age_grp) && !"age_grp" %in% names(demo)) "age_grp", + country = if (!is.null(.country) && !"occr_country" %in% names(demo)) "occr_country" + ) + if (length(missing_cols)) { + cli::cli_abort(c( + "Column{?s} {.field {names(missing_cols)}} not found in the demo table", + i = "The requested condition{?s} cannot be applied: {.val {unname(missing_cols)}} conditions on a period without these columns would exclude every report", + i = "Check available columns with {.fn faers_get}" + )) + } +} + restrict_check_period <- function(period) { if (is.null(period)) { return(NULL) @@ -313,10 +376,12 @@ restrict_parse_dates <- function(x) { if (any(ok)) { out[ok] <- as.Date(s[ok], format = "%Y%m%d") } - # also accept ISO strings if a user hand-edited a table + # also accept ISO strings if a user hand-edited a table (vectorized via + # vapply: as.Date() on a multi-element vector would pass a length>1 + # condition to the old single-value helper and crash) rest <- which(!ok & !is.na(s) & nchar(s) == 10L) if (length(rest)) { - iso <- restrict_parse_one_date(s[rest]) + iso <- vapply(s[rest], restrict_parse_one_date, numeric(1L)) hit <- !is.na(iso) out[rest[hit]] <- as.Date(iso[hit], origin = "1970-01-01") } diff --git a/tests/testthat/test_scan.R b/tests/testthat/test_scan.R index a8837d2..a5a7451 100644 --- a/tests/testthat/test_scan.R +++ b/tests/testthat/test_scan.R @@ -249,8 +249,10 @@ testthat::test_that("faers_phv_scan .role_cod restricts the exposure definition" "PS" ) # NULL keeps everything (default; identical to previous versions) - r_null <- suppressMessages(faers_phv_scan(obj, .min_a = 1L, .role_cod = NULL)) - testthat::expect_equal(nrow(r_null <- r_all), nrow(r_null)) + r_null <- suppressMessages(suppressWarnings( + faers_phv_scan(obj, .min_a = 1L, .role_cod = NULL) + )) + testthat::expect_identical(r_null, r_all) }) testthat::test_that("faers_phv_scan_stratified .role_cod filters within strata", {