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

prompt

User question or instruction.

context

Optional named list (or text) given with the question.

model

Optional model name; the route’s model when NULL.

provider

Older name for route ("api" is "own").

system_prompt

Optional instructions added for the model.

timeout

Seconds to wait for each reply. Default 120.

route

NULL (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.

docs

TRUE (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

route

NULL (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

timeout

Probe 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_browser

Open the GitHub page in a browser.

poll_max_seconds

How long to wait for the GitHub approval.

email

An email address to send a sign-in code to.

code

The code that was emailed (asked for when not given).

token

A 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_url

The endpoint, e.g. "http://localhost:1234/v1".

key

The API key for it (NULL for a server that needs none).

model

Optional model name to ask by default.

Returns

morie_llm_provider_set() and morie_llm_provider_unset(): the settings table, invisibly; morie_llm_provider_show(): the own.* 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

args

Character vector of arguments; defaults to the command line.

out

Connection 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

dir

Target directory (default ~/.local/bin; created if absent).

name

Command 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

refresh

Fetch again even when a day-old copy is cached.

key

A db/table key from the manifest.

db_path

Dataset-store path, as in ``morie_load_dataset``.

Returns

morie_hosted_manifest(): a list; morie_hosted_datasets(): a data frame with key, 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),

\[RR(z) = \exp(\ln(1.08) (z - z_{cf}) / 10)\]

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),

\[RR(z) = 1 + \alpha (1 - e^{-\gamma (z - z_{cf})^{\delta}}),\]

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),

\[RR(z) = \exp(\beta (z - z_{cf}) / 10).\]

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

exposure

Ambient concentration in micrograms per cubic metre (scalar or vector).

outcome

PM2.5: "all_cause_mortality", "ihd" or "stroke". NO2: "all_cause_mortality", "respiratory" or "childhood_asthma".

reference_conc

Counterfactual concentration below which no excess risk is assumed (PM2.5 default 5.8, NO2 default 10).

beta_per_10

Optional log-RR per 10 units overriding the NO2 outcome table.

Returns

A list of class morie_envhealth_crf with rr, log_rr, reference_conc, exposure_conc, pollutant, citation and extra.

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):

\[PAF = p (RR - 1) / (1 + p (RR - 1)).\]

Usage

morie_envhealth_attributable_fraction(rr, exposure_prevalence)

Arguments

rr

Relative risk at the observed exposure level.

exposure_prevalence

Proportion 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):

\[\Delta Y = y_0 N (1 - e^{-\beta \Delta x}).\]

Usage

morie_envhealth_mortality_displaced(
  exposure_delta,
  population,
  baseline_rate,
  beta_per_unit
)

Arguments

exposure_delta

Counterfactual reduction in exposure (positive means the exposure goes down).

population

At-risk population.

baseline_rate

Baseline rate in cases per person-year.

beta_per_unit

Log-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_mean

Population-mean exposure.

exposure_prevalence

Proportion of the population at that level (1 for ambient air).

baseline_rate

Cases per person-year in the unexposed scenario.

population

At-risk population.

pollutant

"PM2.5" or "NO2".

outcome

Outcome key passed to the concentration-response function.

reference_conc

Counterfactual concentration; defaults to the pollutant’s WHO guideline.

Returns

A list of class morie_envhealth_burden with paf, attributable_cases, baseline_cases, population, baseline_rate, exposure_mean, reference_conc, pollutant, citation and extra.

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

data

A data frame.

outcome, exposure, confounders

Column names.

n_bootstrap

Number of resamples (default 100).

random_state

Seed for the resampling.

Returns

A list with ate, se_analytic, se_bootstrap, ci_lower_bs, ci_upper_bs, n_bootstrap and method.

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):

\[CI = (2 / \mu) \, \mathrm{cov}(h_i, R_i)\]

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

data

A data frame.

exposure, income

Column names.

Returns

A list of class morie_envhealth_equity with concentration_index, interpretation, n_quintiles, exposure_mean, citation and extra.

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_table

A data frame with one row per area.

fsa_col, exposure_col, population_col, baseline_rate_col

Column names.

pollutant, outcome

Passed to ``morie_envhealth_burden``.

Returns

The input columns plus rr, paf, attributable_cases and baseline_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".

outcome

Outcome key for the concentration-response function.

region, years

Labels for the report.

demo

Use synthetic demo data.

exposure_csv

Path of a CSV with an exposure column.

exposure_mean, exposure_prevalence

Scalar inputs used when neither demo nor exposure_csv is given.

reference

Counterfactual reference concentration.

baseline_rate

Baseline outcome rate per 100,000 per year.

population

Population at risk.

Returns

The report as a list; its status is "ok", "assumption_failure" or "error", and the attribute exit_status carries 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_name

Label written to the CSV and the manifest.

output_dir

Where emissions.csv and the capsule go. NULL (the default) writes nothing: the measurement is returned in R only.

output_file

CSV file name.

pue, wue

Power and water usage effectiveness multipliers.

country_iso_code, region

Location overrides.

save_to_file

Write the CSV row.

capsule

Seal the run in a bricklayer capsule.

key

A signing key from rmoriebricklayer::fipskg() or rmoriebricklayer::pqckg(); generated per run when NULL.

measure_power_secs

Seconds between utilisation samples of the background sampler (the Python arm’s default is 15; 1 here, since R runs are usually shorter).

tracker

The object from morie_emissions_start().

expr

An expression to evaluate under tracking.

...

Passed to morie_emissions_start().

Returns

morie_emissions_stop(): the emissions in kg CO2eq, with the full row as attribute data and the capsule paths as attribute capsule. morie_emissions_track(): a list with value, emissions_kg, data and capsule.

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_iso

Three-letter ISO code, e.g. "CAN".

region

Unused; 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

dir

The directory morie_emissions_stop() wrote to.

Returns

A list with ok and the bricklayer checks table.

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

data

A vector; indexed elementwise.

treatment

Passed to morie_estimate_propensity_scores.

outcome

See Usage.

covariates

Passed to morie_estimate_propensity_scores.

propensity_col

Optional; may be NULL. Passed to is.null.

outcome_model

Family for the outcome model: "auto" (logistic for a 0/1 outcome, linear otherwise), "linear" or "logistic".

trim

Passed to .mor_trim_ps. Defaults to c(0.01, 0.99).

trim_type

Passed to .mor_trim_ps. Defaults to "value".

ps_model

Passed to morie_estimate_propensity_scores. Defaults to "mle".

ridge_lambda

Passed to morie_estimate_propensity_scores. Defaults to 1.

outcome_fit

One 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

data

A data frame.

treatment

Name of the binary treatment column.

outcome

Name of the outcome column.

covariates

Character vector of covariate names.

propensity_col

Optional: 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

data

Data frame containing the analytical sample.

outcome

Name of the outcome column.

treatment

Name of the binary treatment column.

weights_col

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

Returns

Named list with ate and se (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

data

A data frame.

treatment

Name of the binary treatment column.

outcome

Name of the outcome column.

covariates

Character vector of covariate names.

propensity_col

Optional: 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

data

A vector; indexed elementwise.

treatment

Passed to morie_estimate_propensity_scores.

outcome

See Usage.

covariates

Passed to morie_estimate_propensity_scores.

propensity_col

Optional; may be NULL. Passed to is.null.

outcome_model

Family for the outcome model: "auto" (logistic for a 0/1 outcome, linear otherwise), "linear" or "logistic".

meta_learner

One 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_model applies 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:

\[\widehat{ATE} = \frac{1}{n}\sum_i \bigl[\hat{\mu}_1(X_i) -\]

hat{mu}_0(X_i)bigr]

Usage

morie_estimate_g_computation(
  data,
  treatment,
  outcome,
  covariates,
  outcome_model = c("linear", "logistic")
)

Arguments

data

A vector; indexed elementwise.

treatment

Passed to morie_estimate_propensity_scores.

outcome

See Usage.

covariates

Passed to morie_estimate_propensity_scores.

outcome_model

Family 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

data

A vector; indexed elementwise.

treatment

Passed to morie_estimate_propensity_scores.

outcome

See Usage.

covariates

Passed to morie_estimate_propensity_scores.

group_col

Name of the grouping variable (e.g. "gender").

propensity_col

Optional; may be NULL. Passed to is.null.

outcome_model

Family 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):

\[LATE = \frac{Cov(Y, Z)}{Cov(T, Z)}\]

Usage

morie_estimate_late(data, treatment, outcome, instrument, covariates = NULL)

Arguments

data

A data frame.

treatment

Name of the binary endogenous treatment column.

outcome

Name of the outcome column.

instrument

Name of the binary instrument column.

covariates

Optional 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

data

Passed to .fit_propensity.

treatment

Passed to .fit_propensity.

covariates

Passed to .fit_propensity.

trim

Passed to .mor_trim_ps. Defaults to c(0.01, 0.99).

trim_type

Passed to .mor_trim_ps. Defaults to "value".

ps_model

Passed to .fit_propensity. Defaults to "mle".

ridge_lambda

Passed to .fit_propensity. Defaults to 1.

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

data

A data frame.

treatment

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

outcome

Numeric outcome column name.

covariates

Character vector of confounder column names.

cluster

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

n_folds

Cross-fitting folds (default 5).

seed

Integer seed (default 123).

eps

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

ps

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

Returns

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

Details

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

References

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

Examples

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

Causal DAG toolkit (native)

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

Build a causal DAG

Usage

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

Arguments

edges

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

exposure

Name of the exposure/treatment node.

outcome

Name of the outcome node.

latent

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

Returns

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

Examples

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

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

Usage

morie_dag_identify(dag)

Arguments

dag

A morie_dag.

Returns

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

Examples

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

Estimate the identified effect from data

Usage

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

Arguments

dag

A morie_dag.

data

Data frame containing the observed nodes.

method

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

Returns

The chosen estimator’s result list, plus estimand ("backdoor"), adjustment_set and method. When the estimator reports its own estimand or method, those are kept as estimator_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

dag

A morie_dag.

data

The data frame used for estimation.

method

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

estimator

Passed through to ``morie_dag_estimate()``.

n_reps

Number of refutation replications (default 20).

seed

Random seed.

Returns

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

Examples

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

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

Usage

morie_mrm_dags()

Returns

Named list of morie_dag objects.

Examples

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

Matching (native engines)

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

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

data

Data frame.

treatment

Binary treatment column (0/1).

covariates

Character vector of covariates for the propensity model.

n_neighbors

Number of matches per treated unit (forwarded as ratio).

caliper

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

replace

If TRUE, controls may be re-used. The default FALSE matches MatchIt; with fewer controls than treated units it leaves treated units unmatched (a warning says so) and the ATT then describes the matchable subset: pass TRUE in 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.

ps

Optional 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.

alpha

Significance 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

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of continuous covariates.

n_neighbors

Number of matches per treated unit.

caliper

Maximum Mahalanobis distance for a valid match.

replace

If TRUE, controls may be re-used. The default FALSE matches MatchIt; with fewer controls than treated units it leaves treated units unmatched (a warning says so) and the ATT then describes the matchable subset: pass TRUE in 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.

exact

Optional 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

data

Data frame.

treatment

Binary treatment column name.

exact_vars

Character vector of discrete variables for exact matching.

Returns

A list of class morie_match_result.

Examples

\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

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

n_bins

Either a single integer (applied to every covariate) or a named list mapping covariate name to the number of bins; list entries left NULL/NA fall 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

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

distance

One of "propensity" or "mahalanobis".

ps

Optional pre-computed propensity scores (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

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

n_neighbors

Number of matches per treated unit (M in pkg{Matching}).

pop_size

Genetic-algorithm population size (default 50).

n_generations

Number of GA generations.

seed

Random seed.

Returns

A list of class morie_match_result.

References

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

Examples

\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

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

balance_threshold

Maximum absolute SMD tolerated (default 0.1).

ps

Optional 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

data

Data frame.

treatment

Binary treatment column name.

covariates

Character vector of covariates.

weights

Optional column name of matching / weighting weights.

threshold

Absolute-SMD threshold for the balanced flag.

Returns

A list of class morie_balance_result with balance_table (a data frame) and scalar summaries overall_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

observed

Observed counts (matrix for independence, vector for GOF).

expected

Expected counts for GOF (optional; uniform if NULL).

correct

Apply Yates’ continuity correction to a 2 x 2 table (TRUE, the stats::chisq.test default). FALSE gives 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, y

Numeric vectors (NA dropped).

confidence

Confidence level for CI. Default 0.95.

Returns

A morie_effect_size.

Examples

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

Cramer’s V for a contingency table

Usage

cramers_v(contingency_table, confidence = 0.95)

Arguments

contingency_table

Numeric matrix or table.

confidence

Confidence level. Default 0.95.

Returns

A morie_effect_size.

Examples

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

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

ate

Point estimate of the treatment effect.

se

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

null

Null value. Default 0.

sd_y

Outcome 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

weights

Numeric vector of positive weights.

Returns

Numeric scalar.

Eta-squared from ANOVA sums of squares

Usage

eta_squared(ss_effect, ss_total)

Arguments

ss_effect

Sum of squares for the effect.

ss_total

Total sum of squares.

Returns

A morie_effect_size.

Examples

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

Fisher’s exact test for a 2x2 table

Usage

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

Arguments

contingency_table

2x2 matrix.

alternative

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

Returns

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, y

Numeric vectors (NA dropped).

confidence

Confidence level for CI. Default 0.95.

Returns

A morie_effect_size.

Examples

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

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

scores

Passed to .comet_vec.

human

Passed 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.

center

One 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

x1

Numeric vector (group 1).

x2

Numeric 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_2x2

A 2x2 matrix: rows are treatment, columns are outcome.

alpha

Significance 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_upper at the requested level, and the exact p_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_total

Sums of squares.

df_effect

Numerator d.f. of the effect.

ms_error

Error 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

x

Numeric vector.

mu0

Null 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

df

A data frame.

statistic

A function taking a data frame and returning a scalar.

n_bootstrap

Number of bootstrap replicates.

seed

Random 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

df

A data frame.

aux_vars

Character vector of categorical auxiliary variable names.

population_totals

Named list: "var_level" -> population count. Keys should be "varname_level" (e.g. "gender_female").

initial_weights

Optional numeric vector of starting weights.

max_iter

Maximum IPF iterations.

tol

Convergence 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

df

A data frame.

cluster_col

Name of the cluster identifier column.

n_clusters

Number of clusters to select.

seed

Random seed.

Returns

Data frame of selected units with .weight column.

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

df

A data frame.

strata_col

Name of the stratification column.

population_sizes

Named 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

ic

Passed to naive_variance.

cluster

Passed 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

n

Number of rows.

seed

Random seed for reproducibility.

special_code_rate

Proportion of values replaced with survey-style special missing codes (97/98/99/997/998/999) in discrete fields.

profile

Convenience profile for output naming; ignored when name_map is supplied.

name_map

Optional 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

df

A data frame.

statistic

A 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

data

Raw 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_csv

Path 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

path

Path to a CSV or RDS file.

table_name

Name for the cached table.

db_path

Optional path to a SQLite file (default backend).

con

Optional pre-opened DBI connection (overrides db_path).

Returns

Number of rows cached (invisible).

Examples

\dontshow{if (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_path

Optional path to a SQLite file (default backend).

con

Optional pre-opened DBI connection (overrides db_path).

Returns

A data.frame with columns table and rows.

Examples

\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_name

Name of the table.

db_path

Optional path to a SQLite file (default backend).

con

Optional pre-opened DBI connection (overrides db_path).

Returns

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

Examples

\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

data

A data.frame to cache.

table_name

Name of the destination table.

db_path

Optional path to a SQLite file (default backend).

con

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

Returns

Number of rows written (invisible).

Examples

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_member columns are empty for datasets reachable through the SQLite cache or the CKAN datastore.

Details

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

Examples

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

Get metadata for a single dataset

Usage

morie_dataset_info(key)

Arguments

key

Dataset catalog key (or fuzzy match).

Returns

A named list with dataset metadata.

Examples

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

Opens (or creates) 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_path

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

Returns

A DBI connection object.

Details

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

survey

A 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).

limit

Max records per CKAN request (default 32000).

db_path

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

con

Optional pre-opened DBI connection (overrides db_path).

refresh

Download 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_key

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

limit

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

db_path

Optional override for the database path.

resource_id

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

con

Optional pre-opened DBI connection (overrides db_path).

portal

Optional 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_path

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

con

Optional pre-opened DBI connection (overrides db_path).

Returns

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

Examples

\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_path

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

use_ckan

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

con

Optional pre-opened DBI connection (overrides db_path).

Returns

A data.frame with canonical CPADS columns.

Examples

\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

key

Dataset catalog key (or fuzzy match).

db_path

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

refresh

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

con

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

Returns

A data.frame.

Examples

\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_root

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

Returns

Named list of key paths.

Examples

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

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

Usage

morie_userguide(name = NULL)

Arguments

name

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

Returns

File path string, or character vector of filenames.

Examples

morie_userguide()

Workflow + audit

Query Perseus via Python

Usage

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

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

Arguments

question

User question.

context

Optional context string.

python_bin

Python executable to use. Defaults to MORIE_PYTHON_BIN or python3.

Returns

Agent text response.

Examples

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

Audit declared outputs against files on disk

Usage

morie_audit_public_outputs(project_root = NULL, manifest = NULL)

Arguments

project_root

Project root directory.

manifest

Manifest 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_dir

Directory containing output files.

manifest_path

CSV path to write.

public_prefix

Prefix used in public_path values.

extensions

File 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

question

User question.

context

Optional 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, and note.

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

profile

Name 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

start

Starting directory.

max_up

Maximum 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

x1

Numeric vector (before/condition 1).

x2

Numeric 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_var

Binary numeric vector (0/1).

continuous_var

Continuous 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

n

Sample size per group.

p1

Proportion in group 1.

p2

Proportion in group 2.

sig_level

Type I error rate.

power

Desired 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

n

Sample size per group (NULL to solve for it).

delta

Effect size (difference in means).

sd

Standard deviation (pooled).

sig_level

Type I error rate (alpha).

power

Desired 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

df

A data frame.

size_col

Name of the size measure column.

n

Number of units to select.

seed

Random seed.

replace

Logical; FALSE (default) uses PPS-without-replacement (Madow systematic-like), matching morie.sampling.pps_sample since 2026-05-22. TRUE reverts 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

successes

Number of successes.

n

Total observations.

alpha

Significance 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_root

Project root path.

manifest_path

Optional explicit manifest path.

validate

If 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_2x2

A 2x2 matrix: rows are exposure, columns are outcome.

alpha

Significance 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_2x2

A 2x2 matrix: rows are exposure, columns are outcome (disease = col 1).

alpha

Significance 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

data

Analysis data frame.

output_dir

Optional directory for CSV outputs.

treatment

Treatment column name.

covariates

Covariate 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_name

Module name.

cpads_csv

Path to the CPADS CSV.

output_dir

Optional 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

modules

Character vector of module names.

cpads_csv

Path to the CPADS CSV.

output_dir

Optional 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

steps

Ordered vector of workflow step names.

project_root

Project root directory.

script_map

Named character vector mapping steps to script paths.

stop_on_error

If TRUE, stop at first failure.

verbose

If 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

data

Analysis data frame.

output_dir

Optional directory for CSV outputs.

trim

Quantile pair used to trim extreme IPW values.

treatment

Binary treatment column.

outcome

Binary outcome column.

covariates

Covariate names for the propensity model.

Returns

Named list of output tables and the analysis data. ipw_results holds estimate, se, ci_lower, ci_upper (Wald, 95 percent), n, y1_ipw and y0_ipw; analysis_frame gains ps, ipw, ipw_trimmed and w_survey_ipw (survey weight times ipw_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

step

Step name present in script_map.

project_root

Project root directory.

script_map

Named character vector mapping steps to script paths.

rscript_bin

Optional path to Rscript binary.

verbose

If 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\),

\[ n = \frac{[z_{1-\alpha/2}\sqrt{\bar P(1-\bar P)/B} + z_{1-\beta} \sqrt{P_0(1-P_0) + P_1(1-P_1)(1-B)/B}]^2}{(P_0 - P_1)^2 (1-B)}.\]

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

p0

Event rate at X = 0 (binary) or at the covariate mean (continuous).

or

Odds ratio for X = 1 vs 0 (binary) or per standard deviation (continuous). Ignored for a binary covariate when p1 is given.

alpha

Significance level.

power

Desired power.

two_sided

Logical; one-sided uses \(z_{1-\alpha}\).

B

Fraction of the sample with X = 1 (binary covariate).

covariate

"binary" or "continuous".

p1

Optional 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

data

Data frame with treatment + outcome columns.

treatment

Binary treatment column (0/1).

outcome

Outcome column.

covariates

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

gamma_range

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

n_gamma

Number of Gamma values. Default 20.

Returns

Data frame with Gamma, p_lower, p_upper.

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

x

Numeric vector.

alpha

Significance level for the is_normal flag (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

df

A data frame.

n

Number of units to select.

replace

Sample with replacement? Default FALSE.

seed

Random seed for reproducibility.

Returns

A data frame of n sampled rows with a .weight column 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

x

Numeric vector.

y

Numeric 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

df

A data frame.

strata_col

Name of the stratification column.

n_per_stratum

Either an integer (equal allocation) or a named integer vector mapping stratum levels to sample sizes. If proportional = TRUE, n_per_stratum is treated as the total desired sample size and allocation is proportional to stratum size.

proportional

Logical; if TRUE, allocate proportionally to strata sizes.

seed

Random seed.

Returns

Data frame of sampled rows with a .weight column.

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_tbl

Result 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

x1

Numeric vector (group 1).

x2

Numeric vector (group 2).

equal_var

Assume 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

data

Data frame to validate.

strict

If 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

manifest

Data frame to validate.

strict

If TRUE, stop on validation failures.

Returns

TRUE when 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

x1

Numeric vector (before).

x2

Numeric vector (after).

alternative

"two.sided", "greater", or "less".

exact

Exact 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

path

Output CSV path.

n

Number of rows.

seed

Random seed.

special_code_rate

Proportion of survey-style missing codes.

profile

Naming profile for output columns.

name_map

Optional custom variable name map.

overwrite

If TRUE, overwrite existing file.

Returns

Normalized output path.

Examples

out <- morie_write_synthetic_data(tempfile(fileext = ".csv"), n = 200, seed = 1)
file.exists(out)