Restores the tbl_sample class on a data frame that carries sampling
attributes (design, stages_executed) but has lost its class, for
example after a tidyr operation such as tidyr::uncount().
Usage
as_tbl_sample(x, ...)
# S3 method for class 'tbl_sample'
as_tbl_sample(x, ...)
# S3 method for class 'data.frame'
as_tbl_sample(x, ...)Class preservation
All dplyr verbs (mutate, filter, select, *_join, etc.)
preserve the tbl_sample class automatically.
Preserving the class does not mean the sample remains analyzable:
operations that remove, add, or duplicate rows, or overwrite
internal design columns (.weight, .fpc_k, ...), mark the sample
as modified. Design-based computations (as_svydesign(),
joint_expectation(), design_effect()) reject modified samples.
as_svydesign() documents what the check covers, and why dropping
out-of-domain rows before conversion is not domain estimation.
Restoring the
class with as_tbl_sample() does not clear the mark: the data is
re-verified against the integrity record stored at execution, so a
stripped, altered, and restored object is detected.
Some operations strip the class but keep the sampling attributes.
Use as_tbl_sample() to restore it:
For an operational multi-stage listing, keep the unmodified partial sample
as the first argument to execute() and pass the expanded plain object only
as its frame. Restoring the listing itself is not required. A plain object
that still carries sample provenance is rejected as the frame of a fresh
design execution, because that would rerun stage 1.
Other operations strip both class and attributes and are not recoverable. Use dplyr alternatives instead:
See also
Other helpers:
bound(),
get_design(),
get_stages_executed(),
is_sampling_design(),
is_tbl_sample(),
print.samplyr,
serp()
Examples
design <- sampling_design() |>
stratify_by(region) |>
draw(n = 20)
sample <- execute(design, bfa_eas, seed = 42)
# as_tibble() strips the class but keeps attributes
plain <- tibble::as_tibble(sample)
is_tbl_sample(plain)
#> [1] FALSE
# as_tbl_sample() restores it
restored <- as_tbl_sample(plain)
is_tbl_sample(restored)
#> [1] TRUE