R API

Part of API Reference — MORIE API reference.

Reference for every public function exported by the morie R package. Signatures and descriptions come from the Roxygen2 .Rd files in r-package/morie/man/; see Statistical Methods for the methodology behind each function.

Causal estimators

Note

Documentation for R function estimate_aipw() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function estimate_atc() is pending. Run roxygen2 to generate the .Rd file.

IPW-weighted OLS ATE

Usage

estimate_ate(data, outcome, treatment, weights_col)

Arguments

data

Data frame containing the analytical sample.

outcome

Name of the outcome column.

treatment

Name of the binary treatment column.

weights_col

Name of the weights column (e.g. IPTW).

Returns

Named list with ate and se (HC3-robust).

Examples

set.seed(1)
d <- data.frame(x = rnorm(60), tr = rbinom(60, 1, 0.5))
d$y <- 1 + 0.5 * d$tr + 0.3 * d$x + rnorm(60)
d$wt <- runif(60, 0.5, 1.5)
res <- estimate_ate(d, outcome = "y", treatment = "tr", weights_col = "wt")
res$ate

Note

Documentation for R function estimate_att() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function estimate_cate() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function estimate_g_computation() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function estimate_gate() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function estimate_late() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function estimate_propensity_scores() is pending. Run roxygen2 to generate the .Rd file.

A general (non-OTIS) policy-evaluation entry point for double/debiased machine learning when observations are clustered – e.g. flights within an airspace corridor, students within a school, patients within a hospital. Standard DML standard errors assume independent observations and are anti-conservative under within-cluster correlation of the treatment or the errors. This cross-fits the AIPW (doubly-robust) score and computes a cluster-robust variance from the per-cluster score sums (Liang & Zeger 1986, one-way; Cameron, Gelbach & Miller 2011, up to two-way).

Usage

morie_dml_clustered(
  data,
  treatment,
  outcome,
  covariates,
  cluster = NULL,
  n_folds = 5L,
  seed = 123L,
  eps = 0.02,
  ps = NULL
)

Arguments

data

A data frame.

treatment

Binary treatment column name (0/1 or two-valued).

outcome

Numeric outcome column name.

covariates

Character vector of confounder column names.

cluster

Cluster column name (one-way) or length-2 character vector (two-way). NULL gives the i.i.d. (non-clustered) SE.

n_folds

Cross-fitting folds (default 5).

seed

Integer seed (default 123).

eps

Propensity clip bound in [eps, 1-eps] (default 0.02).

ps

Optional length-nrow(data) vector of externally supplied propensity scores (e.g. from a mixed-effects / cluster-level model); when given it replaces the cross-fitted propensity.

Returns

A list of class morie_dml_clustered with ate, se, ci95, z, pval, n, n_clusters, and se_kind.

Details

Nuisances are cross-fitted (Chernozhukov et al. 2018): a ridge-logistic propensity and per-arm ordinary-least-squares outcome regressions, so the AIPW point estimate is Neyman-orthogonal. Only the SE is cluster-aware; the point estimate is the usual AIPW ATE. Add own-implemented mixed-effects propensities via ps if a corridor random effect is needed.

References

Chernozhukov V, et al. (2018). Double/debiased machine learning. The Econometrics Journal 21(1), C1–C68. doi{10.1111/ectj.12097} Cameron AC, Gelbach JB, Miller DL (2011). Robust inference with multiway clustering. JBES 29(2), 238–249. doi{10.1198/jbes.2010.07136}

Examples

set.seed(1)
G <- 40L; ng <- 10L; n <- G * ng
g <- rep(seq_len(G), each = ng)
u <- stats::rnorm(G)[g]                       # cluster effect
x <- stats::rnorm(n)
d <- stats::rbinom(n, 1, stats::plogis(0.5 * x + u))
y <- 2 * d + x + u + stats::rnorm(n)          # true ATE = 2
df <- data.frame(y = y, d = d, x = x, corridor = g)
morie_dml_clustered(df, "d", "y", "x", cluster = "corridor")$ate

Causal DAG toolkit (native)

Native DAG construction, backdoor identification, estimation, and refutation — a DoWhy-style workflow with no external graph packages.

Build a causal DAG

Usage

morie_dag(edges, exposure, outcome, latent = character())

Arguments

edges

Character vector of edges, each "A -> B".

exposure

Name of the exposure/treatment node.

outcome

Name of the outcome node.

latent

Character vector of unobserved nodes (excluded from any adjustment set).

Returns

An object of class morie_dag: list with nodes, edges (2-column matrix from/to), exposure, outcome, latent.

Examples

g <- morie_dag(c("race -> placement", "race -> outcome",
                 "placement -> outcome"),
               exposure = "placement", outcome = "outcome")
morie_dag_identify(g)

Uses the canonical adjustment set (observed ancestors of exposure or outcome, minus descendants of the exposure) and verifies it with Bayes-Ball d-separation on the graph with outgoing exposure edges removed — if the canonical set fails, no backdoor set exists (van der Zander, Liskiewicz & Textor 2014).

Usage

morie_dag_identify(dag)

Arguments

dag

A morie_dag.

Returns

List with identified (logical), estimand (“backdoor” or NA), adjustment_set (character).

Examples

g <- morie_dag(c("z -> x", "z -> y", "x -> y"), "x", "y")
morie_dag_identify(g)

Estimate the identified effect from data

Usage

morie_dag_estimate(
  dag,
  data,
  method = c("backdoor.aipw", "backdoor.linear", "backdoor.dml")
)

Arguments

dag

A morie_dag.

data

Data frame containing the observed nodes.

method

"backdoor.aipw" (default), "backdoor.linear", or "backdoor.dml" — all native estimators.

Returns

The chosen estimator’s result list, plus adjustment_set and estimand.

Examples

set.seed(1)
z <- rnorm(400); x <- rbinom(400, 1, plogis(z))
y <- 0.8 * x + z + rnorm(400)
df <- data.frame(z = z, x = x, y = y)
g <- morie_dag(c("z -> x", "z -> y", "x -> y"), "x", "y")
morie_dag_estimate(g, df, method = "backdoor.linear")

DoWhy-style robustness checks, all native: a placebo (permuted) treatment should give an effect near zero; adding a random common cause or re-estimating on subsets should leave the estimate stable.

Usage

morie_dag_refute(
  dag,
  data,
  method = c("placebo_treatment", "random_common_cause", "data_subset"),
  estimator = "backdoor.linear",
  n_reps = 20L,
  seed = 42L
)

Arguments

dag

A morie_dag.

data

The data frame used for estimation.

method

One of "placebo_treatment", "random_common_cause", "data_subset".

estimator

Passed through to ``morie_dag_estimate()``.

n_reps

Number of refutation replications (default 20).

seed

Random seed.

Returns

List with original, refuted (mean over reps), reps, passed (logical heuristic), method.

Examples

set.seed(1)
z <- rnorm(400); x <- rbinom(400, 1, plogis(z))
y <- 0.8 * x + z + rnorm(400)
df <- data.frame(z = z, x = x, y = y)
g <- morie_dag(c("z -> x", "z -> y", "x -> y"), "x", "y")
morie_dag_refute(g, df, method = "placebo_treatment",
                 estimator = "backdoor.linear", n_reps = 5)

Ready-made morie_dag objects for the two structures the MRM (Multilevel Reconciliation Methodology) analyses use most: carceral placement (exposure) with demographic + prior-record confounding, and use-of-force reporting with neighbourhood-level confounding. Structures follow the confounding relations documented in the MRM module docs; use them as starting points and edit edges to taste.

Usage

morie_mrm_dags()

Returns

Named list of morie_dag objects.

Examples

names(morie_mrm_dags())
morie_dag_identify(morie_mrm_dags()$placement)

Matching (native engines)

Nearest-neighbour, Mahalanobis, exact, coarsened-exact, optimal-pair, genetic, and cardinality matching, plus balance diagnostics — all implemented natively (no MatchIt/Matching/optmatch runtime dependency).

For each treated unit, finds the n_neighbors closest control units by logit-propensity-score distance. Delegates to pkg{MatchIt} when installed; otherwise uses a base-R implementation.

Usage

morie_matching_nearest_neighbor(
  data,
  treatment,
  covariates,
  n_neighbors = 1L,
  caliper = NULL,
  replace = FALSE,
  ps = NULL,
  alpha = 0.05
)

Arguments

data

Data frame.

treatment

Binary treatment column (0/1).

covariates

Character vector of covariates for the propensity model.

n_neighbors

Number of matches per treated unit.

caliper

Maximum logit-propensity distance for a valid match, expressed in SD units of the logit (or NULL for no caliper).

replace

If TRUE, controls may be re-used.

ps

Optional pre-computed propensity scores.

alpha

Significance level (carried through to details).

Returns

A list with class morie_match_result carrying matched_data, n_treated, n_matched_control, match_pairs, method, and details.

Examples

set.seed(1)
df <- data.frame(
  y = rnorm(150), d = rbinom(150, 1, 0.4),
  x1 = rnorm(150), x2 = rnorm(150),
  region = sample(c("North", "South"), 150, TRUE),
  year = sample(2020:2022, 150, TRUE),
  treat3 = sample(0:2, 150, TRUE))
set.seed(1)
df <- data.frame(d = rbinom(200, 1, 0.4),
                 x1 = rnorm(200), x2 = rnorm(200))
res <- morie_matching_nearest_neighbor(df, "d", c("x1", "x2"),
                                       caliper = 0.2)

Matches on Mahalanobis distance over the supplied covariates, optionally combined with exact matching on discrete variables. Delegates to pkg{MatchIt} when available.

Usage

morie_matching_mahalanobis(
  data,
  treatment,
  covariates,
  n_neighbors = 1L,
  caliper = NULL,
  replace = FALSE,
  exact = NULL
)

Arguments

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of continuous covariates.

n_neighbors

Number of matches per treated unit.

caliper

Maximum Mahalanobis distance for a valid match.

replace

If TRUE, controls may be re-used.

exact

Optional character vector of variables to match exactly prior to distance matching.

Returns

A list of class morie_match_result.

Examples

set.seed(1)
df <- data.frame(
  y = rnorm(150), d = rbinom(150, 1, 0.4),
  x1 = rnorm(150), x2 = rnorm(150),
  region = sample(c("North", "South"), 150, TRUE),
  year = sample(2020:2022, 150, TRUE),
  treat3 = sample(0:2, 150, TRUE))
morie_matching_mahalanobis(df, "d", c("x1", "x2"), n_neighbors = 1)

Matches treated and control units that share identical values on every variable in exact_vars. Delegates to pkg{MatchIt} when available.

Usage

morie_matching_exact(data, treatment, exact_vars)

Arguments

data

Data frame.

treatment

Binary treatment column name.

exact_vars

Character vector of discrete variables for exact matching.

Returns

A list of class morie_match_result.

Examples

set.seed(1)
df <- data.frame(
  y = rnorm(150), d = rbinom(150, 1, 0.4),
  x1 = rnorm(150), x2 = rnorm(150),
  region = sample(c("North", "South"), 150, TRUE),
  year = sample(2020:2022, 150, TRUE),
  treat3 = sample(0:2, 150, TRUE))
morie_matching_exact(df, "d", c("region", "year"))

Coarsens continuous covariates into bins, then performs exact matching on the coarsened values. Returns the matched (uncoarsened) data along with stratum weights. Delegates to pkg{MatchIt}’s method = "cem" (which itself calls pkg{cem}) when available.

Usage

morie_matching_cem(data, treatment, covariates, n_bins = 5L)

Arguments

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

n_bins

Either a single integer (applied to every covariate) or a named list mapping covariate name to the number of bins.

Returns

A list of class morie_match_result; matched_data contains a ._cem_weight column.

References

Iacus, S. M., King, G., & Porro, G. (2012). Causal inference without balance checking: Coarsened exact matching. Political Analysis, 20(1), 1–24.

Examples

set.seed(1)
df <- data.frame(
  y = rnorm(150), d = rbinom(150, 1, 0.4),
  x1 = rnorm(150), x2 = rnorm(150),
  region = sample(c("North", "South"), 150, TRUE),
  year = sample(2020:2022, 150, TRUE),
  treat3 = sample(0:2, 150, TRUE))
morie_matching_cem(df, "d", c("x1", "x2"), n_bins = 5)

Optimal 1:1 pair matching that minimises the total within-pair distance. Delegates to pkg{MatchIt}’s method = "optimal" (which calls pkg{optmatch}); otherwise uses a greedy approximation.

Usage

morie_matching_optimal_pair(
  data,
  treatment,
  covariates,
  distance = "propensity",
  ps = NULL
)

Arguments

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

distance

One of "propensity" or "mahalanobis".

ps

Optional pre-computed propensity scores.

Returns

A list of class morie_match_result.

Examples

set.seed(1)
df <- data.frame(
  y = rnorm(150), d = rbinom(150, 1, 0.4),
  x1 = rnorm(150), x2 = rnorm(150),
  region = sample(c("North", "South"), 150, TRUE),
  year = sample(2020:2022, 150, TRUE),
  treat3 = sample(0:2, 150, TRUE))
morie_matching_optimal_pair(df, "d", c("x1", "x2"))

Uses a genetic algorithm to find weights for Mahalanobis distance matching that maximise covariate balance. Delegates to pkg{Matching::GenMatch} + pkg{Matching::Match} when available; otherwise runs a base-R genetic algorithm.

Usage

morie_matching_genetic(
  data,
  treatment,
  covariates,
  n_neighbors = 1L,
  pop_size = 50L,
  n_generations = 20L,
  seed = 42L
)

Arguments

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

n_neighbors

Number of matches per treated unit.

pop_size

Genetic-algorithm population size (default 50).

n_generations

Number of GA generations.

seed

Random seed.

Returns

A list of class morie_match_result.

References

Diamond, A., & Sekhon, J. S. (2013). Genetic matching for estimating causal effects. Review of Economics and Statistics, 95(3), 932–945.

Examples

set.seed(1)
df <- data.frame(
  y = rnorm(150), d = rbinom(150, 1, 0.4),
  x1 = rnorm(150), x2 = rnorm(150),
  region = sample(c("North", "South"), 150, TRUE),
  year = sample(2020:2022, 150, TRUE),
  treat3 = sample(0:2, 150, TRUE))
morie_matching_genetic(df, "d", c("x1", "x2"),
                       pop_size = 50, n_generations = 20)

Finds the largest matched sample with maximum absolute SMD below balance_threshold. Uses an iterative caliper-tightening heuristic over morie_matching_nearest_neighbor.

Usage

morie_matching_cardinality(
  data,
  treatment,
  covariates,
  balance_threshold = 0.1,
  ps = NULL
)

Arguments

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

balance_threshold

Maximum absolute SMD tolerated (default 0.1).

ps

Optional pre-computed propensity scores.

Returns

A list of class morie_match_result.

References

Zubizarreta, J. R. (2012). Using mixed integer programming for matching in an observational study of kidney failure after surgery. JASA, 107(500), 1360–1371.

Examples

set.seed(1)
df <- data.frame(
  y = rnorm(150), d = rbinom(150, 1, 0.4),
  x1 = rnorm(150), x2 = rnorm(150),
  region = sample(c("North", "South"), 150, TRUE),
  year = sample(2020:2022, 150, TRUE),
  treat3 = sample(0:2, 150, TRUE))
morie_matching_cardinality(df, "d", c("x1", "x2"),
                           balance_threshold = 0.1)

Reports standardised mean differences (SMD), variance ratios, and Kolmogorov-Smirnov statistics for each covariate. When pkg{cobalt} is installed it is used to compute the balance table; otherwise a base-R implementation is used.

Usage

morie_matching_balance(
  data,
  treatment,
  covariates,
  weights = NULL,
  threshold = 0.1
)

Arguments

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

weights

Optional column name of matching / weighting weights.

threshold

Absolute-SMD threshold for the balanced flag.

Returns

A list with balance_table (a data frame), and scalar summaries overall_balance, max_smd, balanced.

Examples

set.seed(1)
df <- data.frame(
  y = rnorm(150), d = rbinom(150, 1, 0.4),
  x1 = rnorm(150), x2 = rnorm(150),
  region = sample(c("North", "South"), 150, TRUE),
  year = sample(2020:2022, 150, TRUE),
  treat3 = sample(0:2, 150, TRUE))
morie_matching_balance(df, "d", c("x1", "x2"))

Effect sizes + tests

Note

Documentation for R function anova_one_way() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function chi_square_test() is pending. Run roxygen2 to generate the .Rd file.

Cohen’s d for independent samples

Usage

cohens_d(x, y, confidence = 0.95)

Arguments

x, y

Numeric vectors (NA dropped).

confidence

Confidence level for CI. Default 0.95.

Returns

A morie_effect_size.

Examples

set.seed(1)
x <- rnorm(30)
y <- rnorm(30, mean = 0.6)
r <- cohens_d(x, y)
r$estimate

Cramer’s V for a contingency table

Usage

cramers_v(contingency_table, confidence = 0.95)

Arguments

contingency_table

Numeric matrix or table.

confidence

Confidence level. Default 0.95.

Returns

A morie_effect_size.

Examples

tbl <- matrix(c(20, 10, 5, 25), nrow = 2)
r <- cramers_v(tbl)
r$estimate

Wraps pkg{EValue} when available. Otherwise applies the same continuous-scale z-stat -> RR approximation as the Python port.

Usage

e_value(ate, se, null = 0)

Arguments

ate

Point estimate of the treatment effect.

se

Standard error of the ATE (must be > 0).

null

Null value. Default 0.

Returns

Scalar E-value (>= 1).

Examples

e_value(ate = 0.5, se = 0.1)

Note

Documentation for R function effective_sample_size() is pending. Run roxygen2 to generate the .Rd file.

Eta-squared from ANOVA sums of squares

Usage

eta_squared(ss_effect, ss_total)

Arguments

ss_effect

Sum of squares for the effect.

ss_total

Total sum of squares.

Returns

A morie_effect_size.

Examples

r <- eta_squared(10, 20)
r$estimate

Fisher’s exact test for a 2x2 table

Usage

fisher_exact_test(contingency_table, alternative = "two.sided")

Arguments

contingency_table

2x2 matrix.

alternative

One of “two.sided”, “less”, “greater”.

Returns

A morie_test_result (subclass of morie_rich_result) with the odds ratio as the test statistic and estimate, the exact p-value, and the table total as n.

Examples

tab <- matrix(c(8, 2, 1, 5), 2, 2)
res <- fisher_exact_test(tab)
res$p_value

Applies J = 1 - 3 / (4 * df - 1).

Usage

hedges_g(x, y, confidence = 0.95)

Arguments

x, y

Numeric vectors (NA dropped).

confidence

Confidence level for CI. Default 0.95.

Returns

A morie_effect_size.

Examples

set.seed(1)
x <- rnorm(30, mean = 0)
y <- rnorm(30, mean = 0.6)
r <- hedges_g(x, y)
r$estimate

Note

Documentation for R function kendall_tau() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function kruskal_wallis_test() is pending. Run roxygen2 to generate the .Rd file.

Levene’s test for equality of variances

Usage

levene_test(..., center = "median")

Arguments

...

Two or more numeric vectors.

center

One of “median” (Brown-Forsythe), “mean”, “trimmed”.

Returns

A morie_test_result (subclass of morie_rich_result) with Levene’s F statistic, p-value, df, and total sample size n.

Examples

set.seed(1)
res <- levene_test(rnorm(40), rnorm(40, sd = 2), center = "median")
res

Note

Documentation for R function mann_whitney_test() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function odds_ratio_ci() is pending. Run roxygen2 to generate the .Rd file.

Omega-squared — less biased than eta-squared

Usage

omega_squared(ss_effect, ss_total, df_effect, ms_error)

Arguments

ss_effect, ss_total

Sums of squares.

df_effect

Numerator d.f. of the effect.

ms_error

Error mean square.

Returns

A morie_effect_size.

Note

Documentation for R function one_sample_t_test() is pending. Run roxygen2 to generate the .Rd file.

Survey + sampling

Note

Documentation for R function bootstrap_sample() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function calibration_weights() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function cluster_sample() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function compute_design_weights() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function design_effect() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function generate_synthetic_data() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function jackknife_estimate() is pending. Run roxygen2 to generate the .Rd file.

Datasets + I/O

Note

Documentation for R function canonicalize_cpads_data() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function load_cpads_data() is pending. Run roxygen2 to generate the .Rd file.

Query Perseus via Python

Usage

morie_ask_percy(
  question,
  context = NULL,
  python_bin = Sys.getenv("MORIE_PYTHON_BIN", "python3")
)

morie_assistant_query(
  question,
  context = NULL,
  python_bin = Sys.getenv("MORIE_PYTHON_BIN", "python3")
)

Arguments

question

User question.

context

Optional context string.

python_bin

Python executable to use. Defaults to MORIE_PYTHON_BIN or python3.

Returns

Agent text response.

Examples

# See the package vignettes for usage examples:
#   vignette(package = "morie")

Returns the path to morie.db that ships with the package (inst/extdata/morie.db). This database contains all CPADS, CCS, CSADS, CSUS, HealthInfobase, and CIHI datasets pre-loaded as SQLite tables.

Usage

morie_builtin_db()

Returns

File path string.

Examples

morie_builtin_db()

Reads a local file and writes it to the cache so that CI and Docker environments (which may lack the original files) can still run tests.

Usage

morie_cache_file(path, table_name, db_path = NULL, con = NULL)

Arguments

path

Path to a CSV or RDS file.

table_name

Name for the cached table.

db_path

Optional path to a SQLite file (default backend).

con

Optional pre-opened DBI connection (overrides db_path).

Returns

Number of rows cached (invisible).

Examples

\dontshow{if (requireNamespace("DBI", quietly = TRUE) && requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf}
tdir <- tempfile("morie-cache-")
dir.create(tdir)
f <- file.path(tdir, "demo.csv")
write.csv(data.frame(x = 1:3, y = 4:6), f, row.names = FALSE)
morie_cache_file(f, "demo", db_path = file.path(tdir, "cache.db"))
\dontshow{\}) # examplesIf}

List all tables in the MORIE cache

Usage

morie_cache_list(db_path = NULL, con = NULL)

Arguments

db_path

Optional path to a SQLite file (default backend).

con

Optional pre-opened DBI connection (overrides db_path).

Returns

A data.frame with columns table and rows.

Examples

\dontshow{if (requireNamespace("DBI", quietly = TRUE) && requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf}
\donttest{
db <- tempfile(fileext = ".db")
morie_cache_store(data.frame(x = 1:3), "demo", db_path = db)
morie_cache_list(db_path = db)
file.remove(db)
}
\dontshow{\}) # examplesIf}

Load a table from the MORIE cache

Usage

morie_cache_load(table_name, db_path = NULL, con = NULL)

Arguments

table_name

Name of the table.

db_path

Optional path to a SQLite file (default backend).

con

Optional pre-opened DBI connection (overrides db_path).

Returns

A data.frame, or NULL if the table does not exist.

Examples

\dontshow{if (requireNamespace("DBI", quietly = TRUE) && requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf}
\donttest{
db <- tempfile(fileext = ".db")
morie_cache_store(
  data = data.frame(x = 1:5),
  table_name = "demo",
  db_path = db
)
morie_cache_load(table_name = "demo", db_path = db)
file.remove(db)
}
\dontshow{\}) # examplesIf}

Writes (or replaces) a table in the shared SQLite cache.

Usage

morie_cache_store(data, table_name, db_path = NULL, con = NULL)

Arguments

data

A data.frame to cache.

table_name

Name of the destination table.

db_path

Optional path to a SQLite file (default backend).

con

Optional pre-opened DBI connection. When supplied, the table is written through con and db_path is ignored. Use this for non-SQLite backends (PostgreSQL, DuckDB, MariaDB).

Returns

Number of rows written (invisible).

Examples

\dontshow{if (requireNamespace("DBI", quietly = TRUE) && requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf}
\donttest{
db <- tempfile(fileext = ".db")
morie_cache_store(
  data = data.frame(x = rnorm(50), y = rnorm(50)),
  table_name = "demo",
  db_path = db
)
file.remove(db)
}
\dontshow{\}) # examplesIf}

Returns a data.frame describing every dataset available through the MORIE data management system. Each row maps a short catalog key to its source, survey, year, file format, local path, SQLite table name, and CKAN resource ID (if available).

Usage

morie_dataset_catalog()

Returns

A data.frame with 44 rows (one per dataset) and columns: key, name, source, survey, year, format, type, large_file, local_path, table_name, ckan_resource_id, download_url, zip_member. The download_url / zip_member columns are empty for datasets reachable through the SQLite cache or the CKAN datastore.

Details

Keys match the Python DATASET_CATALOG in data.py exactly. Use ``morie_load_dataset`` to load by key.

Examples

cat <- morie_dataset_catalog()
nrow(cat)
head(cat[, c("key", "name", "source", "year")])
# Find Ontario carceral datasets:
cat[
  grepl("OTIS|Ontario", paste(cat$source, cat$survey)),
  c("key", "year")
]

Get metadata for a single dataset

Usage

morie_dataset_info(key)

Arguments

key

Dataset catalog key (or fuzzy match).

Returns

A named list with dataset metadata.

Examples

# Use a real catalog key (run `morie_dataset_catalog()$key` to list them):
info <- morie_dataset_info("ocp21")
info$source
info$year
# Fuzzy match works for partial / forgiving keys:
morie_dataset_info("cpads")$key

Opens (or creates) the per-user cache database. The default backend is strong{DuckDB} — zero-config like SQLite, but vectorised + columnar, so it handles the multi-GB-scale open-data PUMFs (TPS, CPADS bulk) that morie ingests without breaking down on analytical queries. For back-compat, an existing SQLite cache at morie.db is reused; if duckdb is unavailable, falls back to SQLite.

Usage

morie_db_connect(db_path = NULL)

Arguments

db_path

Optional path to a DuckDB (*.duckdb) or SQLite (*.db) file. Defaults to the MORIE_CACHE_DB env var, else morie.duckdb / morie.db in the per-user cache directory.

Returns

A DBI connection object.

Details

For non-default backends (PostgreSQL, MariaDB, MS SQL Server, …), construct your own DBI connection and pass it as con to the verb{morie_cache_*} and morie_load_dataset functions:

preformatted{ con <- DBI::dbConnect(RPostgres::Postgres(),

host = “…”, dbname = “morie”, user = “…”, password = “…”)

morie_load_dataset(“ocp21”, con = con) }

Examples

\donttest{
# DuckDB (default when 'duckdb' is installed); pass a '.db' path for SQLite.
if (requireNamespace("duckdb", quietly = TRUE) &&
  requireNamespace("DBI", quietly = TRUE)) {
  tmp <- tempfile(fileext = ".duckdb")
  con <- morie_db_connect(db_path = tmp)
  DBI::dbListTables(con)
  DBI::dbDisconnect(con)
  file.remove(tmp)
}
}

Downloads large bootstrap weight CSVs that are too big to ship with the package. Data is cached in the user cache database for future use.

Usage

morie_download_bootstrap(
  survey = "all",
  limit = 32000L,
  db_path = NULL,
  con = NULL
)

Arguments

survey

One of "csads_2021", "csads_2023", "csus_2019", "csus_2023", or "all" (default).

limit

Max records per CKAN request (default 32000).

db_path

Optional path to a SQLite/DuckDB file (default backend).

con

Optional pre-opened DBI connection (overrides db_path).

Returns

Invisibly, the number of CSV files successfully downloaded.

Examples

\donttest{
# See the package vignettes for usage examples:
#   vignette(package = "morie")
}

Fetch data from the CKAN API and cache it

Usage

morie_fetch_ckan(
  dataset_key = "cpads",
  limit = Inf,
  db_path = NULL,
  resource_id = NULL,
  con = NULL
)

Arguments

dataset_key

One of "cpads", "csads", "csus".

limit

Maximum records to fetch. The CKAN datastore caps a single request at 32000 rows, so larger resources are paged through with offset; the default reads the entire resource.

db_path

Optional override for the database path.

resource_id

Optional CKAN datastore resource id. When supplied (e.g. from morie_dataset_catalog()$ckan_resource_id) it is used directly, so any catalogued dataset can be fetched without a built-in database; dataset_key then only labels the cache table.

con

Optional pre-opened DBI connection (overrides db_path).

Returns

A data.frame.

Examples

\dontrun{
# Requires network access. Fetches the first 5000 rows of the
# Canadian Postsecondary Alcohol and Drug Use Survey from the
# Government of Canada CKAN datastore:
cpads <- morie_fetch_ckan(dataset_key = "cpads", limit = 5000L)
nrow(cpads)
}

List all datasets with cache status

Usage

morie_list_datasets(db_path = NULL, con = NULL)

Arguments

db_path

Optional path to a SQLite/DuckDB file (default backend).

con

Optional pre-opened DBI connection (overrides db_path).

Returns

A data.frame with columns: key, name, source, survey, year, type, cached (logical), rows (integer or NA).

Examples

morie_list_datasets()

Resolution order: enumerate{ item Local RDS/CSV files in standard project locations item SQLite cache (data/cache/morie.db) item CKAN API fetch (requires internet) }

Usage

morie_load_cpads(db_path = NULL, use_ckan = TRUE, con = NULL)

Arguments

db_path

Optional path to a SQLite/DuckDB file (default backend).

use_ckan

Logical; if TRUE and data not found locally or in cache, attempt to fetch from the CKAN API.

con

Optional pre-opened DBI connection (overrides db_path).

Returns

A data.frame with canonical CPADS columns.

Examples

\dontrun{
# Needs the CPADS PUMF (local file, cache, or a live CKAN fetch).
cpads <- morie_load_cpads(use_ckan = TRUE)
if (!is.null(cpads)) head(cpads)
}

Resolution tiers, tried in order: built-in DB -> user cache -> local file -> CKAN datastore -> direct download URL -> ArcGIS layer -> error. Supports fuzzy matching: morie_load_dataset("cpads_2021") resolves to ocp21.

Usage

morie_load_dataset(key, db_path = NULL, refresh = FALSE, con = NULL)

Arguments

key

Dataset catalog key (or fuzzy match).

db_path

Optional path to a SQLite/DuckDB file (default backend).

refresh

If TRUE, bypass the built-in database and the user cache (and, for remotely-backed datasets, the local file) and re-fetch from the remote source, overwriting the cached copy. Use this to pick up time-to-time updates to a dataset.

con

Optional pre-opened DBI connection for the user cache (overrides db_path). The built-in DB read is always SQLite-based and is unaffected by con.

Returns

A data.frame.

Examples

\dontrun{
df <- morie_load_dataset("ocp21") # CPADS 2021-2022 (default DuckDB cache)
df <- morie_load_dataset("ocp21", refresh = TRUE) # force re-fetch

# PostgreSQL cache (run a server first):
# con <- DBI::dbConnect(RPostgres::Postgres(),
#   host = "localhost", dbname = "morie", user = "...")
# df <- morie_load_dataset("ocp21", con = con)
}

Resolve standard project paths

Usage

morie_paths(project_root = NULL)

Arguments

project_root

Project root directory. If NULL, inferred from the current working directory.

Returns

Named list of key paths.

Examples

tryCatch(morie_paths(),
  error = function(e) message("not inside a morie project tree")
)

Lists or retrieves bundled userguide PDF files. These are the official PUMF codebooks and user guides from Health Canada / Statistics Canada.

Usage

morie_userguide(name = NULL)

Arguments

name

Filename (e.g., "20212022-cpads-pumf-user-guide.pdf"). If NULL, lists all available userguides.

Returns

File path string, or character vector of filenames.

Examples

morie_userguide()

Workflow + audit

Note

Documentation for R function ask_percy() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function audit_public_outputs() is pending. Run roxygen2 to generate the .Rd file.

Build a Perseus agent prompt

Usage

morie_build_prompt(question, context = NULL)

build_assistant_prompt(question, context = NULL)

Arguments

question

User question.

context

Optional context string.

Returns

Character scalar prompt.

Examples

# See the package vignettes for usage examples:
#   vignette(package = "morie")

Note

Documentation for R function build_outputs_manifest() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function build_prompt() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function cpads_contract() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function default_synthetic_name_map() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function default_workflow_map() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function find_project_root() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function list_morie_modules() is pending. Run roxygen2 to generate the .Rd file.

Other

Note

Documentation for R function paired_t_test() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function point_biserial_r() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function power_prop_test() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function power_t_test() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function pps_sample() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function proportion_ci() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function read_outputs_manifest() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function risk_difference_ci() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function risk_ratio_ci() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function run_ebac_selection_ipw_analysis() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function run_morie_module() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function run_morie_modules() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function run_pipeline() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function run_propensity_ipw_analysis() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function run_workflow_step() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function sample_size_logistic() is pending. Run roxygen2 to generate the .Rd file.

Wraps pkg{rbounds} when available; otherwise computes normal- approximation Wilcoxon signed-rank bounds in base R.

Usage

sensitivity_rosenbaum(
  data,
  treatment,
  outcome,
  covariates,
  gamma_range = c(1, 3),
  n_gamma = 20L
)

Arguments

data

Data frame with treatment + outcome columns.

treatment

Binary treatment column (0/1).

outcome

Outcome column.

covariates

Covariates (used only for matching approximation, here a simple rank-match).

gamma_range

c(min, max) of Gamma. Default c(1, 3).

n_gamma

Number of Gamma values. Default 20.

Returns

Data frame with Gamma, p_lower, p_upper.

Note

Documentation for R function shapiro_wilk_test() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function simple_random_sample() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function spearman_rho() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function stratified_sample() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function summarize_output_audit() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function two_sample_t_test() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function validate_cpads_data() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function validate_outputs_manifest() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function wilcoxon_signed_rank_test() is pending. Run roxygen2 to generate the .Rd file.

Note

Documentation for R function write_synthetic_data() is pending. Run roxygen2 to generate the .Rd file.