| Title: | Workflow-Oriented Survey Weight Calibration |
|---|---|
| Description: | Provides a disciplined precheck, execution, and diagnostics workflow for survey weighting and raking. Weight construction requires design-only data, a verified external target, outcome-blind planning, and human approval before weight locking, with bilingual reports for decision and statistical audiences. Converts calibrated and replicate weights into standard survey designs, provides optional broom-style result projections, and records serializable production pipeline provenance. Supports fixed, predeclared soft calibration tolerances and categorical entropy balancing from verified margins, plus panel attrition weighting, high-influence unit diagnostics, Fay's balanced repeated replication, and opt-in parallel execution for long runs. Calibration methods follow Deville and Saerndal (1992) <doi:10.1080/01621459.1992.10475217>, and entropy balancing follows Hainmueller (2012) <doi:10.1093/pan/mpr025>. |
| Authors: | Kunxiang Ma [aut, cre], WEIAN DATA TECH (Beijing) Co., Ltd. [cph, fnd] |
| Maintainer: | Kunxiang Ma <[email protected]> |
| License: | GPL (>= 2) |
| Version: | 2.0.1 |
| Built: | 2026-10-14 11:05:04 UTC |
| Source: | https://github.com/weiandata/wfc |
Aligns recalibrated WFC replicate weights to analysis data by exact unit ID
and creates a standard survey::svrepdesign() object. The returned design
uses full-estimate-centered (mse = TRUE) variance so its estimates reproduce
wf_variance().
as_svrepdesign(r, data, id = "id", degf = NULL, ...)as_svrepdesign(r, data, id = "id", degf = NULL, ...)
r |
A |
data |
Non-empty analysis data frame containing the units in |
id |
Unit-ID column in |
degf |
Optional survey design degrees of freedom. |
... |
Additional arguments passed to |
A standard svyrep.design object whose variables include the aligned
.wf_weight base-weight column.
Joins calibrated WFC weights onto an analysis data frame by exact unit ID and
creates a standard survey::svydesign() object. The survey package remains
a suggested dependency.
as_svydesign( w, data, id = "id", ids = ~1, strata = NULL, fpc = NULL, nest = FALSE, ... )as_svydesign( w, data, id = "id", ids = ~1, strata = NULL, fpc = NULL, nest = FALSE, ... )
w |
A |
data |
Non-empty analysis data frame containing the units in |
id |
Unit-ID column in |
ids |
Survey cluster formula, defaulting to independent units. |
strata |
Optional survey strata formula. |
fpc |
Optional finite-population-correction formula. |
nest |
Whether cluster IDs should be relabeled to nest within strata. |
... |
Additional arguments passed to |
A standard survey.design2 object whose variables include the
aligned .wf_weight column.
Convert a weighting quality report to a data frame
## S3 method for class 'wf_quality_report' as.data.frame(x, ...)## S3 method for class 'wf_quality_report' as.data.frame(x, ...)
x |
A |
... |
Unused. |
The report's primary table.
Coerce a variance result to a data frame
## S3 method for class 'wf_variance_result' as.data.frame(x, ...)## S3 method for class 'wf_variance_result' as.data.frame(x, ...)
x |
A |
... |
Unused. |
The result table as a data frame.
Draws the worst design effect and residual margin error for every feasible finite cap.
## S3 method for class 'wf_auto_trim' plot(x, lang = NULL, ...)## S3 method for class 'wf_auto_trim' plot(x, lang = NULL, ...)
x |
A |
lang |
Output language. |
... |
Additional arguments passed to the initial plot calls. |
Invisibly returns x.
Plot blend lambda sensitivity
## S3 method for class 'wf_blend_result' plot(x, lang = NULL, ...)## S3 method for class 'wf_blend_result' plot(x, lang = NULL, ...)
x |
A |
lang |
Output language. |
... |
Additional arguments passed to the initial plot. |
Invisibly returns x.
Draws design effects and effective-sample-size shares by group.
## S3 method for class 'wf_diagnostics' plot(x, lang = NULL, ...)## S3 method for class 'wf_diagnostics' plot(x, lang = NULL, ...)
x |
A |
lang |
Output language. |
... |
Additional arguments passed to |
Invisibly returns x.
Plot propensity overlap and covariate balance
## S3 method for class 'wf_propensity_weights' plot(x, lang = NULL, ...)## S3 method for class 'wf_propensity_weights' plot(x, lang = NULL, ...)
x |
A |
lang |
Output language. |
... |
Additional arguments passed to the initial plot calls. |
Invisibly returns x.
Draws one histogram per group, including the group mean and recorded raking trim bounds when available.
## S3 method for class 'wf_weights' plot(x, max_groups = 9, lang = NULL, ...)## S3 method for class 'wf_weights' plot(x, max_groups = 9, lang = NULL, ...)
x |
A |
max_groups |
Maximum number of groups to plot. |
lang |
Output language. |
... |
Additional arguments passed to |
Invisibly returns x.
Print attrition weights
## S3 method for class 'wf_attrition_weights' print(x, ...)## S3 method for class 'wf_attrition_weights' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print an automatic trim recommendation
## S3 method for class 'wf_auto_trim' print(x, ...)## S3 method for class 'wf_auto_trim' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a guided weighting result
## S3 method for class 'wf_autoweigh_result' print(x, ...)## S3 method for class 'wf_autoweigh_result' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a blend result.
## S3 method for class 'wf_blend_result' print(x, ...)## S3 method for class 'wf_blend_result' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print an outcome-blind cell merge plan
## S3 method for class 'wf_cell_merge_plan' print(x, ...)## S3 method for class 'wf_cell_merge_plan' print(x, ...)
x |
A |
... |
Reserved for future use. |
x, invisibly.
Print a collapse plan
## S3 method for class 'wf_collapse_plan' print(x, ...)## S3 method for class 'wf_collapse_plan' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print outcome-free survey design data
## S3 method for class 'wf_design_data' print(x, ...)## S3 method for class 'wf_design_data' print(x, ...)
x |
A |
... |
Reserved for future use. |
x, invisibly.
Print diagnostics
## S3 method for class 'wf_diagnostics' print(x, ...)## S3 method for class 'wf_diagnostics' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print post-lock outcome impact
## S3 method for class 'wf_impact' print(x, ...)## S3 method for class 'wf_impact' print(x, ...)
x |
A |
... |
Reserved for future use. |
x, invisibly.
Print influence diagnostics
## S3 method for class 'wf_influence' print(x, ...)## S3 method for class 'wf_influence' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a collapse-ladder draft
## S3 method for class 'wf_ladder_draft' print(x, ...)## S3 method for class 'wf_ladder_draft' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a pipeline specification
## S3 method for class 'wf_pipeline' print(x, ...)## S3 method for class 'wf_pipeline' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a post-stratification plan
## S3 method for class 'wf_poststrat_plan' print(x, ...)## S3 method for class 'wf_poststrat_plan' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a precheck result
## S3 method for class 'wf_precheck' print(x, ...)## S3 method for class 'wf_precheck' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a weighting quality report
## S3 method for class 'wf_quality_report' print(x, ...)## S3 method for class 'wf_quality_report' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print replicate weights
## S3 method for class 'wf_replicate_weights' print(x, ...)## S3 method for class 'wf_replicate_weights' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a weight-validation result
## S3 method for class 'wf_validation' print(x, ...)## S3 method for class 'wf_validation' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a variance result
## S3 method for class 'wf_variance_result' print(x, ...)## S3 method for class 'wf_variance_result' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a reviewable weight plan
## S3 method for class 'wf_weight_plan' print(x, ...)## S3 method for class 'wf_weight_plan' print(x, ...)
x |
A |
... |
Reserved for future use. |
x, invisibly.
Print calibrated weights
## S3 method for class 'wf_weights' print(x, ...)## S3 method for class 'wf_weights' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Summarize a post-stratification plan
## S3 method for class 'wf_poststrat_plan' summary(object, ...)## S3 method for class 'wf_poststrat_plan' summary(object, ...)
object |
A |
... |
Unused. |
The plan diagnostics data frame.
Applies category-merge maps consistently to sample data and a target object.
wf_apply_collapse(sample, target, plan)wf_apply_collapse(sample, target, plan)
sample |
Sample data frame. |
target |
A |
plan |
List with |
A list with collapsed sample and target.
Approval records are separate from plans. AI agents may prepare plans but cannot create an approval while declaring themselves as an agent.
wf_approve_plan(plan, approver, role, note = NULL, actor_type = "human")wf_approve_plan(plan, approver, role, note = NULL, actor_type = "human")
plan |
An unchanged, review-ready |
approver |
Non-empty approver name or organizational identifier. |
role |
Non-empty reviewing role. |
note |
Optional review note. |
actor_type |
Actor type. Only |
A wf_plan_approval attestation bound to the plan identity.
Compares fixed unweighted and locked-weight estimates. This function cannot accept target values, selection callbacks, or planning controls, and it never recalculates weights.
wf_assess_impact(weights, data, id, outcomes, level = 0.95)wf_assess_impact(weights, data, id, outcomes, level = 0.95)
weights |
An unchanged |
data |
Analysis data frame with the exact locked unit-ID set. |
id |
Unique identifier column in |
outcomes |
Character vector naming outcome columns. |
level |
Normal-approximation confidence level. |
A wf_impact object with fixed descriptive summaries.
Attach locked weights to analysis data by exact unit ID
wf_attach_weights(data, weights, id, weight_name = ".weight")wf_attach_weights(data, weights, id, weight_name = ".weight")
data |
Full analysis data frame. |
weights |
An unchanged |
id |
Unique identifier column in |
weight_name |
Name of the appended weight column. |
data in its original row order with one locked-weight column.
Models wave-to-wave retention in a panel and returns inverse-retention
weights for retained units. The result inherits from wf_weights, so it can
be composed with later calibration stages through wf_compose().
wf_attrition( panel, retained, formula, id = NULL, by = NULL, stabilize = TRUE, trim = NULL )wf_attrition( panel, retained, formula, id = NULL, by = NULL, stabilize = TRUE, trim = NULL )
panel |
Full prior-wave panel data. |
retained |
Column indicating whether each prior-wave unit was retained into the next wave. |
formula |
One-sided or two-sided formula naming retention predictors. |
id |
Optional unique unit identifier column. |
by |
Optional grouping column; separate retention models are fit by group. |
stabilize |
Whether to multiply inverse probabilities by the group retention rate before normalization. |
trim |
Optional positive scalar cap, applied as |
A wf_attrition_weights object inheriting from wf_weights, with a
$balance diagnostic table and per-group retention log.
Writes a JSON audit record containing result provenance, pipeline metadata, optional guided-workflow decision ledger, input hashes, and user-supplied extra metadata. The writer is dependency-free and intended for machine archiving, not human formatting.
wf_audit_export(x, file, inputs = NULL, extra = NULL)wf_audit_export(x, file, inputs = NULL, extra = NULL)
x |
A WFC result, safe workflow, plan, approval, locked weights, verified target, design-data object, or post-lock impact object. |
file |
Output JSON file path. |
inputs |
Optional named list of input objects whose hashes should be recorded. |
extra |
Optional additional metadata to include in the audit record. |
Invisibly returns file.
Sweeps candidate upper caps by rerunning raking and reports the trade-off between design effect and residual margin error. The function recommends a cap but never applies it to a production result.
wf_auto_trim( design, target, caps = c(2, 3, 4, 5, 6, 8, 10, 12), lo = 0.05, max_deff = 6, max_residual = 0.02, ... )wf_auto_trim( design, target, caps = c(2, 3, 4, 5, 6, 8, 10, 12), lo = 0.05, max_deff = 6, max_residual = 0.02, ... )
design |
An unchanged |
target |
An unchanged, non-demo |
caps |
Unique positive finite upper-cap multipliers. |
lo |
Positive lower-cap multiplier used for every finite candidate. |
max_deff |
Maximum acceptable worst-group design effect. |
max_residual |
Maximum acceptable worst relative margin residual. |
... |
Additional raking settings. ID and base-weight roles are owned by
|
A wf_auto_trim object containing the candidate frontier and the
recommended cap. Inf means no trimming is needed; NA means no candidate
meets both criteria.
Provides the guided WFC experience while enforcing the same WFC 2.0 input boundary used by direct calibration and approved-plan execution.
wf_autoweigh( design, target, dims, method = c("auto", "raking", "poststrat", "logit"), ladder = NULL, min_cell = NULL, bounds = c(0.3, 3), trim = "auto", max_deff = 6, max_residual = 0.02, interactive = base::interactive(), lang = NULL, ... )wf_autoweigh( design, target, dims, method = c("auto", "raking", "poststrat", "logit"), ladder = NULL, min_cell = NULL, bounds = c(0.3, 3), trim = "auto", max_deff = 6, max_residual = 0.02, interactive = base::interactive(), lang = NULL, ... )
design |
An unchanged |
target |
An unchanged, non-demo |
dims |
A |
method |
Calibration method. |
ladder |
Reviewed collapse ladder for post-stratification. |
min_cell |
Positive post-stratification cell-size threshold. |
bounds |
Two-element bounds for logit calibration. |
trim |
Raking trim control. |
max_deff |
Maximum design effect accepted by automatic trimming. |
max_residual |
Maximum margin residual accepted by automatic trimming. |
interactive |
Whether review prompts may be shown. |
lang |
Output language. |
... |
Method settings. ID and base-weight roles cannot be overridden. |
A wf_autoweigh_result carrying verified input identities.
Combines two wf_weights sources at the estimator level. Each source is
estimated within each fusion cell first; the source estimates are then
combined using the effective lambda recorded in the result.
wf_blend( online, offline, by_cell, lambda = c("neff", "inverse_variance", "fixed"), lambda_fixed = NULL, outcome = NULL, level = c("cell", "group"), trim_lambda = c(0.05, 0.95), sensitivity = TRUE )wf_blend( online, offline, by_cell, lambda = c("neff", "inverse_variance", "fixed"), lambda_fixed = NULL, outcome = NULL, level = c("cell", "group"), trim_lambda = c(0.05, 0.95), sensitivity = TRUE )
online |
Online-source |
offline |
Offline-source |
by_cell |
Character vector of cell columns. |
lambda |
Lambda strategy: |
lambda_fixed |
Fixed lambda scalar or key table when |
outcome |
Optional numeric outcome column. |
level |
Lambda level: |
trim_lambda |
Two bounds used to clamp data-driven lambdas. |
sensitivity |
Whether to compute a global-lambda sensitivity sweep. |
A wf_blend_result object.
Enforces the WFC 2.0 verified-input boundary before dispatching to a
calibration engine. Raw data frames and ordinary wf_target objects are not
accepted.
wf_calibrate(design, target, method = "raking", ...)wf_calibrate(design, target, method = "raking", ...)
design |
An unchanged |
target |
An unchanged, non-demo |
method |
Calibration method: |
... |
Method settings. ID and base-weight roles come from |
A wf_weights object carrying the verified input identities.
Creates an ordered, cumulative, validated category-collapse ladder for post-stratification cell resolution. Level 0 is the raw classification; each named level applies one additional set of dimension maps.
wf_collapse_ladder(dims, ...)wf_collapse_ladder(dims, ...)
dims |
A |
... |
Named ladder levels, each a list of named character vectors in
the form |
A wf_collapse_ladder object.
dims <- wf_dims(age = c("young", "old"), education = c("low", "high")) wf_collapse_ladder( dims, level1 = list(age = c(young = "all", old = "all")) )dims <- wf_dims(age = c("young", "old"), education = c("low", "high")) wf_collapse_ladder( dims, level1 = list(age = c(young = "all", old = "all")) )
Multiplies compatible wf_weights objects into one auditable pipeline result.
wf_compose(..., id = NULL, normalize = c("none", "mean1", "sum"))wf_compose(..., id = NULL, normalize = c("none", "mean1", "sum"))
... |
Two or more |
id |
Optional shared ID column in each stage's |
normalize |
Weight normalization mode: |
A composed wf_weights object.
stage1 <- structure( list( data = data.frame(id = c("r1", "r2"), group = "A", weight = c(2, 3)), log = data.frame(group = "A"), achieved = NULL, provenance = list(method = "stage1") ), class = "wf_weights" ) stage2 <- stage1 stage2$data$weight <- c(0.5, 2) stage2$provenance$method <- "stage2" wf_compose(stage1, stage2)stage1 <- structure( list( data = data.frame(id = c("r1", "r2"), group = "A", weight = c(2, 3)), log = data.frame(group = "A"), achieved = NULL, provenance = list(method = "stage1") ), class = "wf_weights" ) stage2 <- stage1 stage2$data$weight <- c(0.5, 2) stage2$provenance$method <- "stage2" wf_compose(stage1, stage2)
Computes per-group quality metrics for a wf_weights object.
wf_diagnose(w, target = NULL, sample = NULL, deff_ok = 3, deff_caveat = 10)wf_diagnose(w, target = NULL, sample = NULL, deff_ok = 3, deff_caveat = 10)
w |
A |
target |
Optional |
sample |
Reserved for future diagnostics. |
deff_ok |
Design-effect threshold for an OK verdict. |
deff_caveat |
Design-effect threshold for caveat verdict. |
A wf_diagnostics object.
Declare calibration dimensions
wf_dims(..., .collapse = list())wf_dims(..., .collapse = list())
... |
Named dimension-level pairs. Use |
.collapse |
Named list of collapse ladders. |
A wf_dims object.
dims <- wf_dims(gender = c("female", "male"), age = c("young", "old")) dimsdims <- wf_dims(gender = c("female", "male"), age = c("young", "old")) dims
Revalidates the plan, human approval, design data, target evidence, and any stored cell map before calling exactly the method recorded in the plan.
wf_execute_plan(plan, approval, design, target)wf_execute_plan(plan, approval, design, target)
plan |
An unchanged |
approval |
A matching |
design |
The unchanged |
target |
The unchanged |
A wf_locked_weights object that also inherits from wf_weights.
Execute a guided workflow with an external human approval
wf_guided_execute(workflow, approval)wf_guided_execute(workflow, approval)
workflow |
An unchanged |
approval |
A matching |
A wf_locked_weights object.
This practitioner-oriented entry point composes design preparation, verified target import, outcome-blind cell planning, and weight planning. It never approves a plan or computes weights.
wf_guided_plan( data, id, calibration, dims, target_file, source_file, source_type = c("population", "reference"), key_map = NULL, count = NULL, feature = NULL, ... )wf_guided_plan( data, id, calibration, dims, target_file, source_file, source_type = c("population", "reference"), key_map = NULL, count = NULL, feature = NULL, ... )
data |
Design-only data frame. |
id |
Unique identifier column. |
calibration |
Declared calibration and boundary columns. |
dims |
A |
target_file |
CSV or XLSX target file. |
source_file |
Companion source DCF file. |
source_type |
Either |
key_map |
Population dimension-to-column mapping. |
count |
Population count column. |
feature |
Reference reciprocal-design-weight column. |
... |
Named safe settings: |
A reviewable wf_safe_workflow; no weights are computed.
Imports an external reference sample only when every file column has a declared design role and the companion DCF record passes the provenance and checksum checks.
wf_import_reference( data_file, source_file, dims, feature, by = NULL, production = TRUE )wf_import_reference( data_file, source_file, dims, feature, by = NULL, production = TRUE )
data_file |
Path to a CSV or XLSX reference sample. |
source_file |
Path to its companion source DCF record. |
dims |
A |
feature |
Name of the reciprocal-design-weight column. |
by |
Optional grouping variable. |
production |
Whether to reject demo-only sources. |
A wf_verified_target object.
Imports CSV or Excel population margins only when a companion DCF record supplies complete provenance and a matching SHA-256 checksum.
wf_import_target( data_file, source_file, dims, key_map, count, by = NULL, by_key = NULL, production = TRUE )wf_import_target( data_file, source_file, dims, key_map, count, by = NULL, by_key = NULL, production = TRUE )
data_file |
Path to a CSV or XLSX population table. |
source_file |
Path to its companion source DCF record. |
dims |
A |
key_map |
Named mapping from dimensions to data columns. |
count |
Name of the population-count column. |
by |
Optional grouping variable. |
by_key |
Optional group-key column or function. |
production |
Whether to reject demo-only sources. |
A wf_verified_target object.
# WFC ships a synthetic demo target beside its companion evidence record. csv_file <- system.file( "extdata", "safe-target-example.csv", package = "WFC" ) csv_source <- paste0(csv_file, ".source.dcf") dims_safe <- wf_dims(sex = c("F", "M"), age = c("18-34", "35+")) # `production = FALSE` is required here only because the bundled file is # declared demo-only. Do not use it to admit an authoritative source whose # evidence record is incomplete. target <- wf_import_target( csv_file, csv_source, dims_safe, key_map = c(sex = "sex", age = "age"), count = "count", production = FALSE ) target$identity # The same demo file is refused as a production source, so a synthetic # file cannot impersonate an authoritative population. try(wf_import_target( csv_file, csv_source, dims_safe, key_map = c(sex = "sex", age = "age"), count = "count" ))# WFC ships a synthetic demo target beside its companion evidence record. csv_file <- system.file( "extdata", "safe-target-example.csv", package = "WFC" ) csv_source <- paste0(csv_file, ".source.dcf") dims_safe <- wf_dims(sex = c("F", "M"), age = c("18-34", "35+")) # `production = FALSE` is required here only because the bundled file is # declared demo-only. Do not use it to admit an authoritative source whose # evidence record is incomplete. target <- wf_import_target( csv_file, csv_source, dims_safe, key_map = c(sex = "sex", age = "age"), count = "count", production = FALSE ) target$identity # The same demo file is refused as a production source, so a synthetic # file cannot impersonate an authoritative population. try(wf_import_target( csv_file, csv_source, dims_safe, key_map = c(sex = "sex", age = "age"), count = "count" ))
Reports the units that contribute most to weight instability. The core
diagnostics are per-unit weight ratio to the group mean, share of the
group's squared-weight mass, and leave-one-out design effect for the top
units. When sample and target are supplied, WFC also reports the largest
share of any target margin represented by that unit.
wf_influence(w, target = NULL, sample = NULL, id = NULL, top = 20)wf_influence(w, target = NULL, sample = NULL, id = NULL, top = 20)
w |
A |
target |
Optional |
sample |
Optional sample data frame aligned by |
id |
Sample ID column required when |
top |
Number of highest-ratio units for which leave-one-out design effects are computed and printed. |
A wf_influence object with a $table data frame.
Creates a serializable specification for a recurring weighting run. The specification records which verified target mode and calibration stage to use and which post-run validation thresholds to check.
wf_pipeline(target, stages, validate = NULL)wf_pipeline(target, stages, validate = NULL)
target |
Target declaration. Use a list with |
stages |
Named stage list with a required |
validate |
Optional validation thresholds. Supported keys are
|
A wf_pipeline object.
Uses only declared design fields, external target margins, ordered dimension levels, and an optional explicit collapse ladder. Study outcomes and custom scoring callbacks are not accepted by this interface.
wf_plan_cells( design, target, dims, min_cell = 5, max_weight_ratio = 4, boundary = target$by, ladder = NULL )wf_plan_cells( design, target, dims, min_cell = 5, max_weight_ratio = 4, boundary = target$by, ladder = NULL )
design |
A |
target |
A non-demo |
dims |
A |
min_cell |
Minimum observed count in every retained joint design cell. |
max_weight_ratio |
Maximum conservative marginal target-to-design ratio. |
boundary |
Optional grouping column; defaults to the target grouping. |
ladder |
Optional explicit |
A reviewable wf_cell_merge_plan. No weights are computed.
Resolves each population joint cell to the finest supported collapse-ladder
level without computing weights. Review this plan before running
wf_poststrat().
wf_plan_poststrat( sample, target, min_cell, ladder, granularity = c("adaptive", "province"), empty_cell = c("redistribute", "flag", "error"), id = NULL )wf_plan_poststrat( sample, target, min_cell, ladder, granularity = c("adaptive", "province"), empty_cell = c("redistribute", "flag", "error"), id = NULL )
sample |
Sample data frame. |
target |
A |
min_cell |
Minimum sample count per resolved cell. |
ladder |
A |
granularity |
Resolution strategy, either |
empty_cell |
Empty-cell policy, one of |
id |
Reserved for future plan-level row diagnostics. |
A wf_poststrat_plan object.
Performs structural checks and records approved-capable settings without calling a calibration engine or computing any weights.
wf_plan_weights( design, target, dims, method = c("raking", "logit", "poststrat"), bounds = c(0.3, 3), min_cell = 5, cell_plan = NULL )wf_plan_weights( design, target, dims, method = c("raking", "logit", "poststrat"), bounds = c(0.3, 3), min_cell = 5, cell_plan = NULL )
design |
A |
target |
A non-demo |
dims |
A |
method |
Planned method: |
bounds |
Planned multiplicative lower and upper bounds, satisfying
|
min_cell |
Minimum support recorded in the plan. |
cell_plan |
Optional reviewed |
A wf_weight_plan. The weights field is always NULL.
Enforces the WFC 2.0 verified-input boundary before cell-level post-stratification.
wf_poststrat(design, target, min_cell, ladder, ...)wf_poststrat(design, target, min_cell, ladder, ...)
design |
An unchanged |
target |
An unchanged, non-demo |
min_cell |
Minimum sample count per resolved cell. |
ladder |
A |
... |
Post-stratification settings other than ID and base-weight roles,
which are owned by |
A wf_weights object with cell_report and collapse_map.
Runs structural feasibility checks before weighting.
wf_precheck( sample, target, id = NULL, na = c("fractional", "drop", "error"), max_na_dims = 2, thin_min = 5, risk_ratio = 10 )wf_precheck( sample, target, id = NULL, na = c("fractional", "drop", "error"), max_na_dims = 2, thin_min = 5, risk_ratio = 10 )
sample |
Sample data frame. |
target |
A |
id |
Optional unique unit identifier column. |
na |
Missing calibration data policy. |
max_na_dims |
Maximum allowed missing calibration dimensions per row. |
thin_min |
Minimum unweighted support before warning. |
risk_ratio |
Target/sample share ratio warning threshold. |
A wf_precheck object.
dims <- wf_dims(gender = c("female", "male")) pop <- data.frame(gender = c("female", "male"), count = c(55, 45)) target <- wf_target_population(pop, c(gender = "gender"), "count", dims) sample <- data.frame(id = 1:4, gender = c("female", "male", "female", "male")) wf_precheck(sample, target, id = "id")dims <- wf_dims(gender = c("female", "male")) pop <- data.frame(gender = c("female", "male"), count = c(55, 45)) target <- wf_target_population(pop, c(gender = "gender"), "count", dims) sample <- data.frame(id = 1:4, gender = c("female", "male", "female", "male")) wf_precheck(sample, target, id = "id")
Creates a strict design object containing only identifiers, calibration variables, and declared sampling-design fields. Any undeclared column blocks construction so study outcomes cannot silently enter weight planning.
wf_prepare_design( data, id, calibration, base_weight = NULL, strata = NULL, clusters = NULL, fpc = NULL )wf_prepare_design( data, id, calibration, base_weight = NULL, strata = NULL, clusters = NULL, fpc = NULL )
data |
A data frame containing design variables only. |
id |
Name of the unique, non-missing record identifier column. |
calibration |
Names of columns permitted for calibration. |
base_weight |
Optional name of a positive base-weight column. |
strata |
Optional names of stratification columns. |
clusters |
Optional names of cluster columns. |
fpc |
Optional names of finite-population-correction columns. |
A wf_design_data object.
design_frame <- data.frame( id = sprintf("r%02d", 1:8), sex = rep(c("F", "M"), 4), age = rep(c("18-34", "35+"), each = 4), base_weight = 1, stringsAsFactors = FALSE ) design <- wf_prepare_design( design_frame, id = "id", calibration = c("sex", "age"), base_weight = "base_weight" ) design # An outcome column has no declared design role, so it blocks construction # instead of silently entering weight planning. with_outcome <- cbind( design_frame, satisfaction = seq(40, 70, length.out = 8) ) try(wf_prepare_design( with_outcome, id = "id", calibration = c("sex", "age"), base_weight = "base_weight" ))design_frame <- data.frame( id = sprintf("r%02d", 1:8), sex = rep(c("F", "M"), 4), age = rep(c("18-34", "35+"), each = 4), base_weight = 1, stringsAsFactors = FALSE ) design <- wf_prepare_design( design_frame, id = "id", calibration = c("sex", "age"), base_weight = "base_weight" ) design # An outcome column has no declared design role, so it blocks construction # instead of silently entering weight planning. with_outcome <- cbind( design_frame, satisfaction = seq(40, 70, length.out = 8) ) try(wf_prepare_design( with_outcome, id = "id", calibration = c("sex", "age"), base_weight = "base_weight" ))
Fits the membership model declared in a wf_target_propensity() object and
converts each online unit's fitted membership probability into a pseudo-design
weight. The result is a wf_weights object suitable as an init_weight for
wf_rake() / wf_poststrat() and as a stage in wf_compose().
wf_propensity( target, weight = c("ipw", "kernel", "matching"), stabilize = TRUE, trim = NULL )wf_propensity( target, weight = c("ipw", "kernel", "matching"), stabilize = TRUE, trim = NULL )
target |
A |
weight |
Pseudo-weight form. Only |
stabilize |
Use stabilized IPW ( |
trim |
Optional positive scalar: clamp weights above |
A wf_propensity_weights object inheriting from wf_weights, with
$overlap and $balance diagnostics.
Enforces the WFC 2.0 verified-input boundary before grouped raking.
wf_rake(design, target, ...)wf_rake(design, target, ...)
design |
An unchanged |
target |
An unchanged, non-demo |
... |
Raking settings other than ID and base-weight roles, which are
owned by |
A wf_weights object carrying verified input identities.
Perturbs base weights by bootstrap, jackknife, or BRR multipliers and
re-runs a calibration pipeline (refit) on each replicate, so the resulting
variance captures calibration uncertainty. Pair with wf_variance().
wf_replicates( data, refit, method = c("bootstrap", "jackknife", "brr"), R = 500, strata = NULL, clusters = NULL, id = NULL, base_weight = NULL, seed = NULL, rho = 0, parallel = FALSE, progress = FALSE )wf_replicates( data, refit, method = c("bootstrap", "jackknife", "brr"), R = 500, strata = NULL, clusters = NULL, id = NULL, base_weight = NULL, seed = NULL, rho = 0, parallel = FALSE, progress = FALSE )
data |
Input data frame (one row per unit). |
refit |
A closure |
method |
Replication method. |
R |
Number of bootstrap replicates (ignored for jackknife / BRR). |
strata |
Optional stratum column name (single stratum if |
clusters |
Optional PSU column name (each row is its own PSU if |
id |
Optional id column aligning replicate weights (row order if |
base_weight |
Optional starting base-weight column (all |
seed |
Optional integer seed for the bootstrap draws. |
rho |
Fay's BRR shrinkage parameter in |
parallel |
Whether to re-run replicate refits with forked parallelism where available, using at most two workers. Windows falls back to serial execution. |
progress |
Whether to show a |
A wf_replicate_weights object.
Creates one structured dossier with manager and analyst projections. It can report calibrated/composed weights or a blend result and render the same payload as Markdown or dependency-free HTML.
wf_report( w, target = NULL, audience = c("manager", "analyst", "decision", "statistician"), lang = NULL, output = c("object", "markdown", "html"), file = NULL )wf_report( w, target = NULL, audience = c("manager", "analyst", "decision", "statistician"), lang = NULL, output = c("object", "markdown", "html"), file = NULL )
w |
A |
target |
Optional |
audience |
Report projection: |
lang |
Output language. Resolution follows explicit argument,
|
output |
Return a structured object, Markdown, or standalone HTML. |
file |
Optional output path for Markdown or HTML. |
A wf_quality_report for output = "object"; otherwise a rendered
character string, or invisibly the structured report when file is used.
# Panel attrition weights are derived from the panel itself, so this # example runs end to end. Reporting calibrated weights follows the same # call; see vignette("safe-weighting-workflow") for that path, which # additionally requires a verified target and a recorded approval. panel <- data.frame( id = paste0("p", 1:24), region = rep(c("A", "B"), each = 12), retained = rep(c(TRUE, TRUE, TRUE, FALSE), times = 6), age = rep(c(25, 35, 45, 55, 65, 75), times = 4), sex = rep(c("female", "male"), times = 12), stringsAsFactors = FALSE ) weights <- wf_attrition( panel, retained = "retained", formula = ~ age + sex, id = "id", by = "region" ) wf_report(weights, audience = "decision") analyst <- wf_report(weights, audience = "statistician") names(analyst$sections)# Panel attrition weights are derived from the panel itself, so this # example runs end to end. Reporting calibrated weights follows the same # call; see vignette("safe-weighting-workflow") for that path, which # additionally requires a verified target and a recorded approval. panel <- data.frame( id = paste0("p", 1:24), region = rep(c("A", "B"), each = 12), retained = rep(c(TRUE, TRUE, TRUE, FALSE), times = 6), age = rep(c(25, 35, 45, 55, 65, 75), times = 4), sex = rep(c("female", "male"), times = 12), stringsAsFactors = FALSE ) weights <- wf_attrition( panel, retained = "retained", formula = ~ age + sex, id = "id", by = "region" ) wf_report(weights, audience = "decision") analyst <- wf_report(weights, audience = "statistician") names(analyst$sections)
Executes a wf_pipeline() specification against verified design and target
objects, records provenance, and evaluates declared validation thresholds.
wf_run( spec, sample, dims = NULL, population = NULL, reference = NULL, base_weight = NULL )wf_run( spec, sample, dims = NULL, population = NULL, reference = NULL, base_weight = NULL )
spec |
A |
sample |
An unchanged |
dims |
Optional |
population |
A verified population target for population mode. |
reference |
A verified reference target for reference mode. |
base_weight |
Deprecated runtime base-weight input. WFC 2.0 requires
the base-weight role to be declared in |
A wf_weights object with pipeline provenance and optional
$pipeline_validation.
Converts selected precheck issues into a reviewable collapse plan using
collapse ladders declared in wf_dims().
wf_suggest_collapse( precheck, dims, checks = c("cat_infeasible", "support_thin", "risk_extreme_ratio"), max_steps = 1 )wf_suggest_collapse( precheck, dims, checks = c("cat_infeasible", "support_thin", "risk_extreme_ratio"), max_steps = 1 )
precheck |
A |
dims |
A |
checks |
Precheck identifiers eligible for collapse suggestions. |
max_steps |
Maximum number of ladder steps to inspect per dimension. |
A wf_collapse_plan object.
Examines worst-group category support and proposes adjacent category merges
in the explicit level order declared by wf_dims(). The result is a draft
for review; no input is modified and no merge is applied automatically.
wf_suggest_ladder(sample, target, dims, min_cell = 5)wf_suggest_ladder(sample, target, dims, min_cell = 5)
sample |
Sample data frame. |
target |
A |
dims |
A |
min_cell |
Minimum required unweighted sample support in every group. |
A wf_ladder_draft containing reviewable levels and a validated
wf_collapse_ladder in $ladder.
data(wfc_example) target <- wf_target_population( wfc_example$population, c(gender = "gender", age = "age"), "count", wfc_example$dims, by = "province" ) wf_suggest_ladder(wfc_example$sample, target, wfc_example$dims, min_cell = 25)data(wfc_example) target <- wf_target_population( wfc_example$population, c(gender = "gender", age = "age"), "count", wfc_example$dims, by = "province" ) wf_suggest_ladder(wfc_example$sample, target, wfc_example$dims, min_cell = 25)
Converts arbitrary population data to a canonical wf_target object.
wf_target_population( pop, key_map, count, dims, by = NULL, by_key = NULL, scale = c("population", "sample", "custom"), sample = NULL, totals = NULL, keep_joint = FALSE )wf_target_population( pop, key_map, count, dims, by = NULL, by_key = NULL, scale = c("population", "sample", "custom"), sample = NULL, totals = NULL, keep_joint = FALSE )
pop |
Population data frame. |
key_map |
Named character vector mapping |
count |
Population count column. |
dims |
A |
by |
Optional grouping variable. |
by_key |
Optional group key column name or function. |
scale |
Target scale, one of |
sample |
Required when |
totals |
Required when |
keep_joint |
Whether to retain per-group joint population cells. |
A wf_target object.
dims <- wf_dims(gender = c("female", "male")) pop <- data.frame(gender = c("female", "male"), count = c(55, 45)) wf_target_population(pop, c(gender = "gender"), "count", dims)dims <- wf_dims(gender = c("female", "male")) pop <- data.frame(gender = c("female", "male"), count = c(55, 45)) wf_target_population(pop, c(gender = "gender"), "count", dims)
Stacks a self-selected online sample and a probability reference sample
into one frame with a membership indicator, so the online sample's selection
propensity can be modelled. No model is fit here; execution happens in
wf_propensity().
wf_target_propensity( online, reference, formula, method = c("logit", "rf", "gbm"), by = NULL, id = NULL )wf_target_propensity( online, reference, formula, method = c("logit", "rf", "gbm"), by = NULL, id = NULL )
online |
Data frame: the self-selected (non-probability) sample. |
reference |
Data frame: the probability reference sample. |
formula |
Two-sided membership formula, e.g. |
method |
Fit backend. Only |
by |
Optional grouping column present in both frames; the propensity model is fit within each group. |
id |
Optional id column in |
A wf_target_propensity object.
Builds a canonical wf_target from a reference sample where feature is the
reciprocal of the design weight.
wf_target_reference( ref, feature, dims, by = NULL, feature_na = c("error", "drop"), feature_gt1 = c("warn", "allow") )wf_target_reference( ref, feature, dims, by = NULL, feature_na = c("error", "drop"), feature_gt1 = c("warn", "allow") )
ref |
Reference sample data frame. |
feature |
Feature value column equal to |
dims |
A |
by |
Optional grouping variable. |
feature_na |
Policy for missing feature values. |
feature_gt1 |
Policy for feature values greater than one. |
A wf_target object.
dims <- wf_dims(gender = c("female", "male")) ref <- data.frame(gender = c("female", "male"), feature = c(0.5, 0.25)) wf_target_reference(ref, "feature", dims)dims <- wf_dims(gender = c("female", "male")) ref <- data.frame(gender = c("female", "male"), feature = c(0.5, 0.25)) wf_target_reference(ref, "feature", dims)
Writes a CSV or Excel data template and a separate companion DCF source
record. The source filename appends .source.dcf to the complete data
filename so CSV and Excel files cannot accidentally share a checksum.
wf_target_template(file, dims, by = NULL, example = FALSE)wf_target_template(file, dims, by = NULL, example = FALSE)
file |
Output path ending in |
dims |
A |
by |
Optional grouping-column name. |
example |
Whether to write synthetic, demo-only rows instead of a blank template. |
Invisibly, a list with data_file and source_file paths.
Detects drift in recurring production weights by comparing group coverage, design effect, effective sample size, total weight, optional margin residuals, and per-unit weight ratios for matching IDs.
wf_validate( new, reference, target = NULL, max_deff_delta = 1, max_ess_loss = 0.2, max_total_shift = 0.05, max_margin_delta = 0.01, max_ratio_p99 = 2, on_issue = c("warn", "error", "none") )wf_validate( new, reference, target = NULL, max_deff_delta = 1, max_ess_loss = 0.2, max_total_shift = 0.05, max_margin_delta = 0.01, max_ratio_p99 = 2, on_issue = c("warn", "error", "none") )
new |
New |
reference |
Reference |
target |
Optional |
max_deff_delta |
Maximum allowed increase in design effect. |
max_ess_loss |
Maximum allowed fractional ESS loss. |
max_total_shift |
Maximum allowed fractional group-total shift. |
max_margin_delta |
Maximum allowed absolute margin-residual increase. |
max_ratio_p99 |
Maximum allowed normalized 99th percentile unit-weight ratio; the reciprocal threshold is applied to the 1st percentile. |
on_issue |
Reaction when drift is detected: |
A wf_validation object.
Applies the unified replication rule
Var = scale * sum_r rscales_r * (theta_r - theta)^2 to any estimator, using
the (scale, rscales) stored by wf_replicates().
wf_variance( replicates, estimator, data, level = 0.95, ci = c("normal", "percentile") )wf_variance( replicates, estimator, data, level = 0.95, ci = c("normal", "percentile") )
replicates |
A |
estimator |
A closure |
data |
The data frame the estimator reads. |
level |
Confidence level in |
ci |
Interval type: |
A wf_variance_result object.
A small, fully simulated dataset for examples and tests. It contains no private source records.
wfc_examplewfc_example
A list with three elements:
Simulated respondent-level sample data.
Simulated population cell counts.
A wf_dims object for gender and age.
Generated by data-raw/make-wfc-example.R.
These S3 methods return base data frames and are registered for the generic
names supplied by the suggested generics package. They do not require or
return tibbles, and all programmatic column names remain stable English keys.
## S3 method for class 'wf_weights' tidy(x, ...) ## S3 method for class 'wf_diagnostics' tidy(x, ...) ## S3 method for class 'wf_blend_result' tidy(x, ...) ## S3 method for class 'wf_variance_result' tidy(x, ...) ## S3 method for class 'wf_weights' glance(x, ...) ## S3 method for class 'wf_diagnostics' glance(x, ...) ## S3 method for class 'wf_blend_result' glance(x, ...) ## S3 method for class 'wf_variance_result' glance(x, ...) ## S3 method for class 'wf_weights' augment(x, data, id = "id", ...)## S3 method for class 'wf_weights' tidy(x, ...) ## S3 method for class 'wf_diagnostics' tidy(x, ...) ## S3 method for class 'wf_blend_result' tidy(x, ...) ## S3 method for class 'wf_variance_result' tidy(x, ...) ## S3 method for class 'wf_weights' glance(x, ...) ## S3 method for class 'wf_diagnostics' glance(x, ...) ## S3 method for class 'wf_blend_result' glance(x, ...) ## S3 method for class 'wf_variance_result' glance(x, ...) ## S3 method for class 'wf_weights' augment(x, data, id = "id", ...)
x |
A supported WFC result object. |
... |
Additional arguments. |
data |
Analysis data to augment with unit weights. |
id |
Unit-ID column in |
tidy() returns an object's primary detail table. glance() returns
a one-row summary. augment() returns data with .weight and .feature
appended in data-row order.