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
dataData frame containing the analytical sample.
outcomeName of the outcome column.
treatmentName of the binary treatment column.
weights_colName of the weights column (e.g. IPTW).
Returns
Named list with
ateandse(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
dataA data frame.
treatmentBinary treatment column name (0/1 or two-valued).
outcomeNumeric outcome column name.
covariatesCharacter vector of confounder column names.
clusterCluster column name (one-way) or length-2 character vector (two-way).
NULLgives the i.i.d. (non-clustered) SE.n_foldsCross-fitting folds (default 5).
seedInteger seed (default 123).
epsPropensity clip bound in
[eps, 1-eps](default 0.02).psOptional 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_clusteredwithate,se,ci95,z,pval,n,n_clusters, andse_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
edgesCharacter vector of edges, each
"A -> B".exposureName of the exposure/treatment node.
outcomeName of the outcome node.
latentCharacter vector of unobserved nodes (excluded from any adjustment set).
Returns
An object of class
morie_dag: list withnodes,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
dagA
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
dagA
morie_dag.dataData 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_setandestimand.
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
dagA
morie_dag.dataThe data frame used for estimation.
methodOne of
"placebo_treatment","random_common_cause","data_subset".estimatorPassed through to
``morie_dag_estimate()``.n_repsNumber of refutation replications (default 20).
seedRandom 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_dagobjects.
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
dataData frame.
treatmentBinary treatment column (0/1).
covariatesCharacter vector of covariates for the propensity model.
n_neighborsNumber of matches per treated unit.
caliperMaximum logit-propensity distance for a valid match, expressed in SD units of the logit (or
NULLfor no caliper).replaceIf
TRUE, controls may be re-used.psOptional pre-computed propensity scores.
alphaSignificance level (carried through to
details).
Returns
A list with class
morie_match_resultcarryingmatched_data,n_treated,n_matched_control,match_pairs,method, anddetails.
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
dataData frame.
treatmentBinary treatment column name.
covariatesCharacter vector of continuous covariates.
n_neighborsNumber of matches per treated unit.
caliperMaximum Mahalanobis distance for a valid match.
replaceIf
TRUE, controls may be re-used.exactOptional 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
dataData frame.
treatmentBinary treatment column name.
exact_varsCharacter 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
dataData frame.
treatmentBinary treatment column name.
covariatesCharacter vector of covariates.
n_binsEither 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_datacontains a._cem_weightcolumn.
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
dataData frame.
treatmentBinary treatment column name.
covariatesCharacter vector of covariates.
distanceOne of
"propensity"or"mahalanobis".psOptional 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
dataData frame.
treatmentBinary treatment column name.
covariatesCharacter vector of covariates.
n_neighborsNumber of matches per treated unit.
pop_sizeGenetic-algorithm population size (default 50).
n_generationsNumber of GA generations.
seedRandom 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
dataData frame.
treatmentBinary treatment column name.
covariatesCharacter vector of covariates.
balance_thresholdMaximum absolute SMD tolerated (default 0.1).
psOptional 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
dataData frame.
treatmentBinary treatment column name.
covariatesCharacter vector of covariates.
weightsOptional column name of matching / weighting weights.
thresholdAbsolute-SMD threshold for the
balancedflag.
Returns
A list with
balance_table(a data frame), and scalar summariesoverall_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, yNumeric vectors (NA dropped).
confidenceConfidence 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_tableNumeric matrix or table.
confidenceConfidence 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
atePoint estimate of the treatment effect.
seStandard error of the ATE (must be > 0).
nullNull 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_effectSum of squares for the effect.
ss_totalTotal 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_table2x2 matrix.
alternativeOne of “two.sided”, “less”, “greater”.
Returns
A
morie_test_result(subclass ofmorie_rich_result) with the odds ratio as the test statistic andestimate, 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, yNumeric vectors (NA dropped).
confidenceConfidence 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.
centerOne of “median” (Brown-Forsythe), “mean”, “trimmed”.
Returns
A
morie_test_result(subclass ofmorie_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_totalSums of squares.
df_effectNumerator d.f. of the effect.
ms_errorError 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
questionUser question.
contextOptional context string.
python_binPython executable to use. Defaults to
MORIE_PYTHON_BINorpython3.
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
pathPath to a CSV or RDS file.
table_nameName for the cached table.
db_pathOptional path to a SQLite file (default backend).
conOptional 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_pathOptional path to a SQLite file (default backend).
conOptional pre-opened DBI connection (overrides
db_path).
Returns
A data.frame with columns
tableandrows.
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_nameName of the table.
db_pathOptional path to a SQLite file (default backend).
conOptional pre-opened DBI connection (overrides
db_path).
Returns
A data.frame, or
NULLif 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
dataA data.frame to cache.
table_nameName of the destination table.
db_pathOptional path to a SQLite file (default backend).
conOptional pre-opened DBI connection. When supplied, the table is written through
conanddb_pathis 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_membercolumns 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
keyDataset 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_pathOptional path to a DuckDB (
*.duckdb) or SQLite (*.db) file. Defaults to theMORIE_CACHE_DBenv var, elsemorie.duckdb/morie.dbin 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
surveyOne of
"csads_2021","csads_2023","csus_2019","csus_2023", or"all"(default).limitMax records per CKAN request (default 32000).
db_pathOptional path to a SQLite/DuckDB file (default backend).
conOptional 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_keyOne of
"cpads","csads","csus".limitMaximum 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_pathOptional override for the database path.
resource_idOptional 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_keythen only labels the cache table.conOptional 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_pathOptional path to a SQLite/DuckDB file (default backend).
conOptional 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_pathOptional path to a SQLite/DuckDB file (default backend).
use_ckanLogical; if TRUE and data not found locally or in cache, attempt to fetch from the CKAN API.
conOptional 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
keyDataset catalog key (or fuzzy match).
db_pathOptional path to a SQLite/DuckDB file (default backend).
refreshIf
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.conOptional pre-opened DBI connection for the user cache (overrides
db_path). The built-in DB read is always SQLite-based and is unaffected bycon.
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_rootProject 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
nameFilename (e.g.,
"20212022-cpads-pumf-user-guide.pdf"). IfNULL, 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
questionUser question.
contextOptional 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
dataData frame with treatment + outcome columns.
treatmentBinary treatment column (0/1).
outcomeOutcome column.
covariatesCovariates (used only for matching approximation, here a simple rank-match).
gamma_rangec(min, max) of Gamma. Default c(1, 3).
n_gammaNumber 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.