R API¶
Part of API Reference — MORIE API reference.
A curated reference for the R package (published as rmorie on
r-universe; the repository copy under r-package/morie is the same
code). Signatures and descriptions come from the Roxygen2 .Rd files
in r-package/morie/man/; see Statistical Methods for the
methodology behind each function.
The package exports 13,655 functions, 5,189 of them morie_* entry
points; this page lists the ones a first analysis reaches for. The
complete reference, one page per function, is the pkgdown site at
https://rootcoder007.github.io/rmorie/reference/ .
Assistant (your own model) and command line¶
The R side of Language models and the data key: the provider chain, the key and the
rmorie shell command shipped inside the package.
Asks the model you set up (see ``morie_llm_detect_provider``) through
rmoriebricklayer. With docs = TRUE the model is given the help of
rmorie, rmoriebricklayer and rmoriedata (rmorie’s own thousands of pages are
searched, the functions nearest the question listed) and tools to read it,
so it can name the right function and its arguments. When no model is set
up, or the automatic route fails, the answer is a short text saying how to
set one up (with attr(, "fallback") TRUE); a route you named is an
error instead.
Usage
morie_llm_ask(
prompt,
context = NULL,
model = NULL,
provider = NULL,
system_prompt = NULL,
timeout = 120,
route = NULL,
docs = TRUE
)
Arguments
promptUser question or instruction.
contextOptional named list (or text) given with the question.
modelOptional model name; the route’s model when NULL.
providerOlder name for
route("api"is"own").system_promptOptional instructions added for the model.
timeoutSeconds to wait for each reply. Default 120.
routeNULL(the saved setting, else the automatic order),"auto","own","ollama"or a provider id such as"anthropic": a route other than auto is the only one asked.docsTRUE(default) to give the model the packages’ help.
Returns
Character scalar: the answer, or the fallback text.
Examples
old <- Sys.getenv(c("OLLAMA_HOST", "XDG_CONFIG_HOME"), unset = NA)
Sys.setenv(OLLAMA_HOST = "off", XDG_CONFIG_HOME = tempfile())
out <- morie_llm_ask("In one word, what is 2 + 2?")
isTRUE(attr(out, "fallback"))
for (v in names(old)) if (is.na(old[[v]])) Sys.unsetenv(v) else do.call(Sys.setenv, as.list(old[v]))
\dontrun{
Sys.setenv(ANTHROPIC_API_KEY = "...")
morie_llm_ask("Which rmorie function fits a staggered difference-in-differences design?")
}
Which route ``morie_llm_ask`` would take now, without sending
anything. The routes are rmoriebricklayer’s: an endpoint of your own, then
each provider whose key is set (OpenAI, Anthropic, Google Gemini, OpenRouter,
Groq, Mistral and more: rmoriebricklayer::llmprvd()),
then Ollama (on this machine, another one, or ollama.com with your Ollama
key). ``morie_llm_config`` or rmorie config setup sets them up.
Usage
morie_llm_detect_provider(route = NULL)
Arguments
routeNULL(the saved setting, else the automatic order),"auto","own","ollama"or a provider id such as"anthropic".
Returns
The route id (
"own","ollama", a provider id), or"local"when no route is set up.
Examples
old <- Sys.getenv(c("OLLAMA_HOST", "XDG_CONFIG_HOME"), unset = NA)
Sys.setenv(OLLAMA_HOST = "off", XDG_CONFIG_HOME = tempfile())
morie_llm_detect_provider()
for (v in names(old)) if (is.na(old[[v]])) Sys.unsetenv(v) else do.call(Sys.setenv, as.list(old[v]))
Probe a local Ollama instance
Usage
morie_llm_probe_ollama(timeout = 2)
Arguments
timeoutProbe timeout in seconds.
Returns
Logical scalar – TRUE when reachable.
Examples
# \dontrun (not \donttest): this reaches the network. \donttest
# examples ARE run by pkgdown and by CRAN's --run-donttest.
\dontrun{
if (requireNamespace("httr2", quietly = TRUE)) {
morie_llm_probe_ollama() # the answer is cached for the session
}
}
Note
Documentation for R function morie_llm_probe_hosted() is pending. Run roxygen2 to generate the .Rd file.
Stores your MORIE data key, the key that opens the curated tables at
data.rmorie.com (``morie_load_hosted_dataset``). It is never a language
model: those you bring yourself (``morie_llm_config``). With
token the key you already hold is checked with the data service and
stored; with email a one-time code is sent there; otherwise the GitHub
device flow runs. The key is stored once, privately, for rmorie,
rmoriebricklayer, rmoriedata and morie. This is
rmoriebricklayer::dlogin().
Usage
morie_llm_login(
open_browser = interactive(),
poll_max_seconds = 600,
email = NULL,
code = NULL,
token = NULL,
...
)
Arguments
open_browserOpen the GitHub page in a browser.
poll_max_secondsHow long to wait for the GitHub approval.
emailAn email address to send a sign-in code to.
codeThe code that was emailed (asked for when not given).
tokenA key you already hold.
...Passed to
rmoriebricklayer::dlogin(): the data access terms and who is asking, which a new key needs (accept_terms,name,affiliation,purpose,restricted,supervisor_name,supervisor_role,supervisor_email); what is not given is asked at the console.
Returns
The key, invisibly.
Examples
\dontrun{
morie_llm_login() # GitHub; asks for the terms, name and reason
morie_llm_login(email = "you@example.org") # an emailed code
}
Forget the stored data key
Usage
morie_llm_logout()
Returns
TRUE (invisibly) when a key was removed.
Examples
old <- Sys.getenv("XDG_CONFIG_HOME", unset = NA)
Sys.setenv(XDG_CONFIG_HOME = tempfile())
morie_llm_logout()
if (is.na(old)) Sys.unsetenv("XDG_CONFIG_HOME") else Sys.setenv(XDG_CONFIG_HOME = old)
Saves an OpenAI-compatible endpoint (chat completions at
base_url/chat/completions) as the own route: the same as
morie_llm_config(own.url = , own.key = , own.model = ).
Usage
morie_llm_provider_set(base_url, key = NULL, model = NULL)
morie_llm_provider_show()
morie_llm_provider_unset()
Arguments
base_urlThe endpoint, e.g.
"http://localhost:1234/v1".keyThe API key for it (
NULLfor a server that needs none).modelOptional model name to ask by default.
Returns
morie_llm_provider_set()andmorie_llm_provider_unset(): the settings table, invisibly;morie_llm_provider_show(): theown.*rows of it.
Examples
old <- Sys.getenv("XDG_CONFIG_HOME", unset = NA)
Sys.setenv(XDG_CONFIG_HOME = tempfile())
morie_llm_provider_set("http://localhost:1234/v1", key = NULL, model = "my-model")
morie_llm_provider_show()
morie_llm_provider_unset()
if (is.na(old)) Sys.unsetenv("XDG_CONFIG_HOME") else Sys.setenv(XDG_CONFIG_HOME = old)
Dispatches the verbs of the rmorie launcher. Verbs:
describe{
item{login [--email ADDRESS] [--code CODE] [--no-browser]}{sign in for
the curated tables at data.rmorie.com with GitHub (device flow) or an
emailed code: the data key, never a language model}
item{login --token [KEY]}{store a data key you already have (prompts
for it when KEY is omitted)}
item{logout}{forget the data key}
item{doctor}{the language-model routes set up on this machine, the one
ask will take, and the data key}
item{config [show | help | get KEY | set KEY VALUE | unset KEY | setup | path]}{show
or change the language-model settings (``morie_llm_config``): a
provider’s key and model, Ollama, your own server, the route;
setup walks through them}
item{models [--route ROUTE]}{the models a route offers, the one in use marked}
item{ask [--model NAME] [--route ROUTE] PROMPT...}{ask the model you set
up, with the help of rmorie, rmoriebricklayer and rmoriedata at hand}
item{analyze SUBJECT [JSON]}{run an analysis subject through cli_main()}
item{explain FILENAME, inspect PATH, verify PATH}{read,
browse and validate module output tables}
item{profile-dataset PATH, sample PATH --n N}{profile a
CSV, draw a sample from it}
item{run-modules, pipeline}{run several modules; the
pipeline tracks compute emissions and seals them in a capsule}
item{emissions, verify-pollution}{measure this machine’s
compute emissions; run the pollution-to-health pipeline}
item{percy, agent, chat}{talk to Perseus through the
provider chain}
item{selftest, tutorial, generate-template,
update}{smoke test, walkthrough, first-paper scaffold, update check}
item{crypto, ingest, download-bootstrap,
exec, edit, percysuits}{file encryption, open-data
feeds, bootstrap weights, evaluate R code, edit a file, pull models}
item{version}{print the package version}
item{help [start | llm | config | r]}{this list, or a guide: getting
started, the language-model routes, every setting, the same from R}
}
Usage
morie_cli(args = commandArgs(trailingOnly = TRUE), out = cat)
Arguments
argsCharacter vector of arguments; defaults to the command line.
outConnection or function for output (default: the console).
Returns
The exit status, invisibly (0 on success).
Examples
morie_cli("version")
morie_cli(c("ask", "--help"))
Links the launcher shipped in the package (inst/bin/rmorie) into a
directory on your PATH so that rmorie login, rmorie ask ...
and the other verbs of ``morie_cli`` work from any shell. On
Windows a rmorie.cmd wrapper is written instead of a symlink.
Usage
install_cli(
dir = file.path(path.expand("~"), ".local", "bin"),
name = "rmorie"
)
Arguments
dirTarget directory (default
~/.local/bin; created if absent).nameCommand name (default
rmorie).
Returns
The path of the installed launcher, invisibly.
Examples
\dontrun{
install_cli()
}
The modules ``morie_run_morie_module`` accepts, in pipeline order.
Usage
morie_module_names()
Returns
A character vector.
Examples
morie_module_names()
The MORIE project keeps 160 databases materialised from Google BigQuery public datasets, plus the Health Infobase tables and the OTIS research files,
public datasets (Chicago crime, EPA air quality, US census, FEC, FDA,
NOAA, NHTSA, Hacker News, Ethereum, World Bank, …) and serves their
tables from the edge. They open with the data key ``morie_llm_login``
stores; a downloaded table is used only when it matches the SHA-256 the
manifest lists for it. The ICPSR, NCVS 38604 and a2aj tables also need their
terms accepted at url{https://data.rmorie.com/terms}. morie_hosted_manifest() returns the gateway’s manifest
(every table with rows, columns, size, SHA-256 and its BigQuery source),
cached for a day; morie_hosted_datasets() the same as a data frame;
morie_load_hosted_dataset("db/table") one table, cached in the
dataset store so later calls are local. ``morie_load_dataset``
and rmorie pull accept the same db/table keys.
Usage
morie_hosted_manifest(refresh = FALSE)
morie_hosted_datasets(refresh = FALSE)
morie_load_hosted_dataset(key, db_path = NULL, refresh = FALSE)
Arguments
refreshFetch again even when a day-old copy is cached.
keyA
db/tablekey from the manifest.db_pathDataset-store path, as in
``morie_load_dataset``.
Returns
morie_hosted_manifest(): a list;morie_hosted_datasets(): a data frame withkey,name,rows,source;morie_load_hosted_dataset(): the table as a data frame.
Examples
\donttest{
# with a stored MORIE key (rmorie login); without one this stops with that advice
try({
head(morie_hosted_datasets())
df <- morie_load_hosted_dataset("fec_cm_2020/fec_cm_2020")
})
}
Pollution to health, compute emissions¶
The R side of Pollution to health and Compute emissions.
morie_envhealth_crf_pm25() is log-linear for all-cause mortality with
the pooled cohort estimate of the WHO 2021 guideline review (Chen and Hoek
2020: RR 1.08, 95% CI 1.06-1.09, per 10 micrograms per cubic metre),
for \(z > z_{cf}\) and 1 otherwise; for the cause-specific outcomes (IHD, stroke) it is the Integrated Exposure-Response curve of Burnett et al. (2014, Eq. 1),
with the GBD 2013 triples; the IER was fit per cause and has no all-cause
form. morie_envhealth_crf_no2() is the log-linear function of the
WHO 2021 review (Huangfu and Atkinson 2020: RR 1.02, 95% CI 1.01-1.04, per
10 micrograms per cubic metre for all-cause mortality),
Usage
morie_envhealth_crf_pm25(
exposure,
outcome = "all_cause_mortality",
reference_conc = 5.8
)
morie_envhealth_crf_no2(
exposure,
outcome = "all_cause_mortality",
reference_conc = 10,
beta_per_10 = NULL
)
morie_envhealth_cheatsheet()
Arguments
exposureAmbient concentration in micrograms per cubic metre (scalar or vector).
outcomePM2.5:
"all_cause_mortality","ihd"or"stroke". NO2:"all_cause_mortality","respiratory"or"childhood_asthma".reference_concCounterfactual concentration below which no excess risk is assumed (PM2.5 default 5.8, NO2 default 10).
beta_per_10Optional log-RR per 10 units overriding the NO2 outcome table.
Returns
A list of class
morie_envhealth_crfwithrr,log_rr,reference_conc,exposure_conc,pollutant,citationandextra.
References
Chen, J. and Hoek, G. (2020). Environment International, 143, 105974. Huangfu, P. and Atkinson, R. (2020). Environment International, 144, 105998. Burnett, R. T. et al. (2014). Environmental Health Perspectives, 122(4), 397-403. WHO (2021). Global Air Quality Guidelines.
Examples
morie_envhealth_crf_pm25(12)$rr
morie_envhealth_crf_no2(25, outcome = "respiratory")$rr
Levin’s formula (Rothman, Greenland and Lash 2008, chapter 5):
Usage
morie_envhealth_attributable_fraction(rr, exposure_prevalence)
Arguments
rrRelative risk at the observed exposure level.
exposure_prevalenceProportion of the population exposed, in
[0, 1].
Returns
The fraction of cases that would be avoided if the exposure were removed.
Examples
morie_envhealth_attributable_fraction(1.5, 0.4)
BenMAP-CE health-impact function (US EPA 2018; Anenberg et al. 2010):
Usage
morie_envhealth_mortality_displaced(
exposure_delta,
population,
baseline_rate,
beta_per_unit
)
Arguments
exposure_deltaCounterfactual reduction in exposure (positive means the exposure goes down).
populationAt-risk population.
baseline_rateBaseline rate in cases per person-year.
beta_per_unitLog-RR per unit of exposure (per unit, not per 10).
Returns
Expected avoided cases.
Examples
morie_envhealth_mortality_displaced(10, 1e6, 0.008, 0.0039)
Chains the concentration-response function, the attributable fraction and the baseline case count into the annual attributable cases (GBD 2019 Risk Factors Collaborators 2020).
Usage
morie_envhealth_burden(
exposure_mean,
exposure_prevalence,
baseline_rate,
population,
pollutant = "NO2",
outcome = "all_cause_mortality",
reference_conc = NULL
)
Arguments
exposure_meanPopulation-mean exposure.
exposure_prevalenceProportion of the population at that level (1 for ambient air).
baseline_rateCases per person-year in the unexposed scenario.
populationAt-risk population.
pollutant"PM2.5"or"NO2".outcomeOutcome key passed to the concentration-response function.
reference_concCounterfactual concentration; defaults to the pollutant’s WHO guideline.
Returns
A list of class
morie_envhealth_burdenwithpaf,attributable_cases,baseline_cases,population,baseline_rate,exposure_mean,reference_conc,pollutant,citationandextra.
Examples
morie_envhealth_burden(25, 1, 0.008, 1e6, pollutant = "NO2")$attributable_cases
Fits the partially linear model of Chernozhukov et al. (2018, section
4.2) with ``morie_estimate_double_ml`` (continuous exposure as
the treatment), then re-fits it on n_bootstrap non-parametric
resamples for a percentile interval (Efron and Tibshirani 1993).
Usage
morie_envhealth_sensitivity(
data,
outcome,
exposure,
confounders,
n_bootstrap = 100L,
random_state = 42L
)
Arguments
dataA data frame.
outcome, exposure, confoundersColumn names.
n_bootstrapNumber of resamples (default 100).
random_stateSeed for the resampling.
Returns
A list with
ate,se_analytic,se_bootstrap,ci_lower_bs,ci_upper_bs,n_bootstrapandmethod.
Examples
\donttest{
set.seed(1)
d <- data.frame(x1 = rnorm(200), x2 = rnorm(200))
d$exposure <- 20 + 2 * d$x1 + rnorm(200)
d$asthma <- 5 + 0.3 * d$exposure + d$x2 + rnorm(200)
morie_envhealth_sensitivity(d, outcome = "asthma", exposure = "exposure",
confounders = c("x1", "x2"), n_bootstrap = 20)$ate
}
Wagstaff, Paci and van Doorslaer (1991):
with \(R_i\) the fractional income rank \((rank_i - 0.5) / n\) (ties kept in input order, as the Python arm’s stable sort does) and the population covariance. Negative values mean lower-income units bear more exposure.
Usage
morie_envhealth_equity(data, exposure, income)
Arguments
dataA data frame.
exposure, incomeColumn names.
Returns
A list of class
morie_envhealth_equitywithconcentration_index,interpretation,n_quintiles,exposure_mean,citationandextra.
Examples
d <- data.frame(exposure = c(30, 25, 20, 15, 10), income = 1:5)
morie_envhealth_equity(d, "exposure", "income")$concentration_index
Applies ``morie_envhealth_burden`` to every row of a table with
one row per area (forward sortation area, tract, …) and returns the rows
sorted by attributable cases, worst first.
Usage
morie_envhealth_burden_by_fsa(
fsa_table,
fsa_col = "fsa",
exposure_col = "exposure",
population_col = "population",
baseline_rate_col = "baseline_rate",
pollutant = "NO2",
outcome = "all_cause_mortality"
)
Arguments
fsa_tableA data frame with one row per area.
fsa_col, exposure_col, population_col, baseline_rate_colColumn names.
pollutant, outcomePassed to
``morie_envhealth_burden``.
Returns
The input columns plus
rr,paf,attributable_casesandbaseline_cases.
Examples
t <- data.frame(fsa = c("M6H", "M5V"), exposure = c(28, 18),
population = c(40000, 60000), baseline_rate = 0.008)
morie_envhealth_burden_by_fsa(t)
The R twin of morie verify-pollution: resolves the exposure (demo
data, a CSV with an exposure and optional income column, or
scalar arguments), logs the assumptions, and when they all hold runs the
concentration-response, attributable-fraction, mortality-displaced, burden
and equity stages.
Usage
morie_verify_pollution(
pollutant,
outcome = "all_cause_mortality",
region = NULL,
years = NULL,
demo = FALSE,
exposure_csv = NULL,
exposure_mean = 0,
exposure_prevalence = 0,
reference = 5.8,
baseline_rate = 500,
population = 1e+06
)
Arguments
pollutant"no2"or"pm25".outcomeOutcome key for the concentration-response function.
region, yearsLabels for the report.
demoUse synthetic demo data.
exposure_csvPath of a CSV with an
exposurecolumn.exposure_mean, exposure_prevalenceScalar inputs used when neither
demonorexposure_csvis given.referenceCounterfactual reference concentration.
baseline_rateBaseline outcome rate per 100,000 per year.
populationPopulation at risk.
Returns
The report as a list; its
statusis"ok","assumption_failure"or"error", and the attributeexit_statuscarries the command-line exit code (0, 1 or 2).
Examples
r <- morie_verify_pollution("no2", demo = TRUE)
r$status
r$pipeline$paf
morie_emissions_start() opens a tracker; morie_emissions_stop()
closes it, appends one row to emissions.csv in output_dir
(the CodeCarbon column layout, the same file the Python package writes)
and, unless capsule = FALSE, seals the run in a bricklayer capsule:
emissions_manifest.json (the measurements, the method and the R
environment) and capsule_bundle.json (SHA-256 digests of both files
under a post-quantum ML-DSA signature). morie_emissions_track()
wraps an expression in the two calls.
Usage
morie_emissions_start(
project_name = "morie",
output_dir = NULL,
output_file = "emissions.csv",
pue = 1,
wue = 0,
country_iso_code = "",
region = "",
save_to_file = !is.null(output_dir),
capsule = !is.null(output_dir),
key = NULL,
measure_power_secs = 1
)
morie_emissions_stop(tracker)
morie_emissions_track(expr, ...)
Arguments
project_nameLabel written to the CSV and the manifest.
output_dirWhere
emissions.csvand the capsule go.NULL(the default) writes nothing: the measurement is returned in R only.output_fileCSV file name.
pue, wuePower and water usage effectiveness multipliers.
country_iso_code, regionLocation overrides.
save_to_fileWrite the CSV row.
capsuleSeal the run in a bricklayer capsule.
keyA signing key from
rmoriebricklayer::fipskg()orrmoriebricklayer::pqckg(); generated per run whenNULL.measure_power_secsSeconds between utilisation samples of the background sampler (the Python arm’s default is 15; 1 here, since R runs are usually shorter).
trackerThe object from
morie_emissions_start().exprAn expression to evaluate under tracking.
...Passed to
morie_emissions_start().
Returns
morie_emissions_stop(): the emissions in kg CO2eq, with the full row as attributedataand the capsule paths as attributecapsule.morie_emissions_track(): a list withvalue,emissions_kg,dataandcapsule.
Details
Power follows the CodeCarbon methodology: CPU thermal design power from
the model name scaled by utilisation as \(TDP (0.1 + 0.9 u^3)\), RAM by
DIMM count, no GPU. Utilisation is sampled every measure_power_secs
by a C++ background thread reading the kernel’s aggregate CPU counters
(/proc/stat on Linux, host_statistics on macOS) and power is
integrated per sample, as the Python tracker does ("machine"
tracking mode). Where no counters exist the R process’s CPU time over
wall time is used instead ("process" mode). Emissions are energy times the grid’s carbon
intensity (``morie_emissions_carbon_intensity``) times PUE. The
country comes from country_iso_code, else the
MORIE_COUNTRY_ISO environment variable, else a geolocation lookup,
else, offline (MORIE_EMISSIONS_OFFLINE set, or the lookup failed),
the system time zone mapped to its country through the IANA zone tables
(every zone and alias of zone.tab and backward:
Europe/Stockholm is Sweden, US/Eastern the United States)
and then the territory of the locale (en_CA.UTF-8 is Canada); the
world average only when none of these names a country. Two-letter codes
are mapped to the energy table’s three-letter codes through the full ISO
3166 list.
The capsule’s signing key is generated for the run unless key is
given, so a verifier learns that the files have not changed since they
were sealed, not who sealed them; pass your own
rmoriebricklayer::fipskg() key to bind the run to you.
Examples
dir <- tempfile()
r <- morie_emissions_track(sum(sqrt(1:1e5)), project_name = "demo",
output_dir = dir, country_iso_code = "CAN")
r$emissions_kg > 0
list.files(dir)
unlink(dir, recursive = TRUE)
Kilograms of CO2-equivalent per kilowatt-hour from the IEA / Our World in Data energy mix shipped with the package (213 countries, as in CodeCarbon): the country’s published intensity when it has one, otherwise the generation-weighted mean of the per-source intensities, and the world average (475 g/kWh) for an unknown country.
Usage
morie_emissions_carbon_intensity(country_iso = "", region = "")
Arguments
country_isoThree-letter ISO code, e.g.
"CAN".regionUnused; kept for parity with the Python arm.
Returns
A number in kg CO2eq per kWh.
Examples
morie_emissions_carbon_intensity("CAN")
morie_emissions_carbon_intensity("") # world average
Re-hashes emissions.csv and emissions_manifest.json in
dir and checks them and the manifest digest against the signed
capsule_bundle.json. Any other file in dir fails the
no_unlisted_files check (the bundle does not cover it), so give the
run a directory of its own.
Usage
morie_emissions_verify(dir)
Arguments
dirThe directory
morie_emissions_stop()wrote to.
Returns
A list with
okand the bricklayercheckstable.
Examples
dir <- tempfile()
morie_emissions_track(sum(1:10), output_dir = dir, country_iso_code = "CAN")
morie_emissions_verify(dir)$ok
unlink(dir, recursive = TRUE)
Causal estimators¶
Combines IPW and outcome regression corrections. Consistent if strong{either} the propensity model strong{or} the outcome model is correctly specified.
Usage
morie_estimate_aipw(
data,
treatment,
outcome,
covariates,
propensity_col = NULL,
outcome_model = c("auto", "linear", "logistic"),
trim = c(0.01, 0.99),
trim_type = "value",
ps_model = "mle",
ridge_lambda = 1,
outcome_fit = "separate"
)
Arguments
dataA vector; indexed elementwise.
treatmentPassed to
morie_estimate_propensity_scores.outcomeSee Usage.
covariatesPassed to
morie_estimate_propensity_scores.propensity_colOptional; may be
NULL. Passed tois.null.outcome_modelFamily for the outcome model:
"auto"(logistic for a 0/1 outcome, linear otherwise),"linear"or"logistic".trimPassed to
.mor_trim_ps. Defaults toc(0.01, 0.99).trim_typePassed to
.mor_trim_ps. Defaults to"value".ps_modelPassed to
morie_estimate_propensity_scores. Defaults to"mle".ridge_lambdaPassed to
morie_estimate_propensity_scores. Defaults to1.outcome_fitOne of
"pooled","separate". Defaults to"separate".
Returns
Named list:
ate,se,ci_lower,ci_upper,n.
Details
The propensity scores come from morie_estimate_propensity_scores()
(native logistic regression); the outcome regression and the
doubly-robust influence-function score are closed form.
Where richer outputs are desired, AIPW::AIPW (with SuperLearner
nuisance learners) is the canonical CRAN counterpart.
Examples
set.seed(1)
df <- data.frame(t = rbinom(60, 1, 0.4), x = rnorm(60))
df$y <- 2 * df$t + df$x + rnorm(60)
morie_estimate_aipw(df, "t", "y", "x") # outcome_model = "auto" picks linear here
Control units receive weight 1; treated units receive \(w_i = (1-\hat{e}(X_i))/\hat{e}(X_i)\).
Usage
morie_estimate_atc(data, treatment, outcome, covariates, propensity_col = NULL)
Arguments
dataA data frame.
treatmentName of the binary treatment column.
outcomeName of the outcome column.
covariatesCharacter vector of covariate names.
propensity_colOptional: name of a pre-computed propensity score column.
Returns
Named list:
atc,se,ci_lower,ci_upper,n_control.
Details
The propensity scores come from morie_estimate_propensity_scores()
(native logistic regression); the weighted difference and its
influence-function SE are closed form.
Examples
if (requireNamespace("AIPW", quietly = TRUE)) {
set.seed(1)
df <- data.frame(t = rbinom(200, 1, 0.4), y = rnorm(200), x = rnorm(200))
morie_estimate_atc(df, "t", "y", "x")
}
Thin wrapper over a weighted stats::lm() plus HC3 robust SEs
from pkg{sandwich} + pkg{lmtest} when installed. Note: this is the
legacy shape used by older MRM pipelines; new code should prefer
morie_estimate_ate() (in R/causal.R) for the richer
morie_te_result return shape.
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(native 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
Treated units receive weight 1; controls receive \(w_i = \hat{e}(X_i)/(1-\hat{e}(X_i))\).
Usage
morie_estimate_att(data, treatment, outcome, covariates, propensity_col = NULL)
Arguments
dataA data frame.
treatmentName of the binary treatment column.
outcomeName of the outcome column.
covariatesCharacter vector of covariate names.
propensity_colOptional: name of a pre-computed propensity score column.
Returns
Named list:
att,se,ci_lower,ci_upper,n_treated.
Details
The propensity scores come from morie_estimate_propensity_scores()
(native logistic regression); the weighted difference and its
influence-function SE are closed form.
Examples
set.seed(2)
df <- data.frame(t = rbinom(200, 1, 0.4), y = rnorm(200), x = rnorm(200))
morie_estimate_att(df, "t", "y", "x")
The strong{T-learner} fits separate outcome models on treated and control units, then predicts the counterfactual for each unit: \(\widehat{CATE}_i = \hat{\mu}_1(X_i) - \hat{\mu}_0(X_i)\).
Usage
morie_estimate_cate(
data,
treatment,
outcome,
covariates,
propensity_col = NULL,
outcome_model = c("linear", "logistic"),
meta_learner = c("t_learner", "s_learner", "x_learner", "dr_learner")
)
Arguments
dataA vector; indexed elementwise.
treatmentPassed to
morie_estimate_propensity_scores.outcomeSee Usage.
covariatesPassed to
morie_estimate_propensity_scores.propensity_colOptional; may be
NULL. Passed tois.null.outcome_modelFamily for the outcome model:
"auto"(logistic for a 0/1 outcome, linear otherwise),"linear"or"logistic".meta_learnerOne of
"t_learner"(default),"s_learner","x_learner"(Kuenzel et al. 2019 – two-stage with propensity-weighted combination; strong under arm imbalance), or"dr_learner"(Kennedy 2023 – cross-fit AIPW pseudo-outcome regressed with the native forest; doubly robust). All four are native;outcome_modelapplies to the T/S-learners only.
Returns
Numeric vector of per-unit CATE estimates.
Details
The strong{S-learner} fits one model with treatment as a feature.
For random-forest CATE estimation prefer grf::causal_forest
(richer heterogeneity, honest sample splitting).
Examples
set.seed(1)
morie_estimate_cate(
data = data.frame(
t = stats::rbinom(100, 1, 0.4),
y = stats::rbinom(100, 1, 0.3), x1 = stats::rnorm(100),
x2 = stats::rnorm(100)
), treatment = "t", outcome = "y",
covariates = c("x1", "x2")
)
Estimates the ATE by:
hat{mu}_0(X_i)bigr]
Usage
morie_estimate_g_computation(
data,
treatment,
outcome,
covariates,
outcome_model = c("linear", "logistic")
)
Arguments
dataA vector; indexed elementwise.
treatmentPassed to
morie_estimate_propensity_scores.outcomeSee Usage.
covariatesPassed to
morie_estimate_propensity_scores.outcome_modelFamily for the outcome model:
"auto"(logistic for a 0/1 outcome, linear otherwise),"linear"or"logistic".
Returns
Named list:
ate,se,ci_lower,ci_upper.
Details
The outcome model is one stats::glm() fit; its predictions with
the treatment set to 1 and to 0 are averaged over the sample. The SE is
the M-estimation sandwich of stdReg::stdGlm() (Sjolander 2016):
the GLM score equations stacked with the two standardisation equations,
so the outcome model’s own uncertainty is included. Computed natively;
cross-validated against stdReg in tests/cross.
References
Sjolander, A. (2016). Regression standardization with the R package stdReg. European Journal of Epidemiology, 31(6), 563–574.
Examples
set.seed(1)
df <- data.frame(t = rbinom(200, 1, 0.4), x = rnorm(200))
df$y <- 1 + 0.5 * df$t + df$x + rnorm(200)
morie_estimate_g_computation(df, "t", "y", "x")
Applies AIPW within each level of group_col to estimate
stratum-specific treatment effects.
Usage
morie_estimate_gate(
data,
treatment,
outcome,
covariates,
group_col,
propensity_col = NULL,
outcome_model = c("linear", "logistic")
)
Arguments
dataA vector; indexed elementwise.
treatmentPassed to
morie_estimate_propensity_scores.outcomeSee Usage.
covariatesPassed to
morie_estimate_propensity_scores.group_colName of the grouping variable (e.g.
"gender").propensity_colOptional; may be
NULL. Passed tois.null.outcome_modelFamily for the outcome model:
"auto"(logistic for a 0/1 outcome, linear otherwise),"linear"or"logistic".
Returns
Data frame with columns:
group,ate,se,ci_lower,ci_upper,n.
Examples
set.seed(3)
df <- data.frame(
t = rbinom(300, 1, 0.4),
y = rnorm(300),
x = rnorm(300),
g = sample(c("A", "B"), 300, replace = TRUE)
)
morie_estimate_gate(df, "t", "y", "x", "g")
Uses a binary instrument \(Z\) to identify the LATE (Imbens & Angrist, 1994):
Usage
morie_estimate_late(data, treatment, outcome, instrument, covariates = NULL)
Arguments
dataA data frame.
treatmentName of the binary endogenous treatment column.
outcomeName of the outcome column.
instrumentName of the binary instrument column.
covariatesOptional character vector of exogenous covariates.
Returns
Named list:
late,se,ci_lower,ci_upper,first_stage_f,n.
Details
With covariates, the native 2SLS k-class engine is used
(module 17; validated against ivreg in tests/cross/).
Without covariates the closed-form Wald estimator and its
delta-method SE are used.
References
Imbens GW, Angrist JD (1994). Identification and estimation of local average treatment effects. Econometrica, 62(2), 467-475.
Examples
if (requireNamespace("EValue", quietly = TRUE)) {
set.seed(1)
n <- 300L
z <- rbinom(n, 1, 0.5)
t <- rbinom(n, 1, plogis(-0.2 + 1.5 * z))
y <- 0.8 * t + rnorm(n)
morie_estimate_late(data.frame(t = t, y = y, z = z), "t", "y", "z")
}
A step of the causal implementation. Called by morie_estimate_aipw,
morie_estimate_atc, morie_estimate_ate and 1 others in the module.
See the file header for the source the module follows.
it follows.
Usage
morie_estimate_propensity_scores(
data,
treatment,
covariates,
trim = c(0.01, 0.99),
trim_type = "value",
ps_model = "mle",
ridge_lambda = 1
)
Arguments
dataPassed to
.fit_propensity.treatmentPassed to
.fit_propensity.covariatesPassed to
.fit_propensity.trimPassed to
.mor_trim_ps. Defaults toc(0.01, 0.99).trim_typePassed to
.mor_trim_ps. Defaults to"value".ps_modelPassed to
.fit_propensity. Defaults to"mle".ridge_lambdaPassed to
.fit_propensity. Defaults to1.
Returns
The value of
.mor_trim_ps.
Examples
set.seed(1)
df <- data.frame(t = rbinom(60, 1, 0.4), x = rnorm(60))
morie_estimate_propensity_scores(df, "t", "x")
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
estimand("backdoor"),adjustment_setandmethod. When the estimator reports its ownestimandormethod, those are kept asestimator_estimand/estimator_method, so every name is unique.
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).
Native greedy nearest-neighbour matching on the logit propensity
score (Rosenbaum & Rubin 1985; caliper per Cochran & Rubin 1973).
The propensity model is base stats::glm; no MatchIt at
runtime. Returns the same morie_match_result shape as
always; cross-validated against MatchIt in tests/cross/.
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 (forwarded as
ratio).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. The defaultFALSEmatches MatchIt; with fewer controls than treated units it leaves treated units unmatched (a warning says so) and the ATT then describes the matchable subset: passTRUEin that case.NULL(the default) re-uses controls only when there are fewer controls than treated units, where 1:1 matching without replacement would leave treated units unmatched and bias the ATT.NULL(the default) re-uses controls only when there are fewer controls than treated units, where 1:1 matching without replacement would leave treated units unmatched and bias the ATT.psOptional propensity scores. When supplied they REPLACE the fitted model: matching is done on the score you pass, aligned to the rows that survive the NA drop – by name when the vector is named, by position when it is one per retained row. A mis-sized vector is refused rather than recycled.
alphaSignificance level (carried through to
details).
Returns
A list of class
morie_match_result.
Examples
\donttest{
set.seed(1)
df <- data.frame(y = rnorm(200), 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)
}
Native nearest-neighbour matching on the Mahalanobis distance of the
covariates (cross-validated against MatchIt::matchit(distance =
"mahalanobis")).
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. The defaultFALSEmatches MatchIt; with fewer controls than treated units it leaves treated units unmatched (a warning says so) and the ATT then describes the matchable subset: passTRUEin that case.NULL(the default) re-uses controls only when there are fewer controls than treated units, where 1:1 matching without replacement would leave treated units unmatched and bias the ATT.NULL(the default) re-uses controls only when there are fewer controls than treated units, where 1:1 matching without replacement would leave treated units unmatched and bias the ATT.exactOptional character vector of variables to match exactly prior to distance matching.
Returns
A list of class
morie_match_result.
Examples
\donttest{
set.seed(1)
df <- data.frame(y = rnorm(200), d = rbinom(200, 1, 0.4),
x1 = rnorm(200), x2 = rnorm(200))
morie_matching_mahalanobis(df, "d", c("x1", "x2"), n_neighbors = 1)
}
Native rmorie implementation: units are stratified on the exact
combination of exact_vars; strata containing both arms are
retained and controls receive CEM-style stratum weights
(weights and subclass columns on the matched data).
No MatchIt at runtime.
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
\donttest{
set.seed(1)
df <- data.frame(d = rbinom(200, 1, 0.4),
region = sample(c("N", "S", "E", "W"), 200, TRUE),
year = sample(2019:2021, 200, TRUE))
morie_matching_exact(df, "d", c("region", "year"))
}
Native rmorie implementation of Coarsened Exact Matching (Iacus, King
& Porro 2012): numeric covariates are coarsened into bins (quantile
cutpoints; Sturges’ rule when n_bins is NA for a
variable), units are exact-matched on the coarsened strata, and
controls receive CEM stratum weights (weights and
subclass columns on the matched data). The multivariate L1
imbalance of the stratification is reported in
details$l1_before. No MatchIt/cem at runtime.
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; list entries left
NULL/NAfall back to Sturges’ rule.
Returns
A list of class
morie_match_result.
References
Iacus, S. M., King, G., & Porro, G. (2012). Causal inference without balance checking: Coarsened exact matching. Political Analysis, 20(1), 1–24.
Examples
\donttest{
set.seed(1)
df <- data.frame(y = rnorm(200), d = rbinom(200, 1, 0.4),
x1 = rnorm(200), x2 = rnorm(200))
morie_matching_cem(df, "d", c("x1", "x2"), n_bins = 5)
}
Native rmorie implementation of optimal 1:1 pair matching: globally minimizes the total matched distance (Rosenbaum 1989), unlike greedy nearest-neighbour. Propensity distance uses an exact non-crossing dynamic program on the logit score; Mahalanobis distance uses an exact shortest-augmenting-path assignment on whitened covariates. No MatchIt/optmatch at runtime.
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 (ignored; retained for back-compat).
Returns
A list of class
morie_match_result.
Examples
\donttest{
set.seed(1)
df <- data.frame(y = rnorm(200), d = rbinom(200, 1, 0.4),
x1 = rnorm(200), x2 = rnorm(200))
morie_matching_optimal_pair(df, "d", c("x1", "x2"))
}
Native rmorie implementation of genetic matching (Diamond & Sekhon
2013): a real-coded genetic algorithm searches the diagonal
Mahalanobis weight matrix maximizing worst-case covariate balance
(paired-t p-value of the worst covariate). Deterministic given
seed. No Matching/rgenoud at runtime; returns a
morie_match_result with the selected weights in
details$best_weights.
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 (
Min pkg{Matching}).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
\donttest{
set.seed(1)
df <- data.frame(y = rnorm(200), d = rbinom(200, 1, 0.4),
x1 = rnorm(200), x2 = rnorm(200))
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; for an
exact mixed-integer-programming alternative see
\link[designmatch:cardmatch]{designmatch::cardmatch}.
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 propensity scores. When supplied they REPLACE the fitted model and become the matching distance directly, aligned to the rows that survive the NA drop.
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
\donttest{
set.seed(1)
df <- data.frame(y = rnorm(200), d = rbinom(200, 1, 0.4),
x1 = rnorm(200), x2 = rnorm(200))
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. For a richer
covariate-balance report (including continuous + categorical handling
and Love-plot rendering), see
\link[cobalt:bal.tab]{cobalt::bal.tab} /
\link[cobalt:love.plot]{cobalt::love.plot}.
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 of class
morie_balance_resultwithbalance_table(a data frame) and scalar summariesoverall_balance,max_smd,balanced.
Examples
\donttest{
set.seed(1)
df <- data.frame(y = rnorm(200), d = rbinom(200, 1, 0.4),
x1 = rnorm(200), x2 = rnorm(200))
morie_matching_balance(df, "d", c("x1", "x2"))
}
Effect sizes + tests¶
One-way ANOVA
Usage
morie_anova_one_way(...)
Arguments
...Numeric vectors, one per group.
Returns
Named list:
F,df_between,df_within,p_value,eta_squared.
Examples
set.seed(1)
morie_anova_one_way(rnorm(30, 0), rnorm(30, 0.5), rnorm(30, 1))
Chi-square test of independence or goodness-of-fit
Usage
morie_chi_square_test(observed, expected = NULL, correct = TRUE)
Arguments
observedObserved counts (matrix for independence, vector for GOF).
expectedExpected counts for GOF (optional; uniform if NULL).
correctApply Yates’ continuity correction to a 2 x 2 table (
TRUE, thestats::chisq.testdefault).FALSEgives the plain Pearson statistic. Cramer’s V always uses the uncorrected statistic.
Returns
Named list:
chi_sq,df,p_value,cramers_v.
Examples
tab <- matrix(c(30, 10, 15, 25), 2)
morie_chi_square_test(tab)$chi_sq # Yates-corrected, as chisq.test()
morie_chi_square_test(tab, correct = FALSE)$chi_sq # Pearson: 11.43
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
Native implementation of the VanderWeele & Ding (2017) OLS E-value.
Supply an outcome SD via sd_y for the recommended standardised
workflow; when sd_y is left at its default of 1, it
back to the closed-form continuous-scale RR proxy used by the
Python port so both ports stay numerically aligned.
Usage
e_value(ate, se, null = 0, sd_y = 1)
Arguments
atePoint estimate of the treatment effect.
seStandard error of the ATE (must be > 0).
nullNull value. Default 0.
sd_yOutcome standard deviation. Default 1 (use the closed-form proxy). Pass the empirical sd to route through
EValue::evalues.OLS()when installed.
Returns
Scalar E-value (>= 1).
Examples
e_value(ate = 0.5, se = 0.1)
(sum w)^2 / sum w^2: how many particles are really
contributing.
Usage
effective_sample_size(weights)
Arguments
weightsNumeric vector of positive weights.
Returns
Numeric scalar.
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
An object of class
"morie_test_result".
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
A step of the comet_native implementation. No other function in the package calls it. See the file header for the source the module follows.
Usage
kendall_tau(scores, human)
Arguments
scoresPassed to
.comet_vec.humanPassed to
.comet_vec.
Returns
A list with
tau,concordant,discordant,n_segments.
Examples
V <- c(1, 2, 3, 4, 5, 6, 7, 8)
kendall_tau(V, V)
Kruskal-Wallis non-parametric ANOVA
Usage
morie_kruskal_wallis_test(...)
Arguments
...Numeric vectors, one per group.
Returns
Named list:
H,df,p_value.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
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
An object of class
"morie_test_result".
Examples
set.seed(1)
res <- levene_test(rnorm(40), rnorm(40, sd = 2), center = "median")
res
Mann-Whitney U test (Wilcoxon rank-sum)
Usage
morie_mann_whitney_test(
x1,
x2,
alternative = c("two.sided", "greater", "less")
)
Arguments
x1Numeric vector (group 1).
x2Numeric vector (group 2).
alternative"two.sided","greater", or"less".
Returns
Named list:
W,p_value,r(effect size).
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Odds ratio and confidence interval from a 2x2 contingency table
Usage
morie_odds_ratio_ci(table_2x2, alpha = 0.05, method = c("exact", "woolf"))
Arguments
table_2x2A 2x2 matrix: rows are treatment, columns are outcome.
alphaSignificance level; sets the width of the interval,
method“exact” (default): the exact conditional interval of fisher.test, solved to machine precision; “woolf”: the log-scale Wald interval with a half added to every cell when one is empty. which is Woolf’s on the log scale (Haldane-Anscombe corrected when a cell is empty).
Returns
Named list:
odds_ratio(the sample odds ratio),ci_lower,ci_upperat the requested level, and the exactp_value.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
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.
Examples
omega_squared(40, 160, 2, 1.5)
One-sample t-test
Usage
morie_one_sample_t_test(
x,
mu0 = 0,
alternative = c("two.sided", "greater", "less")
)
Arguments
xNumeric vector.
mu0Null hypothesis mean (default 0).
alternative"two.sided","greater", or"less".
Returns
Named list:
t,df,p_value,ci.
Examples
set.seed(1)
morie_one_sample_t_test(x = rnorm(50))
Survey + sampling¶
Bootstrap resampling for any statistic
Usage
morie_bootstrap_sample(df, statistic, n_bootstrap = 1000L, seed = 42L)
Arguments
dfA data frame.
statisticA function taking a data frame and returning a scalar.
n_bootstrapNumber of bootstrap replicates.
seedRandom seed.
Returns
Named list:
estimate,se,ci_lower,ci_upper,distribution(numeric vector of bootstrap statistics).
Examples
set.seed(1)
if (requireNamespace("ranger", quietly = TRUE)) {
df <- data.frame(x = rnorm(100))
morie_bootstrap_sample(df, statistic = function(d) mean(d$x))
}
Adjusts initial design weights so that weighted marginal totals match known population totals for each auxiliary variable.
Usage
morie_calibration_weights(
df,
aux_vars,
population_totals,
initial_weights = NULL,
max_iter = 50L,
tol = 1e-06
)
Arguments
dfA data frame.
aux_varsCharacter vector of categorical auxiliary variable names.
population_totalsNamed list:
"var_level"-> population count. Keys should be"varname_level"(e.g."gender_female").initial_weightsOptional numeric vector of starting weights.
max_iterMaximum IPF iterations.
tolConvergence tolerance.
Returns
Numeric vector of calibrated weights.
Examples
set.seed(1)
df <- data.frame(
region = sample(c("A", "B"), 100, TRUE),
sex = sample(c("M", "F"), 100, TRUE)
)
totals <- list(region_A = 60, region_B = 40, sex_M = 55, sex_F = 45)
morie_calibration_weights(df,
aux_vars = c("region", "sex"),
population_totals = totals
)
Randomly selects n_clusters clusters, then takes all units within
selected clusters.
Usage
morie_cluster_sample(df, cluster_col, n_clusters, seed = 42L)
Arguments
dfA data frame.
cluster_colName of the cluster identifier column.
n_clustersNumber of clusters to select.
seedRandom seed.
Returns
Data frame of selected units with
.weightcolumn.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Compute inverse-probability design weights
Usage
morie_compute_design_weights(df, strata_col, population_sizes)
Arguments
dfA data frame.
strata_colName of the stratification column.
population_sizesNamed integer vector: stratum level -> population size.
Returns
Numeric vector of design weights (same length as
nrow(df)).
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
A step of the tlclust_native implementation. No other function in the package calls it. See the file header for the source the module follows. the source it follows.
Usage
design_effect(ic, cluster)
Arguments
icPassed to
naive_variance.clusterPassed to
cluster_variance.
Returns
A list with
se_naive,se_clustered,ratio,note.
Examples
V <- c(1, 2, 3, 4, 5, 6, 7, 8)
design_effect(V, V)
Generates non-identifying synthetic data suitable for development, testing,
and demos. The generator uses a canonical variable set and allows output
column renaming through name_map so it can be adapted to multiple studies.
Synthetic data should not be used for final inferential reporting.
Usage
morie_generate_synthetic_data(
n = 5000L,
seed = 42L,
special_code_rate = 0.02,
profile = c("generic", "morie_legacy"),
name_map = NULL
)
Arguments
nNumber of rows.
seedRandom seed for reproducibility.
special_code_rateProportion of values replaced with survey-style special missing codes (
97/98/99/997/998/999) in discrete fields.profileConvenience profile for output naming; ignored when
name_mapis supplied.name_mapOptional named character vector mapping canonical keys to output column names. Use
``morie_default_synthetic_name_map()``as a template.
Returns
A data.frame with synthetic records.
Examples
df <- morie_generate_synthetic_data(n = 200, seed = 1)
nrow(df)
Delete-1 jackknife variance estimate
Usage
morie_jackknife_estimate(df, statistic)
Arguments
dfA data frame.
statisticA function taking a data frame and returning a scalar.
Returns
Named list:
estimate,se,bias.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Datasets + I/O¶
Canonicalize raw CPADS PUMF columns
Usage
morie_canonicalize_cpads_data(data)
Arguments
dataRaw CPADS data frame.
Returns
Data frame with canonical MORIE analysis columns.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Load the real CPADS CSV from this repository
Usage
morie_load_cpads_data(cpads_csv = .cpads_default_csv())
Arguments
cpads_csvPath to the CPADS CSV.
Returns
Canonicalized CPADS data frame.
Examples
\donttest{
if (requireNamespace("rmoriedata", quietly = TRUE)) withAutoprint({
# Reads and canonicalises the CPADS PUMF CSV. The default CSV lives in
# a morie project tree; the CKAN-fetched PUMF works identically (see
# morie_load_dataset("ocp21")). The tryCatch guard lets the example
# render cleanly on machines without the CSV checked out locally.
tryCatch(morie_load_cpads_data(), error = function(e) message(conditionMessage(e)))
})
}
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
\dontshow{if (morie_has("sql")) withAutoprint(\{ # examplesIf}
morie_builtin_db()
\dontshow{\}) # examplesIf}
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 (morie_has("sql")) withAutoprint(\{ # examplesIf}
# The SQLite backend needs the optional 'RSQLite' package.
if (requireNamespace("RSQLite", quietly = TRUE)) {
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
\donttest{
if (morie_has("sql")) withAutoprint({
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)
})
}
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
\donttest{
if (morie_has("sql")) withAutoprint({
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)
})
}
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
set.seed(1)
\donttest{
if (morie_has("sql")) withAutoprint({
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)
})
}
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) a per-user strong{SQL} cache database. This is the opt-in SQL backend and requires DuckDB or RSQLite to be installed.
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
Note: the DEFAULT cache used by morie_cache_store() / verb{_load()} /
verb{_list()} needs strong{no SQL backend at all} – it uses a zero/light
dependency file store: Parquet via pkg{nanoparquet} (cross-language)
when available, else base-R .rds. Install duckdb (or RSQLite),
or set MORIE_CACHE_BACKEND=duckdb/sqlite, or pass verb{db_path=}, to
use SQL instead – DuckDB is preferred (vectorised + columnar, handles
multi-GB PUMFs and out-of-core analytical queries); an existing
morie.db / morie.duckdb cache is reused for back-compat. For the
multi-user server tier, pass your own PostgreSQL verb{con=}.
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{
if (morie_has("sql")) withAutoprint({
# 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,
refresh = FALSE
)
Arguments
surveyA bootstrap key of
``morie_dataset_catalog``("ocs22bt","ocs24bt","cu20bt","cu23bt"), its survey-year name ("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).refreshDownload again even when the table is already cached (default
FALSE: a cached table is reported and kept).
Returns
Invisibly, the number of surveys available (downloaded or already cached).
Examples
# the bootstrap tables and their keys
cat_ <- morie_dataset_catalog()
cat_[cat_$type == "bootstrap", c("key", "name")]
\donttest{
# the CSADS 2021 bootstrap weights are 376 MB: fetched once, then read from the cache
if (interactive()) morie_download_bootstrap(survey = "csads_2021")
}
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,
portal = 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).portalOptional CKAN portal base URL (e.g.
"https://data.ontario.ca"); the default is open.canada.ca. The catalog gives it for resources on another portal.
Returns
A data.frame.
Examples
\donttest{
# Requires network access. Fetches the first 200 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 = 200L)
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
\dontshow{if (morie_has("sql")) withAutoprint(\{ # examplesIf}
morie_list_datasets()
\dontshow{\}) # examplesIf}
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
\dontshow{if (morie_has("httr2", "jsonlite")) withAutoprint(\{ # examplesIf}
# Local-first and offline: use_ckan = FALSE consults the bundled copy
# and the local cache only, and errors when neither is present.
cpads <- try(morie_load_cpads(use_ckan = FALSE), silent = TRUE)
if (!inherits(cpads, "try-error")) head(cpads)
\dontrun{
# The live CKAN fetch pages through the datastore; it ran for over ten
# minutes in the docs build, so it is shown rather than executed.
cpads <- morie_load_cpads(use_ckan = TRUE)
if (!is.null(cpads)) head(cpads)
}
\dontshow{\}) # examplesIf}
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
\donttest{
if (morie_has("sql")) withAutoprint({
# CPADS 2021-2022: downloaded once from open.canada.ca (39 MB), then a local
# read; try() so a missing optional backend does not fail the check
df <- try(morie_load_dataset("ocp21"))
# re-fetch from the portal to pick up an upstream revision (network):
# df <- morie_load_dataset("ocp21", refresh = TRUE)
# 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 included 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¶
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")
Audit declared outputs against files on disk
Usage
morie_audit_public_outputs(project_root = NULL, manifest = NULL)
Arguments
project_rootProject root directory.
manifestManifest data frame. If
NULL, loaded from disk.
Returns
Data frame containing declared and observed output status.
Examples
# Craft a tempdir manifest + output file, then audit:
tdir <- tempfile("morie-doc-")
dir.create(tdir)
writeLines("x,y\n1,2", file.path(tdir, "results.csv"))
man <- data.frame(
output = "results.csv",
public_path = file.path(tdir, "results.csv"),
size_kb = 0.01, modified = format(Sys.Date())
)
morie_audit_public_outputs(project_root = tdir, manifest = man)
Build an outputs manifest from a directory of artifacts
Usage
morie_build_outputs_manifest(
output_dir,
manifest_path,
public_prefix = "data/manifest/outputs",
extensions = c("csv", "pdf", "png", "html", "txt", "md")
)
Arguments
output_dirDirectory containing output files.
manifest_pathCSV path to write.
public_prefixPrefix used in
public_pathvalues.extensionsFile extensions to include (without dots).
Returns
Manifest data frame.
Examples
# Scan a tempdir of output files and build a manifest CSV:
tdir <- tempfile("morie-doc-")
dir.create(tdir)
writeLines("x,y\n1,2", file.path(tdir, "results.csv"))
writeLines("# report", file.path(tdir, "report.md"))
morie_build_outputs_manifest(tdir, file.path(tdir, "outputs_manifest.csv"))
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")
Describes the morie CPADS contract: the canonical analysis variables expected in a wrangled frame, the raw -> canonical column map, and the conventional on-disk cache path used when a user has wrangled the PUMF themselves.
Usage
morie_cpads_contract()
Returns
A named list with fields
source_kind,expected_wrangled_path,required_variables,raw_column_map, andnote.
Details
CPADS is open data (Open Government Licence – Canada). The
Public Use Microdata File is available at open.canada.ca, dataset
verb{736fa9b2-62e4-4e31-aea4-51869605b363} (resource
verb{d2639429-c304-45a6-90b3-770562f4d46d},
file cpads-2021-2022-pumf2.csv). Aggregate dashboards at
url{https://health-infobase.canada.ca/substance-use/reports/cpads/}.
morie ships a 30-row synthetic at
inst/extdata/cpads_pumf_synthetic.csv for offline CRAN-safe
tests; morie_datasets_cpads(offline = FALSE) fetches the live
PUMF. Earlier morie versions wrongly claimed CPADS was
“FOI/agreement-only”; that was incorrect and has been retracted
as of 3MMM.
Examples
contract <- morie_cpads_contract()
contract$required_variables
Returns a named character vector mapping canonical variable keys used by
``morie_generate_synthetic_data()`` to output column names.
Usage
morie_default_synthetic_name_map(profile = c("generic", "morie_legacy"))
Arguments
profileName profile.
"generic"is recommended for new projects."morie_legacy"reproduces previous EML legacy column names.
Returns
Named character vector.
Examples
morie_default_synthetic_name_map("generic")
Returns the default named map of workflow steps to project script paths.
Usage
morie_default_workflow_map()
Returns
Named character vector.
Examples
morie_default_workflow_map()
Searches upward from start for a directory containing the current
Sphinx/package-root markers, while still tolerating legacy Quarto-era
markers in older checkouts.
Usage
morie_find_project_root(start = getwd(), max_up = 10L)
Arguments
startStarting directory.
max_upMaximum number of parent traversals.
Returns
Absolute path to the detected project root.
Examples
tryCatch(morie_find_project_root(),
error = function(e) message("not inside a morie project tree")
)
List implemented MORIE CPADS modules
Usage
morie_list_morie_modules()
Returns
Data frame describing the implemented module surface.
Examples
morie_list_morie_modules()
Other¶
Paired t-test
Usage
morie_paired_t_test(x1, x2, alternative = c("two.sided", "greater", "less"))
Arguments
x1Numeric vector (before/condition 1).
x2Numeric vector (after/condition 2).
alternative"two.sided","greater", or"less".
Returns
Named list:
t,df,p_value,ci_diff,mean_diff.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Point-biserial correlation
Usage
morie_point_biserial_r(binary_var, continuous_var)
Arguments
binary_varBinary numeric vector (0/1).
continuous_varContinuous numeric vector.
Returns
Named list:
r,p_value.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Mirrors R’s power.prop.test().
Usage
morie_power_prop_test(
n = NULL,
p1 = NULL,
p2 = NULL,
sig_level = 0.05,
power = NULL,
alternative = c("two.sided", "one.sided")
)
Arguments
nSample size per group.
p1Proportion in group 1.
p2Proportion in group 2.
sig_levelType I error rate.
powerDesired power.
alternative"two.sided"or"one.sided".
Returns
Result of
stats::power.prop.test().
Examples
morie_power_prop_test(p1 = 0.30, p2 = 0.20, power = 0.80)
Solve for any missing parameter (n, delta, sd, sig.level,
or power). Mirrors R’s power.t.test().
Usage
morie_power_t_test(
n = NULL,
delta = NULL,
sd = 1,
sig_level = 0.05,
power = NULL,
alternative = c("two.sided", "one.sided"),
type = c("two.sample", "one.sample", "paired")
)
Arguments
nSample size per group (NULL to solve for it).
deltaEffect size (difference in means).
sdStandard deviation (pooled).
sig_levelType I error rate (alpha).
powerDesired power (1 - beta).
alternative"two.sided"or"one.sided".type"two.sample","one.sample", or"paired".
Returns
Result of
stats::power.t.test().
Examples
morie_power_t_test(n = NULL, delta = 0.5, power = 0.80)
Probability proportional to size (PPS) sampling
Usage
morie_pps_sample(df, size_col, n, seed = 42L, replace = FALSE)
Arguments
dfA data frame.
size_colName of the size measure column.
nNumber of units to select.
seedRandom seed.
replaceLogical;
FALSE(default) uses PPS-without-replacement (Madow systematic-like), matchingmorie.sampling.pps_samplesince 2026-05-22.TRUEreverts to the legacy Hansen-Hurwitz with-replacement scheme.
Returns
Data frame of selected units with
.weight(Hansen-Hurwitz weights).
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Wilson score confidence interval for a proportion
Usage
morie_proportion_ci(
successes,
n,
alpha = 0.05,
method = c("wilson", "exact", "wald", "agresti-coull", "clopper-pearson")
)
Arguments
successesNumber of successes.
nTotal observations.
alphaSignificance level (default 0.05 -> 95% CI).
method"wilson"(default),"exact"or"clopper-pearson"(Clopper-Pearson),"agresti-coull", or"wald".
Returns
Named list:
p_hat,ci_lower,ci_upper.
Examples
morie_proportion_ci(35, 100)
Read outputs manifest from a project
Usage
morie_read_outputs_manifest(
project_root = NULL,
manifest_path = NULL,
validate = TRUE
)
Arguments
project_rootProject root path.
manifest_pathOptional explicit manifest path.
validateIf
TRUE, validate schema.
Returns
Manifest data frame.
Examples
# Craft a minimal manifest in tempdir and read it back:
tdir <- tempfile("morie-doc-")
dir.create(tdir)
man <- file.path(tdir, "outputs_manifest.csv")
write.csv(
data.frame(
output = "results.csv",
public_path = file.path(tdir, "results.csv"),
size_kb = 0.01, modified = format(Sys.Date())
),
man,
row.names = FALSE
)
writeLines("x,y\n1,2", file.path(tdir, "results.csv"))
morie_read_outputs_manifest(manifest_path = man)
Risk difference (ARD) with Newcombe CI
Usage
morie_risk_difference_ci(table_2x2, alpha = 0.05)
Arguments
table_2x2A 2x2 matrix: rows are exposure, columns are outcome.
alphaSignificance level.
Returns
Named list:
rd,ci_lower,ci_upper.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Risk ratio (relative risk) with log-normal CI
Usage
morie_risk_ratio_ci(table_2x2, alpha = 0.05)
Arguments
table_2x2A 2x2 matrix: rows are exposure, columns are outcome (disease = col 1).
alphaSignificance level.
Returns
Named list:
rr,ci_lower,ci_upper.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Mirrors the core outputs of the old verb{07_ebac_ipw.R} workflow.
Usage
morie_run_ebac_selection_ipw_analysis(
data,
output_dir = NULL,
treatment = "cannabis_any_use",
covariates = c("age_group", "gender", "province_region", "mental_health",
"physical_health")
)
Arguments
dataAnalysis data frame.
output_dirOptional directory for CSV outputs.
treatmentTreatment column name.
covariatesCovariate names used in the observation model.
Returns
Named list of output tables and the observed-domain analysis frame.
Examples
# Run on a synthetic CPADS-shaped frame (the CKAN-fetched PUMF works
# identically -- see morie_load_cpads_data() for the real frame):
if (TRUE) {
set.seed(1)
n <- 200
cpads <- data.frame(
weight = runif(n, 0.5, 2),
alcohol_past12m = rbinom(n, 1, 0.8),
heavy_drinking_30d = rbinom(n, 1, 0.3),
ebac_tot = abs(rnorm(n, 0.05, 0.03)),
ebac_legal = rbinom(n, 1, 0.7),
cannabis_any_use = rbinom(n, 1, 0.3),
age_group = sample(1:6, n, TRUE),
gender = sample(1:2, n, TRUE),
province_region = sample(1:5, n, TRUE),
mental_health = sample(1:5, n, TRUE),
physical_health = sample(1:5, n, TRUE)
)
morie_run_ebac_selection_ipw_analysis(cpads)
}
Run one implemented MORIE module against CPADS data
Usage
morie_run_morie_module(
module_name,
cpads_csv = .cpads_default_csv(),
output_dir = NULL
)
Arguments
module_nameModule name.
cpads_csvPath to the CPADS CSV.
output_dirOptional directory for CSV outputs.
Returns
Named list of data-frame outputs.
Examples
\donttest{
if (requireNamespace("rmoriedata", quietly = TRUE)) withAutoprint({
# Dispatch one MORIE module against the canonical CPADS CSV. The CSV
# ships with a morie project tree, or is fetched via the CKAN endpoint
# (morie_load_dataset("ocp21")). Wrapped in tryCatch so the example
# documents usage even when the CSV is not checked out locally.
tryCatch(
morie_run_morie_module("descriptive-statistics"),
error = function(e) message(conditionMessage(e))
)
})
}
Run multiple implemented MORIE modules
Usage
morie_run_morie_modules(
modules = morie_list_morie_modules()$name,
cpads_csv = .cpads_default_csv(),
output_dir = NULL
)
Arguments
modulesCharacter vector of module names.
cpads_csvPath to the CPADS CSV.
output_dirOptional directory for CSV outputs.
Returns
Named list of module outputs.
Examples
\donttest{
out <- morie_run_morie_modules(c("descriptive-statistics", "power-design"),
output_dir = tempfile("modules-"))
names(out)
}
Run multiple workflow steps
Usage
morie_run_pipeline(
steps = NULL,
project_root = NULL,
script_map = morie_default_workflow_map(),
stop_on_error = TRUE,
verbose = TRUE
)
Arguments
stepsOrdered vector of workflow step names.
project_rootProject root directory.
script_mapNamed character vector mapping steps to script paths.
stop_on_errorIf
TRUE, stop at first failure.verboseIf
TRUE, streams command output.
Returns
Data frame of step statuses.
Examples
# Build a one-step pipeline in tempdir and dispatch it. The
# real package's morie_default_workflow_map() points at scripts that
# live in a morie project tree.
tdir <- tempfile("morie-doc-")
dir.create(tdir)
step <- file.path(tdir, "step.R")
writeLines('cat("hello from pipeline\\\\n")', step)
morie_run_pipeline(
steps = "demo",
project_root = tdir,
script_map = c(demo = step),
verbose = FALSE
)
Mirrors the core outputs of the old verb{07_propensity.R} workflow.
Usage
morie_run_propensity_ipw_analysis(
data,
output_dir = NULL,
trim = c(0.01, 0.99),
treatment = "cannabis_any_use",
outcome = "heavy_drinking_30d",
covariates = c("age_group", "gender", "province_region", "mental_health",
"physical_health")
)
Arguments
dataAnalysis data frame.
output_dirOptional directory for CSV outputs.
trimQuantile pair used to trim extreme IPW values.
treatmentBinary treatment column.
outcomeBinary outcome column.
covariatesCovariate names for the propensity model.
Returns
Named list of output tables and the analysis data.
ipw_resultsholdsestimate,se,ci_lower,ci_upper(Wald, 95 percent),n,y1_ipwandy0_ipw;analysis_framegainsps,ipw,ipw_trimmedandw_survey_ipw(survey weight timesipw_trimmed).
Details
The weight column is the CPADS survey design weight (wtpumf). The
estimate is the survey-weighted Hajek contrast: each respondent’s weight
is the survey weight times the trimmed inverse-probability weight, and
the treated and control means are sum(w * y) / sum(w) within each arm.
The standard error is the Taylor-linearised (with-replacement) variance
of the two weighted means, holding the weights fixed, so it does not
propagate uncertainty from the estimated propensity score.
Examples
# Run on a synthetic CPADS-shaped frame (the CKAN-fetched PUMF works
# identically -- see morie_load_cpads_data() for the real frame):
set.seed(1)
n <- 200
cpads <- data.frame(
weight = runif(n, 0.5, 2),
alcohol_past12m = rbinom(n, 1, 0.8),
heavy_drinking_30d = rbinom(n, 1, 0.3),
ebac_tot = abs(rnorm(n, 0.05, 0.03)),
ebac_legal = rbinom(n, 1, 0.7),
cannabis_any_use = rbinom(n, 1, 0.3),
age_group = sample(1:6, n, TRUE),
gender = sample(1:2, n, TRUE),
province_region = sample(1:5, n, TRUE),
mental_health = sample(1:5, n, TRUE),
physical_health = sample(1:5, n, TRUE)
)
morie_run_propensity_ipw_analysis(cpads)
Run one project workflow step
Usage
morie_run_workflow_step(
step,
project_root = NULL,
script_map = morie_default_workflow_map(),
rscript_bin = file.path(R.home("bin"), "Rscript"),
verbose = TRUE
)
Arguments
stepStep name present in
script_map.project_rootProject root directory.
script_mapNamed character vector mapping steps to script paths.
rscript_binOptional path to
Rscriptbinary.verboseIf
TRUE, streams command output.
Returns
Named list with step metadata and exit status.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Binary covariate (their eq. 1): with event rates \(P_0\) at X = 0 and \(P_1\) at X = 1, a fraction \(B\) of the sample at X = 1 and \(\bar P = (1-B)P_0 + BP_1\),
Continuous normal covariate (their eq. 2): \(n = (z_{1-\alpha/2} + z_{1-\beta})^2 / (P_0(1-P_0)\log(OR)^2)\), with \(P_0\) the event rate at the covariate mean and OR per standard deviation.
Usage
morie_sample_size_logistic(
p0,
or = NULL,
alpha = 0.05,
power = 0.8,
two_sided = TRUE,
B = 0.5,
covariate = c("binary", "continuous"),
p1 = NULL
)
Arguments
p0Event rate at X = 0 (binary) or at the covariate mean (continuous).
orOdds ratio for X = 1 vs 0 (binary) or per standard deviation (continuous). Ignored for a binary covariate when
p1is given.alphaSignificance level.
powerDesired power.
two_sidedLogical; one-sided uses \(z_{1-\alpha}\).
BFraction of the sample with X = 1 (binary covariate).
covariate"binary"or"continuous".p1Optional event rate at X = 1 (binary covariate).
Returns
Integer total sample size, rounded up.
References
Hsieh FY, Bloch DA, Larsen MD (1998). A simple method of sample size calculation for linear and logistic regression. Statistics in Medicine, 17(14):1623-1634. Reference implementation: powerMediation::SSizeLogisticBin, SSizeLogisticCon.
Examples
morie_sample_size_logistic(0.2, p1 = 0.35) # 276
morie_sample_size_logistic(0.2, or = 1.5, covariate = "continuous") # 299
Native base R rank-matched-pair signed-rank bounds across a Gamma grid, via the normal approximation to the Wilcoxon signed-rank statistic.
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.
Examples
if (requireNamespace("EValue", quietly = TRUE) && requireNamespace("rbounds", quietly = TRUE)) {
set.seed(1)
df <- data.frame(d = rbinom(60, 1, 0.5), x1 = rnorm(60))
df$y <- df$d * 0.5 + df$x1 + rnorm(60)
res <- try(sensitivity_rosenbaum(df, "d", "y", "x1"))
if (!inherits(res, "try-error")) str(res, max.level = 1)
}
Shapiro-Wilk normality test
Usage
morie_shapiro_wilk_test(x, alpha = 0.05)
Arguments
xNumeric vector.
alphaSignificance level for the
is_normalflag (default 0.05).
Returns
Named list:
W,p_value,is_normal.
Examples
set.seed(1)
morie_shapiro_wilk_test(x = rnorm(50))
Simple random sample from a data frame
Usage
morie_simple_random_sample(df, n, replace = FALSE, seed = 42L)
Arguments
dfA data frame.
nNumber of units to select.
replaceSample with replacement? Default
FALSE.seedRandom seed for reproducibility.
Returns
A data frame of
nsampled rows with a.weightcolumn added.
Examples
df <- data.frame(x = 1:100)
srs_sample <- morie_simple_random_sample(df, 20)
Spearman rank correlation
Usage
morie_spearman_rho(x, y)
Arguments
xNumeric vector.
yNumeric vector.
Returns
Named list:
rho,p_value.
Examples
set.seed(1)
morie_spearman_rho(x = rnorm(50), y = rnorm(50))
Proportional or fixed stratified random sample
Usage
morie_stratified_sample(
df,
strata_col,
n_per_stratum,
proportional = FALSE,
seed = 42L
)
Arguments
dfA data frame.
strata_colName of the stratification column.
n_per_stratumEither an integer (equal allocation) or a named integer vector mapping stratum levels to sample sizes. If
proportional = TRUE,n_per_stratumis treated as the total desired sample size and allocation is proportional to stratum size.proportionalLogical; if
TRUE, allocate proportionally to strata sizes.seedRandom seed.
Returns
Data frame of sampled rows with a
.weightcolumn.
Examples
set.seed(1)
df <- data.frame(g = c(rep("A", 60), rep("B", 40)), x = rnorm(100))
morie_stratified_sample(df, "g", n_per_stratum = 10)
Summarize an output audit
Usage
morie_summarize_output_audit(audit_tbl)
Arguments
audit_tblResult from
``morie_audit_public_outputs()``.
Returns
Named list with high-level diagnostics.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Two-sample t-test with tidy output
Usage
morie_two_sample_t_test(
x1,
x2,
equal_var = FALSE,
alternative = c("two.sided", "greater", "less")
)
Arguments
x1Numeric vector (group 1).
x2Numeric vector (group 2).
equal_varAssume equal variances? Default
FALSE(Welch test).alternative"two.sided","greater", or"less".
Returns
Named list:
t,df,p_value,ci_diff,cohens_d.
Examples
set.seed(1)
morie_two_sample_t_test(rnorm(50, 0.5), rnorm(50, 0))
Validate a CPADS analysis data frame
Usage
morie_validate_cpads_data(data, strict = TRUE)
Arguments
dataData frame to validate.
strictIf
TRUE, stop when required variables are missing.
Returns
Character vector of missing variable names.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Validate outputs manifest structure
Usage
morie_validate_outputs_manifest(manifest, strict = TRUE)
Arguments
manifestData frame to validate.
strictIf
TRUE, stop on validation failures.
Returns
TRUEwhen validation passes.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Wilcoxon signed-rank test (paired)
Usage
morie_wilcoxon_signed_rank_test(
x1,
x2,
alternative = c("two.sided", "greater", "less"),
exact = NULL
)
Arguments
x1Numeric vector (before).
x2Numeric vector (after).
alternative"two.sided","greater", or"less".exactExact p-value?
NULL(default): exact below 50 pairs without ties or zero differences, as\link[stats:wilcox.test]{stats::wilcox.test()}.
Returns
Named list:
V,p_value.
Examples
# See the package vignettes for usage examples:
# vignette(package = "morie")
Write synthetic epidemiology-style data to CSV
Usage
morie_write_synthetic_data(
path,
n = 5000L,
seed = 42L,
special_code_rate = 0.02,
profile = c("generic", "morie_legacy"),
name_map = NULL,
overwrite = FALSE
)
Arguments
pathOutput CSV path.
nNumber of rows.
seedRandom seed.
special_code_rateProportion of survey-style missing codes.
profileNaming profile for output columns.
name_mapOptional custom variable name map.
overwriteIf
TRUE, overwrite existing file.
Returns
Normalized output path.
Examples
out <- morie_write_synthetic_data(tempfile(fileext = ".csv"), n = 200, seed = 1)
file.exists(out)