Creates a survey::svydesign() object from a tbl_sample, using
the sampling design metadata (strata, clusters, weights, and
finite population corrections) captured during execute().
Usage
as_svydesign(x, ...)
# S3 method for class 'tbl_sample'
as_svydesign(
x,
...,
nest = TRUE,
method = NULL,
systematic_variance = c("warn", "approximate", "error"),
stages = NULL
)Arguments
- x
A
tbl_sampleobject produced byexecute().- ...
Additional arguments passed to
survey::svydesign(), or tosurvey::twophase()for a sample exported as two phases. In particular, you can passpps = survey::ppsmat(joint_matrix)to supply exact joint inclusion probabilities instead of the default Brewer approximation (see Details). Every argument must be named, and its name must be one the receiving function accepts:nestandmethodfollow the...and so are matched exactly, and a near miss such asnesis reported rather than forwarded. The design arguments themselves (ids,strata,weights,probs,fpc,data, andsubsetfor a two-phase sample) are derived from the sample and cannot be given here.- nest
If
TRUE(the default), relabel cluster ids to enforce nesting within strata, which suits most complex survey designs. Passed tosurvey::svydesign(). It has no effect on a sample exported withsurvey::twophase(), and giving it there raises a warning.- method
For two-phase samples, the variance method passed to
survey::twophase(). One of"full","approx", or"simple". This argument is only accepted for two-phase samples. A materialized occasion is exported by ultimate clusters unlessmethodis given, which asks for its two-phase export instead.- systematic_variance
What to do about the variance approximation used for systematic stages: simple random sampling for
systematic, Brewer's forpps_systematic, and with replacement forpps_systematic_mr."warn"(default) applies it and warns once per call, naming every affected stage and its approximation."approximate"applies it silently, for a caller who has acknowledged it, and"error"refuses. Census stages are exempt, since a stage that took everything within reach contributes no variance, and so is apps_systematicfirst stage exported with a caller-suppliedppsobject. A stage that drew one unit in each pool is exempt too, since a single random start takes each unit with its chance whatever the frame order. Apps_systematic_mrstage is never exempt as a census, since a take of \(N\) or more counts draws, and the with-replacement export gives it a variance even when every unit's hits are fixed. The choice, the affected stages and each stage's approximation are recorded in the"samplyr_systematic_variance"attribute of the result.as_svrepdesign()takes the same argument for its own approximation of these stages.- stages
NULL, the default, exports every executed stage. A prefix of the executed stages, such as1or1:2, keeps those stages and reads the last as drawn with replacement within its parents, without a finite population correction, so it carries the variance of every stage below.stages = 1is the ultimate-cluster variance. A kept stage of random size (bernoulli,pps_poisson), or one below a certainty unit, is refused, because this reading drops the variance of its sample size.as_svrepdesign(x, type = "rwyb")estimates it. A materialized occasion and a settled reserve takestages = 1only, which is how they are exported anyway, and a two-phase sample or one with shared weights takes none (samplyr_error_survey_argument).
Value
A survey.design2 object for single-phase and multi-stage samples
and for materialized occasions, or a twophase/twophase2 object for
two-phase samples and for occasions exported with method. The survey
package is required but not imported, so it must be installed.
Details
Every executed stage contributes one ids term, one fpc term and, when
stratified, one strata term, so survey::svydesign() represents the
multi-stage structure in its linearization (Sarndal et al. 1992, ch.
4.3):
Cluster ids (
ids): thecluster_by()variable of a clustered stage. A stage clustered by several variables, which execution treats as one cluster id, gets one synthesized interaction column. A final unclustered stage gets a synthesized row-identity column so that its sampling variance is represented. A WR or PMR stage uses its.draw_kcolumn, so each draw is an independent unit of the Hansen-Hurwitz variance. This is exact for WR and an approximation for PMR, whose draws are dependent.Strata (
strata): aligned withids. A stage stratified by several variables exports their cross-classification as one synthesized column. Trailing unstratified stages are omitted, and unstratified stages before a stratified stage get a constant placeholder column.Weights (
weights): the.weightcolumn, the product of the per-stage weights described in sample_columns. They are design weights. A sample whose.weightwas edited is refused, and weights adjusted for nonresponse or calibrated are computed on the exported design, withsurvey::calibrate()orsurvey::postStratify().FPC (
fpc): aligned withids, on one scale for every stage. Without an unequal-probability stage drawn without replacement, an equal-probability WOR stage passes its stratum population count \(N_h\), and a WR or PMR stage passes no correction. With one, every WOR stage passes its stage inclusion probability \(1 / w_k = \pi_k\), and WR and PMR stages pass 0. A multi-stage design with a random-size Poisson stage is refused.
For a two-stage stratified-cluster design with a final element stage, the exported call is equivalent to:
survey::svydesign(
ids = ~ ea_id + .id_2, # stage-1 clusters, stage-2 elements
strata = ~ region, # stage-1 strata
weights = ~ .weight, # product of per-stage weights
fpc = ~ .fpc_pi_1 + .fpc_f_2, # per-stage sampling fractions
data = sample,
nest = TRUE
)Multi-stage designs
Exactness depends on the variance treatment available for each method
(variance_estimation). A design whose first stage is a census of PSUs
attributes all variance to the later stages. Executing stages
separately, as stage1 <- execute(design, psu_frame, stages = 1) then
sample <- execute(stage1, listing_frame), still gives one multi-stage
design.
An unclustered element-sampling stage followed by further stages is
not nested cluster sampling, because the later selections are
conditional on the realized element sample, which is phase sampling.
execute() refuses it (samplyr_error_stage_parent_id). Express it as a
two-phase sample instead: execute the element stage under its first-phase
design, then a new second-phase design with that sample as its frame.
A variance compares primary units, so a design whose first stage holds a
single unit not taken with certainty, outside any stratum, has no
variance estimate and is refused (samplyr_error_export_one_unit). That
covers one unit drawn from several and a single draw with replacement,
whose weight of one is an expected hit rather than a certainty. A census
of that unit, or a recorded certainty, is exported, with no first-stage
variance.
Two-phase samples
A new phase-2 sampling_design executed with the phase-1 tbl_sample
as its frame, as in phase2 <- execute(design2, phase1), records a
previous-phase link, and as_svydesign() calls survey::twophase().
Each phase-2 row carries .phase1_row, the position of the phase-1 row it
was drawn from, and the export joins the phases on it. Neither phase needs
to declare an identifier, and a unit phase 1 drew more than once, such as
a PSU hit twice by pps_multinomial, links to the hit phase 2 reached.
Rows that a later phase-2 stage drew from a register of its own carry no
position, so the phases are then joined on the identifiers either phase
declares with cluster_by(), which must identify the phase-1 rows phase 2
reaches (samplyr_error_twophase_bridge) and be constant within each
phase-2 unit (samplyr_error_phase_key_ambiguous).
Phase 2 may take whole phase-1 EAs, or EAs and then some of their
households. Each phase-2 unit must lie within one phase-1 primary unit,
each hit counting as one (samplyr_error_phase_cluster_spans_psu). For
method = "full", declare the households phase 2 draws, as in
cluster_by(hh_id). survey::twophase() reads phase 2 as a subset of
the phase-1 rows, which cannot hold a unit drawn twice, so a phase 2 drawn
with replacement is refused (samplyr_error_twophase_phase2_wr). So is a
phase 1, or a phase 2, whose rows hold a single primary unit outside a
stratum (samplyr_error_export_one_unit).
A phase-1 stratum holding a single unit not taken with certainty has no
variance estimate. The default "full" method would read the unit's
squared total as one and does not follow survey.lonely.psu, so it is
refused (samplyr_error_lonely_psu). "approx" and "simple" estimate
phase 1's part with survey's one-phase code, which follows that option,
and warn under its default "fail" (samplyr_warning_lonely_psu).
The three values of method read the phase-1 part of the variance
differently. "full" reads the probabilities stage by stage, from phase
1's finite population corrections. "approx" and "simple" estimate it
from the phase-2 rows, weighting each phase-1 primary unit by its chance
of entering phase 2. That is exact when phase 2 takes whole phase-1
units or phase 1 selects elements. When phase 2 subsamples inside the
units phase 1 selected, the row's chance stands in for the unit's, which
is one, and the phase-1 part is overstated
(samplyr_warning_twophase_approx). "full" cannot state the
probabilities of a phase 1 drawn with replacement above a later stage,
unless that stage took only certainty units, and is refused there
(samplyr_error_twophase_stage_probs). It is refused as well when phase
2 subsamples inside clusters that phase 1's last stage drew with
replacement, where it understates the variance
(samplyr_error_twophase_wr_subsample). A phase 2 drawn within each hit
is exported as one phase instead (see below). In the second case, draw
the units inside those clusters as a stage of phase 1 first, with
add_stage() |> draw(frac = 1).
The export computes the phase-1 part of the variance with each phase-1
stratum's own sample size, also when phase 2 keeps unequal shares of the
phase-1 strata. A phase 2 stratified across the phase-1 strata can give a
negative variance in some samples, since the Horvitz-Thompson form is not
guaranteed positive, and method = "approx" gives a finite standard
error there.
A clustered first phase needs its second phase drawn inside each of its
units, with stratify_by(<unit>), or by taking whole phase-1 units
before sampling inside them. When phase 2 draws smaller units across the
phase-1 clusters, the estimator is unbiased over repeated samples but
unstable in one, and can be negative
(samplyr_warning_twophase_across_units). The weights are exact either
way.
A subsample within pools is one phase
One shape is not exported as two phases. Phase 1's final stage draws
elements by srswor or systematic, and phase 2 draws the same way,
without clusters, with one stratum per final-stage pool of phase 1, as in
stratify_by(ea_id) when the final stage draws households within EAs. A
simple random subsample of a simple random sample is a simple random
sample, so the two phases are phase 1's multi-stage design with a smaller
final take. as_svydesign() and as_svrepdesign() export it that way,
with phase 1's strata, clusters and finite population corrections and
phase 2's weights, whatever phase 1's earlier stages drew. Half of each
EA's households kept for a second questionnaire is this shape. method
does not apply to it, and no row identifier is needed to link the
phases. Below a stage that can take a unit more than once, each hit is a
pool of its own. Phase 2 names it by the hit number it carries, as in
stratify_by(ea_id, .phase1_draw_1), and is then exported this way.
stratify_by(ea_id) alone pools the hits of an EA drawn twice, and keeps
the two-phase route. When phase 2 is systematic, the final take is a
systematic one, and systematic_variance applies to it, unless phase 2
took every unit of every pool or one unit of each. A phase 2 stratified
more coarsely or more finely than the pools, clustered, or drawn with
unequal probabilities keeps the two-phase route.
Two-phase samples that are refused
survey::twophase() takes no pps for the first phase, so any other
two-phase sample, or occasion exported with method, whose phase 1 was
drawn with unequal probabilities without replacement is refused
(samplyr_error_twophase_phase1_pps, samplyr_error_occasion_phase1_pps).
So are cube, first-stage pps_poisson and the spatial methods, which
are unsupported at either phase. Equal-probability first phases export,
stratified, clustered, multi-stage and with-replacement alike. A
two-phase sample has a replicate export in three shapes, the subsample
within pools above, a second phase of a phase 1 fixed in one primary unit
(every stage taken for sure, which can be a census of its elements), and
random groups of a design executed whole with reps, a refused one
included (see as_svrepdesign()). The weights of a refused sample are
exact, so totals and means are right. For a variance, the ultimate-cluster approximation
treats phase 1's units as drawn with replacement and carries everything
below in them. It leaves out phase 1's correction and overstates the
variance, and more so when phase 2 was drawn across the phase-1 units:
survey::svydesign(ids = ~ea_id, strata = ~region, weights = ~.weight,
data = as.data.frame(phase2))Occasions
A materialized occasion, execute(master, period = p), is exported as one
phase by ultimate clusters. The master's stage-1 units are the clusters,
its stage-1 stratification variables the strata, and the occasion's weights
the weights, with no finite population correction. Every later stage and
the activation are carried in the unit totals, so the master may have
been drawn by any method, with probabilities proportional to size
included. It is the variance rotating household surveys publish for each
quarter or month. Zones and variance pairs are not used, since activation
leaves most zones with one unit or none.
A stage-1 unit taken with certainty, with a later stage drawn inside it, represents itself. It is a stratum of its own, whose clusters are its units of the next stage, since only they vary between samples. A unit of a stratum taken as a census counts as taken with certainty, unless the panels are assigned at stage 1, so that each occasion holds only some of its units. A unit taken with certainty and nothing drawn inside it, a stage-1 cluster with no later stage or an element, is the same in every sample. It is a stratum of its own taken as a census, the one stratum with a finite population correction, so it adds no variance. Leaving out the correction elsewhere overstates the variance where a stratum's sampling fraction is large.
A one-stage master that took every unit, rotated by its panels, varies only by which units an occasion holds. Within each quota block the occasion draws its units without replacement, so the blocks are the strata and the block sizes the correction, which gives the occasion's variance exactly.
A window of several occasions, execute(master, period = 1:3), is exported
the same way. A unit's rows over the window are one cluster, and the
strata are crossed with the quota block and the occasions of the window
a unit is active at, which its panel fixes. The design is calibrated on
each stratum's total of the units' activation multipliers, which leaves
the weights unchanged and gives merged strata ratio residuals.
panel_assignment gives the rule and the smaller strata. method is
refused for a window.
An occasion of a master whose later stages are still drawn one period or
cohort at a time is exported the same way, from its own rows. The
two-phase export reads the whole master and refuses it
(samplyr_error_occasion_provisional).
as_svrepdesign() replicates the same design, and as_survey_design()
follows as_svydesign(). pps is refused (samplyr_error_survey_argument),
and so is an occasion holding a single primary unit
(samplyr_error_occasion_one_unit). An occasion that activates every unit
is the master's own design and is exported as such.
Modified samples and domain analysis
as_svydesign() raises an error on a tbl_sample whose row set changed
after execute() (rows removed by dplyr::filter() or [, added, or
duplicated by a join) or whose internal design columns (.weight,
.weight_k, .fpc_k, ...) were overwritten, dropped, or renamed. The
sample is verified against an integrity record stored at execution (row
count and a hash of the weights, design metadata, and strata and cluster
columns), so changes the dplyr hooks cannot see (base assignment,
rbind(), vctrs operations, third-party verbs) are also caught, and an
overwrite that left every value identical passes. Row reordering,
one-to-one joins, and adding ordinary data columns do not mark the
sample. One complete replicate extracted from a replicated execution
(filter(.replicate == r)) is verified against the execution metadata
and remains supported. A later stage drawn from a modified sample is
refused too, since its weights carry the change, and so is every stage
drawn after it.
A second phase drawn from a modified sample is refused by both exports
as well (samplyr_error_modified_sample). They read the phase-1 rows as
the whole first phase, and removed rows would give it other
probabilities and another variance. Random groups of replicates read
only the replicate totals and remain. To subsample the eligible units of
phase 1, draw phase 2 from phase 1 as executed with the eligibility
column as a phase-2 stratum, then subset the exported design.
Dropping out-of-domain rows before conversion is not domain estimation. The point estimate can agree, but its variance estimate is generally wrong, often too small, because the domain sample size is random under the design. Convert the full sample first and then subset the design:
svy <- as_svydesign(sample)
survey::svymean(~y, subset(svy, domain))
# or with srvyr:
as_survey_design(sample) |> filter(domain) |> summarise(...)Variance by selection method
Which estimator each selection method reaches, how exact it is, and which designs are refused are in variance_estimation.
pps is read as follows. "brewer" is the default treatment and keeps
every stage. FALSE states that no stage is PPS, so it is refused on a
design with one. "overton", survey::HR() and the matrix objects
(survey::ppsmat(), survey::poisson_sampling()) are single-stage in
survey, so a multi-stage sample is exported at stage 1 with a warning.
They need stage 1 drawn with unequal probabilities without replacement,
or by Poisson sampling with a size measure. "overton" and
survey::HR() assume a fixed sample size, so they are refused on a
Poisson stage 1, whose exact variance is the default export.
survey::poisson_sampling() assumes independent selections, so it is
refused on a fixed-size stage 1. A matrix object is indexed by row, so it
also needs one row per stage-1 unit, and a sample with several is refused
(samplyr_error_pps_rows_per_psu). On a fixed-size stage drawn with
unequal probabilities without replacement, a survey::ppsmat() export
defaults to variance = "YG" unless variance is supplied in ...,
because the Horvitz-Thompson quadratic form can be negative even with an
exact joint matrix. Any other pps value is refused
(samplyr_error_pps_argument). A two-phase export takes no pps,
because survey::twophase() does not apply it to the phase-2 variance
(samplyr_error_twophase_phase2_pps). A phase 2 of one stage drawn with
pps_sampford, pps_cps, pps_brewer, pps_sps or pps_pareto is
exported with its joint inclusion probabilities, computed on the phase-1
sample, and needs method = "full". Any other unequal-probability,
balanced or spatial phase 2 is refused with the same class.
Ultimate-cluster variance
Many survey programs publish sampling errors computed as if the primary
units were drawn with replacement within their strata, without a finite
population correction. The variance of every later stage is then carried
by the primary-unit totals, which is why it is called the ultimate-cluster
variance (Hansen, Hurwitz and Madow 1953; Wolter 2007, sec. 2.4). It is
the variance to reproduce when a new design is compared with what an
earlier round published, and as_svydesign(sample, stages = 1) builds
it. A materialized occasion and a settled reserve are always exported
this way.
The export keeps the first stage's strata and units, the zero rows of
empty primary units included. A primary unit taken with probability 1, by
a certainty rule or because its stratum was taken whole, is no draw. When
the next stage drew two units or more inside it, it is a stratum of its
own whose next-stage units are the clusters. When nothing below it is
random, with no stage below or every unit below taken, it is a census
stratum of its own and adds no variance. When the next stage drew a single
unit inside it, as one household in a certainty EA, a stratum of its own
could not estimate the variance below. It then stays a draw of its
stratum, and the spread between that stratum's units stands in for the
variance below it (samplyr_message_stage_certainty_drawn). A stage drawn
with replacement has no such units, even where a unit expects one hit or
more. A design built by hand from as.data.frame(sample) loses the empty
units and reads certainty units as drawn.
stages = 1:k keeps stages 1 to k - 1 with their corrections and reads
stage k the same way. It suits a stage whose variance cannot be
estimated, such as one respondent per household: stages = 1:2 on a
design of EAs, households and one person carries the person stage in the
household totals, and keeps the first stage's correction, which matters
where that stage takes a large share. Exported in full, such a stage
leaves each household a stratum of one unit, which the export names
(samplyr_warning_lonely_psu). The reading leaves out the correction at
stage k, so it overstates the variance most where stage k takes a large
share of its units. A stratum with a single unit stops survey, as for the
full export, unless options(survey.lonely.psu = ) says how to treat it.
So does one below a unit drawn with replacement when survey computes the
later stages, under options(survey.use_rcpp = FALSE) or a calibration by
stage.
A settled reserve
A sample whose reserve is not settled is refused
(samplyr_error_reserve_unsettled), since its weights describe the whole
list. A settled sample is exported by ultimate clusters, with rows added
for the units found ineligible and for the eligible nonrespondents of a
pool with no respondent. reserve_lists gives those rows, the estimates
and calibrations they need, and the exports that refuse a settled
reserve.
A shared estimation weight
A sample from share_weights() carries weights for a population other
than the one that was selected, so it is exported as its source-target
contributions: one row per link, weighted by the recorded coefficient
times the source unit's design weight. This gives the generalized weight
share total exactly for any link structure (Lavallee 2007). The result has
more rows than the transformation returned, but no estimate changes: a
total sums the same terms, and a mean's denominator is the estimated
target population size either way.
A selected source unit linked to no target, such as a dwelling with
nobody in the target population, has no contribution. The export keeps
it as a zero row, just as it keeps a unit found empty, with weight 0,
its source values, and NA in the target variables. That keeps every
sampled unit in the between-unit and within-unit variance as a zero
total. Estimates need na.rm = TRUE, and the export warns
(samplyr_warning_export_empty_parent) when zero rows are added.
An unequal-probability or random-size source design is refused here,
because its variance comes from a structure indexed by the source
sample's rows, which the contribution rows no longer are. Use
as_svrepdesign(), which replicates the source design and applies the
sharing inside every replicate.
References
Hansen, M. H., Hurwitz, W. N. and Madow, W. G. (1953). Sample Survey Methods and Theory. Wiley.
Lavallée, P. (2007). Indirect Sampling. Springer.
Särndal, C.-E., Swensson, B. and Wretman, J. (1992). Model Assisted Survey Sampling. Springer.
Wolter, K. M. (2007). Introduction to Variance Estimation, 2nd ed. Springer.
See also
execute() for producing tbl_sample objects,
survey::svydesign() for the underlying function,
as_survey_design.tbl_sample for converting directly to a srvyr tbl_svy,
as_svrepdesign() for replicate-weight export,
as_svydesign.frame_stack() for overlapping frames
Other survey export:
as_survey_design.tbl_sample(),
as_survey_rep.tbl_sample(),
as_svrepdesign(),
variance_estimators()
Examples
# Stratified sample -> survey design
sample <- sampling_design() |>
stratify_by(region, alloc = "proportional") |>
draw(n = 300) |>
execute(bfa_eas, seed = 42)
svy <- as_svydesign(sample)
survey::svymean(~households, svy)
#> mean SE
#> households 71.668 3.6922
# Two-stage sample: PPS selection of EAs, then households from a listing
selected <- sampling_design() |>
add_stage() |>
stratify_by(region) |>
cluster_by(ea_id) |>
draw(n = 5, method = "pps_brewer", mos = households) |>
add_stage() |>
draw(n = 8) |>
execute(bfa_eas, stages = 1, seed = 2025)
listing <- selected |>
as.data.frame() |>
dplyr::reframe(hh_id = seq_len(households), .by = ea_id)
sample <- execute(selected, listing, seed = 2026)
# Brewer's variance approximation at the PPS stage
svy <- as_svydesign(sample)
# Half of each EA's households, kept as a second phase. It is exported as
# the two-stage design with a take of 4.
half <- sampling_design() |>
stratify_by(ea_id) |>
draw(n = 4) |>
execute(sample, seed = 2027)
svy_half <- as_svydesign(half)
# A joint-probability matrix instead, for a single-stage Sampford sample,
# whose matrix is exact. A matrix needs one row per stage-1 unit, and YG is
# the Sen-Yates-Grundy form for fixed-size sampling without replacement.
sampford <- sampling_design() |>
stratify_by(region) |>
draw(n = 5, method = "pps_sampford", mos = households) |>
execute(bfa_eas, seed = 2025)
jip <- joint_expectation(sampford, bfa_eas)
svy_joint <- as_svydesign(sampford, pps = survey::ppsmat(jip[[1]]), variance = "YG")
survey::svytotal(~population, svy_joint)
#> total SE
#> population 20854071 297150
