Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@
^pkgdown$
^tools$
^Rplots\.pdf$
^README\.Rmd$
^vignettes/articles$
39 changes: 25 additions & 14 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,30 +1,41 @@
Package: drawn
Title: Design-Based Sampling with Known Inclusion Probabilities
Version: 0.1.0
Version: 0.2.0
Authors@R:
person("Justin", "Chase", email = "jchase.msu@gmail.com",
role = c("aut", "cre"))
Description: Draws probability samples from data frames under an explicit,
reusable sampling design: simple random, stratified, systematic, cluster,
multi-stage, weighted (including probability-proportional-to-size),
certainty-plus-sample, reservoir, bootstrap, temporal and spatial. A design
is a value that can be stored, printed and reused, and that knows its own
first- and second-order inclusion probabilities, so a drawn sample carries
the weights needed for Horvitz-Thompson estimation: 'ht_total()' and
'ht_mean()' return a population total or mean with a standard error,
confidence interval and design effect. 'plan_size()' solves for the sample
size a target margin of error requires, and 'as_svydesign()' hands a sample
to the 'survey' package for analysis. Designs whose inclusion probabilities
have no closed form report that rather than supplying an approximation, and
can be estimated by simulation instead.
reusable sampling design: simple random, stratified (proportional, equal
or Neyman), systematic, cluster, multi-stage, probability-proportional-to-
size, certainty-plus-sample, spatially balanced (the local pivotal method
of Grafstrom, Lundstrom and Schelin, 2012), reservoir, bootstrap,
temporal and region-restricted. A design is a value that can be stored,
printed and reused, and that knows its own first- and second-order
inclusion probabilities, so a drawn sample carries the weights needed for
Horvitz-Thompson estimation: 'ht_total()' and 'ht_mean()' return a
population total, mean or proportion, overall or by domain, with a
standard error, a confidence interval on the design's degrees of freedom
and a design effect. Each design gets the variance estimator the
literature recommends for it, and says which: Sen-Yates-Grundy where joint
probabilities are known, Deville's approximation for
probability-proportional-to-size, successive differences for systematic
samples, local means for spatially balanced ones, and a stratified
jackknife otherwise. 'plan_size()' solves for the sample size a target
margin of error requires, and 'as_svydesign()' hands a sample to the
'survey' package for further analysis. Designs whose inclusion
probabilities have no closed form report that rather than supplying an
approximation, and can be estimated by simulation instead.
License: GPL-3
Encoding: UTF-8
Depends:
R (>= 4.1)
Imports:
graphics,
lubridate,
stats
stats,
utils
Suggests:
sampling,
sf (>= 1.0.0),
survey,
testthat (>= 3.0.0),
Expand Down
5 changes: 5 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@ S3method(draw_design,drawn_design_multistage)
S3method(draw_design,drawn_design_reservoir)
S3method(draw_design,drawn_design_simple)
S3method(draw_design,drawn_design_spatial)
S3method(draw_design,drawn_design_spread)
S3method(draw_design,drawn_design_stratified)
S3method(draw_design,drawn_design_systematic)
S3method(draw_design,drawn_design_temporal)
S3method(draw_design,drawn_design_weighted)
S3method(plot,drawn_design)
S3method(print,drawn_by)
S3method(print,drawn_design)
S3method(print,drawn_ht)
S3method(print,drawn_mean)
S3method(print,drawn_plan)
S3method(print,drawn_summary)
S3method(survey::deff,drawn_ht)
S3method(survey::deff,drawn_mean)
export(as_svydesign)
export(deff)
export(design_bootstrap)
Expand All @@ -27,6 +31,7 @@ export(design_multistage)
export(design_reservoir)
export(design_simple)
export(design_spatial)
export(design_spread)
export(design_stratified)
export(design_systematic)
export(design_temporal)
Expand Down
98 changes: 98 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,101 @@
# drawn 0.2.0

An adversarial review of 0.1.0 found estimates that were wrong without saying
so. Every fix below was reproduced by simulation first, and each now has a
test that fails on the old behaviour.

## Wrong answers, fixed

* **One sampled row per stratum reported a variance of 0.** Sen-Yates-Grundy
has no within-stratum pair to sum over, so a stratified sample with one row
in every stratum printed a standard error of exactly zero and a zero-width
interval. `ht_total()` and `ht_mean()` now decline with the reason, as
`survey` does by default, for strata and for `design_temporal()` intervals.
* **A stratum allocated no rows silently biased the total.** Proportional
allocation gives nothing to a stratum smaller than about `N / n`, and Neyman
allocation gives nothing to one whose auxiliary variable is constant. Its
rows then have probability 0 and drop out of every estimate; one example was
84% low. `draw()` now warns, naming the strata and the fix. The
documentation previously claimed `min_per_stratum = 0` "leaves allocation
unbiased" and that a floor biases a total; both were wrong, and are
corrected.
* **The jackknife ignored strata.** It deleted rows across the whole sample,
counting the differences *between* strata as sampling variance: sixty times
too large on a well-stratified frame. It is now the stratified (JKn)
jackknife, and equals the analytic figure exactly for `design_stratified()`
and `design_temporal()`.
* **One row per cluster understated a multistage variance by ~30%.** The
exact two-stage estimator cannot see within-cluster variation when only one
row is taken per cluster. It now declines, and `variance = "auto"` falls back
to the delete-a-cluster (ultimate-cluster) jackknife.
* **Neyman allocation abandoned its own rule when a stratum was capped.** The
surplus from a stratum too small for its share was dealt out round-robin;
it is now re-split in proportion to `size * sd`, as in Cochran (1977, 5.9).
* `ht_mean(estimator = "ht")` printed itself as a Hajek mean.
* `design_systematic(order_by = )` returned rows in sorted order, breaking the
documented promise that rows come back in frame order.
* The documentation for `design_weighted(method = "systematic")` said some
pairs of rows can never be drawn together and pointed to
`sampling::UPsystematicpi2()` for joint probabilities. The rows are shuffled
before the walk, so every pair can co-occur and that function answers a
different design.

## Variance estimators from the literature

Every estimate now reports which estimator produced its variance in `method`,
and names any approximation when it prints.

* **Confidence intervals use t on the design's degrees of freedom** — primary
sampling units minus strata (Korn and Graubard 1999), matching
`survey::degf()`. At four clusters the normal interval covered about 87%;
the t interval restores nominal coverage. `df = Inf` gives the normal
interval.
* **Systematic PPS uses Deville's (1999) approximation**, which needs only
first-order probabilities and scales each row by its own `1 - pi`. It
equals `sampling::varest()` exactly and tracks the empirical variance at
0.98, where the previous jackknife ran at 0.89.
* **Systematic samples get the successive-difference approximation** (Wolter
2007) rather than no variance at all. On a frame sorted by something related
to `y` it stays near the truth where the simple random formula overstates
two- to thirtyfold. Its limits — a cycle matching the interval, or a trend
so smooth the random start is the only variation — are documented.

## New

* `design_spread()` draws a spatially balanced sample by the local pivotal
method (Grafström, Lundström and Schelin 2012): exact first-order
inclusion probabilities, equal or proportional to `size`, with neighbours
competing so the sample covers the space evenly. On a smooth surface its
variance was 14–25% of a simple random sample's. It spreads across any
numeric columns, so it also balances a sample on covariates without
choosing strata. `ht_total()` uses the local mean variance estimator
(Stevens and Olsen 2003) for it.
* `ht_total()` and `ht_mean()` take `by =` for domain estimates computed from
the whole sample rather than a subset of it. Standard errors match
`survey::svyby()` exactly.
* `ht_mean()` accepts a logical `y`, so a proportion is one call.
* `plot(design, data, type = "map")` places every row by two columns and
fills in the selected ones — the view that shows whether a sample covers the
ground.
* Key functions carry `@references` to the methods they implement.

## Handing off to survey

* Multistage designs are expressed as two stages, so `survey`'s standard error
now matches `ht_total()` exactly; it previously differed by up to 5–10%.
* Systematic PPS, alone or as a certainty design's `rest`, maps to
`pps = "brewer"` and agrees with `ht_total()` within 0.2%.
* A reservoir capped by `max_items` uses the rows the stream reached as its
population, not the whole frame.

## Documentation and site

* The README is generated from `README.Rmd`, so every output shown is real.
* New articles: a getting-started walkthrough, how the estimates work (every
estimator, its reference and its simulation check), an audit-sampling
walkthrough, and a spatially balanced field survey.
* `graphics` and `utils` are declared in `Imports`.

# drawn 0.1.0

First release.
Expand Down
94 changes: 86 additions & 8 deletions R/allocation.R
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#'
#' @param n Total to allocate.
#' @param sizes Group sizes, named.
#' @param allocation `"proportional"` or `"equal"`.
#' @param allocation `"proportional"`, `"equal"` or `"neyman"`.
#' @param min_per_stratum Floor per group.
#' @param cap When `TRUE`, no group may be allocated more rows than it holds.
#' `FALSE` when sampling with replacement, where over-allocation is legal.
Expand All @@ -35,21 +35,21 @@ allocate <- function(n, sizes, allocation, min_per_stratum, cap = TRUE,
n <- as.numeric(n)
sizes <- stats::setNames(as.numeric(sizes), names(sizes))

raw <- switch(allocation,
equal = rep(n / k, k),
share <- switch(allocation,
equal = rep(1, k),
neyman = {
if (is.null(spread)) {
stop("Neyman allocation needs `allocation_by`.", call. = FALSE)
}
sp <- spread[names(sizes)]
sp[!is.finite(sp)] <- 0
w <- sizes * sp
# Every stratum with no spread still needs representation; fall back to
# proportional if the auxiliary variable is constant throughout.
if (sum(w) <= 0) n * sizes / sum(sizes) else n * w / sum(w)
# A constant auxiliary variable has no spread to allocate by; fall back
# to proportional rather than dividing by zero.
if (sum(sizes * sp) <= 0) sizes else sizes * sp
},
n * sizes / sum(sizes)
sizes
)
raw <- capped_shares(n, share, sizes, cap)

base <- pmax(min_per_stratum, floor(raw))
if (cap) base <- pmin(base, sizes)
Expand Down Expand Up @@ -94,3 +94,81 @@ allocate <- function(n, sizes, allocation, min_per_stratum, cap = TRUE,

stats::setNames(as.integer(base), names(sizes))
}

#' Continuous allocation with take-all capping
#'
#' Splitting `n` in proportion to `share` can ask a group for more rows than it
#' holds -- routinely under Neyman allocation, where a small, highly variable
#' stratum attracts a large share, and under equal allocation. The textbook
#' remedy (Cochran 1977, section 5.9) takes such a group whole and re-splits
#' what is left over the others *in the same proportions*. Dealing the surplus
#' out one row at a time instead, as rounding does, spreads it evenly and
#' quietly abandons the allocation rule that was asked for.
#'
#' @noRd
capped_shares <- function(n, share, sizes, cap) {
k <- length(sizes)
raw <- numeric(k)
free <- rep(TRUE, k)
left <- n
repeat {
w <- share[free]
raw[free] <- if (sum(w) > 0) left * w / sum(w) else left / sum(free)
if (!cap) break
over <- free & raw > sizes
if (!any(over)) break
raw[over] <- sizes[over]
free[over] <- FALSE
left <- n - sum(raw[!free])
if (!any(free) || left <= 0) {
raw[free] <- 0
break
}
}
raw
}

#' Warn when a group with rows in the frame is allocated none of them
#'
#' A stratum allocated zero rows makes every one of its frame rows unreachable:
#' inclusion probability 0, so a Horvitz-Thompson total omits them and is
#' biased by exactly their total. Proportional allocation does this silently to
#' any stratum smaller than `N / n`, and Neyman allocation to any stratum whose
#' auxiliary variable is constant. It is almost never what was meant.
#'
#' The warning carries its own class so that loops which draw on purpose many
#' times -- the Monte Carlo probabilities -- can silence the repeats.
#'
#' @noRd
warn_empty_groups <- function(n_alloc, sizes, noun = "stratum",
arg = "min_per_stratum") {
empty <- names(n_alloc)[n_alloc == 0L & sizes > 0]
if (!length(empty)) return(invisible(NULL))
shown <- group_label(utils::head(empty, 5L))
more <- if (length(empty) > 5L) paste0(" and ", length(empty) - 5L, " more")
else ""
plural <- length(empty) > 1L
msg <- paste0(
length(empty), " ", if (plural) paste0(sub("um$", "a", noun)) else noun,
" (", paste0("`", shown, "`", collapse = ", "), more, ") ",
if (plural) "are" else "is", " allocated no rows, so ",
if (plural) "their " else "its ", fmt_n(sum(sizes[empty])),
" frame row(s) can never be drawn. A total estimated from this sample ",
"leaves them out entirely. Raise `n`, or set ", arg, " = 1 (or 2, so ",
"each ", noun, " also supports a variance)."
)
warning(structure(class = c("drawn_empty_stratum", "warning", "condition"),
list(message = msg, call = NULL)))
}

#' Evaluate `code`, silencing the empty-stratum warning
#'
#' For loops that draw the same design many times on purpose; the result they
#' return already shows the unreachable rows as zeros.
#'
#' @noRd
quietly_empty <- function(code) {
withCallingHandlers(code, drawn_empty_stratum = function(w) {
invokeRestart("muffleWarning")
})
}
16 changes: 16 additions & 0 deletions R/design-bootstrap.R
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,24 @@
#' `method = "simple"`, where it would have no effect. `NULL` uses
#' `floor(nrow(data)^(1/3))`, a common rule of thumb.
#'
#' @section Not a survey design:
#' The bootstrap resamples the data you already have to approximate the
#' sampling distribution of a statistic (Efron 1979). It is not a probability
#' sample of a finite population, so it has no inclusion probabilities and
#' cannot be passed to [ht_total()]. For the design-based variance of a total
#' or mean, use the estimators there; for a statistic they do not cover, such
#' as a median, this is the tool. Blocks preserve short-range dependence in
#' ordered data (Künsch 1989).
#'
#' @return A design object, for use with [draw()].
#'
#' @references
#' Efron, B. (1979). Bootstrap methods: another look at the jackknife.
#' *Annals of Statistics*, 7, 1–26.
#'
#' Künsch, H. R. (1989). The jackknife and the bootstrap for general
#' stationary observations. *Annals of Statistics*, 17, 1217–1241.
#'
#' @examples
#' df <- data.frame(id = 1:100, value = (1:100) / 10)
#'
Expand Down
28 changes: 12 additions & 16 deletions R/design-multistage.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
#' @param allocation `"equal"` splits `n` evenly across the selected clusters;
#' `"proportional"` splits it in proportion to their size.
#' @param min_per_cluster Minimum rows from each selected cluster. Defaults to
#' `0`, which leaves allocation unbiased.
#' `0`. Take at least two rows per cluster if you intend to estimate a
#' variance: with one, the variation within clusters cannot be measured and
#' [ht_total()] falls back to the ultimate-cluster jackknife.
#' @param replace Sample with replacement within each cluster?
#' @param na_rm Drop rows whose cluster label is `NA` instead of raising an
#' error.
Expand Down Expand Up @@ -109,34 +111,28 @@ exact_inclusion.drawn_design_multistage <- function(design, data) {
no_closed_form(
paste0("`design_multistage()` with n = ", design$n, " over ",
design$n_clusters, " clusters"),
paste0("The remainder goes to the largest clusters selected, so a row's
",
"probability depends on which other clusters were drawn. Choose an
",
"`n` that divides by `n_clusters` (here, a multiple of ",
design$n_clusters, "),
or pass simulate = TRUE.")
paste0("The remainder goes to the largest clusters selected, so a row's ",
"probability\ndepends on which other clusters were drawn. Choose ",
"an `n` that divides by\n`n_clusters` (here, a multiple of ",
design$n_clusters, ").")
)
}
small <- names(sizes)[sizes < m]
if (length(small)) {
no_closed_form(
paste0("`design_multistage()` where ", length(small), " cluster(s) hold ",
"fewer than ", m, " rows"),
paste0("A cluster smaller than the per-cluster take is capped at its own
",
"size and the shortfall is spread over whichever clusters came with
",
"it, so there is no single answer. Lower `n`, drop the small
",
"clusters, or pass simulate = TRUE.")
paste0("A cluster smaller than the per-cluster take is capped at its own ",
"size and the\nshortfall is spread over whichever clusters came ",
"with it, so there is no single\nanswer. Lower `n`, or drop the ",
"small clusters.")
)
}
if (design$min_per_cluster > m) {
no_closed_form(
paste0("`design_multistage(min_per_cluster = ", design$min_per_cluster,
")` above the per-cluster take of ", m),
"Lower `min_per_cluster`, or pass simulate = TRUE."
"Lower `min_per_cluster`."
)
}

Expand Down
Loading
Loading