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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -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")),
Expand Down Expand Up @@ -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'
Expand Down
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ 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)
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)
Expand Down
58 changes: 58 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
158 changes: 158 additions & 0 deletions R/compare-db.R
Original file line number Diff line number Diff line change
@@ -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")
)
))
}
Loading
Loading