diff --git a/DESCRIPTION b/DESCRIPTION index 4e84bdc..5d01a58 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: faers Title: R interface for FDA Adverse Event Reporting System -Version: 1.5.6 +Version: 1.5.7 Authors@R: c( person("Yun", "Peng", , "yunyunp96@163.com", role = c("aut", "cre"), comment = c(ORCID = "0000-0003-2801-3332")), @@ -54,6 +54,9 @@ Collate: 'class-FAERS.R' 'combine-db.R' 'combine.R' + 'compare-db.R' + 'compare-groups.R' + 'compare.R' 'counts-db.R' 'counts.R' 'dedup-db.R' diff --git a/NAMESPACE b/NAMESPACE index 491237e..6686caa 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -6,6 +6,7 @@ export(faers_available) export(faers_before_period) export(faers_clearcache) export(faers_combine) +export(faers_compare) export(faers_counts) export(faers_data) export(faers_dedup) @@ -13,6 +14,7 @@ export(faers_deleted_cases) export(faers_download) export(faers_filter) export(faers_get) +export(faers_group_ids) export(faers_header) export(faers_keep) export(faers_load) diff --git a/NEWS.md b/NEWS.md index a184795..dd40c65 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,61 @@ +# faers 1.5.7 + +* Added `faers_compare()`, a multi-group comparison entry point that runs one + orchestrated analysis over several drug exposure definitions in a single + study scope. It returns the group summary, the per-group event spectrum, the + comparisons actually performed, the full contingency table and signal + metrics for every comparison x event, event x group count/share/signal + matrices, the group overlaps and the run metadata. Two modes are kept + strictly separate and identified in the results: `"background"` compares + each group against the rest of the shared scope (`a + b + c + d == |U|`, the + same universe for every group), while `"pairwise"` compares two selected + groups against each other (`a + b + c + d == |G1| + |G2|`, a denominator + that changes per pair). `"pairwise"` never runs implicitly: every pair must + be listed in `.comparisons`, because per-pair denominators invite + uncorrected multiple comparisons. `"joint"` splitting derives the mutually + exclusive `A-only` / `B-only` / `A+B` / `Neither` report groups, complementing + B against the same role-restricted exposure rules used to define B. The + statistics are not reimplemented: each table is handed to the same + `phv_signal()` a single-group analysis uses, so a group x event row is + byte-identical to the equivalent standalone `faers_phv_signal()` call. + Difficulty-of-use safeguards are explicit: `.mode = "pairwise"` with an + overlapping pair refuses to build a table unless the overlap is reconciled + with `.overlap`, `.min_a` is `0` by default (no implicit threshold) and the + number of dropped rows is reported, and `.top_n` truncates only the display + layer (event spectrum and matrices) while `signal_results` keeps every row + and the truncation is flagged as `display_subset` in the attributes and the + metadata. Joint-group output is a descriptive comparison and + disproportionality analysis of co-reported drugs, **not** a formal + interaction test. + +* Added `faers_group_ids()`, the report-set layer behind `faers_compare()`: + it builds one `primaryid` set per named drug exposure definition on top of + `faers_reports_with()`, reports every pairwise intersection (and the strategy + applied to it), builds the mutually exclusive joint groups, and returns a + report x group membership matrix. `.min_a`-style filtering, statistics and + display concerns stay out of this layer. + +* Fixed `faers_counts()` on duckdb-backed objects for the `reac` event columns + that live in the field itself (`pt`, `meddra_code`, `meddra_pt`): the SQL + builder qualified every event column with the MedDRA hierarchy alias, so + `.events = "pt"` failed with a binder error. Only the columns actually added + by the hierarchy join (`soc_name`, `pt_name`, ...) are now qualified, which + also makes the duckdb count for `pt`/`meddra_code`/`meddra_pt` identical to + the in-memory path. The same fix applies to the counting path used by + `faers_compare()`. + +* Fixed `phv_chisq()`, `phv_fisher()` and `phv_bcpnn_mcmc()` on zero-length + input: they built their result from a list of per-row results and then named + the columns unconditionally, so a zero-length call aborted with + `无法将 N 个名字赋值给一个包含 0 列的 data.table`. This was reachable + through the public API, e.g. + `faers_phv_signal(faers_keep(obj, character()), .events = "pt", .full = obj, + .methods = "chisq")`. They now return their full schema with zero rows, which + keeps the result bindable with a populated one and gives `phv_signal()` a + single source of truth for the metric columns. As a consequence an empty + selection in `faers_compare()` now returns the same `signal_results` columns + as a populated one, so an explicit `.matrix_metric` no longer fails there. + # faers 1.5.6 * Added `faers_reports_with()`, a report set constructor for drug exposure diff --git a/R/compare-db.R b/R/compare-db.R new file mode 100644 index 0000000..908b5a3 --- /dev/null +++ b/R/compare-db.R @@ -0,0 +1,158 @@ +# DuckDB helpers for multi-group comparison (`faers_compare()`). +# +# Why this file exists: per-group event counts need the reports of a group as +# a set, but the public `faers_keep()` cannot be used here. On a duckdb-backed +# object `faers_keep_db()` physically DELETEs rows from the connection shared +# by every object built from the same database (see R/methods-FAERS.R), and the +# only safe alternative, `restrict_private_db_copy()` (R/restrict.R), deep +# copies the whole database once per group. A multi-group comparison would +# therefore pay one full copy per group, which is not acceptable for a +# multi-quarter on-disk database. +# +# Instead the group is registered as a TEMP table and the aggregation happens +# in a single read-only SELECT. The user's tables are never modified. +# +# The temp table name is generated per call rather than fixed. A fixed name is +# not safe: `dbWriteTable(temporary = TRUE)` does not shadow a same-named +# permanent table, it REPLACES it, so a fixed name would destroy whatever the +# user had called `__faers_compare_ids__` - and on an on-disk database the loss +# survives the session. The generated name is checked against the tables the +# connection already knows, so a collision cannot happen; the table is dropped +# again once the counts have been read. +# +# Results are aligned byte-for-byte with the in-memory path exactly like +# `counts_db()` (R/counts-db.R) does: BIGINT -> integer coercion, `setkeyv()` +# on the event columns. Callback preprocessing is shared by both backends in +# R/compare.R. + +# Generates a name no table of this connection currently uses. Deterministic +# (no RNG, so the caller's random stream is untouched) and cheap: one +# `dbListTables()` per group next to the aggregate query that follows. +.compare_id_seq <- new.env(parent = emptyenv()) +.compare_id_seq$n <- 0L + +compare_id_table <- function(con) { + existing <- DBI::dbListTables(con) + repeat { + .compare_id_seq$n <- .compare_id_seq$n + 1L + nm <- sprintf( + "__faers_compare_ids_%d_%d__", Sys.getpid(), .compare_id_seq$n + ) + if (!nm %in% existing) { + return(nm) + } + } +} + +# Register `ids` as a temporary group table and return its name. A zero-length +# set is legal and yields a zero-row table, so empty groups need no special +# case downstream. +# +# `overwrite = FALSE` is deliberate rather than redundant: `compare_id_table()` +# already guarantees the name is free, and refusing to write over anything is +# the one behaviour that can never lose a user table. If the guarantee is ever +# broken the call errors out loudly instead of destroying data. +compare_ingest_ids <- function(con, ids) { + tbl <- compare_id_table(con) + DBI::dbWriteTable( + con, tbl, + data.frame(primaryid = as.character(ids)), + overwrite = FALSE, temporary = TRUE + ) + tbl +} + +# Drop a temp table created by `compare_ingest_ids()`. Only ever called on a +# name this session generated, so it can never touch a user's table. +compare_drop_ids <- function(con, tbl) { + DBI::dbExecute(con, sprintf("DROP TABLE IF EXISTS %s", db_qident(tbl))) + invisible(con) +} + +# One aggregate per event combination, restricted to the registered group. +# Mirrors `db_counts_query()` but scopes `COUNT(DISTINCT primaryid)` to the +# join against `id_table`. Every column reference is qualified because both +# sides of the join carry `primaryid`. +compare_counts_query <- function(field, events, id_table, na_rm = FALSE, + meddra = FALSE, hierarchy = character()) { + if (isTRUE(meddra)) { + from <- sprintf( + "%s AS f LEFT JOIN %s AS m ON f.meddra_hierarchy_idx = m.idx", + db_field_table(field), DB_MEDDRA_TABLE + ) + ev <- vapply(events, function(e) { + if (e %chin% hierarchy) paste0("m.", db_qident(e)) else paste0("f.", db_qident(e)) + }, character(1L)) + } else { + from <- sprintf("%s AS f", db_field_table(field)) + ev <- vapply(events, function(e) paste0("f.", db_qident(e)), character(1L)) + } + join_ids <- sprintf( + "INNER JOIN %s AS g ON f.primaryid = g.primaryid", db_qident(id_table) + ) + where <- "" + if (isTRUE(na_rm)) { + where <- paste("WHERE", paste(sprintf("%s IS NOT NULL", ev), collapse = " AND ")) + } + select <- if (length(ev) == 1L) { + event_name <- if (nzchar(events[[1L]])) db_qident(events[[1L]]) else "event" + sprintf("SELECT %s AS %s, COUNT(DISTINCT f.primaryid) AS N", ev, event_name) + } else { + sprintf("SELECT %s, COUNT(DISTINCT f.primaryid) AS N", paste(ev, collapse = ", ")) + } + sprintf( + "%s FROM %s %s %s GROUP BY %s", + select, from, join_ids, where, paste(ev, collapse = ", ") + ) +} + +# Database-mode per-group counting. Used by `faers_compare()` for every group +# on a duckdb-backed object; the in-memory backend keeps using +# `faers_keep()` + `faers_counts()`. +compare_counts_db <- function(.object, .ids, .events, + .field = "reac", .na.rm = FALSE) { + assert_bool(.na.rm) + con <- .object@db@con + + meddra <- field_needs_meddra(.object, .field) + if (meddra && !DB_MEDDRA_TABLE %in% DBI::dbListTables(con)) { + db_ingest_meddra(con, .object) + } + tbl <- compare_ingest_ids(con, .ids) + on.exit(compare_drop_ids(con, tbl), add = TRUE) + out <- data.table::as.data.table(DBI::dbGetQuery( + con, + compare_counts_query( + .field, .events, id_table = tbl, + na_rm = .na.rm, meddra = meddra, + hierarchy = db_meddra_columns(.object) + ) + )) + # Byte-parity with the memory path (see counts_db()). + if (is.double(out$N)) data.table::set(out, j = "N", value = as.integer(out$N)) + data.table::setkeyv(out, .events) + out +} + +# Narrow projection of the `drug` field used by the single-row combination +# diagnosis: `primaryid`, every drug column a group matches against, and +# `role_cod`. On duckdb only these columns are pulled instead of the whole +# drug table. +compare_drug_rows <- function(.object, cols) { + cols <- setdiff(unique(cols), c("primaryid", "role_cod")) + if (is.null(.object@db)) { + drug <- faers_get(.object, "drug") + return(drug[, c("primaryid", cols, "role_cod"), with = FALSE]) + } + data.table::as.data.table(DBI::dbGetQuery( + .object@db@con, + sprintf( + "SELECT %s FROM %s", + paste( + c("primaryid", vapply(cols, db_qident, character(1L)), "role_cod"), + collapse = ", " + ), + db_field_table("drug") + ) + )) +} diff --git a/R/compare-groups.R b/R/compare-groups.R new file mode 100644 index 0000000..0ba8e7a --- /dev/null +++ b/R/compare-groups.R @@ -0,0 +1,504 @@ +# Report-group construction for multi-group comparison. +# +# A *report group* is a named exposure definition: a set of drug name patterns +# (regular expressions, case-insensitive), optionally a per-drug `role_cod` +# restriction, an AND/OR combination rule and a set of report-level exclusion +# patterns. The definitions are resolved with `faers_reports_with()` (see +# R/restrict-drug.R), so the matching semantics - including the rule that under +# `.logic = "and"` two patterns MAY be satisfied by the SAME drug row +# (fixed-dose combinations / multi-ingredient `prod_ai` entries) and that +# `.exclude_drugs` is report-level and role-agnostic - are inherited verbatim +# rather than reimplemented. +# +# This file only builds and reconciles *report sets*: +# `faers_group_ids()` -> ids + membership + summary + pairwise overlaps +# +# The contingency tables, statistics and matrices live in R/compare.R. + +# ---------- group definition validation ---------- + +# Columns referenced inside `data.table::[.data.table` expressions. +utils::globalVariables(c("n_intersection")) + +.COMPARE_GROUP_KEYS <- c(".drugs", ".roles", ".logic", ".exclude_drugs", ".drug_col") +.COMPARE_OVERLAP_STRATEGIES <- c("keep", "exclude", "repartition", "error") + +# Normalize `.groups` into a named list of fully-specified definitions. A group +# may be given as a plain character vector (shorthand for "these patterns, no +# role restriction, AND, no exclusion") or as a list of the keys above. +.compare_check_groups <- function(.groups, .split) { + if (!is.list(.groups) || !length(.groups)) { + cli::cli_abort("{.arg .groups} must be a non-empty named list of group definitions") + } + nms <- names(.groups) + if (is.null(nms) || anyNA(nms) || any(!nzchar(nms))) { + cli::cli_abort("{.arg .groups} must be fully named, e.g. {.code list(A = \"warfarin\", B = \"metformin\")}") + } + if ("primaryid" %in% nms) { + cli::cli_abort("{.arg .groups} cannot use the reserved name {.val primaryid}; it identifies reports in {.field membership}") + } + dup <- unique(nms[duplicated(nms)]) + if (length(dup)) { + cli::cli_abort(c( + "{.arg .groups} contains duplicated group names", + x = "Duplicated: {.val {dup}}" + )) + } + # `cli` interpolates `{.val {x}}` from the calling frame, which does not see + # namespace constants, so the allowed keys are bound locally first. + allowed_keys <- .COMPARE_GROUP_KEYS + out <- lapply(seq_along(.groups), function(i) { + nm <- nms[[i]] + def <- .groups[[i]] + if (is.character(def)) { + def <- list(.drugs = def) + } + if (!is.list(def)) { + cli::cli_abort(c( + "Group {.val {nm}} must be a character vector of drug patterns or a named list", + i = "Allowed keys: {.val {allowed_keys}}" + )) + } + unknown <- setdiff(names(def), .COMPARE_GROUP_KEYS) + if (length(unknown)) { + cli::cli_abort(c( + "Group {.val {nm}} uses unknown key{?s} {.val {unknown}}", + i = "Allowed keys: {.val {allowed_keys}}" + )) + } + drugs <- .reports_with_check_drugs(def$.drugs) + roles <- .reports_with_check_roles(def$.roles, drugs) + logic <- def$.logic %||% "and" + logic <- restrict_check_values(logic, c("and", "or"), sprintf('.groups[["%s"]][[".logic"]]', nm)) + if (length(logic) != 1L) { + cli::cli_abort("Group {.val {nm}}: {.arg .logic} must be a single string, {.val \"and\"} or {.val \"or\"}") + } + list( + name = nm, + .drugs = drugs, + .roles = roles, + .logic = logic, + .exclude_drugs = .reports_with_check_exclude(def$.exclude_drugs), + .drug_col = def$.drug_col + ) + }) + names(out) <- nms + if (identical(.split, "joint") && length(out) != 2L) { + cli::cli_abort(c( + "{.arg .split = \"joint\"} requires exactly 2 groups, got {length(out)}", + i = "Supply the two drugs to be crossed, e.g. {.code list(A = \"warfarin\", B = \"metformin\")}" + )) + } + out +} + +# Resolve one group definition into a sorted unique `primaryid` vector. +# `faers_reports_with()` emits its own per-pattern message; silence it here so a +# multi-group run does not print one message per group and per comparison. +.compare_group_ids <- function(.object, def) { + # `faers_reports_with()` accepts only `NULL` for "no role restriction", not + # an empty list, so normalize back before delegating. + roles <- if (length(def$.roles)) def$.roles else NULL + excl <- if (length(def$.exclude_drugs)) def$.exclude_drugs else NULL + suppressMessages(faers_reports_with( + .object, + .drugs = def$.drugs, + .roles = roles, + .logic = def$.logic, + .exclude_drugs = excl, + .drug_col = def$.drug_col, + .return = "ids" + )) +} + +# The drug column a definition actually matched against, after the +# `drugname` -> `prod_ai` fallback that `faers_reports_with()` performs. +.compare_group_drug_col <- function(.object, def) { + .reports_with_pick_col(.object, def$.drug_col) +} + +# ---------- joint split ---------- + +.COMPARE_ONLY <- "-only" +.COMPARE_BOTH <- "+" +.COMPARE_NEITHER <- "Neither" + +# Split two exposure sets into the four mutually exclusive joint groups. The +# complement is taken against the SAME exposure definition (`B_ids`), never +# against "any drug row mentioning B": with a role-restricted B only its +# role-qualified rows build `B_ids`, so a report whose B record carries another +# role is correctly absent from B and its complement. +.compare_split_joint <- function(ids, scope_ids) { + a <- ids[[1L]] + b <- ids[[2L]] + nms <- names(ids) + out <- list( + setdiff(a, b), + setdiff(b, a), + intersect(a, b), + setdiff(scope_ids, union(a, b)) + ) + names(out) <- c( + paste0(nms[[1L]], .COMPARE_ONLY), + paste0(nms[[2L]], .COMPARE_ONLY), + paste0(nms[[1L]], .COMPARE_BOTH, nms[[2L]]), + .COMPARE_NEITHER + ) + out +} + +# ---------- overlap reconciliation ---------- + +# All pairwise intersections, for diagnosis and for the comparison layer. +.compare_overlap_table <- function(ids, strategy) { + nms <- names(ids) + if (length(nms) < 2L) { + return(data.table::data.table( + group1 = character(), group2 = character(), + n_intersection = integer(), strategy = character() + )) + } + pairs <- utils::combn(nms, 2L, simplify = FALSE) + out <- data.table::rbindlist(lapply(pairs, function(p) { + n <- length(intersect(ids[[p[[1L]]]], ids[[p[[2L]]]])) + data.table::data.table( + group1 = p[[1L]], group2 = p[[2L]], + n_intersection = as.integer(n), strategy = strategy + ) + })) + out[] +} + +# Globally mutually exclusive sets: each group loses every report listed in any +# other group. Used to turn overlapping exposure definitions into a partition. +.compare_overlap_exclude <- function(ids) { + nms <- names(ids) + out <- lapply(nms, function(nm) { + others <- setdiff(nms, nm) + setdiff(ids[[nm]], Reduce(union, ids[others], init = character())) + }) + names(out) <- nms + out +} + +# Turn the intersection of exactly two overlapping groups into a third group so +# nothing is dropped: `&` joins `A-only` and `B-only`. Restricted to two +# groups because the partition of three or more overlapping sets is ambiguous; +# use `.split = "joint"` for a two-drug cross instead. +.compare_overlap_repartition <- function(ids) { + nms <- names(ids) + if (length(nms) != 2L) { + cli::cli_abort(c( + "{.val .overlap = \"repartition\"} is only defined for exactly 2 groups", + i = "For a two-drug cross use {.code .split = \"joint\"}; otherwise reconcile overlaps pairwise" + )) + } + a <- ids[[1L]] + b <- ids[[2L]] + both <- intersect(a, b) + out <- list(setdiff(a, b), setdiff(b, a), both) + names(out) <- c( + paste0(nms[[1L]], .COMPARE_ONLY), + paste0(nms[[2L]], .COMPARE_ONLY), + paste0(nms[[1L]], "&", nms[[2L]]) + ) + out +} + +.compare_apply_overlap <- function(ids, strategy) { + switch(strategy, + keep = ids, + exclude = .compare_overlap_exclude(ids), + repartition = .compare_overlap_repartition(ids), + error = { + ov <- .compare_overlap_table(ids, strategy) + clash <- ov[n_intersection > 0L] + if (nrow(clash)) { + cli::cli_abort(c( + "Overlapping report groups with {.val .overlap = \"error\"}", + x = "{clash$group1} / {clash$group2}: {clash$n_intersection} shared report{?s}", + i = "Use {.val .overlap = \"exclude\"} or {.val \"repartition\"} to reconcile" + )) + } + ids + }, + cli::cli_abort("Unknown overlap strategy {.val {strategy}}") + ) +} + +# ---------- single-row combination diagnosis ---------- + +# Row-level group coverage: for every drug row, does it alone satisfy the whole +# definition? Under `.logic = "and"` that means every pattern (respecting each +# pattern's role restriction), under `"or"` at least one. +.compare_row_covers <- function(drug, def) { + if (!nrow(drug)) { + return(logical()) + } + hits <- lapply(def$.drugs, function(p) { + .reports_with_row_hit(drug, p, def$.roles[[p]], def$.drug_col) + }) + hits <- do.call(cbind, hits) + if (identical(def$.logic, "and")) { + rowSums(hits) == ncol(hits) + } else { + rowSums(hits) >= 1L + } +} + +# How many reports in `ids_both` have ONE drug row that satisfies both +# definitions at once - i.e. how much of the joint group comes from a +# fixed-dose combination product rather than from two separately recorded +# exposures. This is a description of the exposure data, not a statistical +# interaction test, and it is only computed when `.diagnose_combination`. +.compare_single_row_both <- function(.object, defs, ids_both) { + if (!length(ids_both)) { + return(0L) + } + resolved <- lapply(defs, function(d) { + d$.drug_col <- .compare_group_drug_col(.object, d) + d + }) + cols <- unique(c(vapply(resolved, `[[`, character(1L), ".drug_col"), "role_cod")) + drug <- compare_drug_rows(.object, cols) + keep_ids <- unique(as.character(ids_both)) + drug <- drug[primaryid %chin% keep_ids] + if (!nrow(drug)) { + return(0L) + } + covers <- lapply(resolved, function(d) .compare_row_covers(drug, d)) + both <- Reduce(`&`, covers) + as.integer(length(unique(drug$primaryid[both]))) +} + +# ---------- main entry ---------- + +#' Build report groups from drug exposure definitions +#' +#' `faers_group_ids()` resolves one or more named drug exposure definitions into +#' report (`primaryid`) sets within a fixed study scope, diagnoses how much the +#' groups overlap, and optionally splits two drugs into the four mutually +#' exclusive joint groups `A-only`, `B-only`, `A+B` and `Neither`. +#' +#' @details +#' ## Where the study scope comes from +#' +#' The scope `U` is `.object` itself: narrow it first with [faers_restrict()] +#' (period, demographic or geographic conditions) so that every group is built +#' inside one and the same report universe. No second "full database" argument +#' exists - [faers_compare()] compares each group against the rest of `U`. +#' +#' ## Group definitions +#' +#' Each element of `.groups` is either a character vector of drug name patterns +#' or a list with the keys `.drugs`, `.roles`, `.logic`, `.exclude_drugs` and +#' `.drug_col`, all of which carry the meaning documented in +#' [faers_reports_with()] because that function does the matching. In +#' particular matching is a case-insensitive regular expression, `.roles` +#' restricts which `role_cod` values may satisfy a pattern, and under +#' `.logic = "and"` two patterns **may be satisfied by the same drug row** +#' (fixed-dose combination products). A report matching both an `A` and a `B` +#' definition is therefore placed in the joint group `A+B`; the +#' `n_single_row_both` column of `group_summary` counts how many joint-group +#' reports come from one such multi-ingredient row. +#' +#' ## Joint split +#' +#' With `.split = "joint"` (exactly two groups) the four sets are +#' `A-only = A \ B`, `B-only = B \ A`, `A+B = A n B` and +#' `Neither = U \ (A u B)`. The complement is taken against the **same** +#' exposure definition that built the other group, so a role-restricted `B` +#' (`PS`/`SS` only) contributes only its role-qualified reports to `B` - a +#' report whose B record carries another role is not silently treated as +#' B-exposed. The four sets are mutually exclusive and sum to `U`. +#' +#' ## `.overlap` +#' +#' `"keep"` (default) returns the exposure sets as defined and only reports the +#' pairwise intersections in `group_overlaps`; this is what multi-drug +#' background comparisons need, since each group is compared against the shared +#' scope rather than against another group. `"exclude"` makes the sets mutually +#' exclusive by removing, from every group, all reports listed in any other +#' group. `"repartition"` (two groups only) keeps the information by turning the +#' intersection into a third group `&` alongside `A-only` and `B-only`. +#' `"error"` aborts when any two groups share a report. +#' +#' @param .object A [FAERSascii] object, standardized with +#' [faers_standardize()]. It defines the study scope `U`. +#' @param .groups A named list of group definitions, see *Details*. +#' The name `primaryid` is reserved for the report ID column. +#' @param .split `"none"` (default) keeps the groups as given; `"joint"` splits +#' exactly two groups into `A-only`, `B-only`, `A+B` and `Neither`. +#' @param .overlap `"keep"`, `"exclude"`, `"repartition"` or `"error"`, see +#' *Details*. +#' @param .diagnose_combination A bool. If `TRUE` (default) the joint group's +#' single-row (fixed-dose combination) share is computed for +#' `group_summary$n_single_row_both`. +#' +#' @return A named list: +#' * `ids`: named list of sorted, unique `primaryid` character vectors. +#' * `raw_ids`: report ID sets named by the input definitions, before +#' splitting or overlap handling. +#' * `membership`: [data.table][data.table::data.table] with one row per scope +#' report and one logical column per group. +#' * `summary`: [data.table][data.table::data.table] with `group`, `n_reports`, +#' `share_of_scope`, `n_removed_overlap`, `is_empty`, the definition columns +#' `drugs`, `roles`, `logic`, `exclude_drugs`, `drug_col`, `n_patterns`, and +#' `n_single_row_both`. The `source_definitions` list column contains the +#' named exposure definitions used to build the group, with resolved drug +#' columns. For an intersection, `drugs` and `n_patterns` cover both +#' definitions, `roles` are keyed by source group, and `logic = "and"` +#' describes the intersection of the two definitions. The scalar +#' `drug_col` is `NA` if the definitions use different columns. +#' For a group derived from a single definition, +#' `n_removed_overlap` counts reports removed from that definition. The +#' intersection and `Neither` have zero removals. +#' * `overlaps`: [data.table][data.table::data.table] with `group1`, `group2`, +#' `n_intersection` and `strategy`. +#' * `scope_ids`: report IDs in the study scope. +#' +#' @examples +#' data <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) +#' data <- faers_dedup(data) +#' +#' # three overlapping exposure groups compared against the same scope +#' groups <- faers_group_ids( +#' data, +#' list( +#' insulin = "insulin|humalog", +#' biguanide = "metformin", +#' sulfonylurea = "glyburide|glipizide" +#' ) +#' ) +#' groups$summary +#' groups$overlaps +#' +#' # two drugs crossed into A-only / B-only / A+B / Neither +#' joint <- faers_group_ids( +#' data, list(A = "insulin|humalog", B = "metformin"), +#' .split = "joint" +#' ) +#' lengths(joint$ids) +#' +#' @seealso [faers_compare()] for contingency tables, signal metrics and +#' matrices built on these groups; [faers_reports_with()] for the exposure +#' matching semantics; [faers_restrict()] for fixing the scope first. +#' @export +faers_group_ids <- function(.object, + .groups, + .split = c("none", "joint"), + .overlap = c("keep", "exclude", "repartition", "error"), + .diagnose_combination = TRUE) { + .split <- match.arg(.split) + .overlap <- match.arg(.overlap) + groups <- .compare_build_groups(.object, .groups, .split, .overlap, + .diagnose_combination + ) + groups$raw_ids_by_group <- NULL + groups +} + +.compare_build_groups <- function(.object, .groups, .split, .overlap, + .diagnose_combination) { + assert_bool(.diagnose_combination) + assert_s3_class(.object, "FAERSascii") + if (!.object@standardization) { + cli::cli_abort("{.arg .object} must be standardized using {.fn faers_standardize}") + } + + defs <- .compare_check_groups(.groups, .split) + scope_ids <- sort(unique(as.character(faers_primaryid(.object)))) + n_scope <- length(scope_ids) + + # ---- (1) raw exposure sets, one per definition ---- + raw_defs <- lapply(defs, function(def) { + as.character(.compare_group_ids(.object, def)) + }) + names(raw_defs) <- names(defs) + + # ---- (2) joint split, or overlap reconciliation ---- + # Record source definitions in the same order as the resulting sets. + # Group names are labels and can contain the separators used in a split. + if (identical(.split, "joint")) { + ids <- .compare_split_joint(raw_defs, scope_ids) + sources <- list(1L, 2L, c(1L, 2L), integer()) + } else { + ids <- .compare_apply_overlap(raw_defs, .overlap) + sources <- if (identical(.overlap, "repartition")) { + list(1L, 2L, c(1L, 2L)) + } else { + as.list(seq_along(defs)) + } + } + + # Compare each final group to its source definition. The intersection and + # Neither are new sets, so their baseline is their own membership. + raw_ids_by_group <- stats::setNames(lapply(seq_along(ids), function(i) { + source <- sources[[i]] + if (length(source) == 1L) { + raw_defs[[source]] + } else { + ids[[i]] + } + }), names(ids)) + + # ---- (3) pairwise overlap diagnosis (on the definition-level raw sets) ---- + overlaps <- .compare_overlap_table(raw_defs, .overlap) + + # ---- (4) single-row (fixed-dose) share of the joint group ---- + single_row <- 0L + if (isTRUE(.diagnose_combination) && length(defs) == 2L) { + single_row <- .compare_single_row_both( + .object, defs, intersect(raw_defs[[1L]], raw_defs[[2L]]) + ) + } + + # ---- (5) summary ---- + summary_defs <- lapply(defs, function(def) { + def$.drug_col <- .compare_group_drug_col(.object, def) + def[.COMPARE_GROUP_KEYS] + }) + summary <- data.table::rbindlist(lapply(seq_along(ids), function(i) { + source <- summary_defs[sources[[i]]] + n <- length(ids[[i]]) + is_both <- length(source) == 2L + drugs <- as.character(unlist(lapply(source, `[[`, ".drugs"), use.names = FALSE)) + exclusions <- as.character(unlist(lapply(source, `[[`, ".exclude_drugs"), use.names = FALSE)) + roles <- lapply(source, `[[`, ".roles") + if (length(roles) == 1L) { + roles <- roles[[1L]] + } + drug_cols <- unique(vapply(source, `[[`, character(1L), ".drug_col")) + data.table::data.table( + group = names(ids)[[i]], + n_reports = as.integer(n), + share_of_scope = if (n_scope) n / n_scope else NA_real_, + n_removed_overlap = as.integer(length(raw_ids_by_group[[i]]) - n), + is_empty = n == 0L, + drugs = list(drugs), + roles = list(roles), + logic = if (is_both) "and" else if (length(source)) source[[1L]]$.logic else NA_character_, + exclude_drugs = list(unique(exclusions)), + drug_col = if (length(drug_cols) == 1L) drug_cols[[1L]] else NA_character_, + n_patterns = length(drugs), + n_single_row_both = as.integer(if (is_both) single_row else 0L), + source_definitions = list(source) + ) + })) + + # ---- (6) membership matrix ---- + membership <- data.table::data.table(primaryid = scope_ids) + for (nm in names(ids)) { + membership[[nm]] <- scope_ids %chin% ids[[nm]] + } + + list( + ids = ids, + raw_ids = raw_defs, + membership = membership, + summary = summary[], + overlaps = overlaps[], + scope_ids = scope_ids, + raw_ids_by_group = raw_ids_by_group + ) +} diff --git a/R/compare.R b/R/compare.R new file mode 100644 index 0000000..0caeee5 --- /dev/null +++ b/R/compare.R @@ -0,0 +1,1130 @@ +# Multi-group comparison and joint-group contrast. +# +# `faers_compare()` orchestrates three existing layers and adds no statistics +# of its own: +# +# report sets faers_reports_with() (R/restrict-drug.R) +# per-event counts faers_counts() / counts_db() (R/counts.R, R/counts-db.R) +# 2x2 arithmetic the contingency formulas of faers_phv_table() +# (R/signal.R) +# signal metrics phv_signal() (R/phv_.R) +# +# The two comparison modes differ in what the background is and must never be +# conflated, so `mode`, `comparison_id` and `background_id` travel with every +# row: +# +# "background" - each group G against the rest of the shared scope U +# (a + b + c + d == |U|, one and the same U for every group) +# "pairwise" - two selected groups head to head +# (a + b + c + d == |G1| + |G2|, denominator varies per pair) +# +# Byte-parity with a hand-written single call is a hard requirement, so the +# arithmetic below reproduces R/signal.R line for line instead of re-deriving +# it, and `phv_signal()` produces every metric. + +# ---------- 2x2 arithmetic (mirrors faers_phv_table) ---------- + +# ---------- 2x2 contingency tables ---------- + +# Column names used inside `data.table::[.data.table` expressions. Declared so +# that `R CMD check` does not report them as undefined globals. +utils::globalVariables(c( + "N", "event_label", "group", "denominator", "share", + "universe_N", "universe_share", "comparison_id", "status" +)) + +# Background mode: `faers_phv_table(.object = G, .full = U)`. +# n.1 = reports of U carrying the event, n1. = |G|, n = |U|. +# The identity `G vs U` == `G vs (U \ G)` was verified against the sample data, +# which is why one cached count of U serves every group. +.compare_table_background <- function(universe_counts, group_counts, .events, + n_scope, n_group) { + data.table::setnames(universe_counts, "N", "n.1") + data.table::setnames(group_counts, "N", "a") + out <- merge(universe_counts, group_counts, + by = .events, all = TRUE, allow.cartesian = TRUE + ) + out[, a := data.table::fifelse(is.na(a), 0L, a)] # nolint + out[, b := n_group - a] # nolint + out[, c := n.1 - a] # nolint + out[, d := n_scope - (n_group + n.1 - a)] # nolint + out <- out[, !"n.1"] + data.table::setcolorder(out, c(.events, "a", "b", "c", "d"))[] +} + +# Pairwise mode: `faers_phv_table(.object = G1, .object2 = G2)`. +# Note this arithmetic carries no `a + b + c + d == const` identity of its own; +# the two groups are assumed non-overlapping, which `.overlap` guarantees. +.compare_table_pairwise <- function(counts1, counts2, .events, n1, n0) { + data.table::setnames(counts1, "N", "a") + data.table::setnames(counts2, "N", "c") + out <- merge(counts1, counts2, + by = .events, all = TRUE, allow.cartesian = TRUE + ) + out[, c("a", "c") := lapply(.SD, function(x) { # nolint + data.table::fifelse(is.na(x), 0L, x) + }), .SDcols = c("a", "c")] + out[, b := n1 - a] # nolint + out[, d := n0 - c] # nolint + data.table::setcolorder(out, c(.events, "a", "b", "c", "d"))[] +} + +# ---------- counting ---------- + +# Count every group against the same event data. The callback uses the +# argument conventions of faers_counts() and runs once over the study scope. +.compare_event_counts <- function(.object, scope_ids, ids, .events, dots) { + count_events <- function(.fn = NULL, ..., .field = "reac", .na.rm = FALSE) { + if (is.null(.fn)) { + count_group <- function(group_ids) { + if (is.null(.object@db)) { + return(faers_counts( + faers_keep(.object, group_ids), .events = .events, + .field = .field, .na.rm = .na.rm + )) + } + compare_counts_db(.object, group_ids, .events, + .field = .field, .na.rm = .na.rm + ) + } + return(list(scope = count_group(scope_ids), groups = lapply(ids, count_group))) + } + + data <- faers_get(.object, .field) + if (is.null(.object@db)) { + data <- data.table::copy(data) + } + data <- rlang::as_function(.fn)(data, ...) + if (!data.table::is.data.table(data)) { + cli::cli_abort("{.arg .fn} must return a {.cls data.table}") + } + columns <- unique(c("primaryid", .events)) + missing <- setdiff(columns, names(data)) + if (length(missing)) { + cli::cli_abort("{.arg .fn} must retain the required columns {.val {missing}}") + } + data <- unique(data[, columns, with = FALSE]) + if (!all(data$primaryid %in% scope_ids)) { + cli::cli_abort("{.arg .fn} must return report IDs from the study scope in {.field primaryid}") + } + if (.na.rm) { + keep <- !Reduce(`|`, lapply(data[, .SD, .SDcols = .events], is.na)) + data <- data[keep] + } + tally <- function(rows) { + eval(substitute( + rows[, list(N = .N), keyby = events], + list(events = .events) + )) + } + list( + scope = tally(data), + groups = lapply(ids, function(group_ids) { + keep_rows <- data$primaryid %in% group_ids + tally(data[keep_rows]) + }) + ) + } + do.call(count_events, dots) +} + +# Event-set restriction ------------------------------------------------ +# +# `.event_set` narrows the candidate events after counting, mirroring the +# semantics of `faers_phv_composite()` (R/signal-eventset.R): a character +# vector selects events by value, a logical vector by position, and a function +# is applied to the event column. Unlike `faers_phv_composite()` the events are +# NOT collapsed into one "Composite_Event_Set" row: the whole point of the +# event spectrum and signal matrix is one row per event, so the set only +# decides which events stay. + +# Evaluate the selector against the event values and return the kept values. +.compare_event_keep <- function(event_values, .event_set) { + if (is.function(.event_set)) { + keep <- .event_set(event_values) + } else if (is.logical(.event_set)) { + if (length(.event_set) != length(event_values)) { + cli::cli_abort(c( + "A logical {.arg .event_set} must have one value per candidate event", + i = "Got {length(.event_set)} value{?s} for {length(event_values)} event{?s}." + )) + } + keep <- .event_set + } else if (is.character(.event_set)) { + keep <- event_values %in% .event_set + } else { + cli::cli_abort( + "{.arg .event_set} must be a character vector, a logical vector, or a function" + ) + } + if (!is.logical(keep) || length(keep) != length(event_values)) { + cli::cli_abort( + "{.arg .event_set} must return one logical value per candidate event" + ) + } + event_values[!is.na(keep) & keep] +} + +# Restrict every group/scope count table to the selected events. Returning the +# empty-selection case explicitly keeps the downstream merge honest instead of +# silently comparing everything. +.compare_apply_event_set <- function(per_group, scope_counts, .event_set, .events) { + if (is.null(.event_set)) { + return(list(per_group = per_group, scope_counts = scope_counts, n_selected = NULL)) + } + event_col <- .events[[1L]] + values <- sort(unique(scope_counts[[event_col]]), na.last = TRUE) + keep <- .compare_event_keep(values, .event_set) + per_group <- lapply(per_group, function(x) { + keep_rows <- x[[event_col]] %in% keep + x[keep_rows] + }) + keep_rows <- scope_counts[[event_col]] %in% keep + scope_counts <- scope_counts[keep_rows] + list( + per_group = per_group, scope_counts = scope_counts, + n_selected = length(keep), n_candidates = length(values) + ) +} + +# Short, printable description of `.event_set` for `metadata`. The selector +# itself is not stored when it is a function or a long vector. +.compare_event_set_label <- function(.event_set) { + if (is.null(.event_set)) { + return("all candidate events") + } + if (is.function(.event_set)) { + return("function selector") + } + if (is.logical(.event_set)) { + return(sprintf("logical selector (%d TRUE)", sum(.event_set, na.rm = TRUE))) + } + n <- length(.event_set) + shown <- utils::head(.event_set, 5L) + sprintf( + "character selector (%d value%s: %s%s)", + n, if (n == 1L) "" else "s", + paste(shown, collapse = ", "), + if (n > 5L) ", ..." else "" + ) +} + +# ---------- status annotation ---------- + +.compare_status <- function(ct) { + out <- rep("ok", nrow(ct)) + zero <- ct$a == 0L | ct$b == 0L | ct$c == 0L | ct$d == 0L + out[zero] <- "zero_cell" + empty <- (ct$a == 0L & ct$b == 0L) | (ct$c == 0L & ct$d == 0L) + out[empty] <- "empty_group" + out +} + +# ---------- matrices ---------- + +# Collapse multi-column `.events` into a single `event_label` column when the +# caller asked for more than one event column. A matrix needs one label per +# axis, so `paste(..., sep = " | ")` is used and documented; single-column +# `.events` needs no collapsing and keeps its original column name. +.compare_add_label <- function(dt, .events) { + if (length(.events) < 2L || "event_label" %in% names(dt)) { + return(dt) + } + dt[, event_label := do.call(paste, c(.SD, list(sep = " | "))), .SDcols = .events] + dt +} + +# Event x group counts into a wide matrix. `.what` selects the value column; +# for multi-column `.events` the label column is the collapsed `event_label`. +# +# A cast needs exactly one row per (label, column) pair. `dcast()` on a key +# that repeats does not fail - it aggregates with `length()` and warns, so a +# duplicated key would turn a metric into a row count and the result would +# still look like a matrix. Both keys are therefore checked first and a +# duplicate aborts. +# +# `fill` is the value of a (label, column) pair the source has no row for. It +# is `0` for counts and shares, where an absent row means "no report", and +# `NA` for the signal metric, where an absent row means "not tested" and a `0` +# would read as a null signal instead of a missing one. An `NA` fill is typed +# from the value column so that `set()` below cannot turn a numeric metric +# matrix into a logical one. +.compare_matrix <- function(profile, label_col, group_col, value_col, groups, + fill = 0) { + if (length(fill) == 1L && is.na(fill)) { + fill <- if (is.integer(profile[[value_col]])) NA_integer_ else NA_real_ + } + if (nrow(profile)) { + dup <- profile[, list(.N), by = c(label_col, group_col)][N > 1L] + if (nrow(dup)) { + keys <- do.call(paste, c(utils::head(dup[, c(label_col, group_col), with = FALSE], 5L), + list(sep = " / ") + )) + cli::cli_abort(c( + "{.field {label_col}} x {.field {group_col}} is not unique in the matrix source", + x = "{nrow(dup)} repeated key{?s}: {.val {keys}}", + i = "{.fn dcast} would aggregate {.field {value_col}} into row counts instead of failing", + i = "This is a bug in the caller, not in the data" + )) + } + } + wide <- data.table::dcast( + profile, + stats::as.formula(sprintf("%s ~ %s", label_col, group_col)), + value.var = value_col, fill = fill + ) + for (g in groups) { + if (!g %in% names(wide)) { + data.table::set(wide, j = g, value = rep(fill, nrow(wide))) + } + } + data.table::setcolorder(wide, c(label_col, groups)) + wide[] +} + +# `.top_n` truncation of the DISPLAY layer: keep the top N events per group by +# report count, take the union across groups, and collapse multi-column +# `.events` into `event_label`. Returns the truncated profile, the label column +# name to key matrices on, and the record for `metadata`. +.compare_truncate <- function(profile, .events, .top_n) { + label_col <- if (length(.events) > 1L) "event_label" else .events[[1L]] + profile <- .compare_add_label(profile, .events) + if (is.null(.top_n)) { + return(list(profile = profile, label_col = label_col, top_n = NULL, truncated = FALSE)) + } + keep <- profile[ + order(-N, get(label_col)), + utils::head(.SD, .top_n), + by = "group" + ][[label_col]] + keep <- unique(keep) + data.table::setattr(profile, "display_subset", TRUE) + list( + profile = profile[get(label_col) %in% keep], + label_col = label_col, + top_n = .top_n, + truncated = TRUE, + n_kept = length(keep), + rule = "per-group top-N by report count, union across groups" + ) +} + +# Count / share / signal matrices. `share` and `signal` are keyed on the +# comparison actually performed, so `matrices$signal` is one column per +# `comparison_id`, while `count`/`share` are one column per group. +# +# `signal_results` is keyed on `.events`, not on the collapsed label, so the +# label is rebuilt there before the signal matrix is cast. +# +# The comparison plan supplies the signal columns even when a comparison has +# no results. For a display subset, the count matrix also supplies the row +# order, and untested event/comparison cells are filled with NA. +.compare_matrices <- function(profile, signal_results, .events, label_col, + .matrix_metric, group_names, comparison_ids, + display_subset) { + if (label_col %in% group_names) { + cli::cli_abort(c( + "A group name in {.arg .groups} conflicts with the matrix event column {.val {label_col}}", + i = "Rename the group or choose another {.arg .events} column." + )) + } + if (label_col %in% comparison_ids) { + cli::cli_abort(c( + "A {.field comparison_id} conflicts with the matrix event column {.val {label_col}}", + i = "Change the group names in {.arg .groups} or choose another {.arg .events} column." + )) + } + count <- .compare_matrix(profile, label_col, "group", "N", group_names) + share <- .compare_matrix(profile, label_col, "group", "share", group_names) + + metric <- .matrix_metric %||% grep("_ci_low$", names(signal_results), value = TRUE)[1L] + if (!is.null(.matrix_metric) && !.matrix_metric %in% names(signal_results)) { + # cli interpolates from the calling frame, so bind locally. + wanted <- .matrix_metric + available <- setdiff(names(signal_results), .COMPARE_RESERVED_COLUMNS) + cli::cli_abort(c( + "{.arg .matrix_metric} {.val {wanted}} is not a column of {.field signal_results}", + i = "Available metrics: {.val {available}}" + )) + } + sig_name <- if (is.null(.matrix_metric)) "signal" else .matrix_metric + signal <- if (is.na(metric)) { + data.table::data.table() + } else { + sub <- .compare_add_label(data.table::copy(signal_results), .events) + if (display_subset) { + rows <- count[[label_col]] + sub <- sub[get(label_col) %in% rows] + } + wide <- .compare_matrix( + sub, label_col, "comparison_id", metric, comparison_ids, fill = NA + ) + if (display_subset) { + wide <- wide[match(rows, wide[[label_col]])] + data.table::set(wide, j = label_col, value = rows) + } + wide + } + + out <- list(count = count, share = share) + out[[sig_name]] <- signal + out +} + +# Columns of `signal_results` that are not metrics. +.COMPARE_RESERVED_COLUMNS <- c( + "comparison_id", "mode", "group1", "background_id", "n_total", "status" +) + + +#' Compare multiple drug groups against a shared background +#' +#' `faers_compare()` takes a study scope (a standardized and de-duplicated +#' [FAERSascii] object) plus one or more drug exposure definitions, builds the +#' report groups, counts every event in every group, runs disproportionality +#' analysis for each comparison and returns the results side by side: group +#' summary, event profile, the comparison definitions, the per-comparison +#' signal table, plotting-ready matrices and a metadata record. +#' +#' @details +#' ## Study scope and background +#' +#' `.object` is the scope `U`; narrow it first with [faers_restrict()]. Both +#' comparison modes only ever look inside `U`. +#' +#' * `.mode = "background"`: every group `G` is compared with the rest of `U`, +#' i.e. the 2x2 is `a` = reports of `G` with the event, `c` = reports of +#' `U \ G` with the event, over `n = |U|`. Each analysis uses the same `U`, +#' reports are de-duplicated per table, and every table satisfies +#' `a + b + c + d == |U|`. Identical to +#' `faers_phv_table(.object = G, .full = U)`. +#' * `.mode = "pairwise"`: the background is a *selected* second group, so +#' `n = |G1| + |G2|` and the denominator changes with every pair. Identical to +#' `faers_phv_table(.object = G1, .object2 = G2)` once overlap is reconciled. +#' `.comparisons` must be given explicitly; `NULL` aborts instead of silently +#' running every pair, because per-pair denominators invite uncorrected +#' multiple comparisons. +#' +#' The two modes are marked on every result row (`mode`, `comparison_id`, +#' `background_id`) and summarised in `comparisons`. +#' +#' ## Overlap +#' +#' `.overlap` is forwarded to [faers_group_ids()]. `"keep"` (default) is +#' correct for multi-group background comparisons: each group is compared +#' against the scope, not against another group, and the shared reports are +#' reported in `group_overlaps`. Before a *pairwise* comparison the two groups +#' must not overlap; with `"keep"` and a non-empty intersection the pair aborts +#' with the count, so pass `"exclude"` (remove the intersection from both, the +#' removed counts are recorded) or `"repartition"`/`.split = "joint"` (turn the +#' intersection into its own group). +#' +#' ## Joint-group contrast +#' +#' `faers_group_ids(.split = "joint")` splits two drugs into `A-only`, +#' `B-only`, `A+B` and `Neither` such that the four sets are mutually exclusive +#' and sum to `U`. `faers_compare()` accepts such a split either by being given +#' the four groups as `.groups` or by `.split = "joint"` directly. The result is +#' a **descriptive comparison and disproportionality analysis of co-reported +#' drugs**: it is not a formal drug-interaction test, and `Neither` exists +#' precisely so that the four-way partition stays reportable. +#' +#' ## Display subsets +#' +#' `.top_n`, when set, only truncates the *display* layer (`event_profile` and +#' `matrices`) using the rule "per group, keep the top N events by report count, +#' then take the union across groups"; ties break on the event label so the +#' result is deterministic. The matrices use the same event order, and the +#' event profile covers the same events. When a signal metric is available, +#' the matrix retains a column for every planned comparison and fills cells +#' without a result with `NA`. The event profile is flagged with +#' `attr(., "display_subset") = TRUE` and the selection is recorded in +#' `metadata$display_subset`. `signal_results` includes every result that +#' meets `.min_a`. +#' +#' @param .object A [FAERSascii] object. Must be standardized with +#' [faers_standardize()] and de-duplicated with [faers_dedup()]. +#' @param .groups A named list of group definitions, see [faers_group_ids()]. +#' @param ... Counting options from [faers_counts()], e.g. `.field`, +#' `.fn` or `.na.rm`. A supplied `.fn` runs once on the study scope's +#' selected field, which is read into memory on both backends. It must +#' return a data.table with `primaryid` and all `.events` columns, and its +#' report IDs must belong to the study scope. Additional arguments are passed +#' to `.fn`. When `.na.rm = TRUE`, rows with missing event values are omitted +#' from event counts. Denominators use all reports in each group or study scope. +#' @param .split `"none"` (default) or `"joint"`; see [faers_group_ids()]. +#' @param .mode `"background"` (default) or `"pairwise"`. +#' @param .comparisons For `.mode = "pairwise"`, a list of length-2 character +#' vectors naming the groups to contrast, e.g. +#' `list(c("A-only", "B-only"), c("A+B", "A-only"))`. Ignored, and set to +#' every group, in `"background"` mode. +#' @param .overlap `"keep"` (default), `"exclude"`, `"repartition"` or +#' `"error"`; see [faers_group_ids()]. +#' @param .events A character vector naming the event column(s) in `.field`, +#' passed to [faers_counts()]. Defaults to `"pt"`. With more than one column +#' the combination defines the event, and the matrices use a collapsed +#' `event_label` built with `paste(..., sep = " | ")`. +#' @param .event_set `NULL` (default) to keep every candidate event, or a +#' selector that narrows them. As in [faers_phv_composite()] it may be a +#' character vector of event values, a logical vector with one value per +#' candidate event, or a function applied to the event values that returns a +#' logical vector. Selectors use the sorted distinct values of the first +#' `.events` column, with missing values last when present. A function can +#' select numeric values or missing values, for example using `is.na`. +#' Unlike [faers_phv_composite()] the selected events are +#' **not** collapsed into a single composite row: each event keeps its own row +#' in `event_profile` and `signal_results`, which is what makes the event +#' spectrum and the signal matrix meaningful. The candidate count, the +#' selected count and the selector description are recorded in +#' `metadata$event_scope`. +#' @param .min_a A whole number, `0` (default) to keep every candidate event or +#' a reporting threshold. Comparisons whose `a` falls below it are dropped and +#' counted in `metadata$event_scope$n_below_min_a`. Unlike +#' [faers_phv_scan()] there is no implicit `3` here: candidate events are +#' chosen by the caller's `.events`/`.event_set`. +#' @param .methods Methods passed to [phv_signal()]. Defaults to +#' `c("ror", "prr")`. +#' @param .top_n `NULL` (default) for no truncation, or a whole number for the +#' display subset described in *Details*. +#' @param .matrix_metric `NULL` to use the first available `*_ci_low` column, +#' or the name of the metric column to place in `matrices$signal`. +#' @param .diagnose_combination Forwarded to [faers_group_ids()]. +#' @param .phv_signal_params Other arguments passed to [phv_signal()]. +#' @param BPPARAM Passed to [phv_signal()]. +#' +#' @return A named list of [data.table][data.table::data.table] objects: +#' * `group_summary`: groups, report counts, share of scope, overlap removals, +#' source exposure definitions and the single-row combination count. See +#' [faers_group_ids()] for the columns in this table. +#' * `event_profile`: per group and event, `N` reports, the `denominator` and +#' the within-group `share`, plus the same quantities over the whole scope +#' (`universe_N`, `universe_share`). Every group is laid out over the scope's +#' candidate events, so absent combinations appear as `N = 0` and the table is +#' a complete events x groups grid. Its events are a superset of the ones in +#' `signal_results`, which `.min_a` narrows to the tested comparisons; with +#' `.top_n` it is the displayed grid that every matrix shares. +#' * `comparisons`: which group was compared with which background, the group +#' sizes and the overlap removal counts. For a pair, `n_overlap_shared` +#' counts reports shared by the two groups before reconciliation, using the +#' original definition for each single-definition group and the final set +#' for a derived intersection or complement. `n_overlap_removed` counts the +#' shared reports absent from both final groups, once per report. +#' * `signal_results`: one row per comparison x event with `a`, `b`, `c`, `d`, +#' the `expected` count, every metric from [phv_signal()] and a `status` +#' column (`"ok"`, `"zero_cell"`, `"empty_group"`). The status is +#' `"empty_group"` if either side of the comparison has no reports. +#' * `matrices`: `count`, `share` and one signal matrix (named after +#' `.matrix_metric`, or `signal` for the default `*_ci_low` column), each +#' event x group/comparison. `count` and `share` cover the profile's events; +#' with a signal metric selected, the signal matrix has one column per +#' planned comparison and covers the events in `signal_results`. With +#' `.top_n`, it covers all displayed events in the same order as the count +#' matrix. Cells without a signal result contain `NA`. +#' * `metadata`: scope, groups, events, comparison and denominator definitions, +#' versions, missing-data and truncation records. Overlap diagnostics count +#' pairs with a nonempty intersection and distinct reports shared by two or +#' more input definitions, before splitting or overlap handling. +#' * `group_overlaps`: pairwise intersections of the exposure definitions. +#' +#' @examples +#' data <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) +#' data <- faers_dedup(data) +#' +#' # three drug groups, each against the same scope +#' res <- suppressMessages(faers_compare( +#' data, +#' list( +#' insulin = "insulin|humalog", +#' biguanide = "metformin", +#' sulfonylurea = "glyburide|glipizide" +#' ), +#' .events = "pt", .min_a = 2L +#' )) +#' res$group_summary +#' res$comparisons +#' head(res$signal_results) +#' res$matrices$count[1:5, 1:4] +#' +#' # two drugs crossed into four mutually exclusive groups +#' joint <- suppressMessages(faers_compare( +#' data, list(A = "insulin|humalog", B = "metformin"), +#' .split = "joint", .mode = "pairwise", +#' .comparisons = list(c("A-only", "B-only")), +#' .events = "pt", .min_a = 1L +#' )) +#' joint$comparisons +#' +#' @seealso [faers_group_ids()], [faers_phv_table()], [faers_phv_signal()], +#' [phv_signal()], [faers_phv_scan()], [faers_reports_with()], +#' [faers_restrict()]. +#' @export +faers_compare <- function(.object, + .groups, + ..., + .split = c("none", "joint"), + .mode = c("background", "pairwise"), + .comparisons = NULL, + .overlap = c("keep", "exclude", "repartition", "error"), + .events = "pt", + .event_set = NULL, + .min_a = 0L, + .methods = c("ror", "prr"), + .top_n = NULL, + .matrix_metric = NULL, + .diagnose_combination = TRUE, + .phv_signal_params = list(), + BPPARAM = BiocParallel::SerialParam()) { + .split <- match.arg(.split) + .mode <- match.arg(.mode) + .overlap <- match.arg(.overlap) + assert_s3_class(.object, "FAERSascii") + assert_character(.events, allow_na = FALSE) + if (!length(.events) || any(!nzchar(.events))) { + cli::cli_abort("{.arg .events} must be a non-empty character vector") + } + assert_number_whole(.min_a, min = 0) + assert_number_whole(.top_n, min = 1, allow_null = TRUE) + assert_string(.matrix_metric, allow_null = TRUE, allow_empty = FALSE) + assert_(.phv_signal_params, is.list, "a list") + assert_inclusive(.methods, SCAN_ALL_METHODS, allow_null = TRUE) + if (!.object@standardization) { + cli::cli_abort("{.arg .object} must be standardized using {.fn faers_standardize}") + } + if (!.object@deduplication) { + cli::cli_abort(c( + "{.arg .object} must be de-duplicated using {.fn faers_dedup}", + i = "Comparing un-deduplicated groups would bias every contingency table" + )) + } + # `.field` travels to `faers_counts()` through `...`, so nothing upstream + # has checked it. Two things go wrong when it is left alone: `faers_get()` + # aborts with a bare base-R `match.arg()` error, and an `.events` column + # that does not exist in `.field` is only caught by `data.table` deep in + # the count, with a message translated by the session locale irrelevant to + # the user's actual mistake. Both are checked here instead. + dots <- list(...) + .field <- dots$.field %||% "reac" + assert_string(.field, allow_empty = FALSE) + fields <- FAERS_ASCII_FILE_FIELDS + assert_inclusive(.field, fields) + .events_check <- .compare_check_events(.object, .events, .field) + if (!".na.rm" %in% names(dots)) { + dots[[".na.rm"]] <- FALSE + } + na_rm <- dots[[".na.rm"]] + assert_bool(na_rm, arg = ".na.rm") + + # ---- (1) report groups ---- + groups <- .compare_build_groups( + .object, .groups, + .split = .split, .overlap = .overlap, + .diagnose_combination = .diagnose_combination + ) + ids <- groups$ids + scope_ids <- groups$scope_ids + n_scope <- length(scope_ids) + + # ---- (2) the comparison plan ---- + plan <- .compare_plan(.mode, .comparisons, names(ids)) + + # ---- (3) counts (scope counts are computed once and reused) ---- + counts <- .compare_event_counts(.object, scope_ids, ids, .events, dots) + scope_counts <- counts$scope + per_group <- counts$groups + + # ---- (3b) optional candidate-event restriction ---- + sel <- .compare_apply_event_set(per_group, scope_counts, .event_set, .events) + per_group <- sel$per_group + scope_counts <- sel$scope_counts + + # ---- (4) contingency tables per comparison ---- + tables <- .compare_tables( + plan, per_group, scope_counts, ids, .events, n_scope, .object + ) + + # ---- (5) statistics ---- + signal <- .compare_signal(tables, .methods, .phv_signal_params, BPPARAM) + + # ---- (6) results ---- + group_summary <- groups$summary + signal_results <- .compare_signal_results(signal, plan, ids, .events, .min_a) + comparisons <- .compare_comparison_table( + plan, ids, n_scope, .overlap, groups$raw_ids_by_group + ) + event_profile <- .compare_event_profile( + groups, per_group, scope_counts, .events, n_scope, + .field = .field + ) + # `.top_n` truncates the display layer only; `signal_results` keeps every row. + trunc <- .compare_truncate(event_profile, .events, .top_n) + matrices <- .compare_matrices( + trunc$profile, signal_results, .events, trunc$label_col, + .matrix_metric, names(ids), comparisons$comparison_id, + display_subset = trunc$truncated + ) + metadata <- .compare_metadata( + .object, .groups, groups, plan, .mode, .split, .overlap, + .events, .event_set, .min_a, .methods, .phv_signal_params, + .top_n, .matrix_metric, + .field, n_scope, scope_counts, signal_results, + .events_check, trunc, sel, na_rm + ) + + list( + group_summary = group_summary, + event_profile = trunc$profile, + comparisons = comparisons, + signal_results = signal_results, + matrices = matrices, + metadata = metadata, + group_overlaps = groups$overlaps + ) +} + +# ---------- validation ---------- + +# Event columns must exist in `.field`. For `reac` the allowed set is not just +# the physical columns: standardization joins the MedDRA hierarchy onto it, so +# the hierarchy names are added on top of `pt`/`meddra_code`/`meddra_pt`. Every +# other field is checked against its real columns, which is what the count +# itself would demand anyway -- only here it fails before any work is done and +# with a message that says which field was meant. +.compare_check_events <- function(.object, .events, .field = "reac") { + # `{.field {.field}}` is not valid cli: an interpreted literal may not start + # with a dot, so the value is bound to a local name first. + fld <- .field + allowed <- if (identical(.field, "reac")) { + c( + "pt", "meddra_code", "meddra_pt", + names(faers_meddra(.object, use = "hierarchy")) + ) + } else if (is.null(.object@db)) { + names(faers_get(.object, .field)) + } else { + # `faers_get()` on a db object collects the entire table, which would + # read millions of rows just to learn the column names. The catalog has + # them for free; only the MedDRA hierarchy has to be added back by + # hand, because it is joined in rather than stored. + c( + DBI::dbListFields(.object@db@con, db_field_table(.field)), + if (field_needs_meddra(.object, .field)) db_meddra_columns(.object) + ) + } + bad <- setdiff(.events, allowed) + if (length(bad)) { + cli::cli_abort(c( + "{qty(length(bad))}Unknown column{?s} of the standardized {.field {fld}} data: {.val {bad}}", + i = "Available columns: {.val {allowed}}" + )) + } + list(field = .field, allowed = allowed) +} + +# ---------- comparison plan ---------- + +# What is compared against what. The two modes are kept apart here so no +# downstream step has to guess: a comparison is always an explicit list. +.compare_plan <- function(.mode, .comparisons, group_names) { + if (identical(.mode, "background")) { + if (!is.null(.comparisons)) { + cli::cli_inform(c( + "{.arg .comparisons} is ignored with {.val .mode = \"background\"}", + i = "Every group is compared against the rest of the study scope" + )) + } + return(lapply(group_names, function(g) { + list( + comparison_id = paste0(g, "_vs_rest_of_scope"), + mode = "background", + group1 = g, group2 = NA_character_, + background_id = "rest_of_scope" + ) + })) + } + # ---- pairwise ---- + if (is.null(.comparisons)) { + cli::cli_abort(c( + "{.arg .comparisons} must be supplied with {.val .mode = \"pairwise\"}", + i = "Each pair is contrasted against a different background, so they are never run implicitly", + i = "Available groups: {.val {group_names}}", + i = "Example: {.code .comparisons = list(c(\"{group_names[[1L]]}\", \"{group_names[[length(group_names)]]}\"))}" + )) + } + if (!is.list(.comparisons) || !length(.comparisons)) { + cli::cli_abort("{.arg .comparisons} must be a non-empty list of length-2 character vectors") + } + out <- lapply(seq_along(.comparisons), function(i) { + pair <- .comparisons[[i]] + if (!is.character(pair) || length(pair) != 2L || anyNA(pair)) { + cli::cli_abort(c( + "{.arg .comparisons}[[{i}]] must be a character vector of length 2", + i = "Available groups: {.val {group_names}}" + )) + } + bad <- setdiff(pair, group_names) + if (length(bad)) { + cli::cli_abort(c( + "{.arg .comparisons}[[{i}]] refers to unknown group{?s} {.val {bad}}", + i = "Available groups: {.val {group_names}}" + )) + } + if (identical(pair[[1L]], pair[[2L]])) { + cli::cli_abort("{.arg .comparisons}[[{i}]] names the same group twice") + } + list( + comparison_id = paste0(pair[[1L]], "_vs_", pair[[2L]]), + mode = "pairwise", + group1 = pair[[1L]], group2 = pair[[2L]], + background_id = pair[[2L]] + ) + }) + # `comparison_id` is the column name of `matrices$signal` and the key + # `signal_results` is cast on, so two comparisons sharing one id would be + # cast together and their metric values silently replaced by row counts. + # Refuse instead of returning a matrix that looks plausible but is wrong. + # The same pair listed twice is the common cause; a `_vs_` inside a group + # name (`A_vs_B` vs `C` next to `A` vs `B_vs_C`) is the other one. + ids <- vapply(out, function(x) x$comparison_id, character(1L)) + dup <- unique(ids[duplicated(ids)]) + if (length(dup)) { + entries <- vapply( + .comparisons[ids %chin% dup], paste, character(1L), collapse = " vs " + ) + cli::cli_abort(c( + "{.arg .comparisons} must define distinct comparisons", + x = "Duplicated {.field comparison_id}: {.val {dup}}", + i = "Colliding entries: {.val {entries}}", + i = "Every comparison is one column of {.field matrices$signal}, so the ids have to be unique" + )) + } + out +} + +# ---------- contingency tables ---------- + +# One 2x2 per comparison. Returns a list aligned with `plan`, each element +# carrying its plan entry, the table, and the `n_total` the table conserves. +.compare_tables <- function(plan, per_group, scope_counts, ids, .events, + n_scope, .object) { + lapply(plan, function(cmp) { + if (identical(cmp$mode, "background")) { + ct <- .compare_table_background( + data.table::copy(scope_counts), + data.table::copy(per_group[[cmp$group1]]), + .events, n_scope, length(ids[[cmp$group1]]) + ) + return(list(plan = cmp, ct = ct, n_total = n_scope)) + } + # Pairwise: the arithmetic assumes disjoint groups, so refuse to build a + # table whose denominator would silently double-count shared reports. + overlap <- intersect(ids[[cmp$group1]], ids[[cmp$group2]]) + if (length(overlap)) { + cli::cli_abort(c( + "Groups {.val {cmp$group1}} and {.val {cmp$group2}} share {length(overlap)} report{?s}", + i = "A pairwise table needs disjoint groups: use {.val .overlap = \"exclude\"}, {.val \"repartition\"} or {.code .split = \"joint\"}" + )) + } + n1 <- length(ids[[cmp$group1]]) + n0 <- length(ids[[cmp$group2]]) + ct <- .compare_table_pairwise( + data.table::copy(per_group[[cmp$group1]]), + data.table::copy(per_group[[cmp$group2]]), + .events, n1, n0 + ) + list(plan = cmp, ct = ct, n_total = n1 + n0) + }) +} + +# ---------- statistics ---------- + +# Run `phv_signal()` once per comparison. Statistics are never reimplemented: +# the table is handed to the same function a single-group analysis would use. +# This holds for an empty table too - `phv_signal()` returns its full schema on +# zero-length input - so an empty comparison produces the same columns as a +# populated one and no result shape depends on the data. +.compare_signal <- function(tables, .methods, .phv_signal_params, BPPARAM) { + lapply(tables, function(tbl) { + ct <- tbl$ct + sig <- do.call( + phv_signal, + c( + ct[, c("a", "b", "c", "d")], + list(methods = .methods, BPPARAM = BPPARAM), + .phv_signal_params + ) + ) + list(plan = tbl$plan, ct = ct, n_total = tbl$n_total, signal = sig) + }) +} + +# ---------- result tables ---------- + +# One row per comparison x event: the contingency table, the metrics, the +# provenance (`mode`, `group1`, `background_id`, `n_total`) and the `status` +# flag. `.min_a` drops rows below the reporting threshold and reports the count +# through `attr(, "n_below_min_a")` rather than hiding it. +.compare_signal_results <- function(signal, plan, ids, .events, .min_a) { + n_below <- 0L + out <- data.table::rbindlist(lapply(signal, function(tbl) { + ct <- tbl$ct + if (!nrow(ct)) { + return(NULL) + } + cmp <- tbl$plan + sig <- tbl$signal + res <- data.table::data.table( + comparison_id = cmp$comparison_id, + mode = cmp$mode, + group1 = cmp$group1, + background_id = cmp$background_id, + n_total = as.integer(tbl$n_total) + ) + res <- cbind(res, ct, sig) + res + }), use.names = TRUE, fill = TRUE) + + if (!nrow(out)) { + # Every comparison had an empty contingency table. Rebuild the schema + # from the (zero-row) signal tables so an empty result carries exactly + # the columns a populated one does, metric columns included - the + # metric names come from `phv_signal()` instead of being hardcoded, so + # e.g. `chisq` is never returned without its `chisq_pvalue` companion. + sig_names <- if (length(signal)) names(signal[[1L]]$signal) else character() + out <- data.table::data.table( + comparison_id = character(), mode = character(), group1 = character(), + background_id = character(), n_total = integer() + ) + for (e in .events) data.table::set(out, j = e, value = signal[[1L]]$ct[[e]][0L]) + for (v in c("a", "b", "c", "d")) data.table::set(out, j = v, value = integer()) + for (v in sig_names) data.table::set(out, j = v, value = numeric()) + data.table::set(out, j = "status", value = character()) + data.table::setattr(out, "n_below_min_a", 0L) + return(out[]) + } + + below <- out$a < .min_a + n_below <- sum(below) + out[, status := .compare_status(.SD), .SDcols = c("a", "b", "c", "d")] + if (n_below) { + out <- out[!below] + } + data.table::setattr(out, "n_below_min_a", as.integer(n_below)) + out[] +} + +# Which group was compared against which background, with the sizes and the +# overlap removals that produced them. +# +# Count a shared report as removed only if it is absent from both final arms. +# A joint split can move reports out of a pair even with `.overlap = "keep"`. +.compare_comparison_table <- function(plan, ids, n_scope, .overlap, + raw_ids_by_group) { + data.table::rbindlist(lapply(plan, function(cmp) { + if (identical(cmp$mode, "background")) { + return(data.table::data.table( + comparison_id = cmp$comparison_id, + mode = cmp$mode, + group1 = cmp$group1, + group2 = NA_character_, + background_id = cmp$background_id, + n1 = as.integer(length(ids[[cmp$group1]])), + n0 = as.integer(n_scope - length(ids[[cmp$group1]])), + n_total = as.integer(n_scope), + n_overlap_removed = 0L, + n_overlap_shared = 0L, + strategy = .overlap + )) + } + group1_ids <- ids[[cmp$group1]] + group2_ids <- ids[[cmp$group2]] + shared <- intersect( + raw_ids_by_group[[cmp$group1]], raw_ids_by_group[[cmp$group2]] + ) + removed <- setdiff(setdiff(shared, group1_ids), group2_ids) + data.table::data.table( + comparison_id = cmp$comparison_id, + mode = cmp$mode, + group1 = cmp$group1, + group2 = cmp$group2, + background_id = cmp$background_id, + n1 = as.integer(length(group1_ids)), + n0 = as.integer(length(group2_ids)), + n_total = as.integer(length(group1_ids) + length(group2_ids)), + n_overlap_removed = as.integer(length(removed)), + n_overlap_shared = as.integer(length(shared)), + strategy = .overlap + ) + }), fill = TRUE) +} + +# Per group x event: the group's report count, its denominator (the group's own +# report count, so `share` is a within-group proportion) and the same quantities +# over the whole scope. +# +# Every group is laid out over the SCOPE's candidate events, with `N = 0` where +# the group has no report for an event. That is what makes `event_profile` and +# the count/share matrices a complete events x groups grid consistent with +# `signal_results`, whose rows also come from the scope counts. +.compare_event_profile <- function(groups, per_group, scope_counts, .events, + n_scope, .field = "reac") { + scope <- data.table::copy(scope_counts) + data.table::setnames(scope, "N", "universe_N") + cn <- .events + out <- data.table::rbindlist(lapply(names(per_group), function(nm) { + g <- data.table::copy(per_group[[nm]]) + grid <- merge( + scope[, c(cn, "universe_N"), with = FALSE], g, + by = cn, all.x = TRUE, sort = FALSE + ) + grid[is.na(N), N := 0L] + grid[, group := nm] + grid + }), use.names = TRUE, fill = TRUE) + if (!nrow(out)) { + # Keep the full schema so an empty `.event_set` selection still yields a + # well-formed, zero-row profile instead of a table whose columns are + # missing for every downstream consumer. + empty <- data.table::data.table(group = character()) + for (e in .events) data.table::set(empty, j = e, value = scope_counts[[e]][0L]) + for (v in c("N", "denominator")) data.table::set(empty, j = v, value = integer()) + for (v in c("share", "universe_N", "universe_share")) { + data.table::set(empty, j = v, value = numeric()) + } + data.table::setcolorder( + empty, + c("group", .events, "N", "denominator", "share", "universe_N", "universe_share") + ) + return(empty[]) + } + out[, denominator := as.integer(length(groups$ids[[.BY$group]])), by = "group"] + out[, share := N / denominator] + out[, universe_share := universe_N / n_scope] + data.table::setcolorder( + out, + c("group", .events, "N", "denominator", "share", "universe_N", "universe_share") + ) + data.table::setorderv( + out, + c("group", "N", .events), + order = c(1L, -1L, rep(1L, length(.events))) + ) + out[] +} + +# ---------- metadata ---------- + +# Everything a reader needs to reproduce the run: what the scope was, how the +# groups were defined, which comparison each table belongs to, which rules +# filtered rows, and which software versions produced it. +.compare_metadata <- function(.object, raw_groups, groups, plan, .mode, .split, + .overlap, .events, .event_set, .min_a, .methods, + .phv_signal_params, .top_n, .matrix_metric, + .field, n_scope, scope_counts, signal_results, + .events_check, trunc, sel, na_rm) { + meddra <- faers_meddra(.object, use = "hierarchy") + n_shared_pairs <- sum(groups$overlaps$n_intersection > 0L) + n_reports_shared <- 0L + if (n_shared_pairs > 0L) { + report_ids <- unlist(groups$raw_ids, use.names = FALSE) + n_reports_shared <- length(unique(report_ids[duplicated(report_ids)])) + } + overlap_note <- if (.split == "joint") { + "The joint split puts reports shared by both definitions in their own group." + } else { + switch(.overlap, + keep = paste( + "Reports remain in every group they match. Background comparisons", + "use the rest of the study scope. Pairwise comparisons require", + "disjoint groups." + ), + exclude = "Reports matching multiple definitions are removed from all groups.", + repartition = "Reports shared by both definitions are placed in their own group.", + error = "An overlapping pair aborts the run." + ) + } + list( + call = match.call(expand.dots = FALSE), + faers_version = as.character(utils::packageVersion("faers")), + r_version = paste(R.version$major, R.version$minor, sep = "."), + timestamp = format(Sys.time(), tz = "UTC", usetz = TRUE), + mode = .mode, + split = .split, + overlap_strategy = .overlap, + groups = raw_groups, + scope = list( + n_reports_universe = as.integer(n_scope), + year = .object@year, + quarter = .object@quarter, + standardization = .object@standardization, + deduplication = .object@deduplication, + n_deleted_cases = length(faers_deleted_cases(.object)), + meddra_version = if (is.null(meddra)) NA_character_ else meddra_version(.object@meddra), + n_meddra_hierarchy_columns = if (is.null(meddra)) 0L else ncol(meddra) + ), + events = .events, + event_scope = list( + field = .field, + allowed_columns = .events_check$allowed, + event_set = .compare_event_set_label(.event_set), + n_candidate_events = sel$n_candidates %||% nrow(scope_counts), + n_selected_events = sel$n_selected %||% nrow(scope_counts), + n_universe_events = nrow(scope_counts), + min_a = .min_a, + n_below_min_a = attr(signal_results, "n_below_min_a") %||% 0L + ), + methods = .methods %||% SCAN_ALL_METHODS, + phv_signal_params = .phv_signal_params, + denominator_definition = switch(.mode, + background = "n = |U|: each group is compared against the rest of the study scope, a + b + c + d == |U|", + pairwise = "n = |G1| + |G2|: the background is the selected second group, a + b + c + d == |G1| + |G2|" + ), + background_definition = switch(.mode, + background = "rest_of_scope = U minus the compared group; the same U is used for every group", + pairwise = "the other group of the pair; the denominator changes with every comparison" + ), + comparisons = vapply(plan, `[[`, character(1L), "comparison_id"), + overlap_handling = list( + strategy = .overlap, + n_shared_pairs = n_shared_pairs, + n_reports_shared = n_reports_shared, + pairwise = .mode == "pairwise", + note = overlap_note + ), + missing = list( + na_rm = na_rm, + note = if (na_rm) { + paste( + "Rows with missing event values are excluded from event counts.", + "Report denominators use all reports in each group or scope." + ) + } else { + "NA event values are kept as their own row, matching faers_counts() defaults" + } + ), + truncation = list( + top_n = .top_n, + matrices_applied = trunc$truncated, + event_profile_applied = trunc$truncated, + signal_results_applied = FALSE, + rule = trunc$rule %||% NA_character_, + n_events_kept = trunc$n_kept %||% NA_integer_, + note = paste( + "`.top_n` truncates the display layer only: `event_profile` and", + "the matrices cover the union of each group's top-N events.", + "The matrices use the same event order. When a signal metric is", + "available, its matrix retains all planned comparison columns", + "and uses NA for cells without a result. `signal_results`", + "includes every row that meets `.min_a`." + ) + ), + display_subset = list( + event_profile = trunc$truncated, + matrices = trunc$truncated, + signal_results = FALSE, + top_n = .top_n, + rule = "per-group top-N by report count, union across groups" + ), + matrix_metric = .matrix_metric %||% "first *_ci_low column", + interaction_test = "None. Joint groups are a descriptive comparison and disproportionality analysis of co-reported drugs; a formal interaction test requires its own method definition." + ) +} diff --git a/R/counts-db.R b/R/counts-db.R index d724ea9..1dcd134 100644 --- a/R/counts-db.R +++ b/R/counts-db.R @@ -45,7 +45,11 @@ counts_db <- function(.object, .events = "soc_name", .fn = NULL, ..., if (meddra && !DB_MEDDRA_TABLE %in% DBI::dbListTables(.object@db@con)) { db_ingest_meddra(.object@db@con, .object) } - q <- db_counts_query(.field, .events, na_rm = .na.rm, meddra = meddra) + q <- db_counts_query( + .field, .events, + na_rm = .na.rm, meddra = meddra, + hierarchy = db_meddra_columns(.object) + ) out <- DBI::dbGetQuery(.object@db@con, q) out <- data.table::as.data.table(out) # Byte-parity with the memory path (keyby + integer counts): diff --git a/R/phv_.R b/R/phv_.R index e824e11..9a6e0ff 100644 --- a/R/phv_.R +++ b/R/phv_.R @@ -180,6 +180,12 @@ phv_prr <- function(a, b, c, d, alpha = 0.05) { #' @rdname phv_signal phv_chisq <- function(a, b, c, d, correct = TRUE, BPPARAM = SerialParam()) { assert_phv_table(a, b, c, d) + # Zero-length input has no test to run. Returning the full schema keeps the + # result bindable with a non-empty call (e.g. `phv_signal()` on an empty + # group), instead of `setnames()` failing on a zero-column data.table. + if (!length(a)) { + return(data.table(chisq = numeric(), pvalue = numeric())) + } out <- BiocParallel::bpmapply( function(n11, n10, n01, n00) { out <- stats::chisq.test( @@ -202,6 +208,13 @@ phv_chisq <- function(a, b, c, d, correct = TRUE, BPPARAM = SerialParam()) { #' @rdname phv_signal phv_fisher <- function(a, b, c, d, alpha = 0.05, BPPARAM = SerialParam()) { assert_phv_table(a, b, c, d) + # See `phv_chisq()`: keep the schema so a zero-length call stays bindable. + if (!length(a)) { + return(data.table( + odds_ratio = numeric(), ci_low = numeric(), + ci_high = numeric(), pvalue = numeric() + )) + } out <- BiocParallel::bpmapply( function(n11, n10, n01, n00) { out <- stats::fisher.test( @@ -288,6 +301,11 @@ phv_bcpnn_mcmc <- function(a, b, c, d, alpha = 0.05, n_mcmc = 1e5L, BPPARAM = Se gamma11 * (gamma11 + gamma10 + gamma01 + gamma00) / ((gamma11 + gamma10) * (gamma11 + gamma01)) ) + if (!length(a)) { + # `ic` is computed above and is already zero-length; the MCMC loop has + # nothing to sample, so return the schema directly (see `phv_chisq()`). + return(data.table(ic = ic, ci_low = numeric(), ci_high = numeric())) + } out <- BiocParallel::bpmapply( function(g11, g10, g01, g00) { # sample from the posterior distribution diff --git a/R/utils-db.R b/R/utils-db.R index 098c67b..92a60dc 100644 --- a/R/utils-db.R +++ b/R/utils-db.R @@ -164,6 +164,16 @@ field_needs_meddra <- function(object, field) { isTRUE(object@standardization) && any(field == c("reac", "indi")) } +# Names of the columns `faers_get()` adds to a standardized `reac`/`indi` +# field from the MedDRA hierarchy. Empty when the object carries no MedDRA +# data. `db_counts_query()` needs these to qualify only the join-side columns. +db_meddra_columns <- function(object) { + if (!isTRUE(object@standardization) || is.null(object@meddra)) { + return(character()) + } + names(object@meddra@hierarchy) +} + # Build a SQL string that counts DISTINCT primaryid per event group, with an # optional WHERE clause (used for .na.rm and for event-set filtering). # @@ -171,15 +181,22 @@ field_needs_meddra <- function(object, field) { # that hierarchy-derived event columns (soc_name, pt_name, ...) can be grouped # exactly as the in-memory path derives them — without materializing the field. # +# Only the columns that actually come from the hierarchy are qualified with +# `m.`; the field's own columns (`pt`, `meddra_code`, `meddra_pt`, ...) stay on +# `f.`, because `faers_get()` enriches `reac`/`indi` with the hierarchy rather +# than replacing its columns. `hierarchy` lists the added column names. +# # The output column for a single event is named after the event itself, # matching the memory path's keyby column name. -db_counts_query <- function(field, events, na_rm = FALSE, meddra = FALSE) { +db_counts_query <- function(field, events, na_rm = FALSE, meddra = FALSE, + hierarchy = character()) { tbl <- db_field_table(field) - join <- "" if (isTRUE(meddra)) { tbl <- sprintf("%s AS f LEFT JOIN %s AS m ON f.meddra_hierarchy_idx = m.idx", tbl, DB_MEDDRA_TABLE) - ev <- vapply(events, function(e) paste0("m.", db_qident(e)), character(1L)) + ev <- vapply(events, function(e) { + if (e %chin% hierarchy) paste0("m.", db_qident(e)) else paste0("f.", db_qident(e)) + }, character(1L)) primaryid_sql <- "f.primaryid" } else { ev <- vapply(events, db_qident, character(1L)) diff --git a/man/faers_compare.Rd b/man/faers_compare.Rd new file mode 100644 index 0000000..6f16f68 --- /dev/null +++ b/man/faers_compare.Rd @@ -0,0 +1,231 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/compare.R +\name{faers_compare} +\alias{faers_compare} +\title{Compare multiple drug groups against a shared background} +\usage{ +faers_compare( + .object, + .groups, + ..., + .split = c("none", "joint"), + .mode = c("background", "pairwise"), + .comparisons = NULL, + .overlap = c("keep", "exclude", "repartition", "error"), + .events = "pt", + .event_set = NULL, + .min_a = 0L, + .methods = c("ror", "prr"), + .top_n = NULL, + .matrix_metric = NULL, + .diagnose_combination = TRUE, + .phv_signal_params = list(), + BPPARAM = BiocParallel::SerialParam() +) +} +\arguments{ +\item{.object}{A \link{FAERSascii} object. Must be standardized with +\code{\link[=faers_standardize]{faers_standardize()}} and de-duplicated with \code{\link[=faers_dedup]{faers_dedup()}}.} + +\item{.groups}{A named list of group definitions, see \code{\link[=faers_group_ids]{faers_group_ids()}}.} + +\item{...}{Counting options from \code{\link[=faers_counts]{faers_counts()}}, e.g. \code{.field}, +\code{.fn} or \code{.na.rm}. A supplied \code{.fn} runs once on the study scope's +selected field, which is read into memory on both backends. It must +return a data.table with \code{primaryid} and all \code{.events} columns, and its +report IDs must belong to the study scope. Additional arguments are passed +to \code{.fn}. When \code{.na.rm = TRUE}, rows with missing event values are omitted +from event counts. Denominators use all reports in each group or study scope.} + +\item{.split}{\code{"none"} (default) or \code{"joint"}; see \code{\link[=faers_group_ids]{faers_group_ids()}}.} + +\item{.mode}{\code{"background"} (default) or \code{"pairwise"}.} + +\item{.comparisons}{For \code{.mode = "pairwise"}, a list of length-2 character +vectors naming the groups to contrast, e.g. +\code{list(c("A-only", "B-only"), c("A+B", "A-only"))}. Ignored, and set to +every group, in \code{"background"} mode.} + +\item{.overlap}{\code{"keep"} (default), \code{"exclude"}, \code{"repartition"} or +\code{"error"}; see \code{\link[=faers_group_ids]{faers_group_ids()}}.} + +\item{.events}{A character vector naming the event column(s) in \code{.field}, +passed to \code{\link[=faers_counts]{faers_counts()}}. Defaults to \code{"pt"}. With more than one column +the combination defines the event, and the matrices use a collapsed +\code{event_label} built with \code{paste(..., sep = " | ")}.} + +\item{.event_set}{\code{NULL} (default) to keep every candidate event, or a +selector that narrows them. As in \code{\link[=faers_phv_composite]{faers_phv_composite()}} it may be a +character vector of event values, a logical vector with one value per +candidate event, or a function applied to the event values that returns a +logical vector. Selectors use the sorted distinct values of the first +\code{.events} column, with missing values last when present. A function can +select numeric values or missing values, for example using \code{is.na}. +Unlike \code{\link[=faers_phv_composite]{faers_phv_composite()}} the selected events are +\strong{not} collapsed into a single composite row: each event keeps its own row +in \code{event_profile} and \code{signal_results}, which is what makes the event +spectrum and the signal matrix meaningful. The candidate count, the +selected count and the selector description are recorded in +\code{metadata$event_scope}.} + +\item{.min_a}{A whole number, \code{0} (default) to keep every candidate event or +a reporting threshold. Comparisons whose \code{a} falls below it are dropped and +counted in \code{metadata$event_scope$n_below_min_a}. Unlike +\code{\link[=faers_phv_scan]{faers_phv_scan()}} there is no implicit \code{3} here: candidate events are +chosen by the caller's \code{.events}/\code{.event_set}.} + +\item{.methods}{Methods passed to \code{\link[=phv_signal]{phv_signal()}}. Defaults to +\code{c("ror", "prr")}.} + +\item{.top_n}{\code{NULL} (default) for no truncation, or a whole number for the +display subset described in \emph{Details}.} + +\item{.matrix_metric}{\code{NULL} to use the first available \verb{*_ci_low} column, +or the name of the metric column to place in \code{matrices$signal}.} + +\item{.diagnose_combination}{Forwarded to \code{\link[=faers_group_ids]{faers_group_ids()}}.} + +\item{.phv_signal_params}{Other arguments passed to \code{\link[=phv_signal]{phv_signal()}}.} + +\item{BPPARAM}{Passed to \code{\link[=phv_signal]{phv_signal()}}.} +} +\value{ +A named list of \link[data.table:data.table]{data.table} objects: +\itemize{ +\item \code{group_summary}: groups, report counts, share of scope, overlap removals, +source exposure definitions and the single-row combination count. See +\code{\link[=faers_group_ids]{faers_group_ids()}} for the columns in this table. +\item \code{event_profile}: per group and event, \code{N} reports, the \code{denominator} and +the within-group \code{share}, plus the same quantities over the whole scope +(\code{universe_N}, \code{universe_share}). Every group is laid out over the scope's +candidate events, so absent combinations appear as \code{N = 0} and the table is +a complete events x groups grid. Its events are a superset of the ones in +\code{signal_results}, which \code{.min_a} narrows to the tested comparisons; with +\code{.top_n} it is the displayed grid that every matrix shares. +\item \code{comparisons}: which group was compared with which background, the group +sizes and the overlap removal counts. For a pair, \code{n_overlap_shared} +counts reports shared by the two groups before reconciliation, using the +original definition for each single-definition group and the final set +for a derived intersection or complement. \code{n_overlap_removed} counts the +shared reports absent from both final groups, once per report. +\item \code{signal_results}: one row per comparison x event with \code{a}, \code{b}, \code{c}, \code{d}, +the \code{expected} count, every metric from \code{\link[=phv_signal]{phv_signal()}} and a \code{status} +column (\code{"ok"}, \code{"zero_cell"}, \code{"empty_group"}). The status is +\code{"empty_group"} if either side of the comparison has no reports. +\item \code{matrices}: \code{count}, \code{share} and one signal matrix (named after +\code{.matrix_metric}, or \code{signal} for the default \verb{*_ci_low} column), each +event x group/comparison. \code{count} and \code{share} cover the profile's events; +with a signal metric selected, the signal matrix has one column per +planned comparison and covers the events in \code{signal_results}. With +\code{.top_n}, it covers all displayed events in the same order as the count +matrix. Cells without a signal result contain \code{NA}. +\item \code{metadata}: scope, groups, events, comparison and denominator definitions, +versions, missing-data and truncation records. Overlap diagnostics count +pairs with a nonempty intersection and distinct reports shared by two or +more input definitions, before splitting or overlap handling. +\item \code{group_overlaps}: pairwise intersections of the exposure definitions. +} +} +\description{ +\code{faers_compare()} takes a study scope (a standardized and de-duplicated +\link{FAERSascii} object) plus one or more drug exposure definitions, builds the +report groups, counts every event in every group, runs disproportionality +analysis for each comparison and returns the results side by side: group +summary, event profile, the comparison definitions, the per-comparison +signal table, plotting-ready matrices and a metadata record. +} +\details{ +\subsection{Study scope and background}{ + +\code{.object} is the scope \code{U}; narrow it first with \code{\link[=faers_restrict]{faers_restrict()}}. Both +comparison modes only ever look inside \code{U}. +\itemize{ +\item \code{.mode = "background"}: every group \code{G} is compared with the rest of \code{U}, +i.e. the 2x2 is \code{a} = reports of \code{G} with the event, \code{c} = reports of +\verb{U \\ G} with the event, over \verb{n = |U|}. Each analysis uses the same \code{U}, +reports are de-duplicated per table, and every table satisfies +\verb{a + b + c + d == |U|}. Identical to +\code{faers_phv_table(.object = G, .full = U)}. +\item \code{.mode = "pairwise"}: the background is a \emph{selected} second group, so +\verb{n = |G1| + |G2|} and the denominator changes with every pair. Identical to +\code{faers_phv_table(.object = G1, .object2 = G2)} once overlap is reconciled. +\code{.comparisons} must be given explicitly; \code{NULL} aborts instead of silently +running every pair, because per-pair denominators invite uncorrected +multiple comparisons. +} + +The two modes are marked on every result row (\code{mode}, \code{comparison_id}, +\code{background_id}) and summarised in \code{comparisons}. +} + +\subsection{Overlap}{ + +\code{.overlap} is forwarded to \code{\link[=faers_group_ids]{faers_group_ids()}}. \code{"keep"} (default) is +correct for multi-group background comparisons: each group is compared +against the scope, not against another group, and the shared reports are +reported in \code{group_overlaps}. Before a \emph{pairwise} comparison the two groups +must not overlap; with \code{"keep"} and a non-empty intersection the pair aborts +with the count, so pass \code{"exclude"} (remove the intersection from both, the +removed counts are recorded) or \code{"repartition"}/\code{.split = "joint"} (turn the +intersection into its own group). +} + +\subsection{Joint-group contrast}{ + +\code{faers_group_ids(.split = "joint")} splits two drugs into \code{A-only}, +\code{B-only}, \code{A+B} and \code{Neither} such that the four sets are mutually exclusive +and sum to \code{U}. \code{faers_compare()} accepts such a split either by being given +the four groups as \code{.groups} or by \code{.split = "joint"} directly. The result is +a \strong{descriptive comparison and disproportionality analysis of co-reported +drugs}: it is not a formal drug-interaction test, and \code{Neither} exists +precisely so that the four-way partition stays reportable. +} + +\subsection{Display subsets}{ + +\code{.top_n}, when set, only truncates the \emph{display} layer (\code{event_profile} and +\code{matrices}) using the rule "per group, keep the top N events by report count, +then take the union across groups"; ties break on the event label so the +result is deterministic. The matrices use the same event order, and the +event profile covers the same events. When a signal metric is available, +the matrix retains a column for every planned comparison and fills cells +without a result with \code{NA}. The event profile is flagged with +\code{attr(., "display_subset") = TRUE} and the selection is recorded in +\code{metadata$display_subset}. \code{signal_results} includes every result that +meets \code{.min_a}. +} +} +\examples{ +data <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) +data <- faers_dedup(data) + +# three drug groups, each against the same scope +res <- suppressMessages(faers_compare( + data, + list( + insulin = "insulin|humalog", + biguanide = "metformin", + sulfonylurea = "glyburide|glipizide" + ), + .events = "pt", .min_a = 2L +)) +res$group_summary +res$comparisons +head(res$signal_results) +res$matrices$count[1:5, 1:4] + +# two drugs crossed into four mutually exclusive groups +joint <- suppressMessages(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .split = "joint", .mode = "pairwise", + .comparisons = list(c("A-only", "B-only")), + .events = "pt", .min_a = 1L +)) +joint$comparisons + +} +\seealso{ +\code{\link[=faers_group_ids]{faers_group_ids()}}, \code{\link[=faers_phv_table]{faers_phv_table()}}, \code{\link[=faers_phv_signal]{faers_phv_signal()}}, +\code{\link[=phv_signal]{phv_signal()}}, \code{\link[=faers_phv_scan]{faers_phv_scan()}}, \code{\link[=faers_reports_with]{faers_reports_with()}}, +\code{\link[=faers_restrict]{faers_restrict()}}. +} diff --git a/man/faers_group_ids.Rd b/man/faers_group_ids.Rd new file mode 100644 index 0000000..5fed0ac --- /dev/null +++ b/man/faers_group_ids.Rd @@ -0,0 +1,138 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/compare-groups.R +\name{faers_group_ids} +\alias{faers_group_ids} +\title{Build report groups from drug exposure definitions} +\usage{ +faers_group_ids( + .object, + .groups, + .split = c("none", "joint"), + .overlap = c("keep", "exclude", "repartition", "error"), + .diagnose_combination = TRUE +) +} +\arguments{ +\item{.object}{A \link{FAERSascii} object, standardized with +\code{\link[=faers_standardize]{faers_standardize()}}. It defines the study scope \code{U}.} + +\item{.groups}{A named list of group definitions, see \emph{Details}. +The name \code{primaryid} is reserved for the report ID column.} + +\item{.split}{\code{"none"} (default) keeps the groups as given; \code{"joint"} splits +exactly two groups into \code{A-only}, \code{B-only}, \code{A+B} and \code{Neither}.} + +\item{.overlap}{\code{"keep"}, \code{"exclude"}, \code{"repartition"} or \code{"error"}, see +\emph{Details}.} + +\item{.diagnose_combination}{A bool. If \code{TRUE} (default) the joint group's +single-row (fixed-dose combination) share is computed for +\code{group_summary$n_single_row_both}.} +} +\value{ +A named list: +\itemize{ +\item \code{ids}: named list of sorted, unique \code{primaryid} character vectors. +\item \code{raw_ids}: report ID sets named by the input definitions, before +splitting or overlap handling. +\item \code{membership}: \link[data.table:data.table]{data.table} with one row per scope +report and one logical column per group. +\item \code{summary}: \link[data.table:data.table]{data.table} with \code{group}, \code{n_reports}, +\code{share_of_scope}, \code{n_removed_overlap}, \code{is_empty}, the definition columns +\code{drugs}, \code{roles}, \code{logic}, \code{exclude_drugs}, \code{drug_col}, \code{n_patterns}, and +\code{n_single_row_both}. The \code{source_definitions} list column contains the +named exposure definitions used to build the group, with resolved drug +columns. For an intersection, \code{drugs} and \code{n_patterns} cover both +definitions, \code{roles} are keyed by source group, and \code{logic = "and"} +describes the intersection of the two definitions. The scalar +\code{drug_col} is \code{NA} if the definitions use different columns. +For a group derived from a single definition, +\code{n_removed_overlap} counts reports removed from that definition. The +intersection and \code{Neither} have zero removals. +\item \code{overlaps}: \link[data.table:data.table]{data.table} with \code{group1}, \code{group2}, +\code{n_intersection} and \code{strategy}. +\item \code{scope_ids}: report IDs in the study scope. +} +} +\description{ +\code{faers_group_ids()} resolves one or more named drug exposure definitions into +report (\code{primaryid}) sets within a fixed study scope, diagnoses how much the +groups overlap, and optionally splits two drugs into the four mutually +exclusive joint groups \code{A-only}, \code{B-only}, \code{A+B} and \code{Neither}. +} +\details{ +\subsection{Where the study scope comes from}{ + +The scope \code{U} is \code{.object} itself: narrow it first with \code{\link[=faers_restrict]{faers_restrict()}} +(period, demographic or geographic conditions) so that every group is built +inside one and the same report universe. No second "full database" argument +exists - \code{\link[=faers_compare]{faers_compare()}} compares each group against the rest of \code{U}. +} + +\subsection{Group definitions}{ + +Each element of \code{.groups} is either a character vector of drug name patterns +or a list with the keys \code{.drugs}, \code{.roles}, \code{.logic}, \code{.exclude_drugs} and +\code{.drug_col}, all of which carry the meaning documented in +\code{\link[=faers_reports_with]{faers_reports_with()}} because that function does the matching. In +particular matching is a case-insensitive regular expression, \code{.roles} +restricts which \code{role_cod} values may satisfy a pattern, and under +\code{.logic = "and"} two patterns \strong{may be satisfied by the same drug row} +(fixed-dose combination products). A report matching both an \code{A} and a \code{B} +definition is therefore placed in the joint group \code{A+B}; the +\code{n_single_row_both} column of \code{group_summary} counts how many joint-group +reports come from one such multi-ingredient row. +} + +\subsection{Joint split}{ + +With \code{.split = "joint"} (exactly two groups) the four sets are +\verb{A-only = A \\ B}, \verb{B-only = B \\ A}, \verb{A+B = A n B} and +\verb{Neither = U \\ (A u B)}. The complement is taken against the \strong{same} +exposure definition that built the other group, so a role-restricted \code{B} +(\code{PS}/\code{SS} only) contributes only its role-qualified reports to \code{B} - a +report whose B record carries another role is not silently treated as +B-exposed. The four sets are mutually exclusive and sum to \code{U}. +} + +\subsection{\code{.overlap}}{ + +\code{"keep"} (default) returns the exposure sets as defined and only reports the +pairwise intersections in \code{group_overlaps}; this is what multi-drug +background comparisons need, since each group is compared against the shared +scope rather than against another group. \code{"exclude"} makes the sets mutually +exclusive by removing, from every group, all reports listed in any other +group. \code{"repartition"} (two groups only) keeps the information by turning the +intersection into a third group \verb{&} alongside \code{A-only} and \code{B-only}. +\code{"error"} aborts when any two groups share a report. +} +} +\examples{ +data <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) +data <- faers_dedup(data) + +# three overlapping exposure groups compared against the same scope +groups <- faers_group_ids( + data, + list( + insulin = "insulin|humalog", + biguanide = "metformin", + sulfonylurea = "glyburide|glipizide" + ) +) +groups$summary +groups$overlaps + +# two drugs crossed into A-only / B-only / A+B / Neither +joint <- faers_group_ids( + data, list(A = "insulin|humalog", B = "metformin"), + .split = "joint" +) +lengths(joint$ids) + +} +\seealso{ +\code{\link[=faers_compare]{faers_compare()}} for contingency tables, signal metrics and +matrices built on these groups; \code{\link[=faers_reports_with]{faers_reports_with()}} for the exposure +matching semantics; \code{\link[=faers_restrict]{faers_restrict()}} for fixing the scope first. +} diff --git a/tests/testthat/helper-compare.R b/tests/testthat/helper-compare.R new file mode 100644 index 0000000..2ebe635 --- /dev/null +++ b/tests/testthat/helper-compare.R @@ -0,0 +1,36 @@ +compare_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]]) + ns$db_ingest_meddra(con, mem_obj) + 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 + ) + ) +} + +compare_std_data <- function() { + data <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) + suppressMessages(faers_dedup(data)) +} + +compare_quiet <- function(expr) { + suppressWarnings(suppressMessages(expr)) +} diff --git a/tests/testthat/test-compare-groups.R b/tests/testthat/test-compare-groups.R new file mode 100644 index 0000000..ca1e2d9 --- /dev/null +++ b/tests/testthat/test-compare-groups.R @@ -0,0 +1,255 @@ +test_that("faers_group_ids() keeps groups as defined and reports overlaps", { + data <- compare_std_data() + groups <- compare_quiet(faers_group_ids( + data, + list(insulin = "insulin|humalog", metformin = "metformin") + )) + + expect_named( + groups, + c("ids", "raw_ids", "membership", "summary", "overlaps", "scope_ids") + ) + expect_identical(names(groups$ids), c("insulin", "metformin")) + expect_identical(length(groups$scope_ids), 200L) + + # `"keep"` does not remove anything, but the intersection is reported. + expect_true(all(groups$summary$n_removed_overlap == 0L)) + expect_identical(nrow(groups$overlaps), 1L) + expect_identical( + groups$overlaps$n_intersection, + length(intersect(groups$ids$insulin, groups$ids$metformin)) + ) + + # membership has one row per scope report and one logical column per group. + expect_identical(nrow(groups$membership), length(groups$scope_ids)) + expect_true(all(c("insulin", "metformin") %in% names(groups$membership))) +}) + +test_that("joint split gives four mutually exclusive groups that sum to U", { + data <- compare_std_data() + joint <- compare_quiet(faers_group_ids( + data, + list(A = "insulin|humalog", B = "metformin"), + .split = "joint" + )) + + expect_identical( + names(joint$ids), c("A-only", "B-only", "A+B", "Neither") + ) + # The four sets partition the scope. + expect_identical( + sum(lengths(joint$ids)), length(joint$scope_ids) + ) + for (i in seq_len(4L)) { + for (j in seq_len(4L)) { + if (i < j) { + expect_length(intersect(joint$ids[[i]], joint$ids[[j]]), 0L) + } + } + } + + # Membership is a one-hot encoding. + membership <- as.matrix(joint$membership[, -1L]) + expect_true(all(rowSums(membership) == 1L)) + + # The definitions match set algebra on the raw exposure sets. + ids <- joint$ids + expect_setequal(ids[["A-only"]], setdiff(joint$raw_ids$A, joint$raw_ids$B)) + expect_setequal(ids[["B-only"]], setdiff(joint$raw_ids$B, joint$raw_ids$A)) + expect_setequal(ids[["A+B"]], intersect(joint$raw_ids$A, joint$raw_ids$B)) + expect_setequal( + ids[["Neither"]], + setdiff(joint$scope_ids, union(joint$raw_ids$A, joint$raw_ids$B)) + ) +}) + +test_that("the joint complement uses the same role-restricted definition", { + data <- compare_std_data() + # A report whose only B record carries a role outside the allowed set must + # not be treated as B-exposed by the complement. + joint <- compare_quiet(faers_group_ids( + data, + list( + A = "insulin|humalog", + B = list(.drugs = "metformin", .roles = list(metformin = "PS")) + ), + .split = "joint" + )) + unrestricted <- compare_quiet(faers_group_ids( + data, + list(A = "insulin|humalog", B = "metformin"), + .split = "joint" + )) + + # The restricted B is a subset, so B-only can only shrink or stay equal... + expect_true(length(joint$ids[["B-only"]]) <= length(unrestricted$ids[["B-only"]])) + # ...and every report dropped from B lands outside B, never in A+B. + expect_true(all(joint$ids[["B-only"]] %chin% unrestricted$raw_ids$B)) + expect_true(all(joint$ids[["A+B"]] %chin% joint$raw_ids$B)) +}) + +test_that("a single drug row can satisfy both definitions (fixed-dose products)", { + data <- compare_std_data() + joint <- compare_quiet(faers_group_ids( + data, + list(A = "hydrocodone", B = "acetaminophen"), + .split = "joint" + )) + # The diagnosis is reported and bounded by the joint group size. + expect_true(all(joint$summary$n_single_row_both <= joint$summary$n_reports)) + expect_true("n_single_row_both" %chin% names(joint$summary)) + # This is the documented inheritance from faers_reports_with(): a report + # matching both definitions is placed in `A+B`, not excluded. + expect_true(length(joint$ids[["A+B"]]) >= 0L) +}) + +test_that(".overlap handles shared reports and reports the removals", { + data <- compare_std_data() + groups <- list(A = "insulin|humalog", B = "metformin") + + keep <- compare_quiet(faers_group_ids(data, groups)) + excl <- compare_quiet(faers_group_ids(data, groups, .overlap = "exclude")) + shared <- intersect(keep$ids$A, keep$ids$B) + + # Exclusion removes the intersection from both groups. + expect_length(intersect(excl$ids$A, excl$ids$B), 0L) + expect_setequal(excl$ids$A, setdiff(keep$ids$A, keep$ids$B)) + expect_setequal(excl$ids$B, setdiff(keep$ids$B, keep$ids$A)) + expect_identical( + excl$summary$n_removed_overlap, + c(length(intersect(keep$ids$A, keep$ids$B)), + length(intersect(keep$ids$B, keep$ids$A))) + ) + expect_length(shared, length(shared)) + + # Repartition turns the intersection into its own group. It partitions + # A u B (not the whole scope U): A-only, B-only and A&B are mutually + # exclusive and together contain exactly the reports exposed to either drug. + repart <- compare_quiet(faers_group_ids(data, groups, .overlap = "repartition")) + expect_identical( + names(repart$ids), c("A-only", "B-only", "A&B") + ) + expect_identical( + sum(lengths(repart$ids)), + length(union(keep$ids$A, keep$ids$B)) + ) + expect_setequal( + unlist(repart$ids, use.names = FALSE), + union(keep$ids$A, keep$ids$B) + ) + expect_length(intersect(repart$ids[["A-only"]], repart$ids[["B-only"]]), 0L) + expect_identical( + sum(lengths(repart$ids)), length(keep$ids$A) + length(keep$ids$B) - length(shared) + ) + + # "error" refuses to continue. + expect_error( + compare_quiet(faers_group_ids(data, groups, .overlap = "error")), + "overlap" + ) +}) + +test_that("intersection summaries preserve both exposure definitions", { + data <- compare_std_data() + groups <- list( + A = list( + .drugs = c("insulin", "humalog"), .logic = "or", + .roles = list(insulin = "PS"), .exclude_drugs = "warfarin" + ), + B = list( + .drugs = "metformin", .roles = list(metformin = c("PS", "SS")), + .drug_col = "prod_ai" + ) + ) + for (split in c("joint", "none")) { + result <- faers_group_ids( + data, groups, .split = split, + .overlap = if (split == "joint") "keep" else "repartition" + ) + both <- if (split == "joint") "A+B" else "A&B" + summary <- result$summary[group == both] + expect_identical(summary$drugs[[1L]], c("insulin", "humalog", "metformin")) + expect_identical(summary$n_patterns, 3L) + expect_identical(summary$logic, "and") + expect_identical(summary$drug_col, NA_character_) + expect_identical(summary$roles[[1L]], lapply(groups, `[[`, ".roles")) + defs <- summary$source_definitions[[1L]] + expect_named(defs, c("A", "B")) + expect_identical(defs$A$.logic, "or") + expect_identical(defs$A$.exclude_drugs, "warfarin") + expect_identical(defs$A$.drug_col, "drugname") + expect_identical(defs$B$.drug_col, "prod_ai") + } +}) + +test_that("faers_group_ids() validates its inputs", { + data <- compare_std_data() + + expect_error(faers_group_ids(data, list(primaryid = "insulin")), "reserved name.*primaryid") + + # Unnamed groups. + expect_error( + compare_quiet(faers_group_ids(data, list("insulin", "metformin"))), + "name" + ) + # Unknown definition keys. + expect_error( + compare_quiet(faers_group_ids(data, list(A = list(.nope = "x")))), + "nope" + ) + # A joint split needs exactly two groups. + expect_error( + compare_quiet(faers_group_ids(data, list(A = "insulin"), .split = "joint")), + "two" + ) + # Roles must be named and refer to the group's own drugs. + expect_error( + compare_quiet(faers_group_ids( + data, + list(A = list(.drugs = "insulin", .roles = list(other = "PS"))) + )), + "role" + ) +}) + +test_that("empty groups are legal and flagged", { + data <- compare_std_data() + groups <- compare_quiet(faers_group_ids( + data, + list(A = "insulin|humalog", empty = "no_such_drug_zzz") + )) + expect_identical(length(groups$ids$empty), 0L) + expect_true(groups$summary[group == "empty", is_empty]) + expect_false(groups$summary[group == "A", is_empty]) +}) + +test_that("faers_group_ids() is identical on both backends", { + skip_if_not_installed("duckdb") + skip_if_not_installed("DBI") + + data <- compare_std_data() + db <- compare_db_twin(data) + on.exit(DBI::dbDisconnect(db@db@con, shutdown = TRUE), add = TRUE) + + groups <- list(A = "insulin|humalog", B = "metformin", C = "glyburide") + # `"joint"` and `"repartition"` are defined for exactly two groups. + two <- groups[1:2] + cases <- list( + list(defs = groups, args = list()), + list(defs = two, args = list(.split = "joint")), + list(defs = groups, args = list(.overlap = "exclude")), + list(defs = two, args = list(.overlap = "repartition")) + ) + for (case in cases) { + mem <- compare_quiet(do.call( + faers_group_ids, c(list(data, case$defs), case$args) + )) + dbo <- compare_quiet(do.call( + faers_group_ids, c(list(db, case$defs), case$args) + )) + expect_identical(mem$summary, dbo$summary) + expect_identical(mem$ids, dbo$ids) + expect_identical(mem$overlaps, dbo$overlaps) + expect_identical(mem$membership, dbo$membership) + } +}) diff --git a/tests/testthat/test-compare.R b/tests/testthat/test-compare.R new file mode 100644 index 0000000..c57f116 --- /dev/null +++ b/tests/testthat/test-compare.R @@ -0,0 +1,977 @@ +test_that("background mode conserves the scope in every contingency table", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, + list(A = "insulin|humalog", B = "metformin", C = "glyburide"), + .events = "pt" + )) + + sr <- res$signal_results + expect_true(all(sr$a >= 0L & sr$b >= 0L & sr$c >= 0L & sr$d >= 0L)) + expect_true(all(sr$a + sr$b + sr$c + sr$d == sr$n_total)) + # Every background comparison uses the same scope. + expect_identical(res$metadata$scope$n_reports_universe, 200L) + expect_true(all(sr$n_total == 200L)) + expect_true(all(sr$mode == "background")) + expect_true(all(sr$background_id == "rest_of_scope")) + # The report count of a group bounds its event counts. + expect_true(all(sr$a <= sr$n_total)) + + # One comparison per group. + expect_identical( + res$comparisons$comparison_id, + paste0(c("A", "B", "C"), "_vs_rest_of_scope") + ) + expect_identical(res$comparisons$n1, as.integer(res$group_summary$n_reports)) + expect_identical(res$comparisons$n0, 200L - as.integer(res$group_summary$n_reports)) +}) + +test_that("the event profile counts reports once, with an explicit denominator", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), .events = "pt" + )) + prof <- res$event_profile + + expect_true(all(prof$N >= 0L)) + expect_true(all(prof$N <= prof$denominator)) + expect_true(all(prof$denominator == res$group_summary$n_reports[ + match(prof$group, res$group_summary$group) + ])) + expect_equal(prof$share, prof$N / prof$denominator) + expect_true(all(prof$universe_N >= prof$N)) + expect_equal(prof$universe_share, prof$universe_N / 200) + + # Every group is laid out over the same candidate events, so the profile is + # a complete grid that lines up with `signal_results`. + expect_identical( + sort(unique(prof$pt)), + sort(unique(res$signal_results$pt)) + ) + expect_identical( + prof[, .N, by = "group"]$N, + rep.int(length(unique(prof$pt)), length(unique(prof$group))) + ) + + # Duplicated drug/event rows must not inflate a count: the group count has + # one row per (report, event) pair, and `faers_counts()` counts DISTINCT + # primaryid, so a report with two matching drug rows still counts once. + # The profile is the full grid (`N = 0` for absent events), so only the rows + # the group actually has are compared against the sparse count table. + ids_a <- compare_quiet(faers_reports_with(data, "insulin|humalog", .return = "ids")) + direct <- compare_quiet(faers_counts(faers_keep(data, ids_a), .events = "pt")) + sub <- prof[group == "A" & N > 0L][order(pt)] + expect_identical(sub$N, direct[order(pt)]$N[match(sub$pt, direct[order(pt)]$pt)]) + expect_identical(nrow(sub), nrow(direct)) + expect_true(all(prof[group == "A" & !pt %chin% direct$pt]$N == 0L)) +}) + +test_that("a batch result matches the equivalent single call byte for byte", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, + list(insulin = "insulin|humalog", metformin = "metformin"), + .events = "pt", .methods = c("ror", "prr") + )) + + ids <- compare_quiet(faers_reports_with(data, "insulin|humalog", .return = "ids")) + single <- compare_quiet(faers_phv_signal( + faers_keep(data, ids), + .events = "pt", .full = data, .methods = c("ror", "prr") + )) + + batch <- res$signal_results[ + comparison_id == "insulin_vs_rest_of_scope", + names(single), + with = FALSE + ] + # The only extra column `faers_compare()` adds is `status`, and the + # `n_below_min_a` attribute tracks a filter that did not drop any row here. + data.table::setattr(batch, "n_below_min_a", NULL) + data.table::setkey(batch, pt) + data.table::setkey(single, pt) + expect_identical(batch, single) + expect_identical(res$metadata$event_scope$n_below_min_a, 0L) + + # The cached-scope identity the implementation relies on: comparing a group + # against the whole scope equals comparing it against the scope minus itself. + full <- compare_quiet(faers_phv_table(faers_keep(data, ids), .events = "pt", .full = data)) + rest <- compare_quiet(faers_phv_table( + faers_keep(data, ids), + .events = "pt", .object2 = faers_keep(data, ids, invert = TRUE) + )) + expect_identical(full, rest) +}) + +test_that("pairwise mode uses the two selected groups as its background", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, + list(A = "insulin|humalog", B = "metformin"), + .mode = "pairwise", .comparisons = list(c("A", "B")), + .overlap = "exclude", .events = "pt" + )) + + expect_identical(nrow(res$comparisons), 1L) + expect_identical(res$comparisons$mode, "pairwise") + expect_identical(res$comparisons$group1, "A") + expect_identical(res$comparisons$group2, "B") + expect_identical(res$comparisons$background_id, "B") + expect_identical(res$comparisons$comparison_id, "A_vs_B") + + sr <- res$signal_results + expect_true(all(sr$mode == "pairwise")) + # Pairwise tables conserve |G1| + |G2|, not the scope. + expect_true(all(sr$a + sr$b + sr$c + sr$d == sr$n_total)) + expect_identical( + unique(sr$n_total), res$comparisons$n1 + res$comparisons$n0 + ) + expect_true(all(sr$a <= res$comparisons$n1)) + expect_true(all(sr$c <= res$comparisons$n0)) + + # Exclusion is applied before the table is built, and the removal is recorded. + groups <- compare_quiet(faers_group_ids( + data, list(A = "insulin|humalog", B = "metformin"), .overlap = "exclude" + )) + expect_identical(res$comparisons$n1, as.integer(length(groups$ids$A))) + expect_identical(res$comparisons$n0, as.integer(length(groups$ids$B))) + # Two reports matched both drugs; "exclude" took them out of both arms. + raw <- compare_quiet(faers_group_ids(data, list(A = "insulin|humalog", B = "metformin"))) + shared <- length(intersect(raw$ids$A, raw$ids$B)) + expect_identical(shared, 2L) + expect_identical(res$comparisons$n_overlap_removed, as.integer(shared)) + expect_identical(res$comparisons$n_overlap_shared, as.integer(shared)) + # The tables are built on the reconciled, disjoint groups. + expect_identical(length(intersect(groups$ids$A, groups$ids$B)), 0L) +}) + +test_that("derived comparisons count shared reports absent from both arms", { + data <- compare_std_data() + groups <- list("A & partner" = "insulin|humalog", "B+other" = "metformin") + raw <- faers_group_ids(data, groups)$raw_ids + n_shared <- length(intersect(raw[[1L]], raw[[2L]])) + expect_gt(n_shared, 0L) + + for (split in c("none", "joint")) { + overlap <- if (split == "joint") "keep" else "repartition" + both <- if (split == "joint") "A & partner+B+other" else "A & partner&B+other" + only <- paste0(names(groups), "-only") + grouped <- faers_group_ids(data, groups, .split = split, .overlap = overlap) + expect_identical(grouped$raw_ids, raw) + expect_identical( + grouped$summary$n_removed_overlap[match(c(only, both), grouped$summary$group)], + c(n_shared, n_shared, 0L) + ) + expect_identical(grouped$summary$drugs[[1L]], groups[[1L]]) + expect_identical(grouped$summary$drugs[[2L]], groups[[2L]]) + + res <- compare_quiet(faers_compare( + data, groups, .split = split, .overlap = overlap, + .mode = "pairwise", .comparisons = list(only, c(both, only[[1L]])) + )) + expect_identical(res$comparisons$n_overlap_shared, rep(n_shared, 2L)) + expect_identical(res$comparisons$n_overlap_removed, c(n_shared, 0L)) + } +}) + +test_that("pairwise mode refuses overlapping groups unless reconciled", { + data <- compare_std_data() + expect_error( + compare_quiet(faers_compare( + data, + list(A = "insulin|humalog", B = "metformin"), + .mode = "pairwise", .comparisons = list(c("A", "B")), + .events = "pt" + )), + "disjoint|overlap" + ) + expect_error( + compare_quiet(faers_compare( + data, + list(A = "insulin|humalog", B = "metformin"), + .mode = "pairwise", .comparisons = list(c("A", "B")), + .overlap = "error", .events = "pt" + )) + ) +}) + +test_that("pairwise mode never runs implicitly", { + data <- compare_std_data() + # Every pair changes the denominator, so an implied batch would invite + # uncorrected multiple comparisons; the plan must be stated explicitly. + expect_error( + compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .mode = "pairwise", .events = "pt" + )), + "comparison" + ) +}) + +test_that("joint groups are mutually exclusive and give a four-way partition", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, + list(A = "insulin|humalog", B = "metformin"), + .split = "joint", .events = "pt" + )) + + expect_identical( + res$group_summary$group, c("A-only", "B-only", "A+B", "Neither") + ) + expect_identical(sum(res$group_summary$n_reports), 200L) + # Background mode still uses the scope as the common denominator. + sr <- res$signal_results + expect_true(all(sr$a + sr$b + sr$c + sr$d == 200L)) + # A joint group can be contrasted with a single-only group. + expect_identical( + sort(unique(res$group_summary$group)), + sort(c("A-only", "B-only", "A+B", "Neither")) + ) +}) + +test_that("status flags zero cells and empty groups without altering the numbers", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), .events = "pt" + )) + sr <- res$signal_results + + expect_true(all(sr$status %chin% c("ok", "zero_cell", "empty_group"))) + expect_true(any(sr$status == "ok")) + # A zero cell is flagged but the metric is left untouched: `a = 0` yields + # `ror = 0` and `ror_ci_high = NaN`, exactly as `phv_ror()` produces. + zero <- sr[a == 0L] + if (nrow(zero)) { + expect_true(all(zero$ror == 0)) + expect_true(all(is.nan(zero$ror_ci_high))) + expect_true(all(zero$status == "zero_cell")) + } + # No cell is imputed: the raw zero is still visible in the table. + expect_true(any(sr$a == 0L)) +}) + +test_that("an empty group is legal and flagged rather than an error", { + data <- compare_std_data() + expect_no_error( + res <- compare_quiet(faers_compare( + data, + list(A = "insulin|humalog", empty = "no_such_drug_zzz"), + .events = "pt" + )) + ) + res <- compare_quiet(faers_compare( + data, + list(A = "insulin|humalog", empty = "no_such_drug_zzz"), + .events = "pt" + )) + expect_true(res$group_summary[group == "empty", is_empty]) + sr <- res$signal_results[comparison_id == "empty_vs_rest_of_scope"] + expect_true(all(sr$a == 0L)) + expect_true(all(sr$b == 0L)) + expect_true(all(sr$status == "empty_group")) +}) + +test_that("an empty side is flagged in either comparison direction", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", empty = "no_such_drug_zzz"), + .mode = "pairwise", + .comparisons = list(c("A", "empty"), c("empty", "A")) + )) + sr <- res$signal_results + expect_setequal(unique(sr$comparison_id), c("A_vs_empty", "empty_vs_A")) + expect_true(all(sr$status == "empty_group")) + expect_true(all(sr[comparison_id == "A_vs_empty", c + d] == 0L)) + expect_true(all(sr[comparison_id == "empty_vs_A", a + b] == 0L)) +}) + +test_that(".min_a filters rows and reports how many were dropped", { + data <- compare_std_data() + loose <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), .events = "pt" + )) + strict <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .min_a = 2L + )) + + expect_true(nrow(strict$signal_results) <= nrow(loose$signal_results)) + expect_true(all(strict$signal_results$a >= 2L)) + expect_identical(strict$metadata$event_scope$min_a, 2L) + expect_identical( + strict$metadata$event_scope$n_below_min_a, + as.integer(sum(loose$signal_results$a < 2L)) + ) +}) + +test_that("repeated or colliding comparisons are refused, never aggregated", { + data <- compare_std_data() + groups <- list(A = "insulin|humalog", B = "metformin", C = "glyburide") + + # The same pair twice used to yield one shared `comparison_id`, so the cast + # that builds `matrices$signal` aggregated the metric into a row count and + # returned a plausible-looking matrix of 2s. + expect_error( + compare_quiet(faers_compare(data, groups, + .mode = "pairwise", .overlap = "exclude", + .comparisons = list(c("A", "B"), c("A", "B")), .events = "pt" + )), + "must define distinct comparisons" + ) + # Two *different* pairs can also collapse onto one id when a group name + # already contains the separator: "A_vs_B" vs "A" and "A" vs "B_vs_A". + named <- list(A = "insulin|humalog", B = "metformin", + "A_vs_B" = "glyburide", "B_vs_A" = "glipizide") + expect_error( + compare_quiet(faers_compare(data, named, + .mode = "pairwise", .overlap = "exclude", + .comparisons = list(c("A_vs_B", "A"), c("A", "B_vs_A")), .events = "pt" + )), + "A_vs_B_vs_A" + ) + # Order matters, so the reversed pair is a genuinely different comparison. + ok <- compare_quiet(faers_compare(data, groups, + .mode = "pairwise", .overlap = "exclude", + .comparisons = list(c("A", "B"), c("B", "A")), .events = "pt" + )) + expect_identical( + setdiff(names(ok$matrices$signal), "pt"), + c("A_vs_B", "B_vs_A") + ) + expect_length(unique(ok$comparisons$comparison_id), 2L) +}) + +test_that("the matrix cast refuses a repeated key instead of aggregating", { + # Defence in depth: even if a caller ever hands `dcast()` a repeated key, + # the matrix must fail loudly rather than turn values into row counts. + bad <- data.table::data.table( + event_label = c("x", "x"), comparison_id = c("c", "c"), value = c(1, 2) + ) + expect_error( + faers:::.compare_matrix(bad, "event_label", "comparison_id", "value", "c"), + "is not unique in the matrix source" + ) + # A zero-row source is legal (an empty group) and still casts. + empty <- bad[0L] + expect_identical( + nrow(faers:::.compare_matrix(empty, "event_label", "comparison_id", "value", "c")), + 0L + ) +}) + +test_that("matrices are event by group, with a signal matrix per comparison", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, + list(A = "insulin|humalog", B = "metformin", C = "glyburide"), + .events = "pt" + )) + m <- res$matrices + + expect_named(m, c("count", "share", "signal")) + expect_identical(names(m$count), c("pt", "A", "B", "C")) + expect_identical(names(m$share), c("pt", "A", "B", "C")) + # The signal matrix is keyed on comparisons, not groups. + expect_identical( + names(m$signal), + c("pt", res$comparisons$comparison_id) + ) + # Counts are integers and shares are proportions of the group denominator. + expect_true(all(vapply(m$count[, -1L], is.integer, logical(1L)))) + expect_true(all(unlist(m$share[, -1L]) >= 0 & unlist(m$share[, -1L]) <= 1)) + # The count matrix agrees with the profile (which is a complete grid). + for (g in c("A", "B", "C")) { + expect_identical( + m$count[[g]], + res$event_profile[group == g]$N[match(m$count$pt, res$event_profile[group == g]$pt)] + ) + } +}) + +test_that(".matrix_metric selects the signal matrix column", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .matrix_metric = "ror" + )) + expect_true("ror" %chin% names(res$matrices)) + expect_identical(res$metadata$matrix_metric, "ror") + + expect_error( + compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .matrix_metric = "not_a_metric" + )), + "not_a_metric" + ) +}) + +test_that(".top_n truncates the display layer only and flags it", { + data <- compare_std_data() + full <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), .events = "pt" + )) + trunc <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .top_n = 5L + )) + + # `signal_results` is never truncated. + expect_identical(nrow(trunc$signal_results), nrow(full$signal_results)) + # The profile keeps the union of each group's top-5 events and stays a + # complete grid, so every group shows the same (unioned) event set. + expect_true(nrow(trunc$event_profile) < nrow(full$event_profile)) + n_groups <- length(unique(trunc$event_profile$group)) + expect_true(length(unique(trunc$event_profile$pt)) <= 5L * n_groups) + expect_identical( + trunc$event_profile[, .N, by = "group"]$N, + rep.int(length(unique(trunc$event_profile$pt)), n_groups) + ) + # Every retained event is a top-5 event of at least one group. + top5 <- full$event_profile[ + order(-N, pt), utils::head(.SD, 5L), by = "group" + ]$pt + expect_true(all(unique(trunc$event_profile$pt) %chin% top5)) + # Flagged in both the attribute and the metadata. + expect_true(isTRUE(attr(trunc$event_profile, "display_subset"))) + expect_true(trunc$metadata$display_subset$event_profile) + expect_true(trunc$metadata$display_subset$matrices) + expect_false(trunc$metadata$display_subset$signal_results) + expect_identical(trunc$metadata$truncation$top_n, 5L) + # Untruncated runs are not flagged. + expect_false(isTRUE(attr(full$event_profile, "display_subset"))) +}) + +test_that("display matrices retain comparisons without any signal rows", { + data <- compare_std_data() + groups <- list(A = "insulin|humalog", B = "no_matching_drug_xyz") + + some <- compare_quiet(faers_compare( + data, groups, .top_n = 2L, .min_a = 1L, .matrix_metric = "expected" + )) + ids <- some$comparisons$comparison_id + signal <- some$matrices$expected + expect_named(signal, c("pt", ids)) + expect_identical(signal$pt, some$matrices$count$pt) + expect_identical(signal$pt, some$matrices$share$pt) + expect_false(ids[[2L]] %in% some$signal_results$comparison_id) + expect_identical(signal[[ids[[2L]]]], rep(NA_real_, nrow(signal))) + expect_true(any(is.finite(signal[[ids[[1L]]]]))) + + none <- compare_quiet(faers_compare( + data, groups, .top_n = 2L, .min_a = length(faers_primaryid(data)) + 1L + )) + expect_equal(nrow(none$signal_results), 0L) + expect_gt(nrow(none$matrices$count), 0L) + expect_named(none$matrices$signal, c("pt", ids)) + expect_identical(none$matrices$signal$pt, none$matrices$count$pt) + for (id in ids) { + expect_identical(none$matrices$signal[[id]], rep(NA_real_, nrow(none$matrices$count))) + } +}) + +test_that(".top_n aligns matrices for numeric event columns", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "age_in_years", .field = "demo", .top_n = 2L + )) + labels <- res$matrices$count$age_in_years + expect_true(is.numeric(labels)) + expect_gt(length(labels), 0L) + expect_identical(res$matrices$share$age_in_years, labels) + expect_identical(res$matrices$signal$age_in_years, labels) +}) + +test_that(".event_set narrows candidate events without collapsing them", { + data <- compare_std_data() + selected <- c("ASTHENIA", "ANAEMIA", "DRUG INTERACTION") + res <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .event_set = selected + )) + + expect_setequal(unique(res$signal_results$pt), selected) + expect_setequal(unique(res$event_profile$pt), selected) + expect_true(all(res$event_profile$pt %chin% selected)) + # One row per event per group, NOT a single composite row. + expect_identical(nrow(res$signal_results), 2L * length(selected)) + expect_identical( + nrow(res$event_profile), 2L * length(selected) + ) + expect_false(any(grepl("Composite", res$signal_results$pt))) + expect_identical(res$metadata$event_scope$n_selected_events, 3L) + + # A function selector behaves like the character selector. + by_function <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .event_set = function(x) x %in% selected + )) + expect_setequal(unique(by_function$signal_results$pt), selected) + + # An empty selection yields well-formed empty tables instead of an error. + none <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .event_set = "NO_SUCH_EVENT_XYZ" + )) + expect_identical(nrow(none$signal_results), 0L) + expect_identical(nrow(none$event_profile), 0L) + expect_true(all( + c("group", "pt", "N", "denominator", "share", "universe_N", "universe_share") %chin% + names(none$event_profile) + )) + # Regression: an empty result must carry the same columns and column types + # as a populated one, metric columns included. It used to be built from a + # hardcoded name list that mismatched `phv_signal()` (e.g. `chisq` without + # `chisq_pvalue`), so an explicit `.matrix_metric = "ror"` aborted on an + # empty selection even though it worked on a populated one. + expect_identical(names(none$signal_results), names(res$signal_results)) + expect_identical( + vapply(none$signal_results, function(x) class(x)[[1L]], character(1L)), + vapply(res$signal_results, function(x) class(x)[[1L]], character(1L)) + ) + # `.min_a` accounting survives the empty branch. + expect_identical(attr(none$signal_results, "n_below_min_a"), 0L) + for (metric in c("ror", "expected", "prr")) { + expect_no_error(compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .event_set = "NO_SUCH_EVENT_XYZ", + .matrix_metric = metric + ))) + } + # A metric that really is unknown is still rejected, empty selection or not. + expect_error( + compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .event_set = "NO_SUCH_EVENT_XYZ", + .matrix_metric = "no_such_metric" + )), + "is not a column" + ) + + # A selector of the wrong shape is rejected. + expect_error( + compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .event_set = c(TRUE, FALSE) + )), + "one value per candidate event" + ) + expect_error( + compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = "pt", .event_set = 1:3 + )), + "character vector, a logical vector, or a function" + ) +}) + +test_that(".event_set selects numeric and missing event values", { + data <- compare_std_data() + groups <- list(A = "insulin|humalog", B = "metformin") + demo <- data.table::copy(faers_get(data, "demo")) + demo[1L, age_in_years := NA_real_] + data@data$demo <- demo + ages <- demo$age_in_years + compare_age <- function(object, selector, na_rm = FALSE) { + compare_quiet(faers_compare( + object, groups, .field = "demo", .events = "age_in_years", + .event_set = selector, .na.rm = na_rm + )) + } + + older <- compare_age(data, function(x) x >= 50) + expect_setequal(older$event_profile$age_in_years, ages[!is.na(ages) & ages >= 50]) + expect_identical(older$metadata$event_scope$n_candidate_events, length(unique(ages))) + + age <- ages[!is.na(ages)][[1L]] + expect_identical(unique(compare_age(data, as.character(age))$signal_results$age_in_years), age) + missing_age <- compare_age(data, is.na) + expect_identical(unique(missing_age$event_profile$age_in_years), NA_real_) + expect_identical(missing_age$metadata$event_scope$n_selected_events, 1L) + expect_identical( + unique(missing_age$event_profile$universe_N), + sum(is.na(ages)) + ) + dropped <- compare_age(data, is.na, TRUE) + expect_identical(dropped$event_profile$age_in_years, numeric()) + expect_identical(dropped$signal_results$age_in_years, numeric()) + + skip_if_not_installed("duckdb") + skip_if_not_installed("DBI") + db <- compare_db_twin(data) + on.exit(DBI::dbDisconnect(db@db@con, shutdown = TRUE), add = TRUE) + expect_identical(compare_age(db, function(x) x >= 50)$signal_results, older$signal_results) + expect_identical(compare_age(db, is.na)$event_profile, missing_age$event_profile) +}) + +test_that(".fn runs once on the study scope and all groups use its rows", { + data <- compare_std_data() + groups <- list(A = "insulin|humalog", B = "metformin") + demo <- faers_get(data, "demo") + original_sex <- data.table::copy(demo$sex) + first_id <- sort(demo$primaryid)[[1L]] + ids <- faers_group_ids(data, groups)$ids + calls <- 0L + keep_first <- function(rows, limit) { + calls <<- calls + 1L + data.table::set(rows, j = "sex", value = rep("chosen", nrow(rows))) + rows[order(primaryid)][seq_len(limit)] + } + compare_first <- function(object) { + compare_quiet(faers_compare( + object, groups, .field = "demo", .events = "sex", + .fn = keep_first, limit = 1L + )) + } + mem <- compare_first(data) + expect_identical(calls, 1L) + expect_identical(faers_get(data, "demo")$sex, original_sex) + expect_identical(mem$signal_results$sex, rep("chosen", length(groups))) + expect_identical(mem$signal_results$a, as.integer(vapply(ids, function(x) first_id %in% x, logical(1L)))) + expect_true(all(with(mem$signal_results, a + c == 1L))) + expect_true(all(with(mem$signal_results, a + b + c + d == n_total))) + + expect_error(compare_quiet(faers_compare( + data, groups, .fn = function(rows) rows[, .(pt)] + )), "retain the required columns.*primaryid") + expect_error(compare_quiet(faers_compare( + data, groups, .fn = function(rows) rows[1L][, primaryid := "outside-scope"] + )), "report IDs from the study scope") + + skip_if_not_installed("duckdb") + skip_if_not_installed("DBI") + db <- compare_db_twin(data) + on.exit(DBI::dbDisconnect(db@db@con, shutdown = TRUE), add = TRUE) + db_res <- compare_first(db) + expect_identical(calls, 2L) + expect_identical(db_res$event_profile, mem$event_profile) + expect_identical(db_res$signal_results, mem$signal_results) +}) + +test_that("multi-column events use a collapsed event_label in the matrices", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = c("pt", "soc_name"), .min_a = 1L + )) + + expect_true("event_label" %chin% names(res$event_profile)) + expect_identical(names(res$matrices$count)[[1L]], "event_label") + expect_identical(names(res$matrices$signal)[[1L]], "event_label") + # The label is the documented paste of the event columns. + expect_true(all(grepl(" | ", res$event_profile$event_label, fixed = TRUE))) + # It also survives truncation. + trunc <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), + .events = c("pt", "soc_name"), .min_a = 1L, .top_n = 4L + )) + expect_identical(names(trunc$matrices$count)[[1L]], "event_label") +}) + +test_that("a non-reac .field counts its own event columns", { + data <- compare_std_data() + groups <- list(A = "insulin|humalog", B = "metformin") + + # Regression: `.events` was validated against the `reac` allow-list no + # matter what `.field` said, so every other field aborted before doing any + # work (with an unrelated cli pluralization error). The validation now + # follows `.field`, which makes the documented `...` pass-through usable. + res <- compare_quiet(faers_compare( + data, groups, .events = "drugname", .field = "drug", .min_a = 0L + )) + expect_identical(res$metadata$event_scope$field, "drug") + expect_identical(res$metadata$event_scope$allowed_columns, + names(faers_get(data, "drug"))) + expect_true("drugname" %chin% names(res$event_profile)) + expect_setequal(unique(res$event_profile$group), c("A", "B")) + + # The counts still come from `faers_counts()`, so the group column has to + # reproduce a direct call on the same reports. + ids_a <- compare_quiet(faers_reports_with(data, "insulin|humalog", .return = "ids")) + direct <- compare_quiet(faers_counts( + faers_keep(data, ids_a), .events = "drugname", .field = "drug" + )) + prof <- res$event_profile[group == "A" & N > 0L][order(drugname)] + expect_identical(prof$N, direct[order(drugname)]$N[match(prof$drugname, direct[order(drugname)]$drugname)]) + expect_identical(nrow(prof), nrow(direct)) + + # Every field the object carries, not just `reac`, is reachable. + for (case in list( + list(field = "demo", events = "sex"), + list(field = "outc", events = "outc_cod"), + list(field = "rpsr", events = "rpsr_cod"), + list(field = "indi", events = "indi_pt") + )) { + out <- compare_quiet(faers_compare( + data, groups, .events = case$events, .field = case$field, .min_a = 0L + )) + expect_identical(out$metadata$event_scope$field, case$field) + expect_true(nrow(out$event_profile) > 0L) + } +}) + +test_that("event columns are validated against the chosen .field, in cli style", { + data <- compare_std_data() + groups <- list(A = "insulin|humalog") + + # A column of another field is rejected, and the message names both the + # column and the field it was looked for in. + expect_error( + compare_quiet(faers_compare(data, groups, .events = "pt", .field = "drug")), + "Unknown column of the standardized drug data.*pt" + ) + # Singular/plural are both grammatical (cli quantity). + expect_error( + compare_quiet(faers_compare(data, groups, .events = "nope", .field = "reac")), + "Unknown column of the standardized reac data" + ) + expect_error( + compare_quiet(faers_compare(data, groups, .events = c("nope1", "nope2"))), + "Unknown columns of the standardized reac data" + ) + # `reac` keeps its own allow-list: the MedDRA hierarchy columns are joined + # in by standardization and are not physical `reac` columns. + expect_error( + compare_quiet(faers_compare(data, groups, .events = "caseid")), + "Unknown column" + ) + hier <- compare_quiet(faers_compare(data, groups, .events = "soc_name", .min_a = 0L)) + expect_true("soc_name" %chin% names(hier$event_profile)) + + # `.field` itself is checked before anything else runs. + expect_error( + compare_quiet(faers_compare(data, groups, .events = "pt", .field = "nope")), + "must contain only values from" + ) + expect_error( + compare_quiet(faers_compare(data, groups, .events = "pt", .field = c("reac", "drug"))), + "a single string" + ) +}) + +test_that("missing-event metadata agrees with counts and denominators", { + data <- compare_std_data() + groups <- list(A = "insulin|humalog") + ids <- suppressMessages(faers_reports_with(data, groups$A, .return = "ids")) + demo <- data.table::copy(faers_get(data, "demo")) + demo[primaryid %in% ids[[1L]], sex := NA_character_] + data@data$demo <- demo + + compare_sex <- function(object, na_rm) { + compare_quiet(faers_compare( + object, groups, .field = "demo", .events = "sex", .na.rm = na_rm + )) + } + kept <- compare_sex(data, FALSE) + dropped <- compare_sex(data, TRUE) + expect_false(kept$metadata$missing$na_rm) + expect_true(dropped$metadata$missing$na_rm) + expect_identical(kept$event_profile[is.na(sex)]$N, + as.integer(sum(demo$primaryid %in% ids & is.na(demo$sex)))) + expect_gt(kept$event_profile[is.na(sex)]$N, 0L) + expect_false(anyNA(dropped$event_profile$sex)) + expect_false(anyNA(dropped$signal_results$sex)) + expect_identical(dropped$event_profile$denominator, + rep(length(ids), nrow(dropped$event_profile))) + expect_identical(dropped$comparisons$n_total, kept$comparisons$n_total) + expect_true(all(with(dropped$signal_results, a + b + c + d == n_total))) + + skip_if_not_installed("duckdb") + skip_if_not_installed("DBI") + db <- compare_db_twin(data) + on.exit(DBI::dbDisconnect(db@db@con, shutdown = TRUE), add = TRUE) + for (na_rm in c(FALSE, TRUE)) { + db_res <- compare_sex(db, na_rm) + mem_res <- if (na_rm) dropped else kept + expect_identical(db_res$metadata$missing, mem_res$metadata$missing) + expect_identical(db_res$event_profile, mem_res$event_profile) + expect_identical(db_res$signal_results, mem_res$signal_results) + } +}) + +test_that("overlap metadata counts only intersecting pairs and unique reports", { + data <- compare_std_data() + groups <- list( + A = "insulin|humalog", B = "insulin|humalog", C = "insulin|humalog", + empty = "no_such_drug_zzz" + ) + res <- compare_quiet(faers_compare(data, groups, .overlap = "exclude")) + n_shared <- faers_reports_with(data, groups$A, .return = "count") + expect_gt(n_shared, 0L) + expect_identical(nrow(res$group_overlaps), 6L) + expect_identical(res$metadata$overlap_handling$n_shared_pairs, 3L) + expect_identical(res$metadata$overlap_handling$n_reports_shared, n_shared) + + disjoint <- compare_quiet(faers_compare( + data, groups[c("A", "empty")], .mode = "pairwise", + .comparisons = list(c("A", "empty")) + )) + expect_identical(disjoint$metadata$overlap_handling$n_shared_pairs, 0L) + expect_identical(disjoint$metadata$overlap_handling$n_reports_shared, 0L) + expect_true(disjoint$metadata$overlap_handling$pairwise) +}) + +test_that("metadata documents the scope, groups and algorithms", { + data <- compare_std_data() + res <- compare_quiet(faers_compare( + data, list(A = "insulin|humalog", B = "metformin"), .events = "pt" + )) + md <- res$metadata + + expect_true(all(c( + "call", "faers_version", "r_version", "timestamp", "mode", "split", + "overlap_strategy", "groups", "scope", "events", "event_scope", + "methods", "denominator_definition", "background_definition", + "comparisons", "missing", "truncation", "display_subset", + "interaction_test" + ) %chin% names(md))) + expect_identical(md$mode, "background") + expect_identical(md$split, "none") + expect_identical(md$overlap_strategy, "keep") + expect_identical(md$scope$n_reports_universe, 200L) + expect_true(md$scope$standardization) + expect_true(md$scope$deduplication) + expect_identical(md$events, "pt") + expect_identical(md$methods, c("ror", "prr")) + expect_true(nzchar(md$faers_version)) + expect_true(nzchar(md$r_version)) + expect_true(nzchar(md$denominator_definition)) + expect_true(nzchar(md$background_definition)) + # The joint-group result is explicitly not a formal interaction test. + expect_match(md$interaction_test, "interaction") + # `.groups` is echoed verbatim for reproducibility. + expect_identical(md$groups, list(A = "insulin|humalog", B = "metformin")) +}) + +test_that("faers_compare() requires standardized, de-duplicated input", { + raw <- readRDS(system.file("extdata", "standardized_data.rds", package = "faers")) + expect_error( + compare_quiet(faers_compare(raw, list(A = "insulin"), .events = "pt")), + "de-duplicated" + ) +}) + +test_that("faers_compare() validates its arguments", { + data <- compare_std_data() + groups <- list(A = "insulin|humalog") + + expect_error(compare_quiet(faers_compare(data, groups, .events = character()))) + expect_error(compare_quiet(faers_compare(data, groups, .events = "not_a_column"))) + expect_error(compare_quiet(faers_compare(data, groups, .min_a = -1L))) + expect_error(compare_quiet(faers_compare(data, groups, .methods = "nope"))) + expect_error(compare_quiet(faers_compare(data, groups, .top_n = 0L))) + expect_error(compare_quiet(faers_compare(data, groups, .matrix_metric = ""))) + expect_error(compare_quiet(faers_compare(data, groups, .field = "pt"))) +}) + +test_that("matrix event columns cannot collide with group or comparison names", { + data <- compare_std_data() + expect_error(compare_quiet(faers_compare(data, list(pt = "insulin"), .events = "pt")), + "group name.*conflicts with the matrix event column") + + demo <- data.table::copy(faers_get(data, "demo")) + demo[, A_vs_rest_of_scope := sex] + data@data$demo <- demo + expect_error( + compare_quiet(faers_compare( + data, list(A = "insulin"), .field = "demo", .events = "A_vs_rest_of_scope" + )), + "comparison_id.*conflicts with the matrix event column" + ) +}) + +test_that("faers_compare() is identical on both backends", { + skip_if_not_installed("duckdb") + skip_if_not_installed("DBI") + + data <- compare_std_data() + db <- compare_db_twin(data) + on.exit(DBI::dbDisconnect(db@db@con, shutdown = TRUE), add = TRUE) + + groups <- list(A = "insulin|humalog", B = "metformin", C = "glyburide") + cases <- list( + list(defs = groups, args = list(.events = "pt")), + list(defs = groups, args = list(.events = "soc_name")), + list(defs = groups, args = list(.events = "pt", .event_set = c("ASTHENIA", "ANAEMIA"))), + list(defs = groups, args = list(.events = "pt", .top_n = 4L, .min_a = 1L)), + list(defs = groups, args = list(.events = c("pt", "soc_name"), .min_a = 1L)), + list(defs = groups, args = list(.events = "drugname", .field = "drug", .min_a = 0L)), + list(defs = groups, args = list(.events = "sex", .field = "demo", .min_a = 0L)), + list( + defs = groups[1:2], + args = list( + .split = "joint", .mode = "pairwise", + .comparisons = list(c("A-only", "B-only"), c("A+B", "A-only")), + .events = "pt" + ) + ) + ) + for (case in cases) { + mem <- compare_quiet(do.call( + faers_compare, c(list(data, case$defs), case$args) + )) + dbo <- compare_quiet(do.call( + faers_compare, c(list(db, case$defs), case$args) + )) + for (part in c("group_summary", "event_profile", "comparisons", "group_overlaps")) { + expect_identical(mem[[part]], dbo[[part]]) + } + expect_identical( + mem$signal_results[, .(comparison_id, a, b, c, d, n_total)], + dbo$signal_results[, .(comparison_id, a, b, c, d, n_total)] + ) + expect_identical(mem$matrices$count, dbo$matrices$count) + expect_identical(mem$matrices$share, dbo$matrices$share) + } +}) + +test_that("faers_compare() never writes over a user table on duckdb", { + skip_if_not_installed("duckdb") + skip_if_not_installed("DBI") + + data <- compare_std_data() + db <- compare_db_twin(data) + con <- db@db@con + on.exit(DBI::dbDisconnect(con, shutdown = TRUE), add = TRUE) + + # The group ids used to be registered under one fixed, guessable name, and + # `dbWriteTable(temporary = TRUE)` REPLACES a same-named permanent table + # instead of shadowing it. Both the old fixed name and the exact name the + # counter hands out first are therefore occupied by real user tables here. + fixed <- "__faers_compare_ids__" + first <- sprintf("__faers_compare_ids_%d_1__", Sys.getpid()) + for (nm in c(fixed, first)) { + DBI::dbExecute(con, sprintf('CREATE TABLE "%s" (sentinel VARCHAR)', nm)) + DBI::dbExecute(con, sprintf('INSERT INTO "%s" VALUES (\'keep me\')', nm)) + } + before <- DBI::dbGetQuery( + con, "SELECT table_name FROM duckdb_tables()" + )$table_name + n_before <- length(DBI::dbListTables(con)) + + groups <- list(A = "insulin|humalog", B = "metformin") + mem <- compare_quiet(faers_compare(data, groups, .events = "pt")) + dbo <- compare_quiet(faers_compare(db, groups, .events = "pt")) + + # The comparison still produces the in-memory answer ... + expect_identical(mem$matrices$count, dbo$matrices$count) + expect_identical(mem$event_profile, dbo$event_profile) + + # ... and both user tables are untouched, contents included. + expect_true(all(c(fixed, first) %in% DBI::dbGetQuery( + con, "SELECT table_name FROM duckdb_tables()" + )$table_name)) + for (nm in c(fixed, first)) { + expect_identical( + DBI::dbGetQuery(con, sprintf('SELECT sentinel FROM "%s"', nm))$sentinel, + "keep me" + ) + } + expect_setequal( + setdiff(DBI::dbListTables(con), before), + character() + ) + expect_length(DBI::dbListTables(con), n_before) +}) diff --git a/tests/testthat/test_duckdb.R b/tests/testthat/test_duckdb.R index 6a38544..518e935 100644 --- a/tests/testthat/test_duckdb.R +++ b/tests/testthat/test_duckdb.R @@ -97,6 +97,29 @@ testthat::test_that("faers_counts matches in db mode (single/multi event, na.rm, ) }) +# Regression: the SQL builder qualified EVERY event column with the MedDRA +# hierarchy alias `m.`, but `pt`/`meddra_code`/`meddra_pt` live in `reac` +# itself and are not columns of the hierarchy table. `.events = "pt"` therefore +# failed with `Binder Error: Table "m" does not have a column named "pt"` on a +# duckdb-backed object, while the in-memory path worked. Only the hierarchy's +# own columns may be qualified. +testthat::test_that("faers_counts matches in db mode for reac's own event columns", { + testthat::skip_if_not(has_duckdb) + mem <- sample_object() + db <- db_twin(mem) + for (ev in c("pt", "meddra_code", "meddra_pt")) { + testthat::expect_identical( + faers_counts(mem, .events = ev, .field = "reac"), + faers_counts(db, .events = ev, .field = "reac") + ) + } + # A mixed selection must resolve each column on the right side of the join. + testthat::expect_identical( + faers_counts(mem, .events = c("pt", "soc_name"), .field = "reac"), + faers_counts(db, .events = c("pt", "soc_name"), .field = "reac") + ) +}) + testthat::test_that("faers_phv_table contingency table matches in db mode", { testthat::skip_if_not(has_duckdb) mem <- sample_object() diff --git a/tests/testthat/test_signal.R b/tests/testthat/test_signal.R index 0504794..ddc43de 100644 --- a/tests/testthat/test_signal.R +++ b/tests/testthat/test_signal.R @@ -58,3 +58,57 @@ testthat::test_that("`faers_phv_signal()` works well", { )) testthat::expect_true(data.table::fsetequal(signal, signal2)) }) + +# Regression: the vectorized methods that build their result from a list of +# per-row results (`chisq`, `fisher`, `bcpnn_mcmc`) used to fail on zero-length +# input, because `transpose()`/`rbind()` of an empty list yields a zero-column +# data.table and the following `setnames()` then had nothing to name. They now +# return their full schema, so a zero-length call stays bindable and keeps the +# same columns as a populated one. +testthat::test_that("phv_* methods keep their schema on zero-length input", { + empty <- list(a = numeric(), b = numeric(), c = numeric(), d = numeric()) + methods <- c("ror", "prr", "chisq", "fisher", "bcpnn_norm", "obsexp_shrink", "ebgm") + populated <- suppressWarnings(suppressMessages(do.call( + phv_signal, + c(list(a = c(5, 10, 3), b = c(2, 3, 0), c = c(1, 2, 4), d = c(100, 200, 50)), + list(methods = methods)) + ))) + zero <- suppressWarnings(suppressMessages(do.call( + phv_signal, c(empty, list(methods = methods)) + ))) + testthat::expect_identical(nrow(zero), 0L) + testthat::expect_identical(names(zero), names(populated)) + testthat::expect_identical( + vapply(zero, function(x) class(x)[[1L]], character(1L)), + vapply(populated, function(x) class(x)[[1L]], character(1L)) + ) + + # `chisq`/`fisher`/`bcpnn_mcmc` are the ones that regressed; assert them + # individually so a future rewrite cannot silently drop a companion column + # (e.g. `chisq` without `chisq_pvalue`). + testthat::expect_identical( + names(suppressWarnings(phv_chisq(numeric(), numeric(), numeric(), numeric()))), + c("chisq", "pvalue") + ) + testthat::expect_identical( + names(suppressWarnings(phv_fisher(numeric(), numeric(), numeric(), numeric()))), + c("odds_ratio", "ci_low", "ci_high", "pvalue") + ) + testthat::expect_identical( + names(suppressWarnings( + phv_bcpnn_mcmc(numeric(), numeric(), numeric(), numeric(), n_mcmc = 100L) + )), + c("ic", "ci_low", "ci_high") + ) + + # MCMC-free methods are also callable with nothing to compute. + testthat::expect_identical(nrow(phv_ror(numeric(), numeric(), numeric(), numeric())), 0L) + testthat::expect_identical(nrow(phv_prr(numeric(), numeric(), numeric(), numeric())), 0L) + testthat::expect_identical(nrow(phv_bcpnn_norm(numeric(), numeric(), numeric(), numeric())), 0L) + + # The companion issue: a non-empty call must still fail on malformed input, + # so the guard cannot have swallowed the validation. + testthat::expect_error(phv_chisq(-1, 1, 1, 1), "non-negative") + testthat::expect_error(phv_fisher(1, 1, 1, 1:2), "same length") + testthat::expect_error(phv_bcpnn_mcmc(1, 1, NA_real_, 1), "non-negative") +}) diff --git a/vignettes/full-workflow.Rmd b/vignettes/full-workflow.Rmd index 5c3ad50..ca58bf5 100644 --- a/vignettes/full-workflow.Rmd +++ b/vignettes/full-workflow.Rmd @@ -248,6 +248,116 @@ A few practical notes: - Use `.drug_pattern` to restrict the scan to a drug class, e.g. `faers_phv_scan(data, .events = "pt", .drug_pattern = "insulin|humulin")`. +## Comparing several drug groups + +`faers_phv_signal()` compares one drug against the rest of the study scope. +When the question involves several drugs at once, `faers_compare()` runs them +as one orchestrated analysis so that every group shares the same universe and +the same counting and testing code. + +```{r, eval = FALSE} +# Narrow the scope FIRST: the scope is the background every group is +# compared against, and the denominator of the shared universe. +scope <- faers_restrict(data, .period = c("2004q1", "2004q2")) + +res <- faers_compare( + scope, + list( + insulin = "insulin|humalog", + metformin = "metformin", + # a definition can also constrain the drug role: here only reports + # where the drug is the primary or secondary suspect + vioxx = list(.drugs = "vioxx", .roles = list(vioxx = c("PS", "SS"))) + ), + .events = "pt" +) + +# what each group contained, and how much the groups overlapped +res$group_summary +res$group_overlaps + +# the event spectrum: reports and within-group share per group x event +head(res$event_profile, 10) + +# every comparison x event, with the full 2x2 table and the metrics +res$signal_results[comparison_id == "insulin_vs_rest_of_scope"][order(-ror)] + +# events x groups count / share, plus a signal matrix per comparison +res$matrices$count[1:5, 1:4] +res$matrices$signal[1:5, 1:4] +``` + +Two comparison modes are kept strictly separate, and results identify which one +produced them: + +- `"background"` (default) compares **each group against the rest of the shared + scope**, using one and the same universe `U` for every group, so + `a + b + c + d == |U|` in every table. +- `"pairwise"` compares **two selected groups against each other**, so the + denominator changes with every pair (`a + b + c + d == |G1| + |G2|`). It + never runs implicitly: list each pair in `.comparisons`, otherwise per-pair + denominators would invite uncorrected multiple comparisons. + +```{r, eval = FALSE} +# head-to-head, with an explicit pair list +faers_compare( + scope, + list(insulin = "insulin|humalog", metformin = "metformin"), + .mode = "pairwise", .comparisons = list(c("insulin", "metformin")), + .overlap = "exclude", .events = "pt" +) +``` + +Drug groups commonly share reports. `.overlap` says what to do about that +before a table is built, and the number of reports involved is always reported: + +- `"keep"` (default) leaves the groups as they are. Background mode is still + safe because each table uses the whole scope; in pairwise mode a shared + report would appear in both arms. +- `"exclude"` removes the shared reports from both groups and records the count + in `comparisons$n_overlap_removed`. +- `"repartition"` promotes the shared reports into an extra, mutually exclusive + group (`&`). +- `"error"` stops the run when groups overlap. + +`.split = "joint"` builds the mutually exclusive four-way partition of the +scope for two drugs instead: `A-only`, `B-only`, `A+B` and `Neither`. The +complement is taken against the *same role-restricted exposure rules* used to +define the second drug, so a role-restricted `B` contributes only its +role-qualified reports: + +```{r, eval = FALSE} +joint <- faers_compare( + scope, + list(A = "insulin|humalog", B = "metformin"), + .split = "joint", .events = "pt" +) +joint$group_summary # A-only / B-only / A+B / Neither, summing to |U| +``` + +A few practical notes: + +- The data must be standardized **and** de-duplicated: an un-deduplicated + object would bias every contingency table. +- The statistics are not reimplemented. Each table is handed to the same + `phv_signal()` a single-group analysis uses, so a row of `signal_results` is + identical to the equivalent standalone `faers_phv_signal()` call. +- `.min_a` defaults to `0` (no implicit threshold); rows below it are dropped + and the count is reported in `metadata$event_scope$n_below_min_a`. +- `.top_n` truncates only the display layer (the event spectrum and the + matrices). `signal_results` always keeps every row, and a truncated display + is flagged via `attr(, "display_subset")` and `metadata$display_subset`. +- `.event_set` restricts the candidate events with the same + character / logical / function selectors as `faers_phv_signal_composite()`, + but each event keeps its own row rather than being collapsed into one + composite row. +- Joint groups are a **descriptive** comparison and disproportionality analysis + of co-reported drugs. They are not a formal interaction test; see + `metadata$interaction_test`. +- On `database = "duckdb"` objects the group membership is pushed into the + database as a temporary table and joined in SQL, so the source database is + never modified and results match the in-memory path. + ## sessionInfo ```{r} sessionInfo()