diff --git a/.Rbuildignore b/.Rbuildignore index 8b6670c..a63a9c2 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -11,3 +11,7 @@ ^Rplots\.pdf$ ^README\.Rmd$ ^vignettes/articles$ +^\.stage$ +^drawn$ +^CRAN-AUDIT\..*$ +^RUNBOOK\.md$ diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index 518fde9..05d163e 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -1,8 +1,11 @@ # Derived from https://github.com/r-lib/actions/tree/v2/examples # -# Checks the package on macOS, Windows and Linux, against the current R release, -# the previous one, and R-devel. R-devel is the one that catches deprecations -# before CRAN does; oldrel-1 backs up the `R (>= 4.1)` claim in DESCRIPTION. +# Checks the package on macOS and Windows against the current R release, and +# on Linux against R-devel, the release, the previous release (oldrel-1) and +# R 4.1. R-devel is the one that catches deprecations before CRAN does; the +# R 4.1 leg backs up the `R (>= 4.1)` claim in DESCRIPTION, which oldrel-1 +# does not reach. One more Linux leg builds the PDF manual, fails on any +# NOTE, and checks that README.md was rendered from the current README.Rmd. on: push: branches: [main, master] @@ -23,7 +26,10 @@ jobs: R-CMD-check: runs-on: ${{ matrix.config.os }} - name: ${{ matrix.config.os }} (${{ matrix.config.r }}) + name: ${{ matrix.config.os }} (${{ matrix.config.r }}${{ matrix.config.strict && ', strict' || '' }}) + + # Stops a hung job after an hour rather than the six-hour default. + timeout-minutes: 60 strategy: fail-fast: false @@ -33,12 +39,16 @@ jobs: - {os: windows-latest, r: 'release'} - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} - {os: ubuntu-latest, r: 'release'} + - {os: ubuntu-latest, r: 'release', strict: true} - {os: ubuntu-latest, r: 'oldrel-1'} + - {os: ubuntu-latest, r: '4.1'} env: GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} R_KEEP_PKG_SOURCE: yes - # Surface anything the tests only warn about. + # Lets R CMD check run when a Suggests package is missing. The + # dependency step below installs every Suggests package and fails the + # job if one cannot be installed, so on these runners none is missing. _R_CHECK_FORCE_SUGGESTS_: false steps: @@ -52,27 +62,88 @@ jobs: http-user-agent: ${{ matrix.config.http-user-agent }} use-public-rspm: true + # LaTeX for the PDF manual. Rd.sty sets code in Inconsolata. + - uses: r-lib/actions/setup-tinytex@v2 + if: matrix.config.strict + + - name: Install the Inconsolata font package + if: matrix.config.strict + run: tlmgr install inconsolata + + # HTML Tidy validates the HTML manual; without it the strict check + # reports a NOTE that it skipped the validation. + - name: Install HTML Tidy + if: matrix.config.strict + run: | + sudo apt-get update + sudo apt-get install -y tidy + # `sf` is a Suggests-only dependency and needs GDAL, GEOS and PROJ. # setup-r-dependencies installs the Linux system libraries itself; macOS - # and Windows get binaries. If it ever fails to install on one platform - # the spatial tests skip rather than fail, which is why they are written - # with skip_if_not_installed("sf"). + # and Windows get binaries. If `sf` or any other Suggests package fails + # to install, this step fails the job. The spatial tests are written + # with skip_if_not_installed("sf") for machines without it, such as + # some CRAN check machines. - uses: r-lib/actions/setup-r-dependencies@v2 with: extra-packages: any::rcmdcheck needs: check - name: No duplicate function definitions under R/ - run: Rscript tools/check-duplicates.R + run: | + Rscript tools/check-duplicates.R --self-test + Rscript tools/check-duplicates.R + shell: bash - name: Documentation is consistent with the code run: | + Rscript tools/check-docs.R --self-test R CMD INSTALL --no-multiarch --with-keep.source . Rscript tools/check-docs.R shell: bash + # The sample summary in the README prints the date it was drawn, so a + # change confined to that line is ignored. Pandoc and knitr versions lay + # out tables and error output differently, so both copies are compared + # with table padding removed and an error on two lines ("Error:" then + # "! message") joined into one; the words still have to match. + - name: README.md is rendered from README.Rmd + if: matrix.config.strict + run: | + cp README.md "$RUNNER_TEMP/README.committed.md" + Rscript -e 'rmarkdown::render("README.Rmd", output_options = list(html_preview = FALSE), quiet = TRUE)' + normalise() { + sed -E -e '/^#> +drawn +with seed/d' \ + -e '/^\|/{s/ *\| */|/g; s/-{2,}/-/g}' \ + -e '/^#> (Error|Warning)( in .*)?:$/{N;s/\n#> ! / /}' "$1" + } + diff -u <(normalise "$RUNNER_TEMP/README.committed.md") <(normalise README.md) || { + echo "README.md differs from a fresh render of README.Rmd; run devtools::build_readme() and commit README.md." + exit 1 + } + shell: bash + - uses: r-lib/actions/check-r-package@v2 + if: ${{ !matrix.config.strict }} with: upload-snapshots: true build_args: 'c("--no-manual", "--compact-vignettes=gs+qpdf")' error-on: '"warning"' + + # The incoming checks are off because a first submission always gets + # the "New submission" NOTE; every other NOTE fails this leg. + # --as-cran turns on the check for files dated in the future, which + # asks worldtimeapi.org for the time and gives the NOTE "unable to + # verify current time" when that service does not answer. Turning off + # _R_CHECK_SYSTEM_CLOCK_ keeps the file check against the runner's own + # clock and drops the call to the service. + - uses: r-lib/actions/check-r-package@v2 + if: ${{ matrix.config.strict }} + env: + _R_CHECK_CRAN_INCOMING_: false + _R_CHECK_SYSTEM_CLOCK_: false + with: + upload-snapshots: true + args: 'c("--as-cran")' + build_args: 'c("--compact-vignettes=gs+qpdf")' + error-on: '"note"' diff --git a/.github/workflows/pkgdown.yaml b/.github/workflows/pkgdown.yaml index a4716df..a1c99db 100644 --- a/.github/workflows/pkgdown.yaml +++ b/.github/workflows/pkgdown.yaml @@ -1,7 +1,12 @@ # Derived from https://github.com/r-lib/actions/tree/v2/examples +# +# A pull request builds the site, which knits the articles under +# vignettes/articles that R CMD build leaves out and checks the reference +# index, but does not deploy it. on: push: branches: [main, master] + pull_request: release: types: [published] workflow_dispatch: @@ -43,3 +48,4 @@ jobs: clean: false branch: gh-pages folder: docs + commit-message: Deploy site from ${{ github.sha }} diff --git a/DESCRIPTION b/DESCRIPTION index 9b690c2..5c39ee3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,44 +1,50 @@ Package: drawn Title: Design-Based Sampling with Known Inclusion Probabilities -Version: 0.2.0 +Version: 0.2.0.9000 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 (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, + or Neyman), systematic, cluster, multi-stage, + probability-proportional-to-size, certainty-plus-sample, spatially + balanced (the local pivotal method of Grafström, Lundström 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 + 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, the exact Horvitz-Thompson variance for Poisson sampling, the + approximation of Deville (1999) for systematic + probability-proportional-to-size samples, 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 +Language: en-GB Depends: R (>= 4.1) Imports: graphics, - lubridate, + grDevices, + lubridate (>= 1.9.0), stats, utils Suggests: + data.table, + generics, sampling, sf (>= 1.0.0), survey, - testthat (>= 3.0.0), + testthat (>= 3.1.7), tibble, knitr, rmarkdown diff --git a/NAMESPACE b/NAMESPACE index bf76972..6bde0d2 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,5 +1,31 @@ # Generated by roxygen2: do not edit by hand +S3method(as.data.frame,drawn_by) +S3method(as.data.frame,drawn_contrast) +S3method(as.data.frame,drawn_ht) +S3method(as.data.frame,drawn_mean) +S3method(as.data.frame,drawn_plan) +S3method(as.data.frame,drawn_quantile) +S3method(as.data.frame,drawn_ratio) +S3method(coef,drawn_by) +S3method(coef,drawn_contrast) +S3method(coef,drawn_ht) +S3method(coef,drawn_mean) +S3method(coef,drawn_quantile) +S3method(coef,drawn_ratio) +S3method(confint,drawn_by) +S3method(confint,drawn_contrast) +S3method(confint,drawn_ht) +S3method(confint,drawn_mean) +S3method(confint,drawn_quantile) +S3method(confint,drawn_ratio) +S3method(deff,default) +S3method(deff,drawn_by) +S3method(deff,drawn_contrast) +S3method(deff,drawn_ht) +S3method(deff,drawn_mean) +S3method(deff,drawn_quantile) +S3method(deff,drawn_ratio) S3method(draw_design,default) S3method(draw_design,drawn_design_bootstrap) S3method(draw_design,drawn_design_certainty) @@ -13,17 +39,42 @@ 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(generics::tidy,drawn_by) +S3method(generics::tidy,drawn_contrast) +S3method(generics::tidy,drawn_ht) +S3method(generics::tidy,drawn_mean) +S3method(generics::tidy,drawn_quantile) +S3method(generics::tidy,drawn_ratio) S3method(plot,drawn_design) S3method(print,drawn_by) +S3method(print,drawn_contrast) S3method(print,drawn_design) S3method(print,drawn_ht) S3method(print,drawn_mean) S3method(print,drawn_plan) +S3method(print,drawn_quantile) +S3method(print,drawn_ratio) S3method(print,drawn_summary) +S3method(survey::deff,drawn_by) +S3method(survey::deff,drawn_contrast) S3method(survey::deff,drawn_ht) S3method(survey::deff,drawn_mean) +S3method(survey::deff,drawn_quantile) +S3method(survey::deff,drawn_ratio) +S3method(vcov,drawn_by) +S3method(vcov,drawn_contrast) +S3method(vcov,drawn_ht) +S3method(vcov,drawn_mean) +S3method(vcov,drawn_quantile) +S3method(vcov,drawn_ratio) +export(add_fieldwork) +export(allocation_table) +export(as_drawn) export(as_svydesign) +export(certainty_set) +export(compact_sample) export(deff) +export(deff_cluster) export(design_bootstrap) export(design_certainty) export(design_cluster) @@ -38,16 +89,24 @@ export(design_temporal) export(design_weighted) export(draw) export(draw_design) +export(frame_totals) export(ht_mean) +export(ht_quantile) +export(ht_ratio) export(ht_total) export(inclusion_prob) export(is_design) export(joint_prob) export(plan_size) +export(replicate_weights) export(sample_summary) export(sampling_weight) +export(use_reserves) importFrom(graphics,abline) importFrom(graphics,mtext) importFrom(graphics,par) importFrom(graphics,plot) importFrom(graphics,points) +importFrom(stats,coef) +importFrom(stats,confint) +importFrom(stats,vcov) diff --git a/NEWS.md b/NEWS.md index 8186938..eed09ee 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,1536 @@ +# drawn (development version) + +## Wrong answers, fixed + +* **Reordering, subsetting or binding a weighted sample gave wrong standard + errors.** The sample matched its rows to the frame by position, so a sort + moved each row onto another row's stratum, cluster or systematic position. + Sorting one stratified sample by `y` cut its standard error from 3,015 to + 1,332, and `head()`, `s[cond, ]` and `rbind()` were estimated as if drawn. + Each row now finds its frame row through the new `.row` column, so + reordering by `[`, `dplyr::arrange()` or `data.table::setorder()` changes + nothing, and `ht_total()`, `ht_mean()`, `as_svydesign()` and + `sample_summary()` refuse a subset, a sample bound to another, or a join + that repeats rows. A sample saved by drawn 0.2.0 has no `.row` column and + is still matched by position, so it is refused once the frame columns it + keeps show its rows in another order, unless a column with a different + value in every frame row, such as an id, still matches them in order; + `as_drawn()` rebuilds it with `.row`. +* **Editing the frame in place after drawing changed the sample's + estimates.** The sample kept a reference to the frame, so a data.table + `setkey()`, `setorder()` or `:=` on it afterwards changed the standard + error, interval, degrees of freedom and design effect of a sample already + drawn. In one example `setkey()` halved a cluster sample's standard error; + in another `setorder()` took a certainty sample's design effect from 1.04 + to 171. `draw()` now stores a copy of the frame, column names included, so + `setnames()`, `setcolorder()` or deleting a column with `:=` does not + reach the sample either. +* **A certainty design over a with-replacement `rest` was weighted anyway.** + `draw(weights = TRUE)` checked `replace` only on the outer design, so + `design_certainty()` over `design_simple(replace = TRUE)` or + `design_stratified(replace = TRUE)` returned duplicates weighted as distinct + units, and in one example a total a third too high. It is now refused like + any other with-replacement design. Drawing it without weights is still + allowed. `ht_total()`, `ht_mean()`, `as_svydesign()` and `sample_summary()` + refuse such a sample saved by drawn 0.2.0. +* **Renaming, recoding or dropping a design column in a sample changed its + standard errors.** The degrees of freedom, the jackknife, `as_svydesign()` + and `sample_summary()` read strata and cluster labels from the sample's + columns, while the analytic variance read them from the frame. Dropping a + cluster sample's cluster column set the degrees of freedom to 0, which + removed the interval, and made the jackknife delete rows instead of + clusters, 61% low in one example. Recoding stratum labels broke the + jackknife and `as_svydesign()`, or gave them the wrong strata. Every path + now reads design columns from the copy of the frame stored with the sample, + so only `y` and `by` come from the sample's own columns, and + `as_svydesign()` passes the clusters to `survey` in a `.cluster` column. +* **A spatial sample analysed under another `sf::sf_use_s2()` setting got + the wrong standard error.** Which rows lie inside the region was worked out + again in the current session. A sample drawn under `sf::sf_use_s2(FALSE)`, + the documented workaround for a region that crosses the antimeridian, and + analysed after switching back or after `readRDS()` in a new session got + standard errors for a different region: 5.7 times too large in one example, + and 0 with a zero-width interval in another. The point estimate was not + affected. `ht_total()`, `ht_mean()`, `as_svydesign()` and + `sample_summary()` now check that the design still gives the frame the + inclusion probabilities it gave at draw time, and refuse the sample when it + does not, naming `sf::sf_use_s2()` for a spatial design. That includes a + design that now stops, such as one whose `n` is more than the rows inside + the region under the current setting. A sample saved by drawn 0.2.0, + which records no probabilities for the frame, is checked against its + `.prob` column instead. `?design_spatial` says the setting must be the + same at draw time and after. +* **The jackknife and the local-mean variance treated rows taken with + certainty as random.** A row that is in every possible sample was deleted, + or compared with its neighbours, as if it could have been left out. With + the units `design_weighted(method = "systematic")` takes with certainty, + the jackknife averaged 181 times the true variance on one frame, and + `variance = "auto"` fell back to it when one sampled row was below + certainty. `design_spread(size =)` with dominant sizes averaged 1,270 times + the true variance. Both estimators now hold certain units fixed, and the + jackknife's finite population correction counts only the other units. Its + note says how many units it held fixed. With one unit below certainty the + variance is reported as missing instead. +* **A census got a nonzero jackknife or local-mean standard error.** + `variance = "jackknife"` on a sample of every row or every cluster applied + no finite population correction, giving 114 for a six-cluster census in one + example, and `design_spread()` with `n` equal to the frame reported a + standard error of about 5% of the exact total. Both now give 0, as the + analytic estimators did. +* **`design_weighted()` could give a certain unit a probability a rounding + error below 1.** Depending on the scale of the sizes, a unit whose share + came to exactly 1 got `1 - 1e-16`, so `.prob == 1` missed it and a census + reported a small standard error under a "Deville approximation" note. A + share within `1e-9` of 1 is now taken with certainty at exactly 1, in + `design_weighted()` and `design_spread(size =)`. +* **A certainty design whose `rest` drew no rows reported an exact total.** + When a `rest` of random size, such as Poisson sampling with a small `n`, + drew none of the rows below the threshold, `ht_total()` and `ht_mean()` + gave a standard error of 0 and a zero-width interval although those rows + went unobserved. The total is exact only when no row lies below the + threshold. Otherwise the variance is now missing, with a note naming the + rows `rest` did not reach. +* **Units taken with certainty counted as degrees of freedom.** The t + intervals of `ht_total()` and `ht_mean()` counted every sampled unit, + including the ones `design_weighted()` and `design_spread(size =)` take + with certainty, strata and `design_temporal()` intervals taken whole, + clusters taken whole by a two-stage design that selects every cluster, + and such units inside a certainty design's `rest`. With eight certain units + among ten, systematic PPS reported 9 degrees of freedom where the same + selection built with `design_certainty()` had 1, and its interval covered + 79%; a temporal design whose sparse days were taken whole covered 83%. + Only units below certainty count now, and a stratum or interval holding + none of them drops out. A sample with no unit below certainty has + `df = Inf`, and a certainty design whose `rest` drew nothing has `df` 0. +* **`as_svydesign()` left units taken with certainty in `survey`'s Brewer + stratum.** For `design_weighted(method = "systematic")`, + `design_spread(size =)` and a certainty design over a systematic PPS + `rest`, `survey` still centred and scaled Brewer's approximation over the + certain units, which put its standard error at 23 times `ht_total()`'s on + a frame with four dominant units. They now go to `survey` in a stratum of + their own, taken whole, and the two standard errors agreed within 0.03% + there. +* **A blank stratum or cluster value broke stratified and multistage + designs.** An empty string, such as a blank field read from a file, was + looked up by name, which never matches it. `inclusion_prob()`, + `joint_prob()` and `draw(weights = TRUE)` stopped with "subscript out of + bounds" for a stratified design or a certainty design over one. Neyman + allocation read the blank stratum's spread as 0 and, with + `min_per_stratum` of 1 or more, gave its rows to the other strata without + a word. A multistage sample got `NA` probabilities, weights and totals, and + `sample_summary()` gave a blank group an `NA` frame count. A blank value is + now a key like any other, shown as `(blank)` in messages and summaries. +* **Two strata could be counted as one.** Several `strata` columns were + joined into one key with a carriage return between the values, so + `("x\ry", "z")` and `("x", "y\rz")` made one stratum of two, and the + allocation, the probabilities and the variance were all worked out over + the merged stratum. Two numbers that print alike, such as `0.3` and + `0.1 + 0.2`, were one stratum too. Keys are now built from each column's + integer codes, which cannot collide. +* **A sample estimated under another collation could get the wrong standard + error.** Text strata and a text `order_by` were sorted by the session's + collation, which differs between the C locale of a server and the en_US + locale of a desktop. Where two strata tied in the largest-remainder split, + the extra row went to a different stratum in each, and a stratified + sample drawn in one and estimated in the other got a standard error 5 + times too large in one example. A systematic sample walked on text got + the wrong neighbours for the successive-difference variance, and + `joint_prob()` gave 0 for pairs drawn together. Text is now sorted byte by + byte, as in the C locale, in every session. +* **Two cluster labels that print alike were one cluster.** `0.3` and + `0.1 + 0.2` print the same, and the cluster variance, `joint_prob()` for + cluster and multistage designs, and the jackknife compared cluster labels + as text. A `design_cluster()` sample holding both got no variance, and two + rows of the two clusters got the joint probability of rows in one cluster. + A multistage sample got a Sen-Yates-Grundy variance built on those joint + probabilities. `design_multistage()` also counted the two as one cluster + of twice the size, so their rows got half their inclusion probability and + twice their weight, which doubled their part of an estimated total. + Clusters are now compared by integer codes everywhere. +* **`design_multistage()` refused a factor cluster column with unused + levels.** An unused level counted as a cluster of no rows, so + `inclusion_prob()`, `sampling_weight()`, `joint_prob()`, + `draw(weights = TRUE)` and `plot(type = "probability")` stopped with a + false "no closed-form inclusion probability". Unused levels are now + ignored, as `droplevels()` would drop them. +* **`joint_prob()` gave `NA` for a multistage row with no cluster.** With + `na_rm = TRUE`, a row whose cluster label is missing is never drawn, so its + joint probabilities are 0, as `design_cluster()` gives. `design_multistage()` + gave `NA`, which filled the default matrix over every row with `NA`. +* **`inclusion_prob()` overstated the probabilities of + `design_multistage(replace = TRUE)`.** It gave `(a / A) * m / N_h`, the + expected number of times a row is drawn, where the probability of drawing + it at least once is `(a / A) * (1 - (1 - 1 / N_h)^m)`. In one example, 3 + draws from a cluster of 4 rows gave 0.375 against 0.289. A cluster smaller + than the per-cluster take was refused as capped at its own size, which it + is not with replacement. `draw(weights = TRUE)` refuses with-replacement + designs, so no estimate used these figures. +* **A Hajek mean over one primary sampling unit had a standard error of 0.** + A `by` domain with one sampled row, or with all its sampled rows in one + cluster that stage one could have left out, and a Poisson sample of one + row got a standard error of 0 and a zero-width interval labelled + "analytic", because the linearised residuals of a mean sum to zero inside + the one unit. `survey` gives the same 0. `ht_mean()` now gives such a mean + no standard error, with a note, unless every unit of the domain was taken + with certainty, which makes it exact. Rows taken with certainty count as + one unit, as the jackknife and `as_svydesign()` treat them, so a domain + whose sampled rows were all certain gets no standard error either while + the design could have drawn its other rows. In one systematic PPS example + a domain sampled as its two certain rows got a zero-width interval, where + the domain mean's standard deviation over 1,500 draws was 3.4. `?ht_total` + adds that intervals for domains with few sampled rows cover less often + than `level` says. A domain total, and the `estimator = "ht"` mean, keep + the standard error of 0 their unbiased estimators give such a domain, with + a note that says why the interval has no width. +* **A systematic sample understated the variance when `interval` did not + divide the frame.** The sample size is then random, 30 or 31 rows for 244 + rows at an interval of 8, and successive differences cannot see what that + adds to a total. A constant `y` got a standard error of 0, and a variable + with a coefficient of variation of 0.02 got 0.04 of its true variance and + an interval that never covered the truth. `ht_total()`, domain totals and + `ht_mean(estimator = "ht")` now add a term for the random size, and the + note says so. The default Hajek mean was not affected. +* **`deff()` measured a design against a simple random sample of the whole + frame, rows it could never reach included.** A total estimates over the + rows with a probability above 0, so an equal-probability sample of 20 from + the first 100 of 400 rows, `design_reservoir(max_items = 100)`, reported a + design effect of 0.05, "better than simple random sampling", and a + temporal window or a spatial region over part of the frame read low the + same way. The simple random sample is now drawn from the rows the design + can reach, as `survey` measures it, and that sample gets 1. A + Horvitz-Thompson mean gets its total's design effect. `?deff` says so. +* **A constant `y` got a design effect and a Hajek standard error made of + rounding error.** With unequal weights, a total's design effect came out + as `1.36e+32`, "worse than simple random sampling", and the Hajek mean's + standard error as about `1e-16`, with a design effect that changed from + seed to seed. A Hajek mean of a `y` that takes one value in every sampled + row, overall or in a `by` domain, now has a variance of exactly 0, with a + note, and the design effect of a constant `y` is `NA`. +* **Rows a design drops were counted in its finite population correction.** + `as_svydesign()` gave `survey` the frame's row count as the `fpc` of + `design_systematic(na_rm = TRUE)`, and the jackknife counted every row of + the frame for `design_spread()` and `design_weighted()` with + `na_rm = TRUE`. Both now count the rows the design can reach, and agree + with the same draw from the frame without the dropped rows. The standard + errors moved by under 1% in the examples checked. +* **Size measures whose total overflowed gave every row a probability of + 0.** Positive weights near `1e306` sum to `Inf`, so + `design_weighted()` with `method = "systematic"` or `"poisson"` and + `design_spread(size =)` gave every row a probability of 0 and drew empty + samples without a word, and a certainty design over them took only the + rows above its threshold. Such weights are now divided by the largest of + them first. Weights with a finite total give the same probabilities, and + the same rows for a seed, as before. +* **`joint_prob()` treated a row given twice in `rows` as two rows.** The + pair a repeated row made with itself got the joint probability of two + different rows, 0.015 for a simple random sample of 30 from 240 where the + row's own probability is 0.125, and `simulate = TRUE` gave it 0. It now + gets the row's own probability on both paths. `rows` that are not whole + numbers are refused, where 1.7 was read as row 1. +* **`min_per_stratum` broke the allocation rule between the strata it did not + raise.** The rows a stratum needed to reach the floor were taken back one + at a time from the others, whatever their shares, so those were no longer + split in proportion to size, evenly or by `size * sd`. Under Neyman + allocation with a floor of 4, two large strata with spreads of 1 and 3 got + 19 and 101 rows where the rule gives 35 and 85, and the variance of a total + was 14% higher. The weights followed the rows drawn, so estimates were not + biased, only less precise. A stratum is now held at its floor or its size + and the rest of `n` re-split by the rule over the others, as for a stratum + taken whole, which under Neyman allocation is the split of least variance + within those bounds. When taking whole every stratum with a Neyman share + leaves rows over, strata whose `allocation_by` does not vary share them in + proportion to size, as when no stratum varies, where they were split + evenly. `min_per_cluster` in `design_multistage()` is applied the same way. +* **`design_temporal()` with `unit = "days"` or `"weeks"` drifted off + midnight after a daylight-saving change.** Intervals were a fixed 86,400 + or 604,800 seconds, so in a zone with clock changes every interval after + the change started an hour off midnight. A `Date` column then put two + calendar days into one interval, which shared `per_interval` between them: + ten days of New York dates from 7 March 2024 gave nine intervals, with 10 + and 11 March in one, and `draw()` returned nine rows. Days and weeks now + step by calendar days in the design's zone, so every interval starts at + the clock time of `from` and lasts 23 or 25 hours across a change. + Seconds, minutes and hours are still fixed durations, and + `?design_temporal` says so. +* **`design_temporal()` placed a `Date` whose midnight a daylight-saving + change skips or repeats at the wrong instant.** Where clocks jump from + 00:00 to 01:00, as in Santiago, Cairo and Sao Paulo, the `Date` became + 23:00 the day before and fell in the previous day's or month's interval, + and the same day written as a string did not parse. Where midnight happens + twice, as in the Azores, the instant depended on the rows beside it, so + reversing the frame changed inclusion probabilities and totals. A frame + holding 30 December 2011 in Samoa, a day the zone skipped, stopped every + function with a base R error, even under `na_rm = TRUE`. A `Date`, and a + string without an offset, now stands for the first instant of its day in + the design's zone: 01:00 where midnight is skipped, the first midnight + where it repeats, and the start of the next day for a day the zone + skipped. A string ending in `Z` or an offset such as `+01:00` keeps the + instant it names. drawn now needs lubridate 1.9.0 or later. +* **`design_temporal()` with `unit = "months"` or `"years"` anchored on the + 29th to the 31st ran into the next month.** A window from 31 January had + intervals starting on 2 March, 31 March, 1 May and 31 May, and one from 29 + February by years started its intervals on 1 March in the years between + leap years. Months and years are now added to `from` itself, and a day + the month lacks moves to its last day: 29 February, 31 March, 30 April, + and 28 February in the years between leap years. +* **A `region` given as a list of parts that together cover more than half + the globe selected the rest of the globe.** `design_spatial()` unioned the + parts, and under spherical geometry the union of the two halves of a band + from -60 to 60 degrees of latitude came back as the two polar caps and a + strip 2 degrees wide. The parts are kept separate now, and a row inside any + of them is inside the region. +* **`design_spread()` never drew a row whose inclusion probability was below + `1e-9`.** The pivotal walk set such probabilities to 0 before it started, + while `inclusion_prob()` and the sample's weights still gave them their + value, so a Horvitz-Thompson total was biased by the whole of each such + row's `y`. Every row with a probability above 0 now takes part, however + small, and only the rounding error in a pooled probability is settled to + 0 or 1. +* **`design_reservoir()` stopped reading a list at its first `NULL` + element.** A list was read as a stream, in which `NULL` marks the end, so + the elements after a `NULL`, common in lists built from JSON or with + `lapply()`, were never sampled, and nothing said so. A list's length is + known, so `draw()` now picks positions in it as it does in a data frame. + Every element is an item, `NULL` included, and the elements keep their + names. +* **`design_bootstrap()` renamed or dropped a duplicated column name.** A + data frame with two columns named `a` came back with `a` and `a.1`, and a + tibble lost the second `a` without a word. Both now come back as they went + in, after `.replicate`, as with every other design. +* **`plan_size()` used a proportion's finite population correction for a + mean or a total.** `n0 / (1 + (n0 - 1) / N)` fits a proportion, whose + variance has the divisor `N`. A mean's `sd` has the divisor `N - 1`, and + the smallest size for it is `n0 / (1 + n0 / N)`. Plans for a mean or a + total were sometimes a row too large, and a margin that `N - 1` rows meet + was planned as a census. With `sd = 40` and `N = 10`, a margin of 8.4 gave + all 10 rows and called it a census, where 9 meet it. +* **`plan_size()` added a row when dividing by `response` gave a whole + number.** `21 / 0.7` is `30.000000000000004` in floating point, so 21 rows + at 70% response gave 31 to draw where 30 bring back 21, and with `N = 30` + the plan said the frame was too small at that response rate. +* **`plan_size()` took an estimate from `survey` passed as `deff` for the + design effect.** `survey::svymean(~y, des, deff = TRUE)` is a number + underneath, the estimated mean, so the plan was inflated by the mean of + `y` without a word. `plan_size()` now refuses any object other than the + result of `ht_mean()` or `ht_total()` by its class, and for a `survey` + estimate points to `survey::deff()`. A number marked with `I()` is still + taken as a number. +* **`plot(type = "probability")` on a frame larger than `max_dots` left out + unreachable and take-all rows.** It drew and summarised an evenly spaced + subset of the rows, so rows with probability 0 or 1 between them were + missing from the line, the count of unreachable rows and the range. On a + 10,000-row frame with two unreachable rows, the subtitle gave a range of + 0.0499 to 0.0501 and no unreachable row; with two take-all rows it gave a + highest probability of 0.0883. The counts, the range and the mean now + cover every row, rows taken with certainty are counted too, and above + `max_dots` each step covers a run of rows and passes through its lowest + and highest probability. +* **`plot(type = "selection")` on a frame larger than `max_dots` could show + none of a systematic sample.** The evenly spaced subset of rows it drew + fell in step with the sampling interval, so `design_systematic(interval = + 5)` on 10,000 rows showed 0, 667 or 1,333 of the 4,000 rows shown as + selected, depending on the start, where every start selects 2,000. Each + dot now stands for a run of consecutive rows and is filled when any of + them is selected, and the count under the title covers the whole frame. + +## Refusals and clearer errors + +* `as_svydesign()` and `sample_summary()` give the same reason as + `ht_total()` when a sample has lost its design, and all three name the + steps that drop it (`merge()`, column selection, `subset()`, `transform()`, + `cbind()`) and how to add fieldwork columns instead. +* The refusal of `weights = TRUE` for a with-replacement design, and + `?draw`, gave the bias as "about 15%". It is a factor of + `(n / N) / (1 - (1 - 1 / N)^n)`, about 5% at `n = N / 10`, 58% at `n = N` + and more beyond, applied within each stratum, and both now say so and give + the per-stratum Hansen-Hurwitz form. +* `ht_total()`, `ht_mean()`, `as_svydesign()` and `sample_summary()` refuse a + sample whose `.prob` column was removed, is not numeric, holds a value + outside (0, 1], or differs from the probabilities recorded at draw time + (for a sample saved by drawn 0.2.0, from the ones its design gives). A + removed `.prob` gave a total of 0, and a missing value gave `NA` with a + note saying the jackknife had run. The message says that adjusted weights + belong in `.weight`. +* `ht_total()` and `ht_mean()` refuse an infinite or `NaN` `y`, with the + count and the rows, instead of returning an infinite total or standard + error. A variance that overflows is reported as missing, and the note no + longer says the jackknife ran when it gave no figure. +* `ht_total()` and `ht_mean()` warn, with class `drawn_weight_edited`, when + `.weight` is no longer `1 / .prob`. They use the design probabilities in + `.prob`, while `as_svydesign()` hands `.weight` to `survey`, so after a + nonresponse adjustment the two gave different totals without a word. + `?ht_total` and `?as_svydesign` say which column each uses. +* `ht_total()` and `ht_mean()` warn, with class `drawn_grouped_df`, when the + sample is grouped with `dplyr::group_by()`, which they ignore, and give the + `by` that estimates per group. +* A `by` column that the sample does not have is named in the error. +* `draw(weights = TRUE)` refuses a `design_certainty()` whose `rest` gives + every row below the threshold a probability of 0, such as one with + `n = 0`, because the weighted total would leave those rows out. Drawing + without weights still gives the cut-off sample of the rows above the + threshold. +* An error raised by a certainty design's `rest` in `draw()` or + `inclusion_prob()` now says which rows `rest` was given, as in "In `rest`, + applied to the 230 rows with `w` below 100". `rest` counts only those rows, + so its own message spoke of 230 rows on a frame of 240. +* `design_multistage()` refuses an `n` smaller than `n_clusters`, `n = 0` + included, which selected clusters and then took no rows from some of them, + and a `min_per_cluster` that `n` cannot cover across `n_clusters`, which + `draw()` refused only later. `draw()` warns, with class + `drawn_empty_cluster`, when proportional allocation gives a selected + cluster no rows, and names it. +* A multistage sample from a single cluster gets no variance, with the + reason "A variance needs at least two clusters", as a `design_cluster()` + sample does. The note blamed an unlucky sample for a Sen-Yates-Grundy + estimate that is negative on every such sample, and a constant `y` got an + exact variance of 0. When stage one takes every cluster, as from a frame + of one cluster, each cluster's rows are the units of the analytic + estimator, so totals, means, ratios and domain means inside one cluster + get the variance of a simple random sample within it. The jackknife + still deletes whole clusters, so a domain mean, ratio, quantile or + contrast inside one cluster gets no standard error from it. +* `ht_mean(estimator = "ht")` with `by` refuses a frame whose `by` columns + are missing for some rows, which could be in any domain. Each domain's + total was divided by its frame rows with those left out, so a domain of + 30 frame rows, 10 of them with `by` missing, got a mean 1.5 times too + large. The Hajek mean, the default, needs no domain sizes and is + unaffected. +* An `allocation`, `method`, `unit`, `variance`, `estimator`, `target` or + `type` outside its choices is refused with a message that names the + argument, the value passed and the choices. The message from `match.arg()` + named neither the argument nor the value. `NULL` gives the default, as it + did. A missing cluster label is called a cluster label by + `inclusion_prob()` as well as by `draw()`. +* `ht_total()` and `ht_mean()` stop with the error when something fails + inside a variance estimator, such as running out of memory. Every error was + read as the estimator declining, so `variance = "auto"` fell back to the + jackknife and gave R's message, "cannot allocate vector of size 244.1 Mb" + in one example, as the reason. Only a decline, a condition of class + `drawn_declined`, leads to the jackknife now. `inclusion_prob()` and + `joint_prob()` raise that class where a design has no closed form. +* A variance too large to represent, from values of `y / .prob` above about + `1e154`, is reported as missing with a note to rescale `y`, whichever + estimator ran, and the note says it once. +* `variance = "jackknife"` reports `method = "none"` when the jackknife gives + no figure, as for a systematic or Poisson sample, which is what `?ht_total` + says. It reported `"jackknife"`, in `by` tables too. Its note for strata + with one unit names them, in the words the analytic estimator uses, where + it read "needs two units per stratum as well" with nothing before it, so + `variance = "auto"` gives that reason once. +* A `df` below 1 is refused. It was accepted and the interval dropped without + a word. When the design leaves 0 degrees of freedom, as a Poisson sample of + one row does, the note says that, and `print()` shows it. It blamed one + unit per stratum, and was not printed beside an analytic standard error. +* `inclusion_prob()`, `sampling_weight()`, `joint_prob()` and + `plot(type = "probability")` refuse a design that `draw()` refuses, with + the same message. They answered for it: an `n` of 300 from 240 rows gave + every row 1.25 under `design_simple()`, and a census of 1s under + `design_stratified()` and the systematic and Poisson methods of + `design_weighted()`; an `n_clusters` above the clusters available gave + probabilities above 1; and a window shorter than one interval, or a key + missing in every row under `na_rm = TRUE`, gave every row 0. The same + holds for an `n` above the rows inside a spatial region, for a region + with none, and for the `rest` of a certainty design, checked against the + rows below its threshold. `design_multistage()` refuses an `n` that even + its largest `n_clusters` clusters cannot hold, on both paths. +* The weights of `design_weighted()`, and of a certainty design over it, + must be numeric on every path. `inclusion_prob()`, `joint_prob()`, + `draw(weights = TRUE)` and `plot(type = "probability")` took a column of + `TRUE` as weights of 1 and stopped with a misleading message on a factor + or text one, where `draw()` refused all three. Every message about the + weights names the column, and the one for a weight of 0 or below says to + drop those rows from the frame, since every design that selects in + proportion to size refuses them. `?inclusion_prob` and `?ht_mean` said + such rows get a probability of 0. +* `inclusion_prob()`, `sampling_weight()`, `joint_prob()` and the + successive-difference variance refuse a `design_systematic()` whose + `order_by` column is not in the frame, as `draw()` did. A misspelt + `order_by` gave every row a probability of 0. +* A missing coordinate under `design_spatial()` is reported in the same + words by `draw()` and `inclusion_prob()`, naming the two `coords` + columns. +* `design_stratified()` accepts a `min_per_stratum` larger than some strata + when `n` covers it. Without replacement such a stratum is taken whole, so + the floor needs only its rows: 7 rows meet a floor of 2 over strata of 1, + 1, 1 and 100 rows, where 8 were asked for. The message gives the number + needed and says how many strata are taken whole. +* Neyman allocation refuses an infinite `allocation_by` value, as it refused + a missing one. The spread of a stratum holding `Inf` came out as `NaN` and + was read as none, so the stratum with the most extreme values was + allocated no rows. Finite values large enough to overflow `sd()` split as + the same values on a smaller scale do, and a stratum of small values + beside them keeps its own spread. +* The warning for a stratum allocated no rows says when Neyman allocation + gave it no share because `allocation_by` is constant within it. It then + suggests `min_per_stratum = 1`, since a larger `n` reaches such a stratum + only once every other stratum is taken whole. `design_stratified()` with + `n = 0` no longer warns for every stratum. +* `design_temporal()` checks its zone and bounds when it is built. `tz` must + be a name from `OlsonNames()`, and `from` and `to` must each be one + date-time, date or string that parses, with `to` after `from`. Without + `tz`, a bound that names an instant (a date-time, or a string ending in + `Z` or an offset) paired with a clock time (a date, or a string without + an offset) can fall in either order depending on the zone. Such a pair is + refused when the design is built if it is a day or more out of order, + which no zone's offset can undo, and otherwise when the design is used, + in the zone the window is laid out in. The message names the argument + and gives its value. An unknown zone gave a raw CCTZ error from every + function that used the design, and an unparseable `from` reached + `inclusion_prob()` as "'to' must be a finite number". The message for an + unparseable timestamp in a string column lists the forms that are read, + and a `POSIXct` column in a zone R does not know is named. +* `draw()`, `inclusion_prob()`, `joint_prob()` and `plot()` warn, with class + `drawn_geodesic_edges`, when an edge of a longitude/latitude `region` in + `design_spatial()` passes more than 0.1 degrees (about 11 km) from the + straight line between its corners on a flat map. Under spherical geometry + each edge follows a great circle, so the top edge of a box from -50 to 50 + degrees of longitude at latitude 30 reaches latitude 41.9, and rows that + far outside the box as drawn were sampled without a word. +* The warning about an edge across the antimeridian has class + `drawn_antimeridian` and gives both readings, the short way across the + antimeridian and the long way the longitudes span. It said the region was + "much smaller than its coordinates suggest", which is wrong for a region + meant to cross the antimeridian. `inclusion_prob()`, `joint_prob()` and + `plot(type = "probability")` give it as well as `draw()`, and + `inclusion_prob(simulate = TRUE)` gives it once, not once per simulated + draw. An edge from -180 to 180 still gives it, since both ends lie on one + meridian and a box between them encloses nothing. An edge along a pole, + where every longitude meets, no longer does, so a cap around a pole closed + along it draws without a warning. +* `design_spatial()` refuses a `region` of points or lines, which enclose no + area, and names `sf::st_buffer()`, or `sf::st_collection_extract()` for a + geometry collection. `draw()` found no row inside such a region, or only + rows lying on it. +* `design_spatial()` reprojects each member of a list `region` to `crs` + before combining them, so members in different CRSs work. They were + refused with "`region` must be an sf or sfc geometry, or a list of them, + not list", which blamed the type. +* With longitude/latitude coordinates, `design_spatial()` refuses a latitude + outside -90 to 90 or a longitude outside -180 to 360, which `sf` only + warned about, and says the columns may be in (lat, lon) order or hold + projected coordinates. +* The refusals of `inclusion_prob()`, and of `simulate = TRUE` in + `inclusion_prob()` and `joint_prob()`, for + `design_bootstrap(method = "block")` said each row appears + `n_replicates * n / nrow(data)` times on average. Under the moving-block + bootstrap the first and last `block_length - 1` rows appear less often, + and the message now says so. +* `design_systematic()` given more than one `order_by` column says how to + walk by several: add a column of ranks built from them, such as + `order(order(data$a, data$b, method = "radix"))`, and give its name. + `?design_systematic` has an example. The message said only that + `order_by` must name a single column. + +* `deff()` of a `by` table says that domain estimates carry no design + effect, and points to the estimate without `by`. It said the table "must + come from ht_total() or ht_mean()", which it did, and `survey`'s `deff()` + returned `NULL` with a warning. +* A `by` column named `n`, `variance`, `se`, `ci_lower`, `ci_upper` or + `method`, or `total` for a total and `mean` for a mean, columns the table + of domain estimates uses for its own values, is refused by name. The + table's column overwrote it, so `by = "n"` gave domains labelled by their + counts. +* A `by` table whose columns were selected with `[` or `subset()` prints + as a plain data frame. It kept its class but lost the attributes its + printout reads, and `print()` stopped with "argument is of length zero". +* `ht_total()` refuses a missing `y` with a message that gives the share of + the weight the rows with `y` missing hold, which is about how low a total + over the other rows would be, and points to `ht_mean(na_rm = TRUE)`, `by` + and a weighting-class adjustment through `as_svydesign()`. It said only + how many values were missing. `ht_mean()` points to `na_rm`. +* `plan_size()` refuses an `N` below 1, and plans at most `floor(N)` rows, + so an estimated `N` such as 240.5 gives a whole `n` that `draw()` accepts. + It returned `n = 240.5`, which `draw()` refused, and `n = 0` for + `N = 0.5`. +* `plan_size()` refuses a `margin` of 1 or more for a proportion, and says + to give it as a proportion, such as `0.05` for 5 percentage points. A + margin of 5 planned one row. +* `plan_size()` warns that it ignores `sd` given for a proportion and `p` + given for a mean or a total, and when `sd` is missing and `p` is given its + refusal suggests `target = "proportion"`. Both were ignored without a + word, and `plan_size(margin = 0.03, p = 0.2)` said only that `sd` was + required. +* `plan_size()` refuses a `deff` of `NA` with the reason `deff()` gives one, + a pilot without a variance estimate or with one value of `y`, or a mean + from `ht_mean(na_rm = TRUE)` with `y` missing in some rows, whose design + effect, a domain's, is not estimated. It said only that `deff` must be a + positive number. +* `plan_size()` plans a census when the size for an unbounded frame is too + large for a number, and refuses it for an unbounded `N` with a message + naming `margin` and `level`. It stopped with "missing value where + TRUE/FALSE needed", or returned `n = Inf`. +* `plot()` checks `palette`, `main` and `sub` before it draws anything. + An entry of `palette` the plot does not use, such as `acent`, an entry + without a name, a `NULL` entry, or a value that is not one colour is + refused by name, and a named character vector such as `c(accent = "red")` + is read as a list. A colour R did not know stopped the plot partway, with + part of the page drawn, and a bad `surface` left the margins changed for + the next plot. A misspelt entry was ignored, and a named vector stopped + with "is.list(val) is not TRUE". `main` takes one string, one expression, + or a name or call such as `quote(alpha)`. A number, which was drawn as + text, is refused, so write `main = "5"` for `main = 5`. So are an empty + `expression()`, which stopped the plot partway, and an expression of two + or more parts, which were drawn over each other. +* A message about an argument given a function, a name, an environment or + a data frame names its class, as in "not a function". A function or a + name gave a warning from `is.na()` as well, and a data frame stopped with + "the condition has length > 1". +* `plot()` refuses an argument in `...` that is not a graphical parameter, + such as `simulate`, and names it. It was passed to the panel, where base + graphics dropped it with a warning. +* `plot()` names `y` when the population is not a data frame, where it said + `data`. `plot(type = "map")` names the two columns when no row has both + coordinates, where base graphics stopped with "need finite 'xlim' + values". +* Messages that name a class put "an" before a vowel, as in "not an + integer", where they said "not a integer". +* `draw()`, `inclusion_prob()` and `joint_prob()` refuse a `seed` outside + the integer range, such as `2^31`, and give the range. `set.seed()` + stopped with "supplied seed is not a valid integer" after a coercion + warning. A seed, count, `level` or `df` given as text reads as + `the string "1"` in the message, where it read like the number 1. + `inclusion_prob()` and `joint_prob()` check `seed` without + `simulate = TRUE` too, where they ignored any value. +* `draw()`, `inclusion_prob()` and `joint_prob()` given the design first and + the data second say the two look swapped and how to call the function. + They said only that `design` must come from a constructor. +* A design with no closed-form inclusion probability points to + `inclusion_prob(data, design, simulate = TRUE)`. It said "pass + simulate = TRUE" when raised by `draw(weights = TRUE)` and `plot()`, + neither of which takes `simulate`. A design with no closed-form joint + probability points to `joint_prob(data, design, simulate = TRUE)` as well, + where most of those refusals did not mention it, except a bootstrap, whose + simulation is refused. +* A design class of your own (see `?draw_design`) is refused by + `draw(weights = TRUE)` and the exact probabilities with a message that + points to `inclusion_prob(simulate = TRUE)`, where it said "No inclusion + probability method for design type". A draw method that drops columns of + `data` is refused by the simulations, which counted it as drawing nothing. + +## Behaviour changes + +* `draw(weights = TRUE)` adds a third column, `.row`, after `.prob` and + `.weight`. It holds the row of `data` each sampled row came from. A frame + that already has a `.row` column is refused, as one with `.prob` or + `.weight` is. +* A sample drawn from a data.table takes `:=` without the "Invalid + .internal.selfref" warning. data.table joins `Suggests`. +* `ht_total()` of an empty sample from a design of random size, which Poisson + sampling or a systematic start past the last row can give, returns a total + of 0 with no variance and a note, where it stopped with an error. Over + repeated draws that 0 is what keeps the total unbiased, so a simulation loop + no longer has to catch it. `ht_mean()` refuses the Hajek mean of an empty + sample, which is 0 / 0, and gives 0 for `estimator = "ht"`. An empty sample + from a design that reaches no row, such as one with `n = 0`, is still + refused, and the message says so. `?ht_total` describes this. +* Text keys are sorted byte by byte, as in the C locale, whatever the + session's locale: the order in which strata are drawn and in which they + break allocation ties, the rows of `by` estimates and of + `sample_summary()`, and the walk of a text `order_by`. Text read from a + file without a declared encoding, as `read.csv()` and `readLines()` give + it, is sorted by its bytes in the same way, Latin-1 read in a UTF-8 + session included. An unmarked cluster label and a UTF-8 one with the same + bytes are one cluster in every locale, as they are one stratum; in the C + locale they were two. Factor columns keep their level order. In a locale + whose collation differs from C, a seed can therefore select different rows + than it did in drawn 0.2.0, and a tie can go to another stratum. + `?design_stratified` gives the tie rule. +* `by` estimates come out in key order: numbers in sequence (1, 2, 10, not + 1, 10, 2) and factors in level order, where they were sorted as text. + Domains with no sampled row are still left out, as `survey::svyby()` + leaves them out. +* An sf data frame can be passed as `data` to `design_stratified()` and + `design_spread()`, and an sf sample to `by` in `ht_total()` and `ht_mean()` + and to `sample_summary()` of a stratified or cluster sample. All of these + stopped inside base R on the geometry column. A `by` estimate of an sf + sample is a plain data frame without the geometry. +* When a multistage sample with one row per cluster falls back to the + jackknife and more than a fifth of the clusters were selected, the note + gives the factor by which the jackknife inflates the variance between + clusters. When every cluster was selected, it says that variance is zero by + design and points to `design_stratified()`. `variance = "jackknife"` on a + multistage sample without `size` gives the same factor, and when every + cluster was selected says that `variance = "analytic"` measures the + variation within clusters only. +* A `by` domain gets a variance when a stratum or interval with one sampled + row holds none of its units, read from the `by` columns of the frame + stored with the sample. A domain of strata or intervals taken whole is + exact, with a zero-width interval even at 0 degrees of freedom. Such + domains were refused with a note saying the standard error would be + understated, which was false for them. A domain with units in the lonely + stratum is still refused, and when the frame has no `by` columns the note + says the frame cannot tell. A frame row whose `by` value is missing may + belong to any domain, so a lonely stratum holding one is refused for + every domain, with the same note. +* `ht_mean()` decides whether `y` is a proportion, and so whether its + interval is formed on the logit scale, from what `y` is rather than from + the values the sample drew: a logical `y`, or a column of the frame whose + values are all 0 or 1. A count that came out 0 or 1 in every sampled row + got a logit interval, which cannot pass 1 and so never covered a mean of 1 + or more; it now gets the symmetric interval. A 0/1 column added to the + sample after the draw, or a numeric vector, has no frame column to read + and is still taken for a proportion when every sampled value is 0 or 1, + as before, now with a note saying so and that `proportion = FALSE` gives + the symmetric interval of a count. `by` estimates follow the same rule. +* A proportion estimated at exactly 0 or 1, such as no deviations in 60 + sampled invoices, gets Korn and Graubard's beta interval, with the sampled + rows below certainty as its effective sample size, and a note saying so. + It got a zero-width interval of 0 to 0. For 0 in 60 from a simple random + sample the 95% upper bound is now 4.87%. A design that leaves 0 degrees + of freedom, such as a Poisson sample of one row, gets the Clopper-Pearson + interval over the sampled rows. A census, or a domain of rows taken with + certainty, is still exact. A domain's effective sample size for the beta + interval is capped at its rows below certainty, so its interval is never + narrower than Clopper-Pearson's over them. +* Estimates from `ht_total()` and `ht_mean()` hold `unreachable`, the number + of frame rows with inclusion probability 0, and print it on a line of its + own when there are any, whether or not there is a standard error. `by` + tables carry it as an attribute and print it too. `draw()` warns about + such rows, but a sample saved and read back, or drawn with the warning + muffled, gave a total over part of the frame with no sign of the rest. +* The printout of `ht_total()` and `ht_mean()` shows the note whenever the + standard error is 0, such as the one saying every sampled row was taken + with certainty. +* `sample_summary()` gains `N_reachable`, the rows the design gives a + probability above 0, and prints the sampling fraction over them. `N` is + still every row of the frame. +* A stratified design whose `min_per_stratum` raises a stratum, or a + multistage design whose `min_per_cluster` raises a cluster, can allocate + different counts than drawn 0.2.0 did, as above, and a seed then selects + different rows. Designs where no floor binds allocate and draw as before. +* `design_temporal(tz = NULL)`, the default, lays out the window in the + zone of a `POSIXct` `time` column, and in UTC only when the column has + none: a `Date` or string column, or a `POSIXct` whose `tzone` is empty. + It always used UTC, so a window of local dates over New York data ran from + 19:00 to 19:00 local time. Give `tz = "UTC"` for the old layout. A + printed design shows `tz` as "from the time column, else UTC" when it is + not set. This and the calendar fixes above change the intervals of some + designs. A sample drawn earlier whose probabilities they change is refused + by `ht_total()`, `ht_mean()`, `as_svydesign()` and `sample_summary()`, + which say the design now gives different probabilities; draw it again. +* `design_temporal()` reads timestamps and bounds written as + `"2024-03-01 14:30"` or `"2024-03-01 14"`, with a space or a `T` before + the time. They were unparseable, so such rows stopped the draw or, under + `na_rm = TRUE`, were dropped. A date written day or month first, such as + `"01/02/2024"`, is still refused rather than guessed. +* `design_reservoir()` returns the items of a connection or generator in + the order they arrived, as it returns the rows of a data frame in frame + order. They came back in the order of the reservoir's slots. The items + drawn for a seed are unchanged. A list is now sampled as a data frame is, + so it gives a different sample for a seed than it did. `?design_reservoir` + says that the streaming path and the data-frame path use different + algorithms and so give different samples for one seed. +* `design_bootstrap(method = "block")` with the default `block_length` uses + `floor(nrow(data)^(1/3))` when the row count is a perfect cube too. The + cube root in floating point fell below the whole number, so 64 rows + got runs of 3 instead of 4, and 1,000 rows runs of 9 instead of 10. Such + frames get different replicates for a seed. +* `draw()` with a finite `design_reservoir(max_items =)` pushes the line it + reads past the cap back onto an open connection in text mode, so the next + read starts with it. It was read and dropped. +* The default title of `plot()` names the `order_by` of a systematic + design, its `n_starts` when above 1, and the `within` of a stratified + design. + +* `deff()` is a generic, with methods for the results of `ht_total()` and + `ht_mean()`, and passes any other object to `survey::deff()`. Its + argument is `object`, as in `survey`'s, where it was `x`, so `deff(x = r)` + must become `deff(r)`. Attached after `survey`, drawn's `deff()` masked + `survey`'s and refused every `survey` object, such as the result of + `survey::svymean(deff = TRUE)`. Either package's `deff()` now answers for + both, whichever is attached last. +* `by` tables gain a `variance` column, and their `n` is an integer where it + was a double. The printout leaves `variance` out, since it is the square + of `se`. +* The intervals of `design_temporal()` are named by their start, such as + `2024-01-03 00:00`, in the notes of `ht_total()` and `ht_mean()`, the + strata `as_svydesign()` hands to `survey` and the table of + `sample_summary()`. They were numbered, and a note listed them sorted as + text: `1`, `10`, `2`. +* A printed estimate names its variance method as `method` holds it, the + name the `method` column of a `by` table shows, and says when it is an + approximation: "successive difference, an approximation" where it said + "successive-difference approximation". The README's table of designs uses + the same names. +* A printed `plan_size()` shows a margin of `1e5` as `100,000`, where it + showed `1e+05`. A margin that would take many digits, such as `1e-300`, + stays in scientific notation. +* `sample_summary()` lists every stratum of the frame, one allocated no rows + with 0 drawn, where it listed only the strata drawn. It gives a certainty + design the groups of its `rest`, after a `(certain)` row for the rows + above the threshold, where it gave none, and groups a temporal sample by + interval. The rates print with three decimals, where their widths varied. +* `plan_size()` plans two rows at least when the frame has two, since one + row gives no standard error or interval, and its printout says so. The + result's new `raised` is `TRUE` when this applies. A margin of two + standard deviations planned one row. +* `plan_size()` no longer sets `capped` and `short` together. `capped` means + that only a census meets the margin, and `short` that a smaller sample + would if everyone responded. `capped` was documented as a frame that could + not reach the margin however it was sampled, though a census always + reaches it, and the printout now says the same. +* A printed proportion plan shows the `p` it assumes, where it showed + `sqrt(p * (1 - p))` as `sd`, and the result holds `p`, which is `NA` for a + mean or a total. +* `plot(type = "probability")` puts frame rows on its axis and centres a + plateau on each row, so the first and last rows are as wide as the others + and a one-row frame is drawn. The last row had no width, so a take-all + unit at the end of a frame sorted by size did not show, and frames of two + to four rows had repeated tick labels. The mean's label sits inside the + panel. +* `plot(type = "selection")` and `plot(type = "map")` of a design that + samples with replacement count draws and distinct rows, as in "60 draws, + 51 distinct rows of 240", and ring each row drawn more than once. +* `plot()` of a `design_bootstrap()` shows its first replicate and says so, + whatever its `output`. It marked every row drawn in any replicate, which + at the default 1,000 replicates is every row. `plot(type = "probability")` + no longer points a bootstrap to the selection view. +* `plot()` passes `xlim`, `ylim`, `asp` and the other graphical parameters + in `...` to the panel in place of its own settings. Each one the plot also + set stopped with "formal argument matched by multiple actual arguments", + so a map could not be given `asp = 1` and the probability view could not + be zoomed. In `type = "probability"` the rules, the axis and the mean line + follow the limits given. +* `plot(type = "map")` of a `design_spatial()`, or of a `design_spread()` + with `scale = FALSE`, draws both axes to the same scale, so the map shows + the distances the design works with. Longitude and latitude are drawn + with a degree of longitude at `cos()` of the middle latitude. Other + columns fill the panel as before, and `asp = NA` gives that back for these + two designs. +* `plot(type = "map")` says under its title which columns of `across` it + leaves out when there are more than two, and how many selected rows it + could not place because a coordinate is missing. It used the first two + columns without saying so and counted rows it did not draw among those + selected. When it thins the background it keeps at most `max_dots` of the + unselected rows and says "background thinned to 50 of 210". Its note + "50 of 240 rows shown" came with 71 rows drawn. +* The default title of `plot()`, and the description of a design in + messages, gives every argument that changes what the design draws when it + differs from the default: `replace`, `start`, `allocation_by`, `cost`, + `min_per_stratum`, `min_per_cluster`, `max_items`, `block_length`, + `output`, `batches`, `scale` and `na_rm`, the `coords` of + `design_spatial()`, the `above`, `threshold` and `rest` of + `design_certainty()`, and the `unit` of `design_temporal()`. Several + column names are wrapped in `c()`, so the title reads as R code. + `design_simple(n = 10)` and `design_simple(n = 10, replace = TRUE)` had + the same title, as did a reservoir with and without `max_items`, and a + certainty design's title had no arguments at all. `balanced = FALSE` is + left out. A title or subtitle too long for the figure is drawn smaller, + down to two thirds of its size, and past that is cut and ends in "...", + where it ran off the edge of the figure. +* A printed design shows what a default left as `NULL` means: `start` is + `random` for `design_systematic()`, and `n` is `nrow(data)` and the + default `block_length` is `nrow(data)^(1/3), rounded down` for + `design_bootstrap()`. +* A `seed` is applied with R's default generator, + `set.seed(seed, kind = "Mersenne-Twister", normal.kind = "Inversion", + sample.kind = "Rejection")`, whatever generator the session has selected, + and the session's generator is restored with its state. A seed drew + another sample after `RNGkind("L'Ecuyer-CMRG")` or under + `sample.kind = "Rounding"`. A session left at R's defaults draws the same + samples as before. This holds for the `seed` of `draw()`, + `inclusion_prob()`, `joint_prob()` and `plot()`. +* `draw()` keeps the row names of a frame that has its own, such as the car + names of `mtcars`, on the rows drawn, made unique by `make.unique()` where + a row is drawn more than once. They were replaced by 1, 2, and so on. + Automatic row names are still numbered afresh, and a tibble has none. +* `inclusion_prob(simulate = TRUE)` and `joint_prob(simulate = TRUE)` give a + warning that the draws raise once, at the end, with the number of draws + that raised it. `max_items` below the rows of a frame and a systematic + start past the last row warned once per draw, hundreds of times, and an + empty stratum or cluster was not reported. These two warnings have the + classes `drawn_stream_truncated` and `drawn_empty_start`, and a random + systematic start past the last row is called random, where the message + named `start`. A warning whose details change from draw to draw, such as + the empty cluster or the random start it names, is shown as the first + draw gave it, with the number of draws that gave one like it. When each + draw gives the same few warnings of one kind, the message says how many + each draw gave. +* `inclusion_prob(simulate = TRUE)` and `joint_prob(simulate = TRUE)` time + the draws after the first two, which carry one-off costs such as loading + a package, and a run projected to take more than 30 seconds says how + long, with a progress bar in an interactive session. A run of hours, such + as the default `R` for `design_spread()` on 10,000 rows, gave no sign of + progress. +* The note of a successive-difference variance says that systematic + sampling has no design-unbiased variance estimator only when the walk has + a step of 2 rows or more. `design_systematic(n =)` with `n` above half the + rows walked, and `design_stratified(within = design_systematic())` with + every stratum taking more than half its rows, have a step under 2 rows, + at which every pair of rows can be drawn together. The variance is the + same successive-difference approximation. + +## New + +* `ht_total()` and `ht_mean()` take `alternative = "less"` for a one-sided + upper bound and `"greater"` for a lower bound, labelled as such when + printed. The open end of `ci` is `-Inf` or `Inf`, or 0 or 1 for a + proportion. A one-sided bound is the end of a two-sided interval at + `1 - 2 * (1 - level)`, which is how it had to be asked for before. +* `ht_mean()` takes `proportion`, to say whether `y` is a proportion rather + than leave it to the rule above, and `ci_method = "beta"` for Korn and + Graubard's interval, the one `survey::svyciprop(method = "beta")` gives, + with its effective sample size capped at the number of sampled rows below + certainty. +* `ht_total()` and `ht_mean()` take `contrast`, weights over the `by` + domains such as `c(a = 1, b = -1)`, and return the weighted sum of the + domain estimates with its standard error, interval and degrees of freedom, + as a `drawn_contrast`. The variance comes from one run of the design's + estimator, so the covariance between domains is counted, and for simple + random, stratified, cluster and multistage samples the standard error + equals that of `survey::svycontrast()` on `survey::svyby(covmat = TRUE)`. + A difference of domain means needed linearised residuals built by hand, + and the `survey` route stopped with an error for systematic PPS samples. + The interval is symmetric, for proportions too. +* `certainty_set()` gives the rows of the frame that `design_weighted()` + with `method = "systematic"` or `"poisson"`, or `design_spread()` with + `size`, takes with certainty, before anything is drawn. Its `threshold` + attribute, the smallest size among them, can be passed to + `design_certainty()` to take the same rows with the cut-off made + explicit. +* `design_stratified()` takes the number of rows to draw from each stratum + as `allocation`: a named vector such as + `c(north = 10, south = 5, east = 5)`, or for several `strata` columns a + data frame of those columns and `n`. `n` can be left out and is their sum. + A stratum of the frame with no count, a count for a stratum the frame does + not have and, without replacement, a count above the rows in its stratum + are refused by name. `inclusion_prob()`, `joint_prob()`, the variance + estimators, `as_svydesign()` and `sample_summary()` follow the counts as + given. +* `design_stratified(allocation = "neyman")` takes the standard deviation of + each stratum as `allocation_by`, from a pilot or an earlier survey, in + place of a frame column: a named vector, or a data frame of the `strata` + columns and `sd`. The frame then needs no such column for `draw()`, + `inclusion_prob()`, `joint_prob()` or the variance estimators. The new + `cost` argument takes the cost of one row in each stratum in the same + forms and splits `n` in proportion to `size * sd / sqrt(cost)`, the split + of least variance for its total cost (Cochran 1977, section 5.5). Before, + the only way to get either was a made-up frame column with the wanted + spread. A stratum of the frame missing from either is refused by name, + and a value for a stratum the frame does not have is ignored, so the same + values serve the `rest` of `design_certainty()` when every row of a + stratum is above the threshold. A negative or infinite standard + deviation, a cost of 0 or less, and `cost` without Neyman allocation are + refused when the design is built. +* `allocation_table()` shows, before drawing, how `design_stratified()`, on + its own or as the `rest` of `design_certainty()`, splits `n` over the + strata of a frame: each stratum's size, the rows drawn from it, their + inclusion probability, the standard deviation and cost a Neyman split + used, and whether the stratum was held at its floor, capped at its size, + taken whole or left with no rows. It comes from the same computation as + `draw()` and `inclusion_prob()`. +* `design_spatial(coords =)` and `design_spread(across =)` take the name of + a POINT geometry column, such as the geometry of an `sf` frame, and read + each row's position with `sf::st_coordinates()`. A geometry column with a + CRS of its own is used in that CRS. `plot(type = "map")` places rows by + it too. +* `design_spread(across =)` takes Date and date-time columns, counted in + days and in seconds, so a sample can be spread over time and space + together. `plot(type = "map")` gives them date axes. Any other column that + is not numeric is refused with a pointer to `as.numeric()`. +* `design_spread()` takes `strata`, to spread a sample within each stratum, + and `allocation`, to split `n` over them by `"proportional"` or `"equal"` + allocation or by a count for each stratum, as `design_stratified()` does. + Each stratum is scaled, sized and spread on its own. `ht_total()` and + `ht_mean()` add up the strata's local mean variances, count degrees of + freedom as for a stratified sample, and refuse by name a stratum with one + sampled row below certainty. `as_svydesign()` hands the strata to + `survey`, and `allocation_table()` and `sample_summary()` list them with + the rows each keeps once `na_rm` drops those with a missing value. A count + for a stratum that `na_rm` empties is refused with that reason. The + help page advised spreading within strata for large frames without a way + to do it, and samples drawn stratum by stratum and bound with `rbind()` + are refused by the estimators. +* `design_bootstrap()` takes `method = "circular"`, the circular block + bootstrap of Politis and Romano (1992), in which a run of rows can wrap + from the last row to the first, so every row appears equally often on + average. Under `method = "block"` the first row and the last appear only + `1 / block_length` as often as a row in the middle, which + `?design_bootstrap` now says. +* `design_bootstrap()` takes `output`. `"indices"` returns the replicates as + an integer matrix of row numbers with a column per replicate, and + `"weights"` as a matrix of the number of times each replicate drew each + row, which + `survey::svrepdesign(type = "bootstrap", combined.weights = TRUE)` takes + as replicate weights. Neither copies the data. The default, `"rows"`, + still returns the stacked frame, and for one seed all three hold the same + replicates. +* `design_reservoir()` takes `batches`. With `batches = TRUE`, a function + that returns a data frame on each call is sampled by row rather than by + data frame: Algorithm L runs over the rows, `draw()` returns `n` of them + as one data frame, and `max_items` counts rows. A seed gives the same rows + however the stream is cut into batches. +* `design_systematic()` takes `n`, in place of `interval`, for a sample of + exactly `n` rows. The step is the number of rows walked divided by `n` and + need not be whole: a start `u` is drawn from (0, 1), each row covers + `n / N` of a line from 0 to `n`, and the rows under `u`, `u + 1`, ..., + `u + n - 1` are taken. Every row has probability `n / N`, `joint_prob()` + gives each pair the exact share of starts that take both, and the + successive-difference variance has no term for a random size. Before, an + `interval` that did not divide the frame gave one of two sample sizes, and + a fractional `interval` was refused, so 30 rows from 100 could not be + asked for. `interval` keeps its place as the first argument, and a seed + draws the same rows with it as before. A design saved by drawn 0.2.0 and + read back with `readRDS()` gets the fields added since, so it draws and + gives the probabilities it did then. +* `design_systematic()` takes `n_starts`, for a replicated systematic + sample. With `n_starts = m`, `m` different starts are drawn from + `1:(m * interval)` and each is walked at a step of `m * interval`, so + every row keeps probability `1 / interval` and the expected sample size + is unchanged. `joint_prob()` gives the exact joint probabilities, and + `ht_total()` and `ht_mean()` use the variance between the replicates' + totals, `(1 - 1 / interval) * var(t_r) / m`, which is design-unbiased, on + `m - 1` degrees of freedom. `as_svydesign()` hands the replicates to + `survey` as clusters and gets the same standard error. One start has no + unbiased variance at all, and the successive-difference approximation + was the only figure on offer. +* `design_stratified()` takes `within = design_systematic(order_by = "x")` + for systematic sampling within strata. The strata are allocated as + before, and each is sorted on `x` and walked from a start of its own at a + step of `N_h / n_h` rows, so every row keeps probability `n_h / N_h`. + `joint_prob()` gives the exact joint probabilities, `ht_total()` and + `ht_mean()` add up the strata's successive-difference variances on the + degrees of freedom of a stratified sample, and `as_svydesign()` hands + `survey` the strata. Other designs as `within` are refused, and so is + `design_systematic()` with `interval` or `n` there, since the allocation + sets each stratum's size. `design_systematic()` with neither is now built + for this role, and refused if drawn on its own. +* `design_weighted()` takes `strata` and `allocation`, for sampling in + proportion to size within strata. `n` is split over the strata by + `"proportional"` or `"equal"` allocation over their rows, or by a count + for each stratum, as `design_stratified()` splits it, and each stratum is + then sampled by `"systematic"` or `"poisson"` on its own, with rows past + certainty taken with certainty within it. `"successive"` is refused with + `strata`. `inclusion_prob()` gives `n_h * p_i` within each stratum, + `ht_total()` and `ht_mean()` add up Deville's approximation over the + strata for `"systematic"` and count degrees of freedom as for a + stratified sample, a stratum with one sampled row below certainty is + refused by name, and the jackknife deletes within strata. + `as_svydesign()` hands `survey` the strata, with Brewer's approximation + within each, and `allocation_table()` and `sample_summary()` list them + with the rows each keeps once `na_rm` drops those with a missing weight. A + count for a stratum that `na_rm` empties is refused with that reason. + Samples drawn stratum by stratum and bound with `rbind()` were the only + way before, and the estimators refuse them. +* `design_multistage()` takes `size`, a column holding each cluster's size + measure, to select clusters with probability proportional to it by + systematic PPS, taking a cluster with certainty where `n_clusters` times + its share passes 1, and then the same `n / n_clusters` rows from each by + simple random sampling. A row's inclusion probability is its cluster's + stage-one probability times `m / N_i`, so a measure equal to the + cluster's row count gives every row `n / N`. `ht_total()` and `ht_mean()` + use Deville's approximation over the estimated totals of the clusters + below certainty plus the variance within the selected clusters, which is + the exact two-stage estimator when every cluster has the same chance, and + count each cluster taken with certainty as a stratum of its rows. + `as_svydesign()` hands `survey` the two stages with Brewer's + approximation at the first, or one stage of clusters when a selected + cluster gives one row of several. A measure that differs within a cluster, + `allocation = "proportional"` and an `n` that `n_clusters` does not + divide are refused. +* `inclusion_prob()` gives `design_cluster(balanced = TRUE)` its exact + inclusion probabilities, where it refused them as having no closed form, + so `plot(type = "probability")` and `sampling_weight()` work for it too. A + row of a cluster of `N_i` rows has `(a / A) * E(m) / N_i`, the take `m` + averaged over the selections that include its cluster, worked out from + the sorted cluster sizes. The help page quoted simulated values of 0.41 + and 0.34 for clusters of 4 and 6 rows where the exact ones are 0.417 and + 0.333. +* `draw(weights = TRUE)` weights `design_cluster(balanced = TRUE)`, and + `design_multistage()` without `size` under proportional allocation, with + an `n` that `n_clusters` does not divide or with a cluster smaller than + the take, conditional on the clusters it selected, all of which it + refused before. `.prob` is `(a / A) * m_i / N_i` for the `m_i` rows taken + from cluster `i`, and the sample records the clusters selected. The total + is unbiased given the selection, and so over every selection. + `ht_total()` and `ht_mean()` estimate its variance with the two-stage + formula at each cluster's own take, on `a - 1` degrees of freedom; + `as_svydesign()` hands it to `survey` in two stages, with the same + standard errors; and `sample_summary()` says the weights are conditional. + Proportional allocation needs `min_per_cluster` of at least 1 for this. + `inclusion_prob()` still refuses the multistage cases, whose exact + probabilities average the chance given the clusters selected over every + possible selection. +* `replicate_weights()` builds replicate weights from a sample for + `survey::svrepdesign()`, with the `type`, `scale` and `rscales` to pass + with them. For most designs they are the jackknife of + `ht_total(variance = "jackknife")`, deleting units within strata with + each stratum's finite population correction and holding units taken + with certainty fixed; where the default of `ht_total()` is another + estimator, such as Deville's approximation for systematic PPS, they + give the jackknife's standard error, not the default's. A systematic + sample, alone or within strata, gets successive-difference replicates in + walk order, without the pair the circular form adds between the two + ends of the walk, and a replicated one gets a replicate per start; both + give the standard error `ht_total()` gives by default. + `survey::as.svrepdesign()` stops on the probability-proportional-to-size + and Poisson designs `as_svydesign()` hands over, which is a limitation + of `survey` that `?as_svydesign` now states, for a systematic sample + builds a jackknife that ignores the walk, and for balanced clusters + and `design_multistage()` without `size` keeps a first-stage correction + the jackknife of `ht_total()` leaves out. Poisson sampling, which the + jackknife understates, is refused, and so are replicate weights that + would take more than about 1 GB. +* `frame_totals()` gives the population totals `survey::calibrate()` takes, + the column totals of `model.matrix(formula)` over the rows of the stored + frame that the design could reach, or with `table = TRUE` the counts + `survey::postStratify()` and `survey::rake()` take. Rows outside a + region or time window, past a reservoir's `max_items` or dropped by + `na_rm` are left out, and a missing value in the rows counted is + refused. A name in `formula` that is not a column of the frame, such as + `cutoff` in `~ I(w > cutoff)`, is read from where the formula was + written; a term with no frame column in it, such as `~ cutoff`, has no + value per row and is refused. + Calibrating a design from `as_svydesign()` needed the totals built by + hand. The estimation article has an example; calibration itself stays + with `survey`. + +* The results of `ht_total()` and `ht_mean()`, `by` tables and contrasts + have `coef()`, `vcov()`, `confint()` and `as.data.frame()` methods, and + `tidy()` methods for `generics::tidy()` and so `broom::tidy()`; generics + joins `Suggests`. `confint()` gives the interval the estimate holds, on + the design's degrees of freedom and, for a proportion, on the logit or + beta scale, and forms it again at another `level`. `survey::SE()` and + `survey::cv()` work through these. `vcov()` of a `by` table gives `NA` for + the covariances between domains, which are not estimated, and 0 for two + domains of a stratified sample that share no stratum. Results record + `variable`, the name of `y`, so estimates of several variables can be + bound with `rbind()` of their `as.data.frame()`, and `n_random`, the + sampled rows below certainty. `?ht_total` describes them under "Working + with the result". +* `sample_summary()` reports `n_kish`, Kish's effective sample size + `sum(w)^2 / sum(w^2)`; `n_certain`, the sampled rows taken with certainty, + with `certain_by` splitting them into those above a `design_certainty()` + threshold, those a size measure put at probability 1 and those in a group + the design takes whole, whichever rows a Poisson draw happened to hold; + and `expected_n`, the sum of the inclusion probabilities, printed beside + `n` when the sample size is random, as under Poisson sampling. +* `plot(type = "map")` of a `design_spatial()` design draws the outline of + `region`, with each edge of a longitude/latitude region along its great + circle under spherical geometry, which is how the design decides which + rows are inside. +* `as_drawn()` rebuilds a weighted sample from rows read back from a CSV + file, a spreadsheet or a database table, which keep the rows and lose the + design. It matches each row to the frame through `.row`, or through id + columns named in `by`, and works out the inclusion probabilities again + from the design. Ids that are missing, repeated or not in the frame, a + frame reordered since the draw, which shows in the columns the rows share + with it, and a sample short of the rows drawn, such as the rows that + responded, part of a cluster or a row taken with certainty, are refused. + Text such as `"F"` or `"f"` read back as `FALSE`, a date-time read back + in UTC and an infinite value are not taken for a reordered frame. + `add_fieldwork()` joins fieldwork results keyed by an id to a sample, in + the sample's own order and keeping its design, and refuses repeated or + unknown ids and columns the sample already has; a sampled row with no + result gets a missing value. A sample that had been through a file could + not be estimated from, and `merge()` dropped the design. The refusal of a + sample without its design names both. +* `compact_sample()` replaces the copy of the frame a weighted sample holds + with the columns its design reads, plus any named in `keep`. Each sample + holds its own copy of the whole frame, in memory and in every file it is + saved to, which hands the frame, with any personal data in it, to whoever + receives the file. A simple random sample of 100 from a three-column frame + of a million rows saved to 28 MB, and to 8 MB compacted, most of it the + frame's inclusion probabilities. Estimates, `as_svydesign()` and + `sample_summary()` are unchanged; `ht_mean(estimator = "ht")` with `by`, + `frame_totals()`, and the standard error of a domain when a stratum has + one sampled row, need their columns in `keep`, and say so. `?draw` + describes the cost. +* `ht_mean()` takes `na_rm`. With `na_rm = TRUE` it estimates the mean over + the sampled rows with `y` present, as a domain of the whole sample, with + the design's own variance estimator, and equals + `survey::svymean(na.rm = TRUE)` on `as_svydesign()`, by domain too. The + printed result says how many rows were left out and that they are assumed + missing completely at random, and names any `by` domain left without a row + because every sampled row of it has `y` missing. `?ht_total` has a section + on missing values and nonresponse, with the weighting-class adjustment to + use when that assumption fails, and the estimation article shows the + steps. +* `design_simple()` and `design_spread()` take `reserve`, a number of units + to list after the main sample for replacing units that fieldwork finds + cannot be reached. `draw()` returns the main sample and then the reserves, + numbered in the order they are used by a new `.reserve` column; the main + sample is the one the design draws without `reserve`. For + `design_simple()` the list is one random draw, and for `design_spread()` + the reserves are a second spread sample from the rows the main sample + left, so they cover the space evenly too. `design_spread()` takes + `reserve` only without `size` and `strata`, both refuse `reserve` with + `n = 0`, and `design_certainty()` refuses a `rest` with `reserve`. A + printed simple or spread design shows a `reserve` line. `ht_total()`, + `ht_mean()`, `as_svydesign()` and `sample_summary()` refuse the list. The + new `use_reserves()` takes it with the units found unavailable, replaces + them with the first available reserves, and returns a sample weighted at + `n / (N - u)` over the frame without the `u` units found unavailable. Its + estimates describe the units that can be reached, and `?use_reserves` says + what that assumes. Every unit nobody visited is taken as available, which + the printed `unreachable` line of an estimate says; the estimate keeps `u` + in `unavailable`. `as_drawn()` rebuilds a list read back from a file + through its `.reserve` column. +* `ht_ratio()` estimates the ratio of two population totals, + `sum(y / pi) / sum(x / pi)`, such as audited value per unit of book + value, with a standard error from the linearised residuals + `(y - R x) / X_hat` and the design's own variance estimator, on the + design's degrees of freedom. With `by` it gives each domain's ratio, + estimated from the whole sample. For the designs `as_svydesign()` maps + with identical standard errors it equals `survey::svyratio()`, and + `survey::svyby(..., survey::svyratio)` by domain; systematic, spread and + systematic PPS samples get the estimators `ht_total()` uses for them. A + ratio needed linearised residuals built by hand, or the hand-off to + `survey`. Its result has the `coef()`, `vcov()`, `confint()`, + `as.data.frame()`, `tidy()` and `deff()` methods of the other estimates. +* `ht_total()` takes `ratio`, the name of a frame column `x`, and returns + the ratio estimator of the total: the ratio of `y` to `x` in the sample + times the total of `x` over the frame rows the design can reach, read + from the frame stored with the sample. It equals + `predict(survey::svyratio(), total =)`, and when `y` is close to + proportional to `x` it is more precise than the Horvitz-Thompson total. A + missing `x` in a frame row the design can reach is refused, and so is + `ratio` with `by`. +* `ht_total()` and `ht_mean()` take several column names as `y`, and + return one table with a row per variable, or per variable and domain with + `by`, each row what a call for that variable alone gives. Its `vcov()` + holds the covariances between the variables' estimates, each from one + more run of the design's estimator, `(V(z_a + z_b) - V(z_a) - V(z_b)) / 2`, + which equals `vcov(survey::svytotal(~a + b))` for the designs + `as_svydesign()` maps with identical standard errors. + `ht_total(s, c("y", "w"))` stopped with a message that `y` must be a + numeric column name, and the covariance of two estimates, which the + standard error of their difference needs, was not available at all. A + `y` that is none of one column name, several column names, or a numeric + vector or factor as long as the sample is refused with a message that + lists those forms and says what `y` was, and a column that is not + numeric is named with its type. +* `ht_quantile()` estimates medians, quartiles and other quantiles, overall + or by domain, from the Hajek estimate of the distribution function. The + estimate at `p` is the smallest sampled value whose estimated + distribution function is `p` or more, `survey::svyquantile()`'s default + rule. Its interval is Woodruff's: the interval for the distribution + function at the estimate, from the design's own variance estimator, is + carried back to the scale of `y`, and the standard error is that + interval's width over `2 t`. For the designs `as_svydesign()` maps with + identical standard errors it equals + `survey::svyquantile(interval.type = "mean")` except in three places, and + systematic, spread and systematic PPS samples get the estimators + `ht_total()` uses for them. For a `p` below the share of the weight held + by the smallest sampled value, `survey`'s rule takes the second smallest + value as the estimate and `ht_quantile()` the smallest. A `p` within + `1e-9` above a share of the weight, such as `seq(0, 1, 0.01)[71]`, gives + the value at that share, where `survey` and `stats::quantile(type = 1)` + give the next. A quantile at the largest sampled value, where that + variance is 0 whatever `y` does, gets no standard error, with a note, + where `survey` gives an interval of no width. Quantiles were available + only through `as_svydesign()`. A logical `y` is refused with a pointer to + `ht_mean()`. The result has `coef()`, `vcov()`, `confint()`, + `as.data.frame()` and `tidy()` methods, and `confint()` at another level + forms the Woodruff interval again. `vcov()` of several quantiles has `NA` + for their covariances, which are not estimated. +* `ht_total()` and `ht_mean()` take a factor or character column as `y`, + or a factor as long as the sample, and return the estimated count or + share of each level as a table led by a `level` column, with a + proportion's interval for each share and the covariances between levels + in `vcov()`, as `survey::svytotal(~f)` and `survey::svymean(~f)` give + them. Such a `y` was refused, and shares took one call per level with an + indicator such as `s$f == "a"`, which `?ht_mean` now shows. +* `ht_total()`, `ht_mean()` and `ht_ratio()` take a single number as `y` + or `x` and use it for every row, so `ht_total(s, 1)` estimates the number + of frame rows the design can reach, and with `by` the number in each + domain. A single number was refused. +* `plan_size()` takes the result of `ht_mean()` or `ht_total()` on a pilot + as `deff` and uses its design effect. It refuses a mean when + `target = "total"` and a total for a mean or a proportion, since the two + design effects differ for one sample, by a factor of 42 in one cluster + sample. +* `plan_size()` takes `strata`, a data frame with a row per stratum + holding its size `N` and the standard deviation `sd` within it, or the + expected proportion `p`, and plans a stratified sample: the smallest `n` + whose split by `allocation` (`"proportional"`, `"equal"` or `"neyman"`, + with an optional `cost` column for Neyman) meets the margin, with at + least `min_per_stratum` rows from each stratum, 2 by default. A + `min_per_stratum` of 0 is refused, since without a floor a small stratum + gets no rows until `n` is large, and the estimate leaves it out. `n` is + split as `design_stratified()` splits it, rounding included, and the + split is returned as `allocation`, which `design_stratified(allocation =)` + draws as given. Stratification could enter a plan only through `deff` + before. +* `deff_cluster()` gives the design effect `1 + (m - 1) * icc` of taking + `m` rows from each cluster when rows of one cluster correlate at `icc`, + to pass to `plan_size(deff =)` before a pilot has measured one. +* A plan from `plan_size()` can be passed as `n` to every design that + takes `n`, such as `design_simple(n = plan)`, where it was refused + before. `plan_size()` takes several values of `margin`, `sd`, `p`, `deff` + and `response`, one per plan, and returns a data frame with a row per + plan, and `as.data.frame()` turns a single plan into such a row. +* `plot()` takes `sub`, a string added to the end of the line under the + title. A `sub` given before was matched to an internal argument of the + same name, and `type = "map"` stopped with 'graphical parameter "bg" has + the wrong length'. +* A sample from `draw(weights = TRUE)` records how it was drawn in the + attribute `drawn_meta`: the seed, the generator, the version of drawn, the + time and the number of frame rows. `sample_summary()` returns it as + `drawn` and prints the seed, the version and the date. A sample from + `as_drawn()` records that it was rebuilt, and `use_reserves()` keeps the + record of the draw. + +## Speed and memory + +* Stratum and `by` keys are built from each column's integer codes, so + their cost grows with the number of rows, however many combinations the + columns' levels could form. On 200,000 rows keyed by two columns of 3,000 + values each, the key took 8 seconds where it now takes 0.2, and at 6,000 + values each it ran out of memory. +* `inclusion_prob()`, `joint_prob()` and `draw(weights = TRUE)` take time + linear in the number of strata of a stratified design. At 40,000 strata + each took about 9 seconds. `inclusion_prob()` and `joint_prob()` now take + under a tenth of a second, and `draw(weights = TRUE)` half a second. +* `design_cluster()` and `design_multistage()` find the rows of the + selected clusters in one pass over the frame instead of one pass per + cluster. Selecting 1,000 clusters from a million rows took 16 seconds and + now takes 0.2. The clusters chosen for a seed are unchanged. +* The jackknife sums each unit with `rowsum()`, so its time grows with the + number of rows rather than with rows times units. 20,000 rows took 2.6 + seconds and now take 0.03. +* The analytic variance of simple random, reservoir, spatial, stratified, + temporal and equal-take multistage samples, alone or as the `rest` of + `design_certainty()`, is computed from the variance within each stratum, + interval or cluster, and for a multistage sample the variance between the + estimated cluster totals, in time and memory that grow with the number of + sampled rows. The Sen-Yates-Grundy sum over every pair of sampled rows, + which gives the same figures, held several matrices with a row and a + column per sampled row: a stratified sample of 4,000 rows took 4.8 seconds + and 1.4 GB, growing with the square of the sample, and every `by` domain + built them again. The same sample now takes 0.01 seconds, and 10,000 rows + take 0.04. A census of one row gets its variance of 0 this way rather than + from the jackknife. +* `joint_prob()` refuses a matrix that would need more than about 1 GB, + from about 11,200 rows, and gives the size and `rows = s$.row` as the way + to ask for the rows of a sample `s`. It used to go on and could exhaust + memory. The full matrix is still the default. Stratified, temporal, + cluster, multistage and systematic joint probabilities are filled one + group at a time and need little memory beyond the matrix itself, where they + needed 4 to 12 times its size: a stratified matrix over 5,000 rows took + 2.4 GB and 6.7 seconds, and now takes 0.2 GB and 0.4 seconds. +* `by` estimates work out the strata, clusters, systematic order, certainty + split, spread neighbours and joint probabilities once per call rather than + once per domain, and the analytic variances of simple random, reservoir, + spatial, stratified and temporal samples, alone or as the `rest` of + `design_certainty()`, come from one pass over all the domains. 200 domains + of a stratified sample of 1,000 from 100,000 rows took about 50 seconds + and now take 0.1; 200 domains of a spread sample of 1,000 from 20,000 rows + took 16 seconds and now take 0.3. `variance = "jackknife"` places the + frame's rows in its strata once per call too: 200 domains of a stratified + sample of 300 from a million rows took 21 seconds and now take 1.2. The + standard errors agree with the old ones to rounding error. +* `inclusion_prob()`, `draw(weights = TRUE)` and the estimators of a + `design_temporal()` sample count the rows of every interval in one pass, + where they went over the rows once per interval. 200,000 rows in hourly + intervals over a year took about 6 seconds and now take 0.03. +* `design_bootstrap()` subsets the data once for all replicates, where it + subset it once per replicate and bound the pieces with `rbind()`. The + default 1,000 replicates of a 5,000-row frame with four columns took 13 + seconds and now take 0.4, with the same rows for a seed. It warns, with + class `drawn_bootstrap_size`, when the stacked frame would pass 10 million + rows, and points to `output`. +* `design_reservoir()` on a connection or generator grows its reservoir as + the stream fills it. It set aside all `n` slots before reading, so + `n = 5e7` took 400 MB for a stream of five items. It counts the items read + in a double, so a stream of more than 2,147,483,647 items no longer stops + with "missing value where TRUE/FALSE needed". +* `design_reservoir()` reads a connection 10,000 lines at a time and works + out Algorithm L's swaps within each block, where it called `readLines()` + once per line. Drawing `n = 100` from 500,000 lines took 1.2 seconds and + now takes 0.1, with the same sample for a seed. A larger `n` gains less, + because it makes more swaps and each costs what it did; `n = 20000` went + from 2.0 seconds to 0.8. + +## Handing off to survey + +* `as_svydesign()` hands `survey` a copy of the sample, so an in-place sort + of the sample afterwards no longer changes the survey design's standard + errors. +* Units taken with certainty go to `survey` as one primary sampling unit + per stratum with an `fpc` of 1, through a new `.psu` id column, so + `survey::degf()` gives the same degrees of freedom as `ht_total()` for + certainty designs, strata and intervals taken whole, PPS samples with + certain units, and the clusters `design_multistage()` and + `design_cluster(balanced = TRUE)` take whole when they select every + cluster, and `survey::svyciprop()` gives the same interval as + `ht_mean()`. `survey` had counted each certain row as a unit, and each + cluster taken whole as one more. +* A census, a sample whose every `.prob` is 1, goes to `survey` as + `ids = ~1` with `fpc` the number of rows. Under systematic PPS, alone or + as a certainty design's `rest`, Poisson sampling and + `design_spread(size =)` it stopped `svydesign()` with "subscript out of + bounds". An empty sample is refused with a message + instead of failing inside `survey`, and so is a certainty sample whose + `rest` drew none of the rows below the threshold, which `survey` would + have reported as exact. +* `?as_svydesign`, the estimation article and `cran-comments.md` no longer + say that `survey` agrees with systematic PPS within 0.2%. In simulations on + frames of 100 to 300 rows with gamma and lognormal sizes, standard errors + of totals agreed within 0.5% in most samples and within 3% in all; those + of means differed more as the sampling fraction grew, typically by 3 to 7% + at one half and by up to 12%. Where the probabilities below certainty + spread from 0.05 to 0.95, totals differed by up to 9% and means by up to + 17%. +* `as_svydesign()` labels strata built from several columns as `a . b`. + The labels held a carriage return, which broke a CSV export of the design + variables. Where two labels would read alike, the strata are numbered + instead, so `survey` cannot merge them. +* `as_svydesign()` numbers the clusters in `.cluster`. `survey` made a + factor of the labels, which merged two that print alike, such as `0.3` and + `0.1 + 0.2`, into one primary sampling unit. The cluster column's name + went into the `ids` formula as it stood, so a name with a space, such as + `cluster id`, stopped `svydesign()` with a parse error, and `cl-1` beside a + column `cl` was read as `cl - 1`, which clustered on `cl`. +* `as_svydesign()` hands over `design_certainty()` over a cluster, + multistage, Poisson or replicated systematic `rest`, which it refused as + having no single `survey` design. The certainty rows go to `survey` as one + more primary sampling unit beside the clusters or replicates, taken whole + at both stages of a two-stage `rest`, and a Poisson `rest` becomes + `survey::poisson_sampling()` built from the whole sample's `.prob`, with + the certainty rows at probability 1. Totals, standard errors, domain + estimates and degrees of freedom agree with `ht_total()` as they do for + `rest` on its own. +* A sample from `design_multistage()`, with or without `size`, or + `design_cluster(balanced = TRUE)` with one sampled row from a selected + cluster of several goes to `survey` as one stage of clusters with no + `fpc`. That is the ultimate-cluster design behind the jackknife + `ht_total()` falls back to, so the standard errors agree. In two stages, + `survey` stopped with "has only one PSU at stage 2". +* `as_svydesign()` refuses a sample with a column named `.stratum`, + `.cluster`, `.psu`, `.fpc`, `.fpc2` or `.unit`. It wrote the design into + those columns over the user's, so an analysis of such a column in + `survey` read the design's values. +* `as_svydesign()` refuses unnamed arguments in `...`. It dropped them, so + `as_svydesign(s, ~cl)` handed `survey` the mapped design and ignored + `~cl`. +* `?as_svydesign` and `cran-comments.md` said `survey`'s standard error is + larger than `ht_total()`'s for `design_spread()`. It is larger when `y` + varies smoothly over the coordinates, and smaller in most samples when `y` + has no spatial pattern or the sampling fraction is large, because the + local mean approximation has no finite population correction. + `?as_svydesign` also says that the agreement it states holds under + `survey`'s default `options(survey.ultimate.cluster = FALSE)`. + +## Documentation and site + +* `?ht_total` said the exact multistage estimator understates by about a + third with one row per cluster. It understates by `f1` times the + within-cluster component, where `f1` is the share of clusters selected, and + the jackknife used in its place overstates by `f1` times the + between-cluster component, which came to 3.3 times the true variance in one + example with 30 of 40 clusters selected. `?design_multistage` and + `?inclusion_prob` give the probability under `replace = TRUE`. +* `?designs` and `?design_stratified` name all three allocation rules, + `"neyman"` included, where they described `"proportional"` and `"equal"` + only. +* `?design_spread` gives the local-mean variance estimator's ratio to the + true variance by sample size and sampling fraction, from 1.0 to 4.9 in its + table and 18.9 for 4 rows from 8, and says `deff()` carries the same + overstatement. It said 1 to 1.6 times. A ratio slightly below 1 occurs + too. +* `?design_spatial` explains how the edges of a longitude/latitude region + bow under spherical geometry, how to keep them on their straight lines in + degrees, and how to pass a region larger than a hemisphere as a list of + parts. +* `?design_bootstrap` and the choosing-a-design article say that resampling + rows suits independent rows, and point a sample drawn with strata or + clusters to `survey::as.svrepdesign()`, which resamples clusters within + strata. The help page said the bootstrap was the tool for any statistic + the estimators do not cover, and the article that it estimates the + sampling distribution of whatever you like. `?design_bootstrap` also says + that `n = 0` gives a frame with no rows that keeps its `.replicate` + column, and the README's table of designs lists the circular block + bootstrap. +* `?design_reservoir` says that each line of a connection is an item, a CSV + header included, and shows how to read the header off an open connection + before drawing. It said that items past `max_items` were never read; one + is read, to tell a longer stream from one of exactly `max_items`, and a + function is called once past the cap. A connection that is not open is + opened, read and closed, as `read.csv()` does. Under `batches = TRUE` only + the column names of each batch are compared, and a column whose type + differs between batches takes the type `rbind()` gives the sampled rows. +* `?design_systematic`, `?inclusion_prob` and `?joint_prob` say that a + fixed `start` makes the design deterministic, so `inclusion_prob()`, + `sampling_weight()`, `joint_prob()`, `draw(weights = TRUE)` and the + estimators refuse it, while `inclusion_prob(simulate = TRUE)` reports its + probabilities of 0 and 1. The table in `?inclusion_prob` gave + `1 / interval` for every row without saying the start must be random. + `joint_prob()` and the estimators now refuse a fixed start with the same + message as `inclusion_prob()`, which says to leave `start` as `NULL`. +* `?plan_size` says which design effect to pass: that of `ht_mean()` for a + mean or a proportion and that of `ht_total()` for a total. A mean's design + effect used for a total planned a sample that met its margin in 23% of + samples, against the 95% planned. It also says that a design effect from + one pilot is noisy and worth rounding up, and when `deff()` gives `NA`. +* `?plan_size` says that `margin` is the half-width the plan expects, so the + interval a sample reports is wider about half the time, and gives the t + quantile for 3, 4 and 6 clusters as 2.2, 1.6 and 1.3 times `z`, where it + said "slightly wider". It says that the logit interval `ht_mean()` reports + for a proportion is asymmetric, with an upper arm that exceeds `margin` in + most samples when `p` is small, and cites chapter 4 of Cochran (1977) for + both corrections. +* `?draw` and `?designs` say that a `seed` restores the caller's random + number stream and that `seed = NULL` draws from and advances it. + `?designs` said the stream was always restored. +* `?draw_design` gives the contract for a design class of your own: a + method takes `design` and `data` and returns rows of `data`, which is + enough for `draw()` and `simulate = TRUE` but not for `weights = TRUE` or + the estimators. The site lists it under "Extending", where it was a page + with no contract beside `draw()`. +* `?inclusion_prob` says what a simulation costs: `R` draws, each of which + takes time in proportion to `N^2` for `design_spread()`. +* Claims that went further than the code or the simulations are corrected. + `?ht_total` said the successive-difference variance of a systematic sample + stayed near the truth. Its average over the starts depends on the frame, + 1.6 times the true variance on the estimation article's example; a cycle + whose period divides the interval understates it as a matching period + does; a period of twice the interval overstated it 29-fold in one + simulation; and under a pure trend it falls towards `6 / n` of the truth. + `?ht_total` also says that intervals cover less often than `level` when + `y / pi` is skewed and the sample small, 87% to 91% in most of the cases + it cites, that the Hajek mean covers less often still when `y` is close + to proportional to size, through its ratio bias and a variance estimate + that runs low, and that `variance = "jackknife"` declines for systematic + and Poisson samples, where it said the jackknife always resamples. + `?ht_mean` says the Hajek and Horvitz-Thompson means coincide for an + equal-probability design that can reach every row of the frame, which a + region or `max_items` can prevent. `?designs` says that only + `method = "successive"` of `design_weighted()` returns rows in draw order. + `?design_weighted` says that Poisson sampling takes rows past certainty + with certainty and rescales the rest, as systematic PPS does, where it said + they were capped at 1, and puts successive sampling of weights `1:10` at + `n = 5` up to about 36% from proportional, by exact enumeration, where it + said 35%. `?design_systematic` says that `start` counts along the walk, + sorted by `order_by` when given, and `?draw` that a seed is sure to draw + the same rows only from a frame in the same row order. The estimation + article checks five designs against their exact variance at 1,000 draws, + where the ratios of 0.85 and 0.87 it printed for cluster and Poisson + samples were Monte Carlo error. The spatial-sampling article shows the mean + it promised, and the choosing-a-design article says why one cluster + sample's design effect came out below 1. +* `?drawn` and the package description give Deville's (1999) approximation + as the variance for systematic probability-proportional-to-size samples, + where they gave it for every probability-proportional-to-size design. + Poisson samples get the exact Horvitz-Thompson variance. They cite + Grafström, Lundström and Schelin (2012) by its DOI. The README's table of + designs gives the size of a `design_certainty()` sample as the rows above + the threshold plus `rest`'s, where it said `rest`'s own. +* `?joint_prob`, `?design_systematic`, `?ht_total`, `?as_svydesign`, + `?design_stratified` and the estimation article say that a systematic + sample has no design-unbiased variance estimator at a step of 2 rows or + more, where neighbouring rows are never drawn together. With `n` above + half the rows walked, every pair of rows has a positive joint + probability. `?design_stratified` gave two rows of a stratum less than a + step apart a joint probability of 0; that holds for rows at most + `N_h / n_h - 1` apart, and at a step of 3.33 rows two rows 3 apart are + drawn together one time in five. `?design_systematic` says that + `as_svydesign()` refuses a replicated sample with a replicate that drew + no rows. The estimation article's sections on systematic samples no + longer use one letter for both a row and the interval, and the README's + table of designs gives the successive-difference variance of + `design_stratified(within =)`. + # drawn 0.2.0 An adversarial review of 0.1.0 found estimates that were wrong without saying diff --git a/R/allocation.R b/R/allocation.R index 8e48b25..eeb1871 100644 --- a/R/allocation.R +++ b/R/allocation.R @@ -8,50 +8,63 @@ #' rounding takes four strata of 25 down to 8 rows for a requested 10) nor #' leaves the rare-group floor optional. #' +#' The split itself is continuous and comes from `capped_shares()`, which +#' already respects the floor and the cap. Only the rounding happens here: +#' each group gets the whole part of its share, and the rows left over go one +#' at a time to the largest fractional parts. +#' #' @param n Total to allocate. -#' @param sizes Group sizes, named. +#' @param sizes Group sizes. Everything else is matched to them by position; +#' names, when present, are carried to the result. #' @param allocation `"proportional"`, `"equal"` or `"neyman"`. -#' @param min_per_stratum Floor per group. +#' @param min_per_stratum Floor per group. With `cap`, a group smaller than +#' the floor is taken whole. #' @param cap When `TRUE`, no group may be allocated more rows than it holds. #' `FALSE` when sampling with replacement, where over-allocation is legal. -#' @param spread Per-group standard deviation, for Neyman allocation. Groups +#' @param spread Per-group standard deviation, in the order of `sizes`, for +#' Neyman allocation. Groups #' get shares proportional to `size * spread`, which minimises the variance #' of a total for a fixed `n`: a group whose values barely vary needs fewer #' rows to pin down than an equally sized group that varies a lot. +#' @param cost Per-group cost of one row, in the order of `sizes`, or `NULL`. +#' Neyman shares become `size * spread / sqrt(cost)`. +#' @param noun The group, singular and plural, for the message when the +#' floor needs more than `n`. #' @noRd allocate <- function(n, sizes, allocation, min_per_stratum, cap = TRUE, - spread = NULL, min_arg = "min_per_stratum") { + spread = NULL, min_arg = "min_per_stratum", + noun = c("stratum", "strata"), cost = NULL) { k <- length(sizes) if (k == 0L) return(integer(0)) - if (min_per_stratum * k > n) { - stop(min_arg, " = ", min_per_stratum, " across ", k, - " group(s) needs at least ", min_per_stratum * k, - " rows, but `n` is ", n, ".", call. = FALSE) - } # `n` and `sizes` are both integer, so `n * sizes` is evaluated in 32 bits and # overflows to NA once the product passes 2^31 -- 3,000 rows out of 2.4 # million was enough. Everything downstream is fractional anyway. n <- as.numeric(n) sizes <- stats::setNames(as.numeric(sizes), names(sizes)) + lower <- group_floor(min_per_stratum, sizes, cap) + if (sum(lower) > n) { + small <- sum(sizes < min_per_stratum) + where <- paste0(if (sum(lower) == 1) " row" else " rows", + if (k == 1L) { + paste0(" in the one ", noun[1]) + } else { + paste0(" across these ", k, " ", noun[2]) + }) + stop("`", min_arg, "` = ", min_per_stratum, " needs at least ", sum(lower), + where, + if (cap && small > 0L) { + paste0(", with the ", small, " ", + if (small == 1L) noun[1] else noun[2], " smaller than ", + min_per_stratum, " taken whole") + }, ", but `n` is ", n, ". Raise `n` or lower `", min_arg, "`.", + call. = FALSE) + } - 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 - # 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 - }, - sizes - ) - raw <- capped_shares(n, share, sizes, cap) + share <- allocation_share(allocation, sizes, spread, cost, noun) + raw <- capped_shares(n, share, sizes, cap, lower) - base <- pmax(min_per_stratum, floor(raw)) + base <- floor(raw) if (cap) base <- pmin(base, sizes) short <- n - sum(base) @@ -72,103 +85,430 @@ allocate <- function(n, sizes, allocation, min_per_stratum, cap = TRUE, } i <- i + 1L } - } else if (short < 0) { - # Mirror the branch above: take rows back one at a time, cycling, so a - # group can give up more than one. A single pass could only remove as many - # rows as there are groups, which left the total over target whenever - # min_per_stratum pushed the floor up by more than one row per group. - ord <- order(raw - floor(raw), decreasing = FALSE) - i <- 1L - while (short < 0 && length(ord) > 0) { - j <- ord[(i - 1L) %% length(ord) + 1L] - if (base[j] > min_per_stratum) { - base[j] <- base[j] - 1L - short <- short + 1L - } else { - ord <- ord[ord != j] - i <- i - 1L - } - i <- i + 1L - } } stats::setNames(as.integer(base), names(sizes)) } -#' Continuous allocation with take-all capping +#' Each group's floor #' -#' 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. +#' `min_per_stratum` for every group, except that without replacement a +#' group smaller than the floor is taken whole, so it needs only its own +#' rows. +#' +#' @noRd +group_floor <- function(min_per_stratum, sizes, cap) { + lower <- rep(as.numeric(min_per_stratum), length(sizes)) + if (cap) pmin(lower, as.numeric(sizes)) else lower +} + +#' The share of `n` each group gets under an allocation rule +#' +#' Before the floor and the cap. Under Neyman allocation it is +#' `size * spread`, or `size * spread / sqrt(cost)` with costs, the split of +#' least variance for what the sample costs (Cochran 1977, section 5.5). +#' When no group has any spread, every split has the same variance, and the +#' shares are those for equal spreads: `size`, or `size / sqrt(cost)`. #' #' @noRd -capped_shares <- function(n, share, sizes, cap) { +allocation_share <- function(allocation, sizes, spread = NULL, cost = NULL, + noun = c("stratum", "strata")) { 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 + sizes <- as.numeric(sizes) + switch(allocation, + equal = rep(1, k), + neyman = { + if (is.null(spread)) { + stop("Neyman allocation needs `allocation_by`.", call. = FALSE) + } + sp <- as.numeric(spread) + if (length(sp) != k || anyNA(sp) || any(!is.finite(sp) | sp < 0)) { + stop("Neyman allocation needs a finite spread of 0 or more for ", + "every ", noun[1], ".", call. = FALSE) + } + base <- sizes + if (!is.null(cost)) { + cs <- as.numeric(cost) + if (length(cs) != k || anyNA(cs) || any(!is.finite(cs) | cs <= 0)) { + stop("Neyman allocation needs a finite cost above 0 for every ", + noun[1], ".", call. = FALSE) + } + base <- sizes / sqrt(cs) + } + # A constant auxiliary variable has no spread to allocate by; fall back + # to the shares for equal spreads rather than dividing by zero. + if (!any(sizes > 0 & sp > 0)) return(base) + pow2_scale(base) * pow2_scale(sp) + }, + sizes + ) +} + +#' `x` times the power of two that brings its largest value near 1 +#' +#' Neyman shares depend only on the ratios of the spreads and of the costs. +#' A product of spreads and costs near the limits of a double can overflow +#' to `Inf` or underflow to 0. Scaled first, each lies between 0 and 2, so +#' their product does neither while its ratios are within the range of a +#' double. A power of two changes no digit of a value in that range, so a +#' split whose products stay in range is the same to the last bit. The +#' scaling is done in two steps because the power can exceed the largest +#' double for a subnormal `x`. +#' +#' @noRd +pow2_scale <- function(x) { + top <- max(x, 0) + if (!(top > 0) || !is.finite(top)) return(x) + e <- -floor(log2(top)) + half <- trunc(e / 2) + x * 2^half * 2^(e - half) +} + +#' Continuous allocation between a floor and a cap +#' +#' 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. It can also +#' give a group fewer rows than the floor `lower`. The textbook remedy +#' (Cochran 1977, section 5.9) fixes such a group at its bound and re-splits +#' what is left over the others *in the same proportions*. Raising a group to +#' its floor by taking rows from the others one at a time instead spreads the +#' cost evenly and abandons the allocation rule that was asked for. +#' +#' Each group gets `lambda * share`, held between `lower` and its cap, with +#' the one `lambda` that makes the total `n`; `split_level()` finds it. Under +#' Neyman allocation that is the allocation of least variance within the +#' bounds. Groups whose share is 0, Neyman strata whose values do not vary, +#' get their floor. When even taking every group with a share whole leaves +#' rows over, those go to the groups without a share in proportion to their +#' size, as `allocate()` does when no group has a share. +#' +#' @noRd +capped_shares <- function(n, share, sizes, cap, + lower = numeric(length(sizes))) { + upper <- if (cap) sizes else rep(Inf, length(sizes)) + pos <- share > 0 + raw <- lower + if (sum(upper[pos]) + sum(lower[!pos]) < n) { + raw[pos] <- upper[pos] + raw[!pos] <- bounded_split(n - sum(upper[pos]), sizes[!pos], lower[!pos], + upper[!pos]) + } else { + raw[pos] <- bounded_split(n - sum(lower[!pos]), share[pos], lower[pos], + upper[pos]) + } + raw +} + +#' What the rule asks of each group, at the level the bounds settle on +#' +#' The `lambda * share` that `capped_shares()` holds between the floor and +#' the cap, before the holding: above a group's size when the cap keeps it +#' from more rows, below its floor when the floor gives it more than its +#' share. Groups with a share get `Inf` when even taking all of them whole +#' leaves rows over, and the groups without one then claim in proportion to +#' size, as `capped_shares()` splits those rows. +#' +#' @noRd +share_claim <- function(n, share, sizes, cap, lower) { + sizes <- as.numeric(sizes) + upper <- if (cap) sizes else rep(Inf, length(sizes)) + pos <- share > 0 + claim <- numeric(length(sizes)) + if (sum(upper[pos]) + sum(lower[!pos]) < n) { + claim[pos] <- Inf + if (any(!pos)) { + claim[!pos] <- split_level(n - sum(upper[pos]), sizes[!pos], + lower[!pos], upper[!pos]) * sizes[!pos] } + } else if (any(pos)) { + claim[pos] <- split_level(n - sum(lower[!pos]), share[pos], lower[pos], + upper[pos]) * share[pos] + } + claim +} + +#' Why each group was allocated the rows it was +#' +#' `"empty"` for a group allocated no rows. Without replacement, +#' `"capped"` for one the rule asked more rows of than it holds, and +#' `"take-all"` for one taken whole for another reason: a share that comes to +#' its size, or a size below the floor. `"floor"` for a group raised to +#' `min_per_stratum` from a smaller share, and `"rule"` for the rest. +#' `share` and `lower` are as `allocate()` computes them. +#' +#' @noRd +allocation_status <- function(n, n_alloc, sizes, share, lower, cap) { + sizes <- as.numeric(sizes) + claim <- share_claim(as.numeric(n), share, sizes, cap, lower) + # The level is found in floating point, so a share that comes to a bound + # exactly can land a rounding error either side of it. + tol <- 1e-9 * pmax(1, sizes) + status <- rep("rule", length(sizes)) + status[claim < lower - tol] <- "floor" + if (cap) { + status[n_alloc == sizes] <- "take-all" + status[claim > sizes + tol] <- "capped" + } + status[n_alloc == 0L] <- "empty" + status +} + +#' Split `n` in proportion to positive `share`, between `lower` and `upper` +#' +#' Needs `sum(lower) <= n <= sum(upper)`. The groups held at a bound are found +#' from `split_level()`, and the others share what is left as +#' `left * share / sum(share)`. A split that no bound touches is therefore +#' `n * share / sum(share)` to the last bit, and equal remainders tie. +#' +#' @noRd +bounded_split <- function(n, share, lower, upper) { + if (!length(share)) return(numeric(0)) + at <- split_level(n, share, lower, upper) * share + low <- at <= lower + high <- !low & at >= upper + free <- !low & !high + raw <- ifelse(low, lower, upper) + if (any(free)) { + left <- n - sum(raw[!free]) + raw[free] <- pmin(pmax(left * share[free] / sum(share[free]), + lower[free]), upper[free]) } raw } +#' The `lambda` at which `sum(pmin(pmax(lambda * share, lower), upper))` is `n` +#' +#' The sum is piecewise linear in `lambda` and never decreasing. A group starts +#' to grow at `lower / share` and stops at `upper / share`. Bisection over +#' those knots finds the last one at which the sum is at most `n`, in time +#' that grows as `k log k`, and the level lies on the segment after it, where +#' the sum is the rows of the groups held at a bound plus `lambda` times the +#' shares of the others. Both are summed afresh over the groups. A running +#' sum of slopes, raised by a share at one knot and lowered by it at +#' another, loses a small share added to a much larger one, and with shares +#' many orders of magnitude apart its level can lie far past `n`. +#' +#' @noRd +split_level <- function(n, share, lower, upper) { + from <- lower / share + to <- upper / share + knot <- c(from, to) + knot <- sort(unique(knot[is.finite(knot)]), method = "radix") + if (!length(knot)) return(0) + total <- function(lambda) sum(pmin(pmax(lambda * share, lower), upper)) + a <- 1L + b <- length(knot) + while (a < b) { + m <- (a + b + 1L) %/% 2L + if (total(knot[m]) <= n) a <- m else b <- m - 1L + } + at <- knot[a] + free <- from <= at & to > at + slope <- sum(share[free]) + if (slope <= 0) return(at) + held <- sum(lower[from > at]) + sum(upper[to <= at]) + max(at, (n - held) / slope) +} + #' 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. +#' auxiliary variable is constant. It is almost never what was meant. An `n` +#' of 0 asks for no rows at all and is not warned about. +#' +#' `flat` marks the groups that Neyman allocation gave no share because the +#' column `by` does not vary within them, or, with `by` `NULL`, because the +#' standard deviations given for them are 0. Raising `n` reaches those only +#' once every other group is taken whole, so their message does not suggest +#' it. +#' `fix` replaces the closing advice, for counts given per stratum. #' #' 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] +warn_empty_groups <- function(n_alloc, sizes, labels, noun = "stratum", + arg = "min_per_stratum", flat = NULL, + by = NULL, fix = NULL) { + if (sum(n_alloc) == 0) return(invisible(NULL)) + empty <- which(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, ") ", + nouns <- c(noun, sub("um$", "a", noun)) + flat <- if (is.null(flat)) logical(length(empty)) else flat[empty] + cause <- "" + if (any(flat)) { + some <- !all(flat) + many <- sum(flat) > 1L + who <- if (some) quote_labels(labels[empty[flat]]) else if (many) "them" + else "it" + cause <- paste0( + if (is.null(by)) { + paste0("`allocation_by` gives ", who, " a standard deviation of 0") + } else { + paste0("`", by, "` is constant within ", who) + }, + ", so Neyman allocation gives ", if (many) "them" else "it", + " no share until every other ", noun, " is taken whole. ") + } + fix <- fix %||% paste0( + if (all(flat)) "Set " else "Raise `n`, or set ", arg, " = 1 (or 2, so ", + "each ", noun, " also supports a variance).") + warn_drawn(paste0( + length(empty), " ", nouns[if (plural) 2L else 1L], + " (", quote_labels(labels[empty]), ") ", 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))) + "leaves them out entirely. ", cause, fix + ), "drawn_empty_stratum") +} + +#' Up to five group labels for a message, quoted, and how many more +#' @noRd +quote_labels <- function(labels, max = 5L) { + shown <- paste0("`", group_label(utils::head(labels, max)), "`", + collapse = ", ") + if (length(labels) > max) { + shown <- paste0(shown, " and ", length(labels) - max, " more") + } + shown +} + +# ---- per-stratum values given by the user --------------------------------- + +#' Per-stratum values as a data frame of the strata columns and `value` +#' +#' `spec` is a named vector, for a single `strata` column, whose names are +#' that column's values as text; or a data frame holding the `strata` columns +#' and the `value` column(s). Either way the result is a plain data frame of +#' those columns and nothing else, one row per stratum. A missing stratum +#' value and a stratum given twice are refused. What the values must be is +#' for the caller to check. +#' +#' @noRd +strata_frame <- function(spec, strata, arg, value = "n") { + cols <- c(strata, value) + if (is.data.frame(spec)) { + if (any(strata %in% value)) { + stop("`", arg, "` holds its values in a column named ", + paste0("`", value, "`", collapse = ", "), ", which is also a ", + "`strata` column. Rename the strata column in `data` and in `", + arg, "`.", call. = FALSE) + } + validate_data(spec, cols, arg) + check_key_columns(spec, strata, arg) + out <- lapply(cols, function(col) spec[[col]]) + } else { + if (length(strata) != 1L) { + stop("`", arg, "` is a vector, which names one `strata` column's ", + "values, but `strata` has ", length(strata), " columns. Pass a ", + "data frame with columns ", + paste0("`", utils::head(cols, -1L), "`", collapse = ", "), + " and `", utils::tail(cols, 1L), "` instead.", call. = FALSE) + } + if (!length(spec) || is.null(names(spec)) || anyNA(names(spec))) { + stop("`", arg, "` must be named by stratum, as in ", + "c(north = 10, south = 5), or be a data frame with columns `", + strata, "` and `", value[1], "`.", call. = FALSE) + } + out <- list(names(spec), unname(spec)) + } + names(out) <- cols + out <- structure(out, class = "data.frame", + row.names = seq_along(out[[1L]])) + + key <- group_key(out, strata) + if (anyNA(key)) { + stop(sum(is.na(key)), " row(s) of `", arg, "` have a missing stratum ", + "value. Every row must name a stratum.", call. = FALSE) + } + twice <- unique(as.integer(key)[duplicated(as.integer(key))]) + if (length(twice)) { + stop("`", arg, "` gives ", + if (length(twice) == 1L) "stratum " else "strata ", + quote_labels(levels(key)[twice]), " more than once. Give each ", + "stratum once.", call. = FALSE) + } + out +} + +#' Match per-stratum values given by the user to the strata of a frame +#' +#' `spec` is as for `strata_frame()`. A named vector is matched to the values +#' of the `strata` column as text, as `as.character()` gives them; a data +#' frame is matched on the values themselves, as `group_key2()` compares +#' them, so a number or a date is matched exactly. Returns a data frame of +#' the `value` columns with one row per stratum of `data`, in key order: the +#' levels of `key`, which is `group_key(data, strata)`. A stratum of `data` +#' with no entry is refused by name, so a misspelt stratum cannot quietly +#' get nothing. An entry for a stratum `data` does not have is refused too, +#' unless `ignore_extra`: a count promises rows from its stratum, while a +#' standard deviation or a cost for a stratum with no rows changes nothing, +#' and the same values then serve a part of the frame, such as the `rest` +#' of `design_certainty()`. +#' +#' @noRd +match_strata <- function(spec, data, strata, arg, value = "n", + key = group_key(data, strata), + ignore_extra = FALSE) { + spec <- strata_frame(spec, strata, arg, value) + both <- group_key2(spec, data, strata) + given <- as.integer(both$x) + # Each stratum of `data` on the shared codes, read at its first row. + have <- as.integer(both$table)[match(seq_len(nlevels(key)), + as.integer(key))] + pos <- match(have, given) + if (anyNA(pos)) { + lost <- levels(key)[is.na(pos)] + stop("`", arg, "` has no entry for ", length(lost), " ", + if (length(lost) == 1L) "stratum" else "strata", " of `data`: ", + quote_labels(lost), ". Give one for every stratum.", call. = FALSE) + } + extra <- which(!(given %in% have)) + if (length(extra) && !ignore_extra) { + stop("`", arg, "` names ", length(extra), " ", + if (length(extra) == 1L) "stratum" else "strata", + " that `data` does not have: ", + quote_labels(levels(both$x)[given[extra]]), ". Check the ", + "spelling, or drop ", if (length(extra) == 1L) "it" else "them", ".", + call. = FALSE) + } + out <- spec[pos, value, drop = FALSE] + row.names(out) <- NULL + out } -#' Evaluate `code`, silencing the empty-stratum warning +#' Refuse a count for a stratum whose every row `na_rm` drops #' -#' For loops that draw the same design many times on purpose; the result they -#' return already shows the unreachable rows as zeros. +#' A spread or weighted design splits `n` over the strata of the rows it +#' keeps, so a stratum `na_rm` empties is not one of them, and +#' `match_strata()` would refuse its count as one for a stratum `data` does +#' not have. This names the reason instead. `key` is `group_key()` of the +#' `strata` over every row of `data`, `keep` the rows kept, and `what` why +#' the others were dropped, as in "a missing weight in `w`". #' #' @noRd -quietly_empty <- function(code) { - withCallingHandlers(code, drawn_empty_stratum = function(w) { - invokeRestart("muffleWarning") - }) +refuse_emptied_counts <- function(design, data, key, keep, what) { + if (!has_counts(design)) return(invisible(NULL)) + code <- as.integer(key) + k <- nlevels(key) + emptied <- which(tabulate(code, k) > 0L & tabulate(code[keep], k) == 0L) + if (!length(emptied)) return(invisible(NULL)) + spec <- strata_frame(design$allocation, design$strata, "allocation") + both <- group_key2(spec, data, design$strata) + first <- match(emptied, code) + named <- emptied[as.integer(both$table)[first] %in% as.integer(both$x)] + if (!length(named)) return(invisible(NULL)) + one <- length(named) == 1L + stop("`allocation` gives ", + if (one) "a count for stratum " else "counts for strata ", + quote_labels(levels(key)[named]), ", but na_rm = TRUE drops every ", + "row of ", if (one) "it" else "them", " for ", what, ". Fill in ", + "those values, or leave ", if (one) "the stratum" else "those strata", + " out of `allocation`.", call. = FALSE) } diff --git a/R/clusters.R b/R/clusters.R index c5b7e24..3592c4b 100644 --- a/R/clusters.R +++ b/R/clusters.R @@ -1,54 +1,243 @@ # Stage-one cluster selection, shared by design_cluster() and # design_multistage(). # -# Both designs select clusters the same way, and the two subtle traps here -- -# sample() reinterpreting a length-one numeric cluster id as a range, and `==` -# against an NA label fabricating all-NA rows -- are easy to reintroduce. One -# copy means one place to get them right. +# Both designs select clusters the same way. Every later step compares +# cluster labels, from the probabilities and the variance to the degrees of +# freedom and the hand-off to `survey`. Comparing them as text merges two +# numbers that print alike, such as 0.3 and 0.1 + 0.2, and counting them with +# table() turns a factor's unused levels into clusters of no rows. Each row's +# cluster is therefore an integer code, and the codes are built in one place. + +#' Integer codes for cluster labels +#' +#' Codes number the distinct labels in order of first appearance. Labels are +#' compared on their stored values: doubles exactly, dates and times on their +#' underlying numbers, factors by level, so a level no row uses has no code. A +#' missing label gets `NA`. +#' +#' @noRd +cluster_codes <- function(labels) { + v <- cluster_values(labels) + match(v, unique(v[!is.na(v)])) +} + +#' The values cluster labels are compared on +#' +#' A factor's level numbers, the underlying numbers of a date or time, text +#' as `key_text()` gives it, and any other vector as it is. Through +#' `key_text()` an unmarked label and a UTF-8 one with the same bytes are one +#' cluster in every locale, as they are one stratum. +#' +#' @noRd +cluster_values <- function(labels) { + if (is.factor(labels)) { + as.integer(labels) + } else if (is.object(labels) && is.atomic(labels)) { + unclass(labels) + } else { + key_text(labels) + } +} #' Validate the cluster column and select clusters at random #' +#' Clusters are numbered in order of first appearance and `n_clusters` of +#' those numbers are sampled, so the clusters chosen for a seed are the ones +#' `sample(unique(labels), n_clusters)` would give. Sampling the numbers also +#' keeps `sample()` from reading a single numeric cluster id as a range. The +#' rows of the chosen clusters are found in one pass over the frame. +#' +#' A multistage design with `size` selects the numbers by systematic PPS +#' over the clusters' stage-one probabilities in `cl$pi1`, with clusters at +#' probability 1 always among them. +#' #' @param design A cluster or multistage design. #' @param data The population. +#' @param cl `cluster_setup(design, data)`, when the caller has it already. #' @return A list of `data` (with NA labels handled), the row indices of each -#' selected cluster, and their sizes. +#' selected cluster, their sizes, their labels, and their codes in +#' `chosen`, all in the order the clusters were selected. #' @noRd -select_clusters <- function(design, data) { - validate_data(data, required_columns = design$clusters) - check_key_columns(data, design$clusters, "clusters") +select_clusters <- function(design, data, cl = cluster_setup(design, data)) { + # Dropping rows with no label leaves every other row's code unchanged, since + # codes number the labels in order of first appearance. + if (!all(cl$present)) data <- reindex(data, which(cl$present)) + code <- cl$code[cl$present] + labels <- cl$labels[cl$present] + k <- cl$total - col <- design$clusters - data <- drop_na_rows(data, is.na(data[[col]]), design$na_rm, - "a missing cluster label") - labels <- data[[col]] - levels_present <- unique(labels) - - if (design$n_clusters > length(levels_present)) { - stop("`n_clusters` (", design$n_clusters, ") exceeds the ", - length(levels_present), " cluster(s) available.", call. = FALSE) + chosen <- if (is.null(cl$pi1)) { + sample.int(k, size = design$n_clusters) + } else { + systematic_pps(cl$pi1) } + pos <- match(code, chosen) + hit <- which(!is.na(pos)) + idx <- split(hit, structure(pos[hit], + levels = as.character(seq_along(chosen)), + class = "factor")) + names(idx) <- NULL - chosen <- sample_values(levels_present, design$n_clusters) - - # `%in%`, never `==`: NA == "a" is NA, and indexing with NA manufactures - # all-NA rows that were never in the data. - idx <- lapply(chosen, function(cl) which(labels %in% cl)) - names(idx) <- as.character(chosen) - - list(data = data, idx_by_cluster = idx, sizes = lengths(idx)) + list(data = data, idx_by_cluster = idx, sizes = lengths(idx), + labels = labels[match(chosen, code)], chosen = as.integer(chosen)) } -#' How many distinct clusters the population holds +#' Each row's cluster, and how many distinct clusters the population holds +#' +#' Shared by the two designs' probabilities, variances and hand-off to +#' `survey`. `code` is each row's cluster from `cluster_codes()`, `NA` where +#' the label is missing, and `total` the number of clusters, the `A` in the +#' stage-one selection probability `n_clusters / A`. `values` holds the +#' value each code stands for, as `cluster_values()` gives it, so rows of +#' another frame can be coded alike. #' -#' Shared by the two designs' inclusion probabilities, both of which need the -#' stage-one selection probability `n_clusters / n_clusters_total`. +#' A multistage design with `size` cannot place a row whose size is missing, +#' so such a row has no code, like a row with no label, and the clusters are +#' numbered over the rows left. #' #' @noRd count_clusters <- function(design, data) { - validate_data(data, required_columns = design$clusters) + validate_data(data, required_columns = c(design$clusters, design$size)) check_key_columns(data, design$clusters, "clusters") labels <- data[[design$clusters]] - list(labels = labels, - present = !is.na(labels), - total = length(unique(labels[!is.na(labels)]))) + v <- cluster_values(labels) + if (!is.null(design$size)) { + check_key_columns(data, design$size, "size") + v[is.na(data[[design$size]])] <- NA + } + values <- unique(v[!is.na(v)]) + code <- match(v, values) + present <- !is.na(code) + list(labels = labels, code = code, present = present, + total = if (any(present)) max(code[present]) else 0L, + values = values) +} + +#' Refuse a cluster selection the frame cannot supply +#' +#' The checks the draw and the probabilities of both cluster designs share: +#' the `na_rm` policy, a frame with no labelled row, and more clusters asked +#' for than it holds. Without them [inclusion_prob()] gave `n_clusters / A` +#' above 1 where [draw()] refused. Returns `count_clusters()`. +#' +#' @noRd +cluster_setup <- function(design, data) { + cl <- count_clusters(design, data) + unlabelled <- is.na(cl$labels) + check_na_policy(unlabelled, design$na_rm, "a missing cluster label") + if (!is.null(design$size)) { + check_na_policy(!cl$present & !unlabelled, design$na_rm, + paste0("a missing size in `", design$size, "`")) + } + if (!any(cl$present)) { + stop("Every row has a missing cluster label", + if (!is.null(design$size)) " or size", ".", call. = FALSE) + } + if (design$n_clusters > cl$total) { + stop("`n_clusters` (", design$n_clusters, ") exceeds the ", cl$total, + " cluster(s) available.", call. = FALSE) + } + cl +} + +# ---- weights conditional on the clusters selected ---------------------------- + +#' Does draw(weights = TRUE) weight a design conditional on its clusters? +#' +#' Balanced cluster sampling takes from each selected cluster as many rows as +#' the smallest of them holds, and a multistage design without `size` splits +#' `n` over the clusters it selected. When that split is not the same for +#' every selection, under proportional allocation, an `n` that `n_clusters` +#' does not divide, or a cluster smaller than `n / n_clusters`, a row's +#' probability depends on which other clusters were selected. Such a design +#' is weighted conditional on the clusters selected; see +#' `conditional_inclusion()`. A design drawn with replacement is not, since +#' draw() refuses it weights. +#' +#' @noRd +conditional_design <- function(design, data) { + if (inherits(design, "drawn_design_cluster")) { + return(isTRUE(design$balanced)) + } + if (!inherits(design, "drawn_design_multistage") || + !is.null(design$size) || design$replace) { + return(FALSE) + } + cl <- count_clusters(design, data) + !multistage_fixed(design, tabulate(cl$code, cl$total)) +} + +#' Refuse a conditionally weighted draw before anything is sampled +#' +#' The checks of the design's own setup, and a floor of one row per selected +#' cluster. Proportional allocation with `min_per_cluster = 0` can give a +#' selected cluster no rows, and weights conditional on the selection would +#' then count that cluster's total as 0 while scaling the others by +#' `A / a` as if it had been measured. Returns the setup. +#' +#' @noRd +conditional_setup <- function(design, data) { + if (inherits(design, "drawn_design_multistage") && + design$allocation == "proportional" && design$min_per_cluster < 1L) { + stop("`min_per_cluster` is 0, so proportional allocation can give a ", + "selected cluster no rows, and `weights = TRUE` weights each row ", + "conditional on the clusters selected, which would count that ", + "cluster's total as 0. Set min_per_cluster = 1 or more.", + call. = FALSE) + } + if (inherits(design, "drawn_design_multistage")) { + multistage_setup(design, data) + } else { + cluster_setup(design, data) + } +} + +#' The rows each selected cluster gives +#' +#' `sizes` holds the selected clusters' row counts, in the order they were +#' selected. A balanced cluster design takes the smallest of them from every +#' cluster, a whole-cluster design takes them all, and a multistage design +#' splits `n` with `multistage_takes()`. +#' +#' @noRd +cluster_takes <- function(design, sizes) { + if (inherits(design, "drawn_design_multistage")) { + return(multistage_takes(design, sizes)) + } + if (design$balanced) rep(min(sizes), length(sizes)) else sizes +} + +#' Inclusion probabilities conditional on the clusters selected +#' +#' For a design that `conditional_design()` accepts, `selection` holds the +#' codes of the clusters a draw selected, in the order it selected them, +#' which is the order the allocation breaks ties in. A row of selected +#' cluster `i`, of `N_i` rows, gets `(a / A) * m_i / N_i`: the chance that +#' its cluster is selected, times the chance that it is drawn once these +#' clusters are, with `m_i` the rows the design takes from cluster `i` given +#' this selection. Weighting by its reciprocal turns each selected cluster's +#' rows into `A / a` times an unbiased estimate of the cluster's total, so +#' the estimate of the total is unbiased given the selection, and therefore +#' over every selection. +#' +#' A row of a cluster that was not selected gets `NA`. The selection does not +#' fix its probability, and the design has no closed form for it. A row the +#' design drops, for a missing cluster label, gets 0. +#' +#' @noRd +conditional_inclusion <- function(design, data, selection) { + cl <- conditional_setup(design, data) + sizes <- tabulate(cl$code, cl$total) + take <- cluster_takes(design, sizes[selection]) + if (any(take < 1L)) { + stop("The allocation gives ", sum(take < 1L), " of the clusters ", + "selected no rows, so weights conditional on the selection would ", + "count their totals as 0. Set min_per_cluster = 1 or more.", + call. = FALSE) + } + p <- rep(NA_real_, cl$total) + p[selection] <- design$n_clusters / cl$total * take / sizes[selection] + out <- numeric(nrow(data)) + out[cl$present] <- p[cl$code[cl$present]] + out } diff --git a/R/design-bootstrap.R b/R/design-bootstrap.R index c18bd65..1327086 100644 --- a/R/design-bootstrap.R +++ b/R/design-bootstrap.R @@ -1,29 +1,62 @@ #' Bootstrap sampling #' -#' Generates bootstrap replicates. `"simple"` resamples rows independently; -#' `"block"` is a moving-block bootstrap, which preserves the serial dependence -#' in ordered data by concatenating `ceiling(n / block_length)` independently -#' chosen blocks per replicate. +#' Generates bootstrap replicates. `"simple"` resamples rows independently. +#' `"block"` is the moving-block bootstrap (Künsch 1989), which keeps the +#' serial dependence in ordered data by concatenating `ceiling(n / +#' block_length)` runs of `block_length` consecutive rows per replicate, each +#' starting at a row chosen at random. A run must fit inside the frame, so +#' fewer runs cover the first and last `block_length - 1` rows, and the first +#' row and the last turn up only `1 / block_length` as often as a row in the +#' middle. `"circular"` (Politis and Romano 1992) joins the last row to the +#' first, so a run can wrap around the end and every row turns up equally +#' often on average. #' -#' [draw()] returns all replicates in one data frame with a leading `.replicate` -#' column. Split them with `split(out, out$.replicate)`. +#' By default [draw()] returns all replicates in one data frame with a leading +#' `.replicate` column. Split them with `split(out, out$.replicate)`. That +#' frame holds `n_replicates * n` rows, a copy of the data for each replicate, +#' and [draw()] warns, with class `drawn_bootstrap_size`, when it would exceed +#' 10 million rows. `output = "indices"` and `output = "weights"` return the +#' same replicates as a matrix instead. #' #' @param n_replicates Number of replicates to generate. #' @param n Rows per replicate. `NULL` uses `nrow(data)`, the standard -#' nonparametric bootstrap. -#' @param method `"simple"` or `"block"`. -#' @param block_length Block length for `method = "block"`, and an error for -#' `method = "simple"`, where it would have no effect. `NULL` uses -#' `floor(nrow(data)^(1/3))`, a common rule of thumb. +#' nonparametric bootstrap. `n = 0` gives replicates with no rows. The +#' frame then has no rows but keeps its `.replicate` column, so `split()` +#' returns no replicates at all, while +#' `split(out, factor(out$.replicate, seq_len(n_replicates)))` returns +#' `n_replicates` empty ones. A plan from [plan_size()] gives its `n`. +#' @param method `"simple"`, `"block"` or `"circular"`. +#' @param block_length Run length for `method = "block"` and `"circular"`, and +#' an error for `method = "simple"`, where it would have no effect. `NULL` +#' uses `floor(nrow(data)^(1/3))`, a common rule of thumb. +#' @param output What [draw()] returns. +#' * `"rows"`, the default, returns the resampled rows of every replicate in +#' one data frame, with a leading `.replicate` column. +#' * `"indices"` returns an integer matrix with `n` rows and a column per +#' replicate, holding the rows of `data` that each replicate drew, in +#' order. Row `i` of replicate `r` is `data[out[i, r], ]`. +#' * `"weights"` returns an integer matrix with a row for each row of `data` +#' and a column per replicate, holding the number of times each replicate +#' drew that row. With the default `n`, these are replicate weights for +#' `survey::svrepdesign(type = "bootstrap", combined.weights = TRUE)`. +#' +#' For one seed, all three hold the same replicates. #' #' @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). +#' or mean, use the estimators there. +#' +#' Resampling rows treats them as independent draws from one distribution. +#' For such data and a statistic those estimators do not cover, such as a +#' median, the bootstrap is the standard tool. A sample drawn with strata or +#' clusters is not such data, and resampling its rows one by one ignores the +#' strata and treats the rows of a cluster as independent. Resample the +#' clusters within strata instead, for example with +#' `survey::as.svrepdesign(as_svydesign(s), type = "subbootstrap")`. Runs of +#' rows keep short-range dependence in ordered data (Künsch 1989). #' #' @return A design object, for use with [draw()]. #' @@ -34,6 +67,10 @@ #' Künsch, H. R. (1989). The jackknife and the bootstrap for general #' stationary observations. *Annals of Statistics*, 17, 1217–1241. #' +#' Politis, D. N. and Romano, J. P. (1992). A circular block-resampling +#' procedure for stationary data. In R. LePage and L. Billard (eds.), +#' *Exploring the Limits of Bootstrap*, 263–270. Wiley. +#' #' @examples #' df <- data.frame(id = 1:100, value = (1:100) / 10) #' @@ -43,65 +80,149 @@ #' # A statistic per replicate #' vapply(split(reps, reps$.replicate), function(r) mean(r$value), numeric(1)) #' +#' # The same replicates as row numbers, without copying the data +#' idx <- draw(df, design_bootstrap(n_replicates = 5, n = 20, +#' output = "indices"), seed = 1) +#' apply(idx, 2, function(i) mean(df$value[i])) +#' +#' # Runs of 10 rows that may wrap from the last row to the first +#' circ <- draw(df, design_bootstrap(n_replicates = 200, method = "circular", +#' block_length = 10, output = "weights"), +#' seed = 1) +#' range(rowMeans(circ)) +#' #' @family designs #' @seealso [draw()] #' @export design_bootstrap <- function(n_replicates = 1000L, n = NULL, - method = c("simple", "block"), - block_length = NULL) { - method <- match.arg(method) + method = c("simple", "block", "circular"), + block_length = NULL, + output = c("rows", "indices", "weights")) { + method <- check_choice(method, c("simple", "block", "circular"), "method") + output <- check_choice(output, c("rows", "indices", "weights"), "output") if (method == "simple" && !is.null(block_length)) { - stop("`block_length` only applies to method = \"block\". Set the method, ", - "or leave `block_length` as NULL.", call. = FALSE) + stop("`block_length` only applies to method = \"block\" or ", + "\"circular\". Set the method, or leave `block_length` as NULL.", + call. = FALSE) } new_design("bootstrap", list( n_replicates = check_count(n_replicates, "n_replicates", allow_zero = FALSE), - n = if (is.null(n)) NULL else check_count(n, "n"), + n = if (is.null(n)) NULL else check_count(plan_n(n), "n"), method = method, block_length = if (is.null(block_length)) NULL else - check_count(block_length, "block_length", allow_zero = FALSE) + check_count(block_length, "block_length", allow_zero = FALSE), + output = output )) } #' @export draw_design.drawn_design_bootstrap <- function(design, data) { validate_data(data) - if (".replicate" %in% names(data)) { + # A design saved before `output` existed returns rows, as it did then. + output <- design$output %||% "rows" + if (output == "rows" && ".replicate" %in% names(data)) { stop("`data` already has a column called `.replicate`, which labels the ", "bootstrap replicates. Rename it.", call. = FALSE) } n_rows <- nrow(data) n <- design$n %||% n_rows + if (output == "rows" && as.numeric(n) * design$n_replicates > 1e7) { + warn_drawn(paste0( + "`design_bootstrap()` returns ", + fmt_n(as.numeric(n) * design$n_replicates), " rows here, ", + fmt_n(design$n_replicates), " replicates of ", fmt_n(n), ". ", + "output = \"indices\" or \"weights\" gives the same replicates as a ", + "matrix of row numbers or counts." + ), "drawn_bootstrap_size") + } - if (design$method == "block") { - block_length <- design$block_length %||% max(1L, floor(n_rows^(1 / 3))) + idx <- bootstrap_index(design, n_rows, n) + switch(output, + indices = idx, + weights = { + counts <- vapply(seq_len(ncol(idx)), + function(r) tabulate(idx[, r], nbins = n_rows), + integer(n_rows)) + dim(counts) <- c(n_rows, ncol(idx)) + counts + }, + rows = { + out <- reindex(data, as.vector(idx)) + k <- ncol(out) + # cbind() on a data.frame demotes a tibble, and every other design keeps + # the input's class, so the column is built in place. It is moved to the + # front by position, since selecting by name drops a duplicated column + # name from a tibble. A data frame's `[[<-` and `[` make duplicated + # names unique, so the names are set last. + out[[".replicate"]] <- rep(seq_len(ncol(idx)), each = n) + out <- out[, c(k + 1L, seq_len(k)), drop = FALSE] + names(out) <- c(".replicate", names(data)) + out + } + ) +} + +#' The rows each bootstrap replicate draws +#' +#' An integer matrix with `n` rows and one column per replicate. Replicates +#' are drawn one after another, with the same calls to the random number +#' generator as when each replicate was built and subset on its own. +#' +#' @noRd +bootstrap_index <- function(design, n_rows, n) { + method <- design$method + if (method != "simple") { + block_length <- bootstrap_block_length(design, n_rows) if (block_length > n_rows) { stop("`block_length` (", block_length, ") exceeds the number of rows (", n_rows, ").", call. = FALSE) } + n_blocks <- ceiling(n / block_length) + offset <- rep(seq_len(block_length) - 1L, times = n_blocks) + keep <- seq_len(n) } - - parts <- lapply(seq_len(design$n_replicates), function(i) { - idx <- if (design$method == "simple") { - sample.int(n_rows, size = n, replace = TRUE) - } else { - n_blocks <- ceiling(n / block_length) + one <- switch(method, + simple = function() sample.int(n_rows, size = n, replace = TRUE), + block = function() { starts <- sample.int(n_rows - block_length + 1L, n_blocks, replace = TRUE) - # Several blocks per replicate, so it is not confined to one run. - unlist(lapply(starts, function(s) s:(s + block_length - 1L)), - use.names = FALSE)[seq_len(n)] + (rep(starts, each = block_length) + offset)[keep] + }, + circular = function() { + starts <- sample.int(n_rows, n_blocks, replace = TRUE) + # Past the last row, a run carries on from the first. In doubles, so a + # frame of more than 2^30 rows cannot overflow. + at <- (rep(as.numeric(starts), each = block_length) - 1 + offset) %% + n_rows + 1 + as.integer(at[keep]) } - out <- reindex(data, idx) - # cbind() on a data.frame demotes a tibble, and every other design keeps - # the input's class. Build the column in place instead. - out[[".replicate"]] <- rep(i, nrow(out)) - out[, c(".replicate", setdiff(names(out), ".replicate")), drop = FALSE] - }) + ) + idx <- vapply(seq_len(design$n_replicates), function(r) one(), integer(n)) + dim(idx) <- c(n, design$n_replicates) + idx +} - out <- do.call(rbind, parts) - rownames(out) <- NULL - out +#' The run length of a block bootstrap: as given, else floor(N^(1/3)) +#' @noRd +bootstrap_block_length <- function(design, n_rows) { + # 64^(1/3) is 3.9999999999999996 in floating point, so the small offset + # keeps a perfect cube from rounding down. + design$block_length %||% max(1L, as.integer(floor(n_rows^(1 / 3) + 1e-9))) +} + +#' What a refusal says about how often each row appears +#' @noRd +bootstrap_counts <- function(design) { + if (identical(design$method, "block")) { + return(paste0( + "Under method = \"block\" rows do not all appear equally often. Runs ", + "must fit inside the frame, so the first and last block_length - 1 ", + "rows appear less often than the rest; under method = \"circular\" ", + "every row appears n_replicates * n / nrow(data) times on average." + )) + } + paste0("If you want the expected number of times each row appears, that is ", + "n_replicates * n / nrow(data).") } # ---- inclusion probability ------------------------------------------------ @@ -110,6 +231,5 @@ draw_design.drawn_design_bootstrap <- function(design, data) { exact_inclusion.drawn_design_bootstrap <- function(design, data) { stop("A bootstrap resamples the sample; it is not a probability sample of a ", "finite population, so it has no inclusion probability.\n", - "If you want the expected number of times each row appears, that is ", - "n_replicates * n / nrow(data).", call. = FALSE) + bootstrap_counts(design), call. = FALSE) } diff --git a/R/design-certainty.R b/R/design-certainty.R index 6b34971..ac6b9d5 100644 --- a/R/design-certainty.R +++ b/R/design-certainty.R @@ -11,6 +11,14 @@ #' nothing to its variance. That is the whole point: the uncertainty in the #' estimate comes only from the part you sampled. #' +#' A `rest` with a random sample size, such as +#' `design_weighted(method = "poisson")` with a small `n`, can draw none of the +#' rows below the threshold. Those rows then went unobserved, so [ht_total()] +#' and [ht_mean()] report no variance rather than an exact total. +#' `draw(weights = TRUE)` refuses a `rest` that can never draw any of them, +#' such as one with `n = 0`; without weights the draw is a cut-off sample of +#' the rows above the threshold. +#' #' @param above Column holding the size measure. #' @param threshold Rows with `above >= threshold` are taken with certainty. #' @param rest A design applied to the rows below the threshold. Its `n` is the @@ -42,8 +50,8 @@ #' @export design_certainty <- function(above, threshold, rest, na_rm = FALSE) { if (!is_design(rest)) { - stop("`rest` must be a design for the rows below the threshold, not a ", - class(rest)[1], ". See ?designs.", call. = FALSE) + stop("`rest` must be a design for the rows below the threshold, not ", + a_class(rest), ". See ?designs.", call. = FALSE) } if (inherits(rest, "drawn_design_certainty")) { stop("`rest` cannot itself be a certainty design; use one threshold.", @@ -55,6 +63,11 @@ design_certainty <- function(above, threshold, rest, na_rm = FALSE) { "`.replicate` column and present resampled duplicates as distinct ", "units.", call. = FALSE) } + if (reserve_size(rest) > 0L) { + stop("`rest` has `reserve = ", reserve_size(rest), "`, and a certainty ", + "design lists no reserves. Leave `reserve` out of `rest`.", + call. = FALSE) + } if (!is.numeric(threshold) || length(threshold) != 1L || is.na(threshold)) { stop("`threshold` must be a single number.", call. = FALSE) } @@ -95,6 +108,81 @@ certainty_split <- function(design, data) { rest = setdiff(seq_len(nrow(data)), take)) } +#' The certainty split, with the frame handed to `rest`, for the variance +#' +#' `certainty_split()` plus `rest_data`, the rows below the threshold, which +#' the variance estimators and the jackknife pass to `rest`. Kept in `ctx`, +#' a `variance_context()`, so the domains of one sample split the frame once. +#' +#' @noRd +certainty_parts <- function(design, data, ctx = NULL) { + from_context(ctx, "certainty", { + sp <- certainty_split(design, data) + sp$rest_data <- sp$data[sp$rest, , drop = FALSE] + sp + }) +} + +#' Describe the rows below the threshold, for messages +#' @noRd +rows_below <- function(design, n) { + paste0(n, if (n == 1L) " row" else " rows", " with `", design$above, + "` below ", format(design$threshold, big.mark = ",", + scientific = FALSE, digits = 15)) +} + +#' Evaluate a call on `rest`, saying so in any error it raises +#' +#' `rest` sees only the rows below the threshold, so its own messages count +#' those, as in "cannot exceed the number of rows (230)" on a frame of 240. +#' The prefix says which rows it was given. The condition keeps its class. +#' +#' @noRd +in_rest <- function(design, n_below, code) { + tryCatch(code, error = function(e) { + e$message <- paste0("In `rest`, applied to the ", + rows_below(design, n_below), ": ", + conditionMessage(e)) + e$call <- NULL + stop(e) + }) +} + +#' The variance when `rest` drew none of the rows below the threshold +#' +#' A `rest` with a random size, such as Poisson, can come up empty. The rows +#' below the threshold then went unobserved, and their share of the total has +#' no variance that can be measured. Calling the total exact would hide them. +#' +#' @noRd +empty_rest <- function(design, n_below) { + list(variance = NA_real_, note = paste0( + "No variance can be estimated for the ", rows_below(design, n_below), + ", because `rest` drew none of them. Use a `rest` with a fixed sample ", + "size, or a larger expected one.")) +} + +#' Refuse weights when `rest` can never draw a row below the threshold +#' +#' With every row below the threshold at probability 0, a weighted total +#' leaves those rows out and is biased low by their whole share. A cut-off +#' sample of the rows above the threshold is still a legitimate selection, so +#' only `weights = TRUE` is refused. +#' +#' @noRd +check_rest_reach <- function(design, data, p_all) { + sp <- certainty_split(design, data) + below <- sp$keep[sp$rest] + if (length(below) && all(p_all[below] == 0)) { + stop("`rest` gives all ", rows_below(design, length(below)), + " an inclusion probability of 0, so a weighted total would leave ", + "them out. Give `rest` a sample size above 0, or draw with ", + "weights = FALSE to take the rows above the threshold alone.", + call. = FALSE) + } + invisible(design) +} + #' @export draw_design.drawn_design_certainty <- function(design, data) { sp <- certainty_split(design, data) @@ -110,7 +198,8 @@ draw_design.drawn_design_certainty <- function(design, data) { call. = FALSE) } below[[key]] <- sp$rest - drawn_below <- draw_design(design$rest, below) + drawn_below <- in_rest(design, length(sp$rest), + draw_design(design$rest, below)) reindex(data, c(sp$take, drawn_below[[key]]), sort = TRUE) } @@ -122,8 +211,10 @@ exact_inclusion.drawn_design_certainty <- function(design, data) { out <- numeric(nrow(data)) # dropped rows keep their 0 out[sp$keep[sp$take]] <- 1 if (length(sp$rest)) { - out[sp$keep[sp$rest]] <- exact_inclusion(design$rest, - sp$data[sp$rest, , drop = FALSE]) + out[sp$keep[sp$rest]] <- in_rest( + design, length(sp$rest), + exact_inclusion(design$rest, sp$data[sp$rest, , drop = FALSE]) + ) } out } @@ -135,19 +226,19 @@ joint_inclusion.drawn_design_certainty <- function(design, data, rows) { k <- length(rows) out <- matrix(0, k, k) - is_certain <- rows %in% sp$keep[sp$take] + above <- rows %in% sp$keep[sp$take] # A certainty row is in every sample, so a pair containing one co-occurs # exactly when the other row is drawn. - if (any(is_certain)) { - out[is_certain, ] <- rep(pi_all[rows], each = sum(is_certain)) - out[, is_certain] <- rep(pi_all[rows], times = sum(is_certain)) - out[is_certain, is_certain] <- 1 + if (any(above)) { + out[above, ] <- rep(pi_all[rows], each = sum(above)) + out[, above] <- rep(pi_all[rows], times = sum(above)) + out[above, above] <- 1 } # A row the design dropped is in no sample, so every joint probability # involving it is 0 -- which is the answer, not an error. `rows` defaults to # the whole frame, so erroring here made the documented default unusable. - free <- which(!is_certain) + free <- which(!above) pos <- match(rows[free], sp$keep[sp$rest]) live <- free[!is.na(pos)] if (length(live)) { @@ -160,7 +251,7 @@ joint_inclusion.drawn_design_certainty <- function(design, data, rows) { out[gone, ] <- 0 out[, gone] <- 0 } - diag(out) <- pi_all[rows] + out[diag_index(k)] <- pi_all[rows] out } @@ -170,16 +261,20 @@ joint_inclusion.drawn_design_certainty <- function(design, data, rows) { #' fixed amount to the total and nothing at all to its variance. What is left is #' the variance of `rest` over the rows below the threshold -- which is where #' this hands off, so that `rest`'s own special cases (Poisson's independent -#' units, systematic's refusal) apply instead of being silently bypassed. +#' units, systematic's successive-difference estimator and its refusal of a +#' fixed start) apply instead of being silently bypassed. +#' +#' The total is exact only when the frame has no rows below the threshold. A +#' `rest` that drew none of them leaves their share unobserved. #' #' @noRd -ht_variance.drawn_design_certainty <- function(design, data, rows, y, pi_i) { - sp <- certainty_split(design, data) +ht_variance.drawn_design_certainty <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + sp <- certainty_parts(design, data, ctx) free <- !(rows %in% sp$keep[sp$take]) if (!any(free)) { - return(list(variance = 0, - note = paste0("Every sampled row was taken with certainty, so ", - "the total is exact rather than estimated."))) + if (length(sp$rest)) return(empty_rest(design, length(sp$rest))) + return(all_certain()) } pos <- match(rows[free], sp$keep[sp$rest]) if (anyNA(pos)) { @@ -187,6 +282,17 @@ ht_variance.drawn_design_certainty <- function(design, data, rows, y, pi_i) { "Some sampled rows were dropped by this design's `na_rm`, so they have ", "no place in the frame the variance is computed over."))) } - ht_variance(design$rest, sp$data[sp$rest, , drop = FALSE], pos, - y[free], pi_i[free]) + ht_variance(design$rest, sp$rest_data, pos, y[free], pi_i[free], + rest_domain(domain, sp), sub_context(ctx, "rest")) +} + +#' A domain's frame rows, restricted to the rows handed to `rest` +#' +#' `domain` is `NULL`, `NA` or a logical vector over the frame, as +#' `ht_variance_dispatch()` takes it. +#' +#' @noRd +rest_domain <- function(domain, sp) { + if (is.null(domain) || identical(domain, NA)) return(domain) + domain[sp$keep[sp$rest]] } diff --git a/R/design-cluster.R b/R/design-cluster.R index de89653..80f0469 100644 --- a/R/design-cluster.R +++ b/R/design-cluster.R @@ -7,17 +7,51 @@ #' @param clusters Column naming each row's cluster. #' @param n_clusters Number of clusters to select. #' @param balanced Take an equal number of rows from each selected cluster, -#' equal to the smallest selected cluster's size. +#' equal to the smallest selected cluster's size. See "Balanced clusters". #' @param na_rm Drop rows whose cluster label is `NA` instead of raising an #' error. When `FALSE`, missing labels are never treated as a cluster of their #' own. #' +#' @section Balanced clusters: +#' With `balanced = TRUE`, each of the `a` clusters selected out of `A` +#' gives `m` rows by simple random sampling, `m` being the size of the +#' smallest of them. A row of a cluster of `N_i` rows has inclusion +#' probability `(a / A) * E(m) / N_i`, where `E(m)` is the average take +#' over the selections that include its cluster. [inclusion_prob()] +#' computes it exactly: given that cluster `i` is selected, the take is at +#' least `s` rows when the other `a - 1` clusters selected all hold `s` rows +#' or more, which happens with probability +#' `choose(c_s - 1, a - 1) / choose(A - 1, a - 1)`, `c_s` being the number +#' of clusters of `s` rows or more, and `E(m)` adds these up for `s` from 1 +#' to `N_i`. On clusters of 2, 4, 6 and 8 rows with two selected, that gives +#' 0.5, 0.417, 0.333 and 0.25. +#' +#' `draw(weights = TRUE)` weights a balanced sample conditional on the +#' clusters it selected instead: `.prob` is `(a / A) * m / N_i` for the `m` +#' taken in this draw. The estimate of a total is then `A / a` times the sum +#' of the selected clusters' estimated totals, which is unbiased whichever +#' clusters were selected, and so over all of them. [ht_total()] and +#' [ht_mean()] use the two-stage variance of [design_multistage()], with the +#' variance between the estimated cluster totals and within each cluster, +#' and [as_svydesign()] hands the sample to `survey` in two stages. The +#' smallest selected cluster is taken whole and adds no variance within it. +#' When it holds one row, every cluster gives one, the variation within +#' clusters cannot be measured, and the variance falls back to the +#' delete-a-cluster jackknife. Joint probabilities have no closed form; +#' [joint_prob()] estimates them with `simulate = TRUE`. +#' #' @return A design object, for use with [draw()]. #' #' @examples #' df <- data.frame(id = 1:100, site = rep(paste0("s", 1:10), each = 10)) #' unique(draw(df, design_cluster("site", n_clusters = 3), seed = 1)$site) #' +#' # Balanced: the take is the smallest selected cluster's size, so a row of +#' # a large cluster is less likely to be drawn +#' uneven <- data.frame(site = rep(c("a", "b", "c", "d"), c(2, 4, 6, 8))) +#' bal <- design_cluster("site", n_clusters = 2, balanced = TRUE) +#' round(tapply(inclusion_prob(uneven, bal), uneven$site, unique), 3) +#' #' @family designs #' @seealso [draw()] #' @export @@ -36,28 +70,56 @@ draw_design.drawn_design_cluster <- function(design, data) { sel <- select_clusters(design, data) data <- sel$data keep <- if (design$balanced) { - take_within(sel$idx_by_cluster, rep(min(sel$sizes), length(sel$sizes)), - FALSE) + take_within(sel$idx_by_cluster, cluster_takes(design, sel$sizes), FALSE) } else { unlist(sel$idx_by_cluster, use.names = FALSE) } - reindex(data, keep, sort = TRUE) + out <- reindex(data, keep, sort = TRUE) + # draw(weights = TRUE) weights a balanced sample conditional on these + # clusters, and removes the attribute otherwise. + attr(out, "drawn_selection") <- sel$chosen + out } # ---- inclusion probability ------------------------------------------------ #' @noRd exact_inclusion.drawn_design_cluster <- function(design, data) { + cl <- cluster_setup(design, data) + a <- design$n_clusters + out <- numeric(nrow(data)) if (design$balanced) { - no_closed_form( - "`design_cluster(balanced = TRUE)`", - paste0("The per-cluster take is the smallest SELECTED cluster's size, ", - "which is random.\nUse balanced = FALSE for a closed form.") - ) + sizes <- tabulate(cl$code, cl$total) + p <- a / cl$total * balanced_take(sizes, a) / sizes + out[cl$present] <- p[cl$code[cl$present]] + return(out) } - cl <- count_clusters(design, data) - check_na_policy(!cl$present, design$na_rm, "a missing cluster key") - out <- rep(design$n_clusters / cl$total, nrow(data)) - out[!cl$present] <- 0 + out[cl$present] <- a / cl$total out } + +#' Each cluster's average take under balanced cluster sampling +#' +#' `a` of the `A` clusters, of `sizes` rows, are selected by simple random +#' sampling, and each gives as many rows as the smallest of them holds. For +#' cluster `i` this is that take averaged over the selections that include +#' `i`. Given `i`, the other `a - 1` are a simple random sample of the other +#' `A - 1` clusters, and the take is at least `s`, for `s` up to `N_i`, when +#' all of them hold `s` rows or more: probability +#' `choose(c_s - 1, a - 1) / choose(A - 1, a - 1)`, with `c_s` the number of +#' clusters, `i` among them, of `s` rows or more. The average take is the sum +#' of these over `s = 1, ..., N_i`. `c_s` changes only at the cluster sizes, +#' so the sum runs over the distinct sizes, in increasing order, each term +#' covering the values of `s` up to it from the size before. Computed on the +#' log scale, since the counts of selections overflow for a few hundred +#' clusters. +#' +#' @noRd +balanced_take <- function(sizes, a) { + A <- length(sizes) + d <- sort(unique(sizes)) + # Clusters of d[k] rows or more: those not of d[k] - 1 rows or fewer. + c_s <- A - findInterval(d - 1, sort(sizes)) + p <- exp(lchoose(c_s - 1, a - 1) - lchoose(A - 1, a - 1)) + cumsum(diff(c(0, d)) * p)[match(sizes, d)] +} diff --git a/R/design-multistage.R b/R/design-multistage.R index 7ded7b1..7a89ba4 100644 --- a/R/design-multistage.R +++ b/R/design-multistage.R @@ -4,22 +4,108 @@ #' second. `n` is the total across the selected clusters under both allocations, #' matching [design_stratified()]. #' +#' @section When the take depends on the clusters selected: +#' Without `size`, the `n` rows are split over the clusters selected, so a +#' cluster's take is the same in every sample only under `"equal"` +#' allocation of an `n` that divides by `n_clusters`, with no cluster +#' smaller than `n / n_clusters`. Otherwise, under `"proportional"` +#' allocation, with a remainder that goes to the largest clusters selected, +#' or with a small cluster capped at its size and its shortfall dealt to the +#' others, a row's inclusion probability depends on which other clusters +#' were selected. It is the chance of drawing the row given the clusters +#' selected, averaged over every possible selection, which has no closed +#' form, so [inclusion_prob()] refuses it. +#' +#' `draw(weights = TRUE)` weights such a sample conditional on the clusters +#' it selected. With `a` of `A` clusters selected and `m_i` of the `N_i` +#' rows of cluster `i` taken, `.prob` is `(a / A) * m_i / N_i`, and the +#' estimate of a total is `A / a` times the sum of the selected clusters' +#' estimated totals. That is unbiased whichever clusters were selected, and +#' so over all of them. [ht_total()] and [ht_mean()] estimate its variance +#' with the two-stage formula, the variance between the estimated cluster +#' totals plus that within each cluster at its own take, on `a - 1` degrees +#' of freedom, and [as_svydesign()] hands it to `survey` in two stages, +#' where the standard errors agree. The variance falls back to the +#' delete-a-cluster jackknife when a selected cluster gives one row of +#' several. Proportional allocation needs `min_per_cluster` of at least 1 +#' for weights, since a selected cluster with no rows would count as a +#' cluster total of 0. +#' +#' @section Clusters in proportion to size: +#' With `size`, the clusters are selected with probability proportional to a +#' size measure, such as a count of households from a census, by +#' systematic PPS as in [design_weighted()]: cluster `i` gets +#' `pi_i = n_clusters * M_i / sum(M)`, and a cluster large enough that this +#' passes 1 is taken with certainty, the rest of `n_clusters` being spread +#' over the others. Each selected cluster then gives the same `m = n / +#' n_clusters` rows by simple random sampling, so a row of cluster `i`, of +#' `N_i` rows, has inclusion probability `pi_i * m / N_i`. When the measure +#' is the cluster's row count and no cluster is certain, every row gets +#' `n / N`: the design is self-weighting, with a fixed number of interviews +#' per cluster. +#' +#' The measure is a property of the cluster, so every row of a cluster must +#' carry the same value; a cluster with two values is refused. `n` must be a +#' multiple of `n_clusters`, and `allocation` must be `"equal"`. +#' +#' [ht_total()] and [ht_mean()] estimate the variance as Deville's +#' approximation over the estimated totals of the selected clusters below +#' certainty, each scaled by its own `1 - pi_i`, plus the variance within the +#' selected clusters, each divided by its `pi_i`. That is the two-stage +#' estimator of [design_multistage()] without `size` when every `pi_i` is +#' equal. A cluster taken with certainty is a stratum, and adds only the +#' variance of the simple random sample within it. The degrees of freedom +#' count the clusters below certainty less one, and in each certain cluster +#' the sampled rows less one. The variance is declined when one cluster +#' below certainty is selected. With one row taken per cluster, whose +#' variation within clusters cannot be measured, [ht_total()] falls back to +#' the delete-a-cluster jackknife over the clusters below certainty, with no +#' finite population correction, and declines if a cluster taken with +#' certainty gives one row of several. In simulations of 2,000 draws +#' each from frames of 78 or 80 clusters of 10 to 600 rows, taking 2 or 5 +#' rows from each of 12 or 20 clusters, with and without clusters taken +#' with certainty, the variance averaged 0.94 to 1.02 times the true +#' variance of the total, and 95% intervals covered 93% to 95% of the time. +#' +#' [as_svydesign()] hands the design to `survey` in two stages with +#' Brewer's approximation at the first. A sample with one row from a +#' selected cluster of several goes over in one stage instead, as the +#' clusters of that jackknife, and the standard errors agree. Joint +#' probabilities have no closed form; [joint_prob()] estimates them with +#' `simulate = TRUE`. +#' #' @param clusters Column naming each row's cluster. #' @param n_clusters Number of clusters to select at stage one. -#' @param n Total rows to draw across the selected clusters. Make it a -#' multiple of `n_clusters`, and no larger than `n_clusters` times the -#' smallest cluster, if you intend to estimate: otherwise the per-cluster take -#' depends on which clusters were selected and there is no closed-form -#' inclusion probability. See [inclusion_prob()]. +#' @param n Total rows to draw across the selected clusters, at least +#' `n_clusters`, or a plan from [plan_size()]. A multiple of `n_clusters`, +#' no larger than `n_clusters` times the smallest cluster, gives every +#' selected cluster the same take and every row a closed-form inclusion +#' probability. Otherwise the take depends on which clusters were +#' selected, and `draw(weights = TRUE)` weights the sample conditional on +#' them. See "When the take depends on the clusters selected". #' @param allocation `"equal"` splits `n` evenly across the selected clusters; -#' `"proportional"` splits it in proportion to their size. +#' `"proportional"` splits it in proportion to their size, and its weights +#' are conditional on the clusters selected. Proportional allocation can +#' give a small selected cluster no rows; [draw()] then warns with class +#' `drawn_empty_cluster` and names it. #' @param min_per_cluster Minimum rows from each selected cluster. Defaults to -#' `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. +#' `0`, and `n_clusters * min_per_cluster` must not exceed `n`. A cluster +#' smaller than the minimum is taken whole. `draw(weights = TRUE)` needs at +#' least 1 under proportional allocation. 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? A selected +#' cluster then gives its full share of `n` however small it is, and a row's +#' inclusion probability is the chance of being drawn at least once, +#' `(n_clusters / N_clusters) * (1 - (1 - 1 / N_h)^m)` for a take of `m` +#' from a cluster of `N_h` rows. +#' @param na_rm Drop rows whose cluster label, or `size`, is `NA` instead of +#' raising an error. +#' @param size Optional column holding each cluster's size measure, the same +#' on every row of a cluster: positive, finite and numeric. Clusters are +#' then selected with probability proportional to it. See "Clusters in +#' proportion to size". #' #' @return A design object, for use with [draw()]. #' @@ -27,30 +113,186 @@ #' df <- data.frame(id = 1:100, site = rep(paste0("s", 1:10), each = 10)) #' nrow(draw(df, design_multistage("site", n_clusters = 4, n = 12), seed = 1)) #' +#' # Villages selected in proportion to their households, then 5 households +#' # from each: every household has the same chance, 20 / 260 +#' hh <- data.frame(village = rep(paste0("v", 1:8), +#' times = c(10, 20, 30, 40, 20, 50, 60, 30))) +#' hh$households <- ave(seq_len(nrow(hh)), hh$village, FUN = length) +#' pps <- design_multistage("village", n_clusters = 4, n = 20, +#' size = "households") +#' unique(round(inclusion_prob(hh, pps), 4)) +#' #' @family designs #' @seealso [draw()] #' @export design_multistage <- function(clusters, n_clusters, n, allocation = c("equal", "proportional"), min_per_cluster = 0L, replace = FALSE, - na_rm = FALSE) { + na_rm = FALSE, size = NULL) { + clusters <- check_columns(clusters, "clusters", 1L) + n_clusters <- check_count(n_clusters, "n_clusters", allow_zero = FALSE) + n <- check_count(plan_n(n), "n") + min_per_cluster <- check_count(min_per_cluster, "min_per_cluster") + allocation <- check_choice(allocation, c("equal", "proportional"), + "allocation") + if (n < n_clusters) { + stop("`n` (", n, ") is smaller than `n_clusters` (", n_clusters, + "), so some selected clusters would give no rows. Raise `n` to at ", + "least ", n_clusters, ", or lower `n_clusters`.", call. = FALSE) + } + if (min_per_cluster * n_clusters > n) { + stop("`min_per_cluster` = ", min_per_cluster, " across ", n_clusters, + " clusters needs at least ", min_per_cluster * n_clusters, + " rows, but `n` is ", n, ". Raise `n` or lower `min_per_cluster`.", + call. = FALSE) + } + if (!is.null(size)) { + size <- check_columns(size, "size", 1L) + if (allocation != "equal") { + stop("`allocation` is \"", allocation, "\", but with `size` every ", + "selected cluster gives the same number of rows. Leave ", + "`allocation` out, or set it to \"equal\".", call. = FALSE) + } + if (n %% n_clusters != 0L) { + lower <- n %/% n_clusters * n_clusters + stop("`n` (", n, ") is not a multiple of `n_clusters` (", n_clusters, + "), and with `size` every selected cluster gives the same number ", + "of rows. Use n = ", if (lower > 0L) paste0(lower, " or n = "), + lower + n_clusters, ".", call. = FALSE) + } + } new_design("multistage", list( - clusters = check_columns(clusters, "clusters", 1L), - n_clusters = check_count(n_clusters, "n_clusters", allow_zero = FALSE), - n = check_count(n, "n"), - allocation = match.arg(allocation), - min_per_cluster = check_count(min_per_cluster, "min_per_cluster"), + clusters = clusters, + n_clusters = n_clusters, + n = n, + allocation = allocation, + min_per_cluster = min_per_cluster, replace = check_flag(replace, "replace"), - na_rm = check_flag(na_rm, "na_rm") + na_rm = check_flag(na_rm, "na_rm"), + size = size )) } +#' Refuse a multi-stage design the frame cannot supply +#' +#' The cluster checks, and an `n` above the rows held by the `n_clusters` +#' largest clusters, which no selection can supply. Shared by the draw and the +#' probabilities, so both refuse with the same message. An `n` that only some +#' selections can supply is the draw's to refuse, against the clusters it +#' selected; the probabilities have no closed form there. Returns +#' `count_clusters()`, with `pi1`, each cluster's stage-one probability by +#' code, for a design with `size`. +#' +#' @noRd +multistage_setup <- function(design, data) { + cl <- cluster_setup(design, data) + if (!is.null(design$size)) cl$pi1 <- cluster_pi(design, data, cl) + if (!design$replace) { + sizes <- tabulate(cl$code[cl$present], cl$total) + most <- sum(sort(sizes, decreasing = TRUE)[seq_len(design$n_clusters)]) + if (design$n > most) { + stop("`n` (", design$n, ") exceeds the ", most, " row(s) available ", + "across the ", design$n_clusters, " selected cluster(s), even ", + "with the largest selected. Use replace = TRUE, raise ", + "`n_clusters`, or lower `n`.", call. = FALSE) + } + } + cl +} + +#' Each cluster's stage-one probability, in proportion to its size measure +#' +#' `pps_pi()` over one measure per cluster, in code order. The measure is +#' read from the rows of each cluster, which must agree. `cl` is +#' `cluster_setup()`. +#' +#' @noRd +cluster_pi <- function(design, data, cl) { + col <- design$size + v <- data[[col]] + check_weights(v, col) + code <- cl$code[cl$present] + v <- v[cl$present] + first <- match(seq_len(cl$total), code) + measure <- v[first] + off <- which(v != measure[code]) + if (length(off)) { + i <- off[1] + label <- cl$labels[cl$present][i] + stop("`", col, "` must hold one size for each cluster, but cluster `", + group_label(as.character(label)), "` has ", format(measure[code[i]]), + " and ", format(v[i]), ". Give every row of a cluster the ", + "cluster's size measure.", call. = FALSE) + } + pps_pi(measure, design$n_clusters) +} + +#' The stage-one selection of a multistage design with `size`, from its frame +#' +#' Each frame row's cluster `code`, `NA` for a row the design drops; the +#' `values` those codes stand for; each cluster's stage-one probability `pi1` +#' and row count `sizes`, by code; and `m`, the rows taken from each selected +#' cluster. The variance, the degrees of freedom, the jackknife and +#' `as_svydesign()` read it. +#' +#' @noRd +cluster_stage <- function(design, data) { + cl <- multistage_setup(design, data) + list(code = cl$code, values = cl$values, pi1 = cl$pi1, + sizes = tabulate(cl$code, cl$total), + m = design$n %/% design$n_clusters) +} + +#' The sampling units of a multistage sample with `size` +#' +#' A cluster selected below certainty is a primary sampling unit, and all of +#' them share one stratum. A cluster taken with certainty is a stratum of its +#' own whose units are its sampled rows, since only they were drawn at +#' random; one taken whole as well is a single unit, with no variance. For +#' the sampled rows `units` of the frame `pop`, returns each row's cluster +#' `code` in the frame's numbering, its unit `psu` and its `stratum`: 1 below +#' certainty, and `1 + code` for a cluster taken with certainty. `pop_stratum` +#' gives the stratum of every frame row, `NA` for a row the design drops. +#' +#' @noRd +cluster_units <- function(design, units, pop, ctx = NULL) { + st <- from_context(ctx, "stage_one", cluster_stage(design, pop)) + code <- match(cluster_values(units[[design$clusters]]), st$values) + A <- length(st$pi1) + certain <- is_certain(st$pi1) + whole <- certain & st$sizes <= st$m + row_unit <- certain[code] & !whole[code] + psu <- code + psu[row_unit] <- A + which(row_unit) + list(code = code, psu = psu, + stratum = ifelse(certain[code], 1L + code, 1L), + pop_stratum = ifelse(certain[st$code], 1L + st$code, 1L)) +} + #' @export draw_design.drawn_design_multistage <- function(design, data) { - sel <- select_clusters(design, data) - data <- sel$data - sizes <- sel$sizes + sel <- select_clusters(design, data, multistage_setup(design, data)) + n_alloc <- multistage_takes(design, sel$sizes) + warn_empty_clusters(n_alloc, sel$labels, design$n) + + out <- reindex(sel$data, + take_within(sel$idx_by_cluster, n_alloc, design$replace), + sort = TRUE) + # draw(weights = TRUE) weights the sample conditional on these clusters + # when the take depends on them, and removes the attribute otherwise. + attr(out, "drawn_selection") <- sel$chosen + out +} +#' Split `n` over the selected clusters +#' +#' `sizes` holds the selected clusters' row counts, in the order they were +#' selected; the allocation breaks ties in that order. Shared by the draw +#' and `conditional_inclusion()`, so the weights follow the take the draw +#' made. +#' +#' @noRd +multistage_takes <- function(design, sizes) { # Not check_draw_size(): the bound here is the rows across the SELECTED # clusters, not nrow(data), and the generic message would name the wrong # number. @@ -64,7 +306,8 @@ draw_design.drawn_design_multistage <- function(design, data) { # The denominator is the rows in the SELECTED clusters, not the population. n_alloc <- allocate(design$n, sizes, design$allocation, design$min_per_cluster, cap = !design$replace, - min_arg = "min_per_cluster") + min_arg = "min_per_cluster", + noun = c("cluster", "clusters")) if (!design$replace && sum(n_alloc) != design$n) { stop("`n` (", design$n, ") cannot be allocated across these ", @@ -72,15 +315,54 @@ draw_design.drawn_design_multistage <- function(design, data) { design$min_per_cluster, "; the allocation totals ", sum(n_alloc), " row(s).", call. = FALSE) } + n_alloc +} + +#' Does every selection give each cluster the same take? +#' +#' Equal allocation of an `n` that `n_clusters` divides, with no cluster, +#' among `sizes`, smaller than the take unless rows are drawn with +#' replacement. Otherwise the take depends on which clusters are selected. +#' +#' @noRd +multistage_fixed <- function(design, sizes) { + design$allocation == "equal" && design$n %% design$n_clusters == 0L && + (design$replace || all(sizes >= design$n %/% design$n_clusters)) +} - reindex(data, take_within(sel$idx_by_cluster, n_alloc, design$replace), - sort = TRUE) +#' Warn when the allocation leaves a selected cluster with no rows +#' +#' Proportional allocation can round a small cluster's share down to nothing. +#' The cluster was selected, but this draw takes none of its rows, so its rows +#' are missing from the sample. Unlike an empty stratum, such a cluster may get +#' rows in another draw, alongside other clusters, so the warning speaks of +#' this draw only. A cluster smaller than `min_per_cluster` is taken whole and +#' is not empty. +#' +#' @noRd +warn_empty_clusters <- function(n_alloc, labels, n) { + empty <- which(n_alloc == 0L) + if (!length(empty)) return(invisible(NULL)) + shown <- paste0("`", group_label(as.character(labels[utils::head(empty, 5L)])), + "`", collapse = ", ") + more <- if (length(empty) > 5L) paste0(" and ", length(empty) - 5L, " more") + else "" + plural <- length(empty) > 1L + warn_drawn(paste0( + "The allocation gives ", + if (plural) paste0(length(empty), " selected clusters (", shown, more, ")") + else paste0("selected cluster ", shown), + " none of the ", n, " rows, so this draw takes nothing from ", + if (plural) "them" else "it", ". Set min_per_cluster = 1 to take at least ", + "one row from every selected cluster." + ), "drawn_empty_cluster") } # ---- inclusion probability ------------------------------------------------ #' @noRd exact_inclusion.drawn_design_multistage <- function(design, data) { + cl <- multistage_setup(design, data) if (design$allocation == "proportional") { no_closed_form( "`design_multistage(allocation = \"proportional\")`", @@ -88,11 +370,9 @@ exact_inclusion.drawn_design_multistage <- function(design, data) { "selected.\nUse allocation = \"equal\" for a closed form.") ) } - cl <- count_clusters(design, data) - check_na_policy(!cl$present, design$na_rm, "a missing cluster key") - labels <- cl$labels keep <- cl$present - sizes <- table(labels[keep]) + code <- cl$code + sizes <- tabulate(code, cl$total) # A closed form needs every selected cluster to contribute the same number of # rows, whichever clusters those turn out to be. Two things break that, and @@ -102,10 +382,16 @@ exact_inclusion.drawn_design_multistage <- function(design, data) { # the largest selected clusters, so a cluster's take depends on the company # it keeps; # * a cluster smaller than the per-cluster target -- it is capped at its own - # size and the shortfall is dealt to the others. + # size and the shortfall is dealt to the others. Sampling with + # replacement has no cap, so this one applies only without it. # - # Averaging over the possibilities is not a closed form, and the average is not - # the answer: it was out by 13% on a four-cluster frame and could exceed 1. + # The exact probability is the stage-one probability times the take given + # the selection, over N_h, averaged over every selection that includes the + # row's cluster, which needs those selections enumerated. Putting + # the average take, n / n_clusters, in its place was out by up to 17% on a + # four-cluster frame and could exceed 1. draw(weights = TRUE) weights such + # a sample conditional on the selection it made instead; see + # conditional_inclusion(). m <- design$n %/% design$n_clusters if (design$n %% design$n_clusters != 0L) { no_closed_form( @@ -117,7 +403,7 @@ exact_inclusion.drawn_design_multistage <- function(design, data) { design$n_clusters, ").") ) } - small <- names(sizes)[sizes < m] + small <- if (design$replace) integer(0) else which(sizes < m) if (length(small)) { no_closed_form( paste0("`design_multistage()` where ", length(small), " cluster(s) hold ", @@ -136,8 +422,20 @@ exact_inclusion.drawn_design_multistage <- function(design, data) { ) } - stage1 <- design$n_clusters / cl$total + stage1 <- if (is.null(cl$pi1)) { + design$n_clusters / cl$total + } else { + cl$pi1[code[keep]] + } + N_h <- as.numeric(sizes[code[keep]]) out <- numeric(nrow(data)) - out[keep] <- stage1 * (m / as.numeric(sizes[as.character(labels[keep])])) + # With replacement, m draws from a cluster of N_h rows reach a given row at + # least once with probability 1 - (1 - 1/N_h)^m. m / N_h is the expected + # number of times it is drawn, which overstates the probability. + out[keep] <- stage1 * if (design$replace) { + 1 - (1 - 1 / N_h)^m + } else { + m / N_h + } out } diff --git a/R/design-reservoir.R b/R/design-reservoir.R index 82b0be9..ecdc13f 100644 --- a/R/design-reservoir.R +++ b/R/design-reservoir.R @@ -4,18 +4,70 @@ #' single pass, using Algorithm L (Li 1994), which skips ahead geometrically #' instead of drawing a random number for every item (Vitter 1985). #' -#' A data frame is not a stream: its length is already known and it already fits -#' in memory, so [draw()] takes a direct vectorised path for one. Reach for the -#' streaming path when the data genuinely does not fit — pass a connection, or a -#' function that returns the next item and `NULL` at end of stream. For those, -#' [draw()] returns a list rather than a data frame. -#' -#' @param n Reservoir size. Fewer items come back if the stream is shorter; the -#' result is never padded. -#' @param max_items Stop after reading this many items. Rows past it are never -#' read, so [inclusion_prob()] gives them `0` and gives the rows before it -#' `n / max_items` rather than `n / N`. `Inf` reads the whole -#' stream. Warns when the cap actually truncates. +#' A data frame or a list is not a stream: its length is already known and it +#' already fits in memory, so [draw()] picks `n` positions in it at random and +#' returns them in their original order. Every element of a list is an item, +#' `NULL` included, and the elements keep their names. The streaming path is +#' for data that does not fit in memory. Pass it a connection, or a function +#' that returns the next item and `NULL` at end of stream. It holds at most `n` +#' items at a time, plus the block it is reading, and returns them in the order +#' they arrived. For a list, a connection or a function, [draw()] returns a +#' list rather than a data frame, except with `batches = TRUE`. +#' +#' The two paths use different algorithms, so for one seed a stream gives a +#' different sample from a data frame or list holding the same items. Each +#' path on its own gives the same sample for the same seed. +#' +#' @section Items in a stream: +#' Each line of a connection is one item, a character string as [readLines()] +#' returns it, and a header line is an item like any other. To leave a CSV +#' header out of the sample, open the connection, read the header with +#' `readLines(con, n = 1)` and then draw from the connection, which is read +#' from where the header left off. `read.csv(text = c(header, unlist(lines)))` +#' turns the sampled lines into a data frame (see the examples). [draw()] +#' reads a connection in blocks of 10,000 lines, which gives the same sample +#' for a seed as reading it line by line. +#' +#' A function is called once for each item, and whatever it returns is that +#' item, a data frame included, so a function that returns blocks of rows +#' gives a sample of whole blocks. With `batches = TRUE` the rows are the +#' items instead: each call returns a data frame of rows, every batch with the +#' same columns in the same order, and [draw()] returns `n` of those rows as +#' one data frame, bound with [rbind()] in the order they arrived. [draw()] +#' compares only the column names. A column whose type differs between +#' batches, such as one that [read.csv()] reads as logical in a batch where it +#' is empty, takes the type [rbind()] gives the sampled rows. Cutting the same +#' rows into batches of other sizes gives the same sample for a seed. Between +#' batches it keeps at most `max(2 * n, 1024)` rows, some of them already +#' dropped from the sample, besides the batch being read. +#' +#' @section What is read: +#' A connection that is not open is opened, read to its end (or to one line +#' past a finite `max_items`) and closed, as [read.csv()] does, so it cannot +#' be drawn from twice. A connection that is already open is read from where +#' it stands and left open. +#' +#' With a finite `max_items`, [draw()] reads one item past the cap, because +#' only that read tells a stream of exactly `max_items` items from a longer +#' one. On an open connection in text mode the line goes back with +#' [pushBack()], so the next read starts with it. A connection opened in +#' binary mode (`"rb"`) cannot take a line back, and loses it. A function is +#' called once past the cap and what it returns is dropped; with +#' `batches = TRUE`, so are the rows of a batch that run past the cap. +#' +#' @param n Reservoir size, or a plan from [plan_size()]. Fewer items come +#' back if the stream is shorter; the result is never padded. +#' @param max_items Stop after this many items, or rows with +#' `batches = TRUE`. Items past the cap are never sampled, so +#' [inclusion_prob()] gives rows past it `0` and gives the rows before it +#' `n / max_items` rather than `n / N`. A stream is read one item past the +#' cap; see "What is read". `Inf` reads the whole stream. Warns when the cap +#' truncates. +#' @param batches If `TRUE`, `data` is a function that returns a data frame of +#' rows on each call and `NULL` at the end, and the reservoir samples rows +#' rather than whole data frames. [draw()] then returns a data frame. A data +#' frame given as `data` is sampled by rows either way; a list or a +#' connection is refused. #' #' @return A design object, for use with [draw()]. #' @@ -38,10 +90,32 @@ #' } #' unlist(draw(gen, design_reservoir(n = 5), seed = 1)) #' +#' # A CSV file read line by line, with its header left out of the sample +#' path <- tempfile(fileext = ".csv") +#' write.csv(data.frame(id = 1:200, value = (1:200) %% 7), path, +#' row.names = FALSE) +#' con <- file(path, "r") +#' header <- readLines(con, n = 1) +#' lines <- draw(con, design_reservoir(n = 5), seed = 1) +#' close(con) +#' read.csv(text = c(header, unlist(lines))) +#' +#' # The same file parsed 50 rows at a time, sampling rows: the same five +#' # rows as above for the same seed +#' con <- file(path, "r") +#' header <- readLines(con, n = 1) +#' next_rows <- function() { +#' lines <- readLines(con, n = 50) +#' if (length(lines) == 0) NULL else read.csv(text = c(header, lines)) +#' } +#' draw(next_rows, design_reservoir(n = 5, batches = TRUE), seed = 1) +#' close(con) +#' unlink(path) +#' #' @family designs #' @seealso [draw()] #' @export -design_reservoir <- function(n, max_items = Inf) { +design_reservoir <- function(n, max_items = Inf, batches = FALSE) { if (!(identical(max_items, Inf) || (is.numeric(max_items) && length(max_items) == 1L && !is.na(max_items) && max_items >= 1 && @@ -50,8 +124,9 @@ design_reservoir <- function(n, max_items = Inf) { call. = FALSE) } new_design("reservoir", list( - n = check_count(n, "n"), - max_items = max_items + n = check_count(plan_n(n), "n"), + max_items = max_items, + batches = check_flag(batches, "batches") )) } @@ -59,25 +134,71 @@ design_reservoir <- function(n, max_items = Inf) { draw_design.drawn_design_reservoir <- function(design, data) { n <- design$n max_items <- design$max_items + # A design saved before `batches` existed has none, and reads items. + batches <- isTRUE(design$batches) if (is.data.frame(data)) { validate_data(data) n_rows <- nrow(data) if (is.finite(max_items) && max_items < n_rows) { - warning("`max_items` (", max_items, ") is below the ", n_rows, - " available rows; sampling only the first ", max_items, ".", - call. = FALSE) + warn_drawn(paste0("`max_items` (", max_items, ") is below the ", + n_rows, " available rows; sampling only the first ", + max_items, "."), "drawn_stream_truncated") n_rows <- as.integer(max_items) } idx <- if (n >= n_rows) seq_len(n_rows) else sort(sample.int(n_rows, n)) return(reindex(data, idx)) } - next_item <- as_stream(data) - con <- attr(next_item, "close_when_done") - if (!is.null(con)) on.exit(close(con), add = TRUE) - reservoir <- vector("list", n) - count <- 0L + # A list's length is known, so its positions are sampled as a data frame's + # rows are. Reading it as a stream would end it at its first NULL element. + if (is.list(data)) { + if (batches) { + stop("`batches = TRUE` needs a function that returns data frames, and ", + "`data` is a list. Bind its data frames with do.call(rbind, data) ", + "and draw from the result, or leave `batches` FALSE to sample ", + "whole elements.", call. = FALSE) + } + n_items <- length(data) + if (is.finite(max_items) && max_items < n_items) { + truncation_warning(max_items) + n_items <- as.integer(max_items) + } + idx <- if (n >= n_items) seq_len(n_items) else sort(sample.int(n_items, n)) + return(data[idx]) + } + + stream <- as_stream(data, batches) + if (!is.null(stream$close)) on.exit(close(stream$close), add = TRUE) + out <- if (is.null(stream$read)) { + reservoir_stream(data, n, max_items) + } else { + reservoir_blocks(stream$read, n, max_items, rows = batches, + give_back = stream$give_back) + } + if (out$truncated) truncation_warning(max_items) + out$items +} + +#' Algorithm L over a next-item function +#' +#' Returns `items`, the sampled items in the order they arrived, `count`, the +#' number of items read, and `truncated`, whether the stream held more than +#' `max_items`. `count` is a double, which counts exactly past +#' `.Machine$integer.max`. The reservoir starts with at most 1,024 slots and +#' doubles until it holds `n`, so a large `n` costs memory only for the items +#' a stream supplies. +#' +#' A function is called once per item, so this loop handles one item at a +#' time; [reservoir_blocks()] makes the same draws for a stream read in +#' blocks. +#' +#' @noRd +reservoir_stream <- function(next_item, n, max_items) { + slots <- min(n, 1024) + reservoir <- vector("list", slots) + arrived <- numeric(slots) + count <- 0 truncated <- FALSE if (n > 0L) { @@ -96,60 +217,307 @@ draw_design.drawn_design_reservoir <- function(design, data) { truncated <- TRUE break } - count <- count + 1L + count <- count + 1 if (count <= n) { + if (count > slots) { + slots <- min(n, 2 * slots) + length(reservoir) <- slots + length(arrived) <- slots + } reservoir[[count]] <- item + arrived[count] <- count } else if (count == next_swap) { - reservoir[[sample.int(n, 1L)]] <- item + slot <- sample.int(n, 1L) + reservoir[[slot]] <- item + arrived[slot] <- count + w <- w * exp(log(stats::runif(1)) / n) + next_swap <- next_swap + floor(log(stats::runif(1)) / log(1 - w)) + 1 + } + } + } + + # Trim rather than pad with NULLs when the stream was short. + held <- seq_len(min(count, n)) + list(items = reservoir[held][order(arrived[held])], count = count, + truncated = truncated) +} + +#' Algorithm L over a stream read in blocks +#' +#' `read(want)` returns the next block of items, or `NULL` at the end of the +#' stream. A block is a list or a character vector of items, or with +#' `rows = TRUE` a data frame whose rows are the items. `want` is the most +#' items worth reading, one past `max_items`; a reader may return fewer or, +#' for a function's batches, more. `give_back(block, k)` receives a block +#' that ran past `max_items` and the number of its items that were within +#' it. +#' +#' The swaps Algorithm L makes are worked out block by block, as positions +#' within the block, and draw the same random numbers in the same order as +#' reading one item at a time would. A seed therefore gives the same sample +#' however the stream is cut into blocks. +#' +#' Returns `items`, the sampled items in the order they arrived (a list, or a +#' data frame with `rows = TRUE`), `count`, the number of items read, and +#' `truncated`, whether the stream held more than `max_items`. `count` is a +#' double, which counts exactly past `.Machine$integer.max`. +#' +#' @noRd +reservoir_blocks <- function(read, n, max_items, rows = FALSE, + give_back = NULL) { + held <- if (rows) row_reservoir(n) else item_reservoir(n) + count <- 0 + truncated <- FALSE + + if (n > 0L) { + # Algorithm L: once the reservoir fills, skip ahead geometrically rather + # than drawing once per item. + w <- exp(log(stats::runif(1)) / n) + next_swap <- n + floor(log(stats::runif(1)) / log(1 - w)) + 1 + + repeat { + block <- read(max_items - count + 1) + if (is.null(block)) break + held$check(block) + k <- NROW(block) + # Only an item past `max_items` shows that the stream held more. + # Testing the count before reading warned on a stream of exactly + # `max_items`, where nothing was left behind. + if (count + k > max_items) { + truncated <- TRUE + k <- max_items - count + if (!is.null(give_back)) give_back(block, k) + } + + pos <- numeric(0) + slot <- integer(0) + if (count < n) { + pos <- seq_len(min(k, n - count)) + slot <- count + pos + } + while (next_swap <= count + k) { + m <- length(pos) + 1L + pos[m] <- next_swap - count + slot[m] <- sample.int(n, 1L) w <- w * exp(log(stats::runif(1)) / n) next_swap <- next_swap + floor(log(stats::runif(1)) / log(1 - w)) + 1 } + if (length(pos) > 0L) held$put(block, pos, slot, count + pos) + + count <- count + k + if (truncated) break } } - if (truncated) { - warning("Stopped after `max_items` = ", max_items, " item(s); the stream ", - "may have held more.", call. = FALSE) + list(items = held$items(), count = count, truncated = truncated) +} + +#' The reservoir of a stream of items +#' +#' `put(block, pos, slot, at)` stores the items at positions `pos` of a block +#' in `slot`, in order, so a slot written twice keeps the later item. The +#' reservoir starts with at most 1,024 slots and doubles until it holds `n`, +#' so a large `n` costs memory only for the items a stream supplies. +#' +#' @noRd +item_reservoir <- function(n) { + slots <- min(n, 1024) + kept <- vector("list", slots) + arrived <- numeric(slots) + list( + check = function(block) NULL, + put = function(block, pos, slot, at) { + top <- max(slot) + if (top > slots) { + slots <<- min(n, max(2 * slots, top)) + length(kept) <<- slots + length(arrived) <<- slots + } + kept[slot] <<- block[pos] + arrived[slot] <<- at + }, + items = function() { + # Trim rather than pad with NULLs when the stream was short. + filled <- which(arrived > 0) + kept[filled[order(arrived[filled])]] + } + ) +} + +#' The reservoir of a stream of data frames, sampled by row +#' +#' Each block that adds rows keeps a piece holding only those rows, and every +#' slot points at a row of a piece. A piece is dropped once none of its rows +#' is held, and the pieces are bound into one when they hold more than twice +#' the rows in the reservoir, or 1,024, so between blocks they hold at most +#' `max(2 * n, 1024)` rows. `check(block)` refuses a block that is not a data +#' frame or whose columns differ from the first block's. +#' +#' @noRd +row_reservoir <- function(n) { + slots <- min(n, 1024) + piece_of <- integer(slots) + row_of <- integer(slots) + arrived <- numeric(slots) + pieces <- list() + live <- integer(0) + stored <- 0 + filled <- 0 + first <- NULL + seen <- 0 + + # The held rows, as one data frame in the order they arrived. Pieces are + # numbered in arrival order and rows within a piece too, so taking each + # piece's rows in turn keeps that order. + bind_held <- function() { + held <- seq_len(filled) + held <- held[order(arrived[held])] + from <- piece_of[held] + parts <- lapply(unique(from), function(p) { + reindex(pieces[[p]], row_of[held][from == p]) + }) + out <- if (length(parts) == 1L) parts[[1L]] else do.call(rbind, parts) + # The batches' row names number rows within each batch, not rows of a + # frame, so the sample numbers its rows afresh. + rownames(out) <- NULL + list(data = out, slots = held) } - # Trim rather than pad with NULLs when the stream was short. - reservoir[seq_len(min(count, n))] + list( + check = function(block) { + seen <<- seen + 1 + if (!is.data.frame(block)) { + stop("`data` returned ", a_class(block), " on call ", seen, + ", where `batches = TRUE` needs a data frame of rows. Return ", + "each batch as a data frame, and NULL at the end of the stream.", + call. = FALSE) + } + if (is.null(first)) { + first <<- empty_like(block) + } else if (!identical(names(block), names(first))) { + stop("Batch ", seen, " from `data` ", + column_change(names(block), names(first)), + " where batch 1 has ", quote_labels(names(first)), ". Return ", + "the same columns, in the same order, from every call.", + call. = FALSE) + } + NULL + }, + put = function(block, pos, slot, at) { + last <- !duplicated(slot, fromLast = TRUE) + pos <- pos[last] + slot <- slot[last] + top <- max(slot) + if (top > slots) { + slots <<- min(n, max(2 * slots, top)) + length(piece_of) <<- slots + length(row_of) <<- slots + length(arrived) <<- slots + } + # Slots fill in order, so the highest slot written is the count held. + filled <<- max(filled, top) + old <- piece_of[slot] + old <- old[!is.na(old) & old > 0L] + id <- length(pieces) + 1L + pieces[[id]] <<- reindex(block, pos) + live[id] <<- length(pos) + stored <<- stored + length(pos) + piece_of[slot] <<- id + row_of[slot] <<- seq_along(pos) + arrived[slot] <<- at[last] + if (length(old) > 0L) { + live <<- live - tabulate(old, nbins = id) + for (p in unique(old)[live[unique(old)] == 0L]) { + stored <<- stored - nrow(pieces[[p]]) + pieces[p] <<- list(NULL) + } + } + if (stored > 2 * max(filled, 512)) { + one <- bind_held() + pieces <<- list(one$data) + live <<- length(one$slots) + stored <<- length(one$slots) + piece_of[one$slots] <<- 1L + row_of[one$slots] <<- seq_along(one$slots) + } + }, + items = function() { + if (is.null(first)) return(data.frame()) + if (filled == 0) return(first) + bind_held()$data + } + ) +} + +#' How a batch's columns differ from the first batch's +#' @noRd +column_change <- function(now, first) { + added <- setdiff(now, first) + lost <- setdiff(first, now) + parts <- c( + if (length(added) > 0L) paste("adds", quote_labels(added)), + if (length(lost) > 0L) paste("lacks", quote_labels(lost)) + ) + if (length(parts) == 0L) { + return(paste0("has the columns ", quote_labels(now), ",")) + } + paste0(paste(parts, collapse = " and "), ",") } -#' Turn the supported inputs into a next-item function #' @noRd -as_stream <- function(x) { +truncation_warning <- function(max_items) { + warn_drawn(paste0("Stopped after `max_items` = ", max_items, " item(s); ", + "the stream may have held more."), "drawn_stream_truncated") +} + +#' Turn a connection or function into a block reader +#' +#' Returns `read(want)`, which gives the next block of items or `NULL`, +#' `close`, a connection opened here for the caller to close when the reading +#' is done, and `give_back(block, k)`, which pushes the items of `block` past +#' the first `k` back onto a connection the caller opened. A function of +#' items, read one call at a time, gets none of them. +#' +#' @noRd +as_stream <- function(x, batches = FALSE, block = 10000L) { if (is.function(x)) { if (length(formals(x)) > 0L) { stop("A stream function must take no arguments.", call. = FALSE) } - return(x) + # A function of items is read one call at a time by reservoir_stream(). + return(if (batches) list(read = function(want) x()) else list()) } if (inherits(x, "connection")) { + if (batches) { + stop("`batches = TRUE` needs a function that returns data frames, and ", + "`data` is a connection, which gives lines. Read the connection ", + "in a function that returns each block of lines as a data frame; ", + "see the examples in ?design_reservoir.", call. = FALSE) + } # An on.exit() here would close the connection when *this* function # returns, long before the reader below has read a byte from it. The # caller's own open connections are left alone; one opened here is closed # by draw_design(), which knows when the reading is done. opened_here <- !isOpen(x) if (opened_here) open(x, "r") - reader <- function() { - line <- readLines(x, n = 1L, warn = FALSE) - if (length(line) == 0L) NULL else line + read <- function(want) { + lines <- readLines(x, n = min(block, want), warn = FALSE) + if (length(lines) == 0L) NULL else lines } - attr(reader, "close_when_done") <- if (opened_here) x else NULL - return(reader) - } - if (is.list(x)) { - i <- 0L - n <- length(x) - return(function() { - i <<- i + 1L - if (i > n) NULL else x[[i]] - }) + # The line read past `max_items` goes back onto a connection the caller + # opened, so their next read starts with it. Only a text-mode connection + # takes lines back, and one opened here is closed anyway. When a full + # block ends at the cap, the next block is that one line and `k` is 0, + # where `lines[-seq_len(k)]` would be empty. + give_back <- if (!opened_here && identical(summary(x)$text, "text")) { + function(lines, k) pushBack(lines[seq_along(lines) > k], x) + } + return(list(read = read, close = if (opened_here) x, + give_back = give_back)) } stop("`data` must be a data frame, list, connection, or zero-argument ", - "function for a reservoir design, not a ", class(x)[1], ".", + "function for a reservoir design, not ", a_class(x), ".", call. = FALSE) } diff --git a/R/design-simple.R b/R/design-simple.R index 5e9f28f..ab2ca28 100644 --- a/R/design-simple.R +++ b/R/design-simple.R @@ -2,11 +2,43 @@ #' #' Draws `n` rows uniformly at random. #' -#' @param n Number of rows to draw. A single non-negative whole number. +#' @section Reserves: +#' Fieldwork often finds that some sampled units cannot be reached: a site +#' with no access, a business that has closed, a plot under water. `reserve` +#' draws that many more units with the main sample, as a list to replace them +#' from. [draw()] returns the `n` units of the main sample followed by the +#' `reserve` units, with an integer `.reserve` column: 0 for the main sample, +#' and 1, 2, ... for the reserves, in the order they are used. The list is +#' one random draw of `n + reserve` units in random order, so the main sample +#' is a simple random sample of `n`, the one the design without `reserve` +#' draws with the same seed, and the first `k` units of the list are a +#' simple random sample of `k` for any `k`. +#' +#' Visit every unit of the main sample, and for each one found unavailable, +#' visit the next reserve. [use_reserves()] takes the list and what the +#' visits found, and returns the sample to estimate from: the first `n` units +#' of the list found available. They are a simple random sample of `n` from +#' the units of the frame that are available, and [use_reserves()] weights +#' them as one, with probability `n / (N - u)` when `u` listed units were +#' found unavailable. Replacing units changes what is estimated: the totals +#' and means are those of the units that can be reached, not of the whole +#' frame. "What the estimates describe" in [use_reserves()] has the details. +#' +#' Until then the list is not a sample to estimate from. [inclusion_prob()] +#' and the `.prob` column give every row the main sample's probability, +#' `n / N`, and [ht_total()], [ht_mean()], [as_svydesign()] and +#' [sample_summary()] refuse the list. +#' +#' @param n Number of rows to draw. A single non-negative whole number, or a +#' plan from [plan_size()]. #' @param replace Sample with replacement? Note that `draw(weights = TRUE)` #' declines a with-replacement design: `.prob` would be the chance of #' appearing at least once, which does not weight a sample holding #' duplicates. See [draw()]. +#' @param reserve Number of reserve units to list after the main sample, to +#' replace units found unavailable in the field. A single non-negative whole +#' number; `n + reserve` cannot exceed the rows of the frame. Not available +#' with `replace = TRUE` or `n = 0`. See "Reserves". #' #' @return A design object, for use with [draw()]. #' @@ -15,33 +47,160 @@ #' draw(df, design_simple(n = 10), seed = 1) #' draw(df, design_simple(n = 150, replace = TRUE), seed = 1) #' +#' # Ten units and three reserves, used in the order of `.reserve` +#' draw(df, design_simple(n = 10, reserve = 3), seed = 1) +#' #' @family designs -#' @seealso [draw()] +#' @seealso [draw()], [use_reserves()] #' @export -design_simple <- function(n, replace = FALSE) { - new_design("simple", list( - n = check_count(n, "n"), - replace = check_flag(replace, "replace") - )) +design_simple <- function(n, replace = FALSE, reserve = 0) { + n <- check_count(plan_n(n), "n") + replace <- check_flag(replace, "replace") + reserve <- check_reserve(reserve, n) + if (replace && reserve > 0L) { + stop("`reserve` lists units to visit in place of unavailable ones, and ", + "`replace = TRUE` can draw a unit more than once. Use ", + "replace = FALSE with `reserve`.", call. = FALSE) + } + new_design("simple", list(n = n, replace = replace, reserve = reserve)) } -#' @export -draw_design.drawn_design_simple <- function(design, data) { +#' Refuse a simple random sample the frame cannot supply +#' +#' The checks every path runs before it draws or answers, so +#' [inclusion_prob()] and [joint_prob()] refuse what [draw()] refuses, with +#' the same message. Returns the frame rows the design can select: every +#' row, less those use_reserves() recorded as unavailable. +#' +#' @noRd +simple_setup <- function(design, data) { validate_data(data) + keep <- available_rows(design, nrow(data)) + check_draw_size(design$n, length(keep), design$replace) + check_reserve_size(design, length(keep)) + keep +} - check_draw_size(design$n, nrow(data), design$replace) - - idx <- sample.int(nrow(data), size = design$n, replace = design$replace) - reindex(data, idx) +#' @export +draw_design.drawn_design_simple <- function(design, data) { + keep <- simple_setup(design, data) + r <- reserve_size(design) + idx <- sample.int(length(keep), size = design$n, replace = design$replace) + if (r > 0L) { + # The reserves are drawn from the rows left, after the main sample, so + # the main sample is the one the design without `reserve` draws, and the + # list is one random ordering of `n + reserve` distinct rows. + left <- setdiff(seq_along(keep), idx) + idx <- c(idx, left[sample.int(length(left), r)]) + } + out <- reindex(data, keep[idx]) + if (r > 0L) out <- with_reserve(out, design$n, r) + out } # ---- inclusion probability ------------------------------------------------ #' @noRd exact_inclusion.drawn_design_simple <- function(design, data) { - if (design$replace) { + keep <- simple_setup(design, data) + N <- length(keep) + out <- numeric(nrow(data)) + out[keep] <- if (design$replace) { # P(selected at least once) over n independent draws. - return(rep(1 - (1 - 1 / nrow(data))^design$n, nrow(data))) + 1 - (1 - 1 / N)^design$n + } else { + design$n / N + } + out +} + +# ---- reserves --------------------------------------------------------------- + +#' The number of reserves a design lists +#' +#' 0 for a design without `reserve`, including one saved before it existed. +#' +#' @noRd +reserve_size <- function(design) { + design[["reserve"]] %||% 0L +} + +#' The same design without its reserves +#' +#' Its draws are the main samples of the design's lists, with the same random +#' numbers, which is what the simulated probabilities and the plots count. +#' +#' @noRd +main_design <- function(design) { + if (reserve_size(design) > 0L) design[["reserve"]] <- 0L + design +} + +#' Check `reserve`, which needs a main sample to replace units of +#' +#' With `n = 0` there is no unit for a reserve to replace, and the list +#' would hold the reserves alone at probability 0. Returns `reserve` as an +#' integer. +#' +#' @noRd +check_reserve <- function(reserve, n) { + reserve <- check_count(reserve, "reserve") + if (reserve > 0L && n == 0) { + stop("`reserve` is ", reserve, " and `n` is 0, so there is no main ", + "sample for the reserves to replace units of. Set `n` to 1 or more, ", + "or leave out `reserve`.", call. = FALSE) + } + reserve +} + +#' Refuse more rows than the frame holds for the list and its reserves +#' @noRd +check_reserve_size <- function(design, n_rows) { + r <- reserve_size(design) + total <- as.numeric(design$n) + r + if (r > 0L && total > n_rows) { + stop("`n` and `reserve` together (", total, ") cannot exceed the number ", + "of rows (", n_rows, "). Lower `reserve`.", call. = FALSE) + } + invisible(TRUE) +} + +#' Frame rows a design can select, less those found unavailable +#' +#' use_reserves() records the frame rows found unavailable as `unavailable` +#' on the design of the sample it returns, and the design gives them +#' probability 0. A design built by a constructor has none. +#' +#' @noRd +available_rows <- function(design, n_rows) { + gone <- design[["unavailable"]] + if (is.null(gone)) return(seq_len(n_rows)) + if (length(gone) && max(gone) > n_rows) { + stop("`design` records units found unavailable in rows up to ", + max(gone), ", and `data` has ", n_rows, " rows. It is the design of ", + "a sample from use_reserves(), and holds for that sample's frame ", + "only.", call. = FALSE) + } + which(!seq_len(n_rows) %in% gone) +} + +#' Put the `.reserve` column in front of a drawn list +#' +#' `out` holds the `n` rows of the main sample and then the `r` reserves in +#' the order they are used. The column is built in place and moved to the +#' front by position, as `.replicate` is, so the frame keeps its class. +#' +#' @noRd +with_reserve <- function(out, n, r) { + if (".reserve" %in% names(out)) { + stop("`data` already has a column called `.reserve`, which draw() adds ", + "to number the reserves of a design with `reserve`. Rename it.", + call. = FALSE) } - rep(design$n / nrow(data), nrow(data)) + k <- ncol(out) + nm <- names(out) + out[[".reserve"]] <- c(integer(n), seq_len(r)) + out <- out[, c(k + 1L, seq_len(k)), drop = FALSE] + names(out) <- c(".reserve", nm) + out } diff --git a/R/design-spatial.R b/R/design-spatial.R index 72dc12e..eb01c2f 100644 --- a/R/design-spatial.R +++ b/R/design-spatial.R @@ -9,7 +9,48 @@ #' @section Coordinate order: #' `coords` is `c(x, y)` — longitude first, then latitude — matching #' [sf::st_as_sf()]. Getting this backwards puts your points somewhere else -#' entirely, so it is worth checking against a known landmark once. +#' entirely, so it is worth checking against a known landmark once. When the +#' coordinates are longitude and latitude, a latitude outside -90 to 90 or a +#' longitude outside -180 to 360 is refused, since it means the columns are +#' the wrong way round or hold projected coordinates. +#' +#' A POINT geometry column, such as the geometry of an `sf` frame, can stand +#' in for the two columns: name it alone, as in `coords = "geometry"`, and +#' each row's position is read with [sf::st_coordinates()]. The column's own +#' CRS is used when it has one, and `region` is reprojected to it. +#' +#' @section Edges of a longitude/latitude region: +#' With spherical geometry ([sf::sf_use_s2()], the default), each edge of a +#' longitude/latitude `region` follows the great circle between its two +#' corners, the shortest path on the globe. On a flat longitude/latitude map +#' that path bows towards the nearer pole wherever the edge runs east-west +#' away from the equator; edges along a meridian or the equator do not bow. +#' A wide box is therefore a different shape from the rectangle it looks like +#' on such a map. The top edge of a box from -50 to 50 degrees of longitude +#' and -30 to 30 of latitude reaches latitude 41.9 at longitude 0, so a row +#' at (0, 41) is inside it, and its bottom edge reaches -41.9. A box from -5 +#' to 5 degrees of longitude and 40 to 50 of latitude takes in a row at +#' (0, 50.05) and leaves out one at (0, 40.05). +#' +#' [draw()], [inclusion_prob()], [joint_prob()] and +#' [plot()][plot.drawn_design] warn, with class `drawn_geodesic_edges`, when +#' an edge of `region` passes more than 0.1 degrees (about 11 km) from the +#' straight line between its corners on a longitude/latitude map. To make the +#' edges follow those straight lines, add vertices along them in degree space +#' before you build the design: +#' +#' ``` +#' flat <- sf::st_set_crs(region, NA) # coordinates as plain numbers +#' flat <- sf::st_segmentize(flat, 0.1) # a vertex at least every 0.1 degrees +#' region <- sf::st_set_crs(flat, 4326) +#' ``` +#' +#' An edge 0.1 degrees long bows by about a metre at most. The CRS has to come +#' off for the middle step: on a region that keeps it, +#' [sf::st_segmentize()] needs the lwgeom package and places the new vertices +#' along the great circles, under either s2 setting, and the bow stays. A +#' region larger than a hemisphere needs splitting first; see the next +#' section. #' #' @section Regions that cross the antimeridian: #' With spherical geometry enabled ([sf::sf_use_s2()], the default), consecutive @@ -21,20 +62,66 @@ #' nothing. #' #' Ring orientation is not the cause and reversing it does not help: `sf` -#' normalises winding, so both directions give the same strip. Adding -#' intermediate vertices does not reliably help either, because the intermediate -#' edges still bow along geodesics. -#' -#' [draw()] warns whenever any edge of `region` spans more than 180 degrees of -#' longitude. If you hit it, either split the region at the antimeridian into two -#' polygons, or switch to planar interpretation with `sf::sf_use_s2(FALSE)`. -#' -#' @param coords Two column names, `c(x, y)` — longitude then latitude. -#' @param region An `sf` or `sfc` geometry, or a list of them, which is unioned. -#' Reprojected to `crs` when it differs. -#' @param n Number of rows to draw from inside the region. +#' normalises winding, so both directions give the same strip. Adding vertices +#' along the edges in degree space, as in the previous section, does not +#' rescue a region this large either. s2 takes the smaller of the two areas a +#' ring divides the globe into as its inside, so a ring around more than half +#' the globe encloses the rest of the globe instead. +#' +#' The short way is the right reading for a region meant to cross the +#' antimeridian, such as a box from longitude 179 to -179. [draw()], +#' [inclusion_prob()], [joint_prob()] and [plot()][plot.drawn_design] warn, +#' with class `drawn_antimeridian`, whenever an edge of `region` joins two +#' longitudes more than 180 degrees apart, and the warning gives both +#' readings. An edge from -180 to 180 is one of them: both ends lie on the +#' same meridian, so under spherical geometry the edge spans no longitude, +#' and a box from -180 to 180 encloses nothing. An edge along a pole, where +#' every longitude meets, does not warn, so a cap around a pole closed along +#' it does not either. If you meant the short way, `region` is what you +#' drew. If you meant the long way, split the region into parts smaller than +#' a hemisphere, add vertices to each as in the previous section, and pass +#' the parts as a list; or switch to planar interpretation with +#' `sf::sf_use_s2(FALSE)`. +#' Splitting works under the default setting. Switching has to happen before +#' [draw()] and stay in force for every estimate from the sample; see the next +#' section. +#' +#' @section The s2 setting at draw time and after: +#' Which rows fall inside `region` depends on [sf::sf_use_s2()]. With spherical +#' geometry the edges of a longitude/latitude region are great-circle arcs, and +#' without it they are straight lines in longitude and latitude, so rows near an +#' edge can be inside under one setting and outside under the other. Use the +#' same setting when you draw a sample and whenever you analyse it. +#' +#' [ht_total()], [ht_mean()], [as_svydesign()] and [sample_summary()] find the +#' region's rows again each time they run, because the variance, the design +#' effect and `survey`'s population count all depend on them. They compare the +#' result with the inclusion probabilities stored at draw time, or with the +#' `.prob` column of a sample saved by drawn 0.2.0, and refuse the sample when +#' the two differ, naming `sf::sf_use_s2()`. The comparison catches any change +#' in which rows are inside, including one that comes with another version of +#' sf. A region that holds fewer than `n` rows under the current setting +#' leaves nothing to compare, and the sample is refused the same way. The +#' point estimate would not have moved, since it uses the stored `.prob`, but +#' the standard error would. +#' +#' `sf_use_s2()` is a session setting, and a new R session starts with it +#' `TRUE` unless the `_SF_USE_S2` environment variable says otherwise. A sample +#' drawn under `sf::sf_use_s2(FALSE)` and saved with [saveRDS()] needs +#' `sf::sf_use_s2(FALSE)` again after [readRDS()]. +#' [inclusion_prob()] and [joint_prob()] on the frame follow the current +#' setting too. +#' +#' @param coords Two column names, `c(x, y)` with longitude first, or the +#' name of one POINT geometry column. See "Coordinate order". +#' @param region An `sf` or `sfc` geometry of POLYGON or MULTIPOLYGON +#' features, or a list of them. A row inside any of them is inside the +#' region. Each is reprojected to the coordinates' CRS when its own differs. +#' @param n Number of rows to draw from inside the region, or a plan from +#' [plan_size()]. #' @param crs Coordinate reference system of the coordinate columns. Defaults to -#' EPSG:4326. +#' EPSG:4326. A geometry column named in `coords` keeps its own CRS when it +#' has one. #' @param na_rm Drop rows with missing coordinates instead of raising an error. #' #' @return A design object, for use with [draw()]. @@ -54,15 +141,16 @@ #' @export design_spatial <- function(coords, region, n, crs = 4326, na_rm = FALSE) { coords <- check_columns(coords, "coords") - if (length(coords) != 2L) { + if (length(coords) > 2L) { stop("`coords` must name exactly two columns, c(x, y) -- longitude then ", - "latitude. Got ", length(coords), ".", call. = FALSE) + "latitude -- or one POINT geometry column. Got ", length(coords), ".", + call. = FALSE) } check_region(region, crs) new_design("spatial", list( coords = coords, region = region, - n = check_count(n, "n"), + n = check_count(plan_n(n), "n"), crs = crs, na_rm = check_flag(na_rm, "na_rm") )) @@ -70,147 +158,481 @@ design_spatial <- function(coords, region, n, crs = 4326, na_rm = FALSE) { #' @export draw_design.drawn_design_spatial <- function(design, data) { - require_suggested("sf", "spatial sampling") - validate_data(data, required_columns = design$coords) - - bad <- is.na(data[[design$coords[1]]]) | is.na(data[[design$coords[2]]]) - if (any(bad)) { - data <- drop_na_rows(data, bad, design$na_rm, "missing coordinates") - } - - inside <- which(spatial_inside(design, data, warn = TRUE)) + inside <- which(spatial_setup(design, data)) + reindex(data, sort(inside[sample.int(length(inside), design$n)])) +} - if (length(inside) == 0L) { +#' Rows inside the region, refusing a region that cannot supply `n` +#' +#' The checks the draw and the probabilities share, so [inclusion_prob()] +#' refuses what [draw()] refuses, with the same message: no row inside +#' `region`, or fewer than `n`. Returns `spatial_inside()`. +#' +#' @noRd +spatial_setup <- function(design, data) { + require_suggested("sf", "spatial sampling") + inside <- spatial_inside(design, data) + k <- sum(inside) + if (k == 0L) { stop("No rows fall inside `region`. If you expected a much larger area, ", "see the \"Regions that cross the antimeridian\" section of ", "?design_spatial.", call. = FALSE) } - if (design$n > length(inside)) { - stop("`n` (", design$n, ") exceeds the ", length(inside), + if (design$n > k) { + stop("`n` (", design$n, ") exceeds the ", k, " row(s) inside `region`.", call. = FALSE) } - - reindex(data, sort(inside[sample.int(length(inside), design$n)])) + inside } #' Which rows fall inside the design's region #' #' Shared by the draw method and [inclusion_prob()], so the two can never -#' disagree about what "inside" means. +#' disagree about what "inside" means. A row with a missing coordinate is +#' outside, once the design's `na_rm` allows it. #' #' @noRd -spatial_inside <- function(design, data, warn = FALSE) { - x_col <- design$coords[1] - y_col <- design$coords[2] - x <- data[[x_col]] - y <- data[[y_col]] +spatial_inside <- function(design, data) { + pts <- spatial_points(design, data) + x <- pts$x + y <- pts$y + + ok <- !is.na(x) & !is.na(y) + what <- paste0("missing coordinates in ", pts$label) + check_na_policy(!ok, design$na_rm, what) + if (length(ok) && !any(ok)) { + stop("Every row has ", what, ".", call. = FALSE) + } if (!is.numeric(x) || !is.numeric(y)) { - stop("`", x_col, "` and `", y_col, "` must both be numeric.", call. = FALSE) + stop("`", design$coords[1], "` and `", design$coords[2], + "` must both be numeric.", call. = FALSE) } + check_lonlat(x[ok], y[ok], pts) - region <- design$region - if (is.list(region) && !inherits(region, c("sf", "sfc"))) { - # do.call(st_union, region) maps the third and later elements onto - # st_union()'s own arguments. - region <- sf::st_union(do.call(c, lapply(region, sf::st_geometry))) + region <- region_geometry(design$region, pts$crs) + data_sf <- sf::st_as_sf(data.frame(x = x[ok], y = y[ok]), + coords = c("x", "y"), crs = pts$crs) + out <- rep(FALSE, nrow(data)) + out[ok] <- lengths(sf::st_intersects(data_sf, region)) > 0L + out +} + +#' Each row's two coordinates, and the CRS they are in +#' +#' `coords` names two columns, or one POINT geometry column whose X and Y +#' are read with `sf::st_coordinates()`, and `geometry` says which. `label` +#' names the columns for messages, and `names` the two coordinates. +#' +#' @noRd +spatial_points <- function(design, data) { + coords <- design$coords + validate_data(data, required_columns = coords) + cols <- coordinate_columns(data, coords, "coords") + if (length(cols) != 2L) { + stop("`coords` must name two coordinate columns, c(x, y) -- longitude ", + "then latitude -- or one POINT geometry column, not ", + format_bad(coords), ".", call. = FALSE) } - region <- sf::st_geometry(region) + list( + x = cols[[1L]], y = cols[[2L]], names = names(cols), + crs = spatial_crs(design, data), geometry = length(coords) == 1L, + label = paste0("`", coords, "`", collapse = " or ") + ) +} - if (is.na(sf::st_crs(region))) { - stop("`region` has no CRS. Set one with sf::st_set_crs().", call. = FALSE) +#' The CRS of the coordinates: a geometry column's own, else `crs` +#' @noRd +spatial_crs <- function(design, data) { + geom <- if (length(design$coords) == 1L && is.data.frame(data)) { + data[[design$coords]] + } + if (inherits(geom, "sfc") && !is.na(sf::st_crs(geom))) { + return(sf::st_crs(geom)) } + sf::st_crs(design$crs) +} - ok <- !is.na(x) & !is.na(y) - check_na_policy(!ok, design$na_rm, - paste0("a missing `", x_col, "` or `", y_col, "`")) - data_sf <- sf::st_as_sf(data[ok, , drop = FALSE], coords = c(x_col, y_col), - crs = design$crs, remove = FALSE) - if (sf::st_crs(region) != sf::st_crs(data_sf)) { - region <- sf::st_transform(region, sf::st_crs(data_sf)) +#' Numeric coordinates behind column names +#' +#' A POINT geometry column, such as an `sf` frame's geometry, stands for its +#' X and Y coordinates, read with `sf::st_coordinates()`; an empty point +#' gives `NA`. Any other geometry is refused. With `time = TRUE` a Date column +#' becomes days and a date-time column seconds since 1970. Other columns come +#' back as they are, for the caller to check. The result is a named list of +#' vectors, two for a geometry column and one for any other. +#' +#' @noRd +coordinate_columns <- function(data, cols, arg, time = FALSE) { + out <- lapply(cols, function(nm) { + col <- data[[nm]] + if (inherits(col, "sfc")) { + return(point_coordinates(col, nm, arg)) + } + if (time && inherits(col, "Date")) { + col <- as.numeric(col) + } else if (time && inherits(col, "POSIXt")) { + col <- as.numeric(as.POSIXct(col)) + } + stats::setNames(list(col), nm) + }) + do.call(c, out) +} + +#' The X and Y coordinates of a POINT geometry column +#' @noRd +point_coordinates <- function(col, nm, arg) { + require_suggested("sf", "coordinates from a geometry column") + type <- unique(as.character(sf::st_geometry_type(col, by_geometry = TRUE))) + other <- setdiff(type, "POINT") + if (length(other)) { + stop("`", arg, "` names `", nm, "`, a geometry column holding ", other[1], + " geometry. Only POINT geometry gives each row one position; ", + "reduce each feature to a point first, for example with ", + "sf::st_point_on_surface().", call. = FALSE) } + xy <- sf::st_coordinates(col) + stats::setNames(list(unname(xy[, "X"]), unname(xy[, "Y"])), + paste(nm, c("X", "Y"))) +} - if (isTRUE(warn)) warn_if_antimeridian(region) +#' Refuse coordinates that cannot be longitude and latitude +#' +#' Under a longitude/latitude CRS, sf reads longitudes from -180 to 360 and +#' latitudes from -90 to 90, and only warns about values outside them. A +#' latitude past 90 is the sign of columns in (lat, lon) order, and a value +#' in the hundreds of thousands the sign of projected coordinates under the +#' default `crs`. +#' +#' @noRd +check_lonlat <- function(x, y, pts) { + if (!isTRUE(sf::st_is_longlat(pts$crs))) return(invisible(NULL)) + bad_y <- y[!(y >= -90 & y <= 90)] + bad_x <- x[!(x >= -180 & x <= 360)] + if (!length(bad_y) && !length(bad_x)) return(invisible(NULL)) + k <- if (length(bad_y)) 2L else 1L + bad <- if (k == 2L) bad_y else bad_x + v <- bad[which.max(abs(bad))] + what <- if (k == 2L) { + "-90 to 90, the range of a latitude" + } else { + "-180 to 360, the widest range sf reads as longitude" + } + col <- if (pts$geometry) { + paste0("The ", c("X", "Y")[k], " coordinate of ", pts$label) + } else { + paste0("`", pts$names[k], "`") + } + fix <- if (pts$geometry) { + "If they are projected, set the column's CRS with sf::st_set_crs()." + } else { + paste0("`coords` is c(x, y), longitude first: if it names the columns ", + "in (lat, lon) order, swap them. If the coordinates are ", + "projected, set `crs` to their system.") + } + stop(col, " holds ", format(v, big.mark = ",", scientific = FALSE, + trim = TRUE), + ", outside ", what, ", and the coordinates are in a ", + "longitude/latitude CRS (", crs_label(pts$crs), "). ", fix, + call. = FALSE) +} - out <- rep(FALSE, nrow(data)) - out[ok] <- lengths(sf::st_intersects(data_sf, region)) > 0L - out +#' @noRd +crs_label <- function(crs) { + if (!is.na(crs$epsg)) paste0("EPSG:", crs$epsg) else crs$input } -#' Warn when a ring edge spans more than 180 degrees of longitude +#' `region` as one geometry in the coordinates' CRS #' -#' Under s2 such an edge is drawn the short way, across the antimeridian, so the -#' polygon is not the region the coordinates suggest. Checking the raw -#' coordinates is exact and cheap; comparing areas is not, because a collapsed -#' ring and its bounding box collapse together. +#' Each member of a list is checked and reprojected on its own before they +#' are combined, since `c()` refuses geometries in different CRSs. The +#' members stay separate features rather than being unioned: a row inside +#' any of them is inside the region either way, and under s2 the union of +#' two parts that together cover more than a hemisphere comes back as the +#' rest of the globe. #' #' @noRd -warn_if_antimeridian <- function(region) { - if (!isTRUE(sf::sf_use_s2())) { - return(invisible(NULL)) +region_geometry <- function(region, crs) { + crs <- sf::st_crs(crs) + listed <- is.list(region) && !inherits(region, c("sf", "sfc")) + parts <- if (listed) region else list(region) + if (!length(parts)) { + stop("`region` is an empty list.", call. = FALSE) } - if (is.na(sf::st_crs(region)) || !isTRUE(sf::st_is_longlat(region))) { - return(invisible(NULL)) + geoms <- lapply(seq_along(parts), function(i) { + part <- parts[[i]] + arg <- if (listed) paste0("`region[[", i, "]]`") else "`region`" + g <- tryCatch(sf::st_geometry(part), error = function(e) { + stop(arg, " must be an sf or sfc geometry", + if (!listed) ", or a list of them", ", not ", + if (is.null(part)) "NULL" else class(part)[1], ".", call. = FALSE) + }) + if (is.na(sf::st_crs(g))) { + stop(arg, " has no CRS. Set one with sf::st_set_crs().", call. = FALSE) + } + check_region_type(g, arg) + if (sf::st_crs(g) != crs) g <- sf::st_transform(g, crs) + g + }) + if (length(geoms) == 1L) geoms[[1L]] else do.call(c, geoms) +} + +#' A region has to enclose an area +#' +#' A point or a line has no inside, so no row could fall within it, and a +#' sample drawn from it would be refused only at [draw()] with "No rows fall +#' inside `region`". +#' +#' @noRd +check_region_type <- function(g, arg) { + type <- unique(as.character(sf::st_geometry_type(g, by_geometry = TRUE))) + other <- setdiff(type, c("POLYGON", "MULTIPOLYGON")) + if (!length(other)) return(invisible(NULL)) + fix <- if (any(other %in% c("GEOMETRYCOLLECTION", "GEOMETRY"))) { + "Take its polygons with sf::st_collection_extract(region, \"POLYGON\")." + } else { + paste0("A point or a line encloses no area; for the area around it, ", + "use sf::st_buffer().") } + stop(arg, " must be POLYGON or MULTIPOLYGON geometry, not ", other[1], + ". ", fix, call. = FALSE) +} + +#' The outline of `region`, as `plot(type = "map")` draws it +#' +#' The rings of `region` in the coordinates' CRS, as `x` and `y` with an `NA` +#' between rings. Under spherical geometry each edge of a longitude/latitude +#' region is the great-circle arc between its corners, which bows away from +#' the straight line a flat map would draw, so vertices are added along each +#' arc at most 50 km apart before the outline is drawn. Under planar +#' geometry, or with projected coordinates, the edges are the straight lines +#' between the corners. +#' +#' The vertices are placed here rather than by sf::st_segmentize(), which +#' needs the lwgeom package for longitude/latitude geometry, and follow the +#' sphere's great circles, as s2's edges do, where lwgeom follows the +#' ellipsoid. +#' +#' @noRd +region_outline <- function(design, data) { + crs <- spatial_crs(design, data) + region <- region_geometry(design$region, crs) + arcs <- isTRUE(sf::st_is_longlat(crs)) && isTRUE(sf::sf_use_s2()) + cs <- sf::st_coordinates(sf::st_cast(region, "MULTIPOLYGON")) + ring <- cs[, intersect(c("L1", "L2", "L3"), colnames(cs)), drop = FALSE] + id <- do.call(paste, c(unname(as.data.frame(ring)), sep = ".")) + pieces <- split(seq_len(nrow(cs)), factor(id, levels = unique(id))) + parts <- lapply(pieces, function(i) { + x <- unname(cs[i, "X"]) + y <- unname(cs[i, "Y"]) + if (arcs) great_circle_path(x, y, km = 50) else list(x = x, y = y) + }) + gap <- function(v) v[-length(v)] + list(x = gap(unlist(lapply(parts, function(p) c(p$x, NA)), + use.names = FALSE)), + y = gap(unlist(lapply(parts, function(p) c(p$y, NA)), + use.names = FALSE))) +} + +#' Vertices along the great-circle arcs between consecutive points +#' +#' `lon` and `lat` are in degrees. Each arc between consecutive points gets +#' evenly spaced vertices at most `km` kilometres apart on a sphere of radius +#' 6,371 km, by spherical linear interpolation, and the points themselves +#' are kept as given. Each new vertex's longitude is put within 180 degrees +#' of the straight-line interpolation between the arc's ends, so an arc from +#' longitude 190 to 200 stays in that range. Ends that coincide or lie +#' opposite each other fix no single arc and are joined directly. +#' +#' @noRd +great_circle_path <- function(lon, lat, km = 50) { + n <- length(lon) + if (n < 2L) return(list(x = lon, y = lat)) + u <- unit_vector(lon, lat) + a <- u[-n, , drop = FALSE] + b <- u[-1L, , drop = FALSE] + across <- cbind(a[, 2] * b[, 3] - a[, 3] * b[, 2], + a[, 3] * b[, 1] - a[, 1] * b[, 3], + a[, 1] * b[, 2] - a[, 2] * b[, 1]) + sin_w <- sqrt(rowSums(across^2)) + w <- atan2(sin_w, rowSums(a * b)) + steps <- ifelse(sin_w < 1e-12, 1, pmax(1, ceiling(w * 6371 / km))) + dx <- lon[-1L] - lon[-n] + dx <- dx - 360 * round(dx / 360) - span <- tryCatch({ - cs <- sf::st_coordinates(region) - ring_cols <- intersect(c("L1", "L2", "L3"), colnames(cs)) - rings <- split( - cs[, "X"], - interaction(as.data.frame(cs[, ring_cols, drop = FALSE]), drop = TRUE) - ) - max(vapply(rings, function(v) if (length(v) < 2L) 0 else max(abs(diff(v))), - numeric(1))) - }, error = function(e) NA_real_) - - if (is.finite(span) && span > 180) { - warning("An edge of `region` spans ", round(span), - " degrees of longitude. Under spherical geometry that edge is ", - "drawn the short way, across the antimeridian, so `region` is much ", - "smaller than its coordinates suggest. See the \"Regions that cross ", - "the antimeridian\" section of ?design_spatial.", call. = FALSE) + x <- vector("list", n) + y <- vector("list", n) + for (k in seq_len(n - 1L)) { + t <- seq_len(steps[k] - 1L) / steps[k] + p <- (sin((1 - t) * w[k]) %o% a[k, ] + sin(t * w[k]) %o% b[k, ]) / + sin_w[k] + ref <- lon[k] + t * dx[k] + turn <- atan2(p[, 2], p[, 1]) * 180 / pi - ref + x[[k]] <- c(lon[k], ref + turn - 360 * round(turn / 360)) + y[[k]] <- c(lat[k], asin(pmax(-1, pmin(1, p[, 3]))) * 180 / pi) } + x[[n]] <- lon[n] + y[[n]] <- lat[n] + list(x = unlist(x, use.names = FALSE), y = unlist(y, use.names = FALSE)) +} + +# ---- warnings about the region's edges -------------------------------------- + +#' Warn about edges that s2 draws differently from a flat map +#' +#' Called once by [draw()], [inclusion_prob()] and [joint_prob()], and through +#' them by `plot()`, and not by the draw method, so a simulation of `R` draws +#' warns once. Only spherical geometry on longitude/latitude coordinates is +#' affected. Anything that fails here fails again, with its own message, in +#' the call that follows, so failures are passed over in silence. +#' +#' @noRd +warn_region <- function(design, data) { + while (inherits(design, "drawn_design_certainty")) design <- design$rest + if (!inherits(design, "drawn_design_spatial") || + !requireNamespace("sf", quietly = TRUE) || !isTRUE(sf::sf_use_s2())) { + return(invisible(NULL)) + } + edges <- tryCatch({ + crs <- spatial_crs(design, data) + if (isTRUE(sf::st_is_longlat(crs))) { + region_edges(region_geometry(design$region, crs)) + } + }, error = function(e) NULL) + if (is.null(edges) || !length(edges$x0)) return(invisible(NULL)) + warn_antimeridian(edges) + warn_geodesic_edges(edges) invisible(NULL) } +#' Every edge of every ring, as the coordinates of its two ends +#' @noRd +region_edges <- function(region) { + cs <- sf::st_coordinates(sf::st_cast(region, "MULTIPOLYGON")) + ring <- cs[, intersect(c("L1", "L2", "L3"), colnames(cs)), drop = FALSE] + n <- nrow(cs) + from <- if (n > 1L) { + which(rowSums(ring[-1L, , drop = FALSE] != ring[-n, , drop = FALSE]) == 0) + } else { + integer(0) + } + list(x0 = unname(cs[from, "X"]), y0 = unname(cs[from, "Y"]), + x1 = unname(cs[from + 1L, "X"]), y1 = unname(cs[from + 1L, "Y"])) +} + +#' Warn when an edge joins longitudes more than 180 degrees apart +#' +#' s2 draws such an edge the short way, across the antimeridian. That is +#' what a region meant to cross it needs, and the opposite of what a region +#' meant to go the long way round needs, so the warning gives both readings. +#' Checking the raw coordinates is exact and cheap; comparing areas is not, +#' because a collapsed ring and its bounding box collapse together. +#' +#' An edge from -180 to 180 counts: both ends lie on one meridian, so s2 +#' gives it no extent in longitude, and a box spanning every longitude +#' encloses nothing. An edge along a pole does not count, since every +#' longitude meets there and the edge has no length in either reading; a +#' cap around a pole is closed that way. +#' +#' @noRd +warn_antimeridian <- function(e) { + dx <- e$x1 - e$x0 + span <- abs(dx) + pole <- abs(abs(e$y0) - 90) < 1e-9 & abs(abs(e$y1) - 90) < 1e-9 + span[pole] <- 0 + i <- which.max(span) + if (!length(i) || !(span[i] > 180)) return(invisible(NULL)) + short <- abs(dx[i] - 360 * round(dx[i] / 360)) + taken <- if (short < 1e-9) { + paste0("Under spherical geometry both lie on the same meridian, so the ", + "edge spans 0 degrees of longitude.") + } else { + paste0("Under spherical geometry it takes the short way, across the ", + "antimeridian, a span of ", fmt_coord(short), " degrees.") + } + warn_drawn(paste0( + "An edge of `region` joins longitudes ", fmt_coord(e$x0[i]), " and ", + fmt_coord(e$x1[i]), ". ", taken, " If you meant it to span the ", + fmt_coord(span[i]), " degrees of longitude between the two values, ", + "split `region`; see the \"Regions that cross the antimeridian\" ", + "section of ?design_spatial."), + "drawn_antimeridian") +} + +#' Warn when an edge strays far from the straight line in degrees +#' +#' The distance is measured from points a quarter, a half and three quarters +#' of the way along the straight line between the edge's ends, in longitude +#' and latitude, to the great circle through those ends, as an angle at the +#' centre of the globe. An edge longer than 180 degrees of longitude is taken +#' the short way, as s2 takes it. +#' +#' @noRd +warn_geodesic_edges <- function(e, limit = 0.1) { + dx <- e$x1 - e$x0 + dx <- dx - 360 * round(dx / 360) + a <- unit_vector(e$x0, e$y0) + b <- unit_vector(e$x0 + dx, e$y1) + normal <- cbind(a[, 2] * b[, 3] - a[, 3] * b[, 2], + a[, 3] * b[, 1] - a[, 1] * b[, 3], + a[, 1] * b[, 2] - a[, 2] * b[, 1]) + len <- sqrt(rowSums(normal^2)) + # Ends that coincide, or lie opposite each other, fix no great circle. + flat <- len < 1e-12 + len[flat] <- 1 + bow <- numeric(length(len)) + for (t in c(0.25, 0.5, 0.75)) { + p <- unit_vector(e$x0 + t * dx, e$y0 + t * (e$y1 - e$y0)) + off <- abs(rowSums(p * normal)) / len + bow <- pmax(bow, asin(pmin(off, 1)) * 180 / pi) + } + bow[flat] <- 0 + i <- which.max(bow) + if (!length(i) || !(bow[i] > limit)) return(invisible(NULL)) + km <- bow[i] * pi / 180 * 6371 + warn_drawn(paste0( + "An edge of `region`, from (", fmt_coord(e$x0[i]), ", ", + fmt_coord(e$y0[i]), ") to (", fmt_coord(e$x1[i]), ", ", + fmt_coord(e$y1[i]), "), follows a great circle under spherical geometry ", + "and passes ", format(signif(bow[i], 3)), " degrees (about ", + format(signif(km, 2), big.mark = ","), " km) from the straight line ", + "between its ends on a longitude/latitude map. Rows near it can be ", + "inside `region` though outside the polygon as drawn on such a map, or ", + "the reverse. See the \"Edges of a longitude/latitude region\" section ", + "of ?design_spatial to make the edges follow those lines."), + "drawn_geodesic_edges") +} + +#' Points on the unit sphere, one row per longitude and latitude in degrees +#' @noRd +unit_vector <- function(lon, lat) { + lon <- lon * pi / 180 + lat <- lat * pi / 180 + cbind(cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat)) +} + +#' @noRd +fmt_coord <- function(x) format(signif(x, 6)) + # ---- inclusion probability ------------------------------------------------ #' @noRd exact_inclusion.drawn_design_spatial <- function(design, data) { - require_suggested("sf", "spatial sampling") - validate_data(data, required_columns = design$coords) - inside <- spatial_inside(design, data) + inside <- spatial_setup(design, data) out <- numeric(nrow(data)) - if (!any(inside)) return(out) - out[inside] <- min(1, design$n / sum(inside)) + out[inside] <- design$n / sum(inside) out } -#' A region has to be geometry `sf` can read, with a CRS +#' A region has to be polygons `sf` can read, with a CRS #' #' Both were stored unchecked, so a NULL region or a nonsense CRS surfaced much -#' later as a raw `sf` message that named neither argument. +#' later as a raw `sf` message that named neither argument. The region is +#' built once here, as `region_geometry()` builds it at draw time, so each +#' member of a list is checked and reprojected to `crs` before it is stored. #' #' @noRd check_region <- function(region, crs) { if (!requireNamespace("sf", quietly = TRUE)) return(invisible(NULL)) - geom <- tryCatch({ - if (is.list(region) && !inherits(region, c("sf", "sfc"))) { - if (!length(region)) { - stop("`region` is an empty list.", call. = FALSE) - } - sf::st_union(do.call(c, lapply(region, sf::st_geometry))) - } else { - sf::st_geometry(region) - } - }, error = function(e) { - stop("`region` must be an sf or sfc geometry, or a list of them, not ", - if (is.null(region)) "NULL" else class(region)[1], ". (", - conditionMessage(e), ")", call. = FALSE) - }) - if (is.na(sf::st_crs(geom))) { - stop("`region` has no CRS. Set one with sf::st_set_crs().", call. = FALSE) - } tryCatch(sf::st_crs(crs), error = function(e) { stop("`crs` is not a coordinate reference system sf recognises: ", conditionMessage(e), call. = FALSE) @@ -219,5 +641,6 @@ check_region <- function(region, crs) { stop("`crs` is not a coordinate reference system sf recognises.", call. = FALSE) } + region_geometry(region, crs) invisible(NULL) } diff --git a/R/design-spread.R b/R/design-spread.R index 8a26a14..b116df1 100644 --- a/R/design-spread.R +++ b/R/design-spread.R @@ -30,6 +30,17 @@ #' not decide the distances alone; set `scale = FALSE` for coordinates that #' already share a unit, such as projected metres. #' +#' A Date column in `across` counts in days and a date-time (POSIXct) column +#' in seconds since 1970, so time can be spread over alongside space. Keep +#' `scale = TRUE` when mixing them with coordinates, or the column in the +#' larger unit decides the distances. `size` has to be numeric. +#' +#' A POINT geometry column, such as the geometry of an `sf` frame, counts as +#' its two coordinates, read with [sf::st_coordinates()]: `across = +#' "geometry"` spreads over the map. Distances are measured in the +#' geometry's own units, so longitude and latitude are treated as plain +#' numbers; a projected CRS gives distances in metres. +#' #' @section Variance: #' The joint inclusion probabilities of a pivotal design have no closed form, #' and treating the sample as simple random would give away exactly the gain @@ -37,27 +48,120 @@ #' mean variance estimator (Stevens and Olsen 2003; Grafström and Schelin #' 2014), which compares each sampled row with the mean of itself and its three #' nearest sampled neighbours. It is an approximation, reported as -#' `method = "local mean"`, and errs on the conservative side: in the -#' package's simulations it runs from about 1 to 1.6 times the true variance, -#' higher for small samples and large sampling fractions. +#' `method = "local mean"`, and usually overstates the variance. The table +#' gives the ratio of its average to the true variance of the total, over +#' 1,000 draws from one frame per cell, by `n` and the sampling fraction +#' `f = n / N`. The frames are uniform on the unit square, spread with +#' `scale = FALSE`; the smooth surface is the one in the examples, and the +#' other variable is normal noise unrelated to position. +#' +#' | Variable | `n` | `f` = 0.05 | 0.2 | 0.5 | 0.8 | +#' |:--|--:|--:|--:|--:|--:| +#' | smooth surface | 8 | 2.2 | 2.5 | 2.3 | 3.6 | +#' | | 20 | 1.6 | 1.5 | 2.3 | 1.4 | +#' | | 40 | 1.1 | 1.3 | 1.9 | 2.1 | +#' | unrelated to position | 8 | 1.0 | 1.4 | 1.8 | 4.7 | +#' | | 20 | 1.0 | 1.2 | 1.8 | 4.5 | +#' | | 40 | 1.0 | 1.3 | 1.9 | 4.9 | +#' +#' For a variable unrelated to position the ratio is close to `1 / (1 - f)`, +#' since the estimator then reduces to the with-replacement variance of a +#' simple random sample. It also varies from frame to frame: with `n = 20` +#' and `f = 0.05`, four frames of 400 rows gave 0.96 to 1.15 for that +#' variable and 1.36 to 1.52 for the smooth surface, so a ratio slightly +#' below 1 occurs too. Below about 10 sampled rows the ratio climbs: `n = 4` +#' gave 2.4 for the smooth surface at `f = 0.05`, and 18.9 on a frame of 8 +#' rows. +#' +#' [deff()] divides this variance by a simple random sample's, so it carries +#' the same overstatement: at a ratio of 2, a spread sample with a true design +#' effect of 0.8 reports 1.6, worse than a simple random sample when it is +#' better. Rows taken with certainty, because their `size` puts them past it +#' or because `n` is the whole frame, are in every sample and add no variance, +#' so the estimator leaves them out. +#' +#' @section Strata: +#' With `strata`, `n` is split over the strata as [design_stratified()] +#' splits it, by `allocation`, and each stratum is then spread on its own, as +#' if it were a frame of its own: `scale` standardises the columns within the +#' stratum, `size` sets probabilities proportional to size within it, and a +#' row competes only with rows of its own stratum. [inclusion_prob()] gives +#' `n_h / N_h` within stratum `h`, or `n_h * p_i` with `size`, exactly. +#' +#' The strata are drawn independently, so [ht_total()] and [ht_mean()] add up +#' the local mean variance of each stratum, and the degrees of freedom are +#' the sampled rows below certainty less the strata that hold them. A stratum +#' with one sampled row below certainty has no neighbour to compare it with, +#' and the variance is refused with the stratum named, as a stratified +#' sample's is; draw at least two rows in every stratum. [as_svydesign()] +#' hands the strata to `survey`, [allocation_table()] shows the split before +#' anything is drawn, and [sample_summary()] lists the rows drawn from each +#' stratum. +#' +#' Drawing each stratum with a design of its own and binding the samples with +#' [rbind()] does not give a sample to estimate from. The bound sample keeps +#' the first draw's frame and design, so [ht_total()] refuses it; use +#' `strata` instead. +#' +#' @section Reserves: +#' `reserve` lists that many more rows after the main sample, to visit in +#' place of rows found unavailable in the field, as [design_simple()] does. +#' The reserves are a second spread sample, of `reserve` rows at equal +#' probability from the rows the main sample left, so they cover the space +#' as evenly as the main sample does, and they come in random order. +#' [draw()] returns the main sample in frame order followed by the reserves, +#' with an integer `.reserve` column: 0 for the main sample, and 1, 2, ... +#' for the reserves, in the order they are used. The main sample is the one +#' the design without `reserve` draws with the same seed. +#' +#' [use_reserves()] takes the list and what the visits found, and returns +#' the sample to estimate from. It weights the rows used as a spread sample +#' of `n` from the frame without the `u` rows found unavailable, at +#' probability `n / (N - u)`. That is the average of the rows' probabilities, +#' not each row's own, so the weights are an approximation. The variance is +#' the local mean estimator, as for any spread sample. Only an unstratified +#' design without `size`, whose rows all have probability `n / N`, takes +#' `reserve`. #' #' @section Cost: #' Each step finds a nearest neighbour among the rows still undecided, so the #' draw takes time proportional to `N^2`: under a second for 5,000 rows, and -#' several seconds at 20,000. For much larger frames, spread within strata or -#' thin the frame first. +#' several seconds at 20,000. With `strata`, the walk runs within each +#' stratum and the time grows with the square of each stratum's size: 20,000 +#' rows in four strata of 5,000 took under a third of the time they took as +#' one frame. For much larger frames, use strata, or thin the frame first. #' #' @param across Column names to spread the sample across: two coordinates for -#' a map, or any numeric auxiliary variables. At least one. -#' @param n Number of rows to draw. Fixed, not expected. +#' a map, or any numeric auxiliary variables. At least one. A Date or +#' date-time column, and a POINT geometry column, are read as numbers; see +#' "Spreading over more than space". +#' @param n Number of rows to draw, the total across `strata` when given, or +#' a plan from [plan_size()]. +#' Fixed, not expected. With counts in `allocation` it can be left out and +#' is their sum; when given, it must equal that sum. #' @param size Optional column of positive size measures. When given, rows are #' included with probability proportional to size — `n * size / sum(size)`, #' with rows past certainty taken whole, exactly as #' [design_weighted()] — and spread at the same time. #' @param scale Standardise each column of `across` to unit standard deviation #' before measuring distance. See "Spreading over more than space". -#' @param na_rm Drop rows with a missing value in `across` or `size` instead of -#' raising an error. +#' @param na_rm Drop rows with a missing value in `across`, `size` or +#' `strata` instead of raising an error. +#' @param strata Optional column name(s) defining strata, to spread the +#' sample within each one. Several columns are cross-classified. See +#' "Strata". +#' @param allocation How `n` is split across `strata`: `"proportional"` to +#' each stratum's size, or `"equal"`, by the largest-remainder method of +#' [design_stratified()], with a stratum that would get more rows than it +#' holds taken whole; or the count for each stratum, as a named vector such +#' as `c(north = 10, south = 5)` when `strata` is one column, or a data +#' frame of the `strata` columns and `n`. Counts follow the rules of +#' [design_stratified()]: every stratum of the frame needs one, a count for +#' a stratum the frame does not have is refused, and no count may exceed +#' the rows in its stratum. Only with `strata`. +#' @param reserve Number of reserve rows to list after the main sample, to +#' replace rows found unavailable in the field. Not available with `size`, +#' `strata` or `n = 0`. See "Reserves". #' #' @return A design object, for use with [draw()]. #' @@ -102,18 +206,75 @@ #' plot(spread, plots, type = "map", seed = 1) #' par(op) #' +#' # Spread within two regions, each given rows in proportion to its size +#' plots$region <- ifelse(plots$x < 0.5, "west", "east") +#' by_region <- design_spread(c("x", "y"), n = 40, scale = FALSE, +#' strata = "region") +#' allocation_table(plots, by_region) +#' ht_total(draw(plots, by_region, seed = 1, weights = TRUE), "biomass") +#' #' @family designs #' @seealso [draw()], [design_spatial()] to restrict sampling to a region, -#' [design_weighted()] for size-proportional selection without spreading. +#' [design_weighted()] for size-proportional selection without spreading, +#' [design_stratified()] for the allocation rules, [allocation_table()], +#' [use_reserves()]. #' @export design_spread <- function(across, n, size = NULL, scale = TRUE, - na_rm = FALSE) { + na_rm = FALSE, strata = NULL, + allocation = c("proportional", "equal"), + reserve = 0) { + if (!missing(n)) n <- plan_n(n) + across <- check_columns(across, "across") + if (is.null(strata)) { + if (!missing(allocation) && !is.null(allocation)) { + stop("`allocation` splits `n` over strata, and `strata` is NULL. Name ", + "the strata columns in `strata`, or leave `allocation` out.", + call. = FALSE) + } + allocation <- NULL + n <- check_count(n, "n") + } else { + strata <- check_columns(strata, "strata") + if (is.numeric(allocation) || is.data.frame(allocation)) { + allocation <- check_stratum_counts(allocation, strata) + n <- counts_n(if (!missing(n)) n, allocation) + } else { + if (!is.null(allocation) && !is.character(allocation)) { + stop("`allocation` must be \"proportional\", \"equal\" or the count ", + "for each stratum, not ", format_bad(allocation), ".", + call. = FALSE) + } + allocation <- check_choice(allocation, c("proportional", "equal"), + "allocation") + if (missing(n) || is.null(n)) { + stop("`n` is missing. Give the total number of rows to draw, or the ", + "count for each stratum in `allocation`.", call. = FALSE) + } + n <- check_count(n, "n") + } + } + size <- if (is.null(size)) NULL else check_columns(size, "size", 1L) + scale <- check_flag(scale, "scale") + na_rm <- check_flag(na_rm, "na_rm") + reserve <- check_reserve(reserve, n) + if (reserve > 0L && (!is.null(size) || !is.null(strata))) { + by <- if (!is.null(size)) "size" else "strata" + stop("`reserve` needs every row at the same probability, and `", by, + "` ", if (by == "size") { + "makes it proportional to size" + } else { + "splits `n` over strata" + }, ". Leave out `", by, "` or `reserve`.", call. = FALSE) + } new_design("spread", list( - across = check_columns(across, "across"), - n = check_count(n, "n"), - size = if (is.null(size)) NULL else check_columns(size, "size", 1L), - scale = check_flag(scale, "scale"), - na_rm = check_flag(na_rm, "na_rm") + across = across, + strata = strata, + n = n, + allocation = allocation, + size = size, + scale = scale, + na_rm = na_rm, + reserve = reserve )) } @@ -123,54 +284,133 @@ design_spread <- function(across, n, size = NULL, scale = TRUE, #' agree on which rows are dropped, how the columns are scaled, and what each #' row's probability is. #' +#' `keep` holds the frame rows the design can use, and `x` and `pi` the +#' scaled positions and target probabilities of those rows. The rest is by +#' position in `keep`: `idx` lists the rows of each stratum, in key order, +#' `code` gives each row's stratum as a position in `labels`, `sizes` and +#' `n_alloc`, and `n_alloc` is the rows drawn from each stratum. A design +#' without `strata` has one stratum, with no `code` or `labels`. Each stratum +#' is scaled and sized on its own, as a frame of its own would be, and its +#' split of `n` comes from `stratum_allocation()`, as a stratified design's +#' does. +#' #' @noRd spread_frame <- function(design, data) { cols <- c(design$across, design$size) - validate_data(data, required_columns = cols) - check_key_columns(data, cols, "across") - for (nm in cols) { - if (!is.numeric(data[[nm]])) { - stop("`", nm, "` must be numeric to spread across or size by, not ", - class(data[[nm]])[1], ".", call. = FALSE) + strata <- design$strata + validate_data(data, required_columns = c(cols, strata)) + geom <- vapply(cols, function(nm) inherits(data[[nm]], "sfc"), logical(1)) + check_key_columns(data, cols[!geom], "across") + if (!is.null(strata)) check_key_columns(data, strata, "strata") + for (nm in design$across) { + col <- data[[nm]] + if (!is.numeric(col) && !inherits(col, c("Date", "POSIXt", "sfc"))) { + stop("`", nm, "` must be numeric to spread across, not ", + class(col)[1], ". A Date, date-time or POINT geometry column ", + "works too; convert anything else to numbers first, for example ", + "with as.numeric().", call. = FALSE) } } - bad <- Reduce(`|`, lapply(data[cols], is.na)) + if (!is.null(design$size) && !is.numeric(data[[design$size]])) { + stop("`", design$size, "` must be numeric to size by, not ", + class(data[[design$size]])[1], ".", call. = FALSE) + } + x_cols <- coordinate_columns(data, design$across, "across", time = TRUE) + bad <- spread_missing(x_cols, + if (!is.null(design$size)) data[[design$size]]) + key <- if (!is.null(strata)) group_key(data, strata) + if (!is.null(strata)) bad <- bad | is.na(key) check_na_policy(bad, design$na_rm, paste0("a missing value in ", - paste0("`", cols, "`", collapse = ", "))) + paste0("`", c(cols, strata), "`", collapse = ", "))) keep <- which(!bad) if (!length(keep)) stop("Every row has a missing value.", call. = FALSE) + # Rows use_reserves() found unavailable are outside the design's frame. + if (!is.null(design[["unavailable"]])) { + keep <- intersect(keep, available_rows(design, nrow(data))) + } - x <- as.matrix(data[keep, design$across, drop = FALSE]) - storage.mode(x) <- "double" + x <- matrix(vapply(x_cols, function(v) as.numeric(v[keep]), + numeric(length(keep))), + nrow = length(keep), dimnames = list(NULL, names(x_cols))) if (any(!is.finite(x))) { stop("`across` contains non-finite values.", call. = FALSE) } - if (design$scale) { - s <- apply(x, 2, stats::sd) - s[!is.finite(s) | s == 0] <- 1 - x <- sweep(x, 2, s, "/") - } - if (design$n > length(keep)) { - stop("`n` (", design$n, ") cannot exceed the number of rows (", - length(keep), ").", call. = FALSE) - } - pi <- if (is.null(design$size)) { - rep(design$n / length(keep), length(keep)) + if (is.null(strata)) { + if (design$n > length(keep)) { + stop("`n` (", design$n, ") cannot exceed the number of rows (", + length(keep), ").", call. = FALSE) + } + check_reserve_size(design, length(keep)) + al <- list(idx = list(seq_along(keep)), sizes = length(keep), + n_alloc = design$n) } else { + refuse_emptied_counts(design, data, key, keep, paste0( + "a missing value in ", paste0("`", cols, "`", collapse = ", "))) + al <- stratum_allocation(design, table_frame( + lapply(strata, function(col) data[[col]][keep]), strata, list())) + } + w <- NULL + if (!is.null(design$size)) { w <- data[[design$size]][keep] check_weights(w, design$size) - pps_pi(w, design$n) } - list(keep = keep, x = x, pi = pi) + + pi <- numeric(length(keep)) + for (h in seq_along(al$idx)) { + i <- al$idx[[h]] + if (design$scale) { + s <- apply(x[i, , drop = FALSE], 2, stats::sd) + s[!is.finite(s) | s == 0] <- 1 + x[i, ] <- sweep(x[i, , drop = FALSE], 2, s, "/") + } + pi[i] <- if (is.null(w)) { + al$n_alloc[h] / length(i) + } else { + pps_pi(w[i], al$n_alloc[h]) + } + } + list(keep = keep, x = x, pi = pi, idx = al$idx, code = al$code, + labels = al$labels, sizes = al$sizes, n_alloc = al$n_alloc) +} + +#' Rows with a missing value in any column a spread design reads +#' +#' `x_cols` is `coordinate_columns()` of `across`, so an empty point counts +#' as missing; `size` is that column, or `NULL`. +#' +#' @noRd +spread_missing <- function(x_cols, size = NULL) { + Reduce(`|`, lapply(c(x_cols, if (!is.null(size)) list(size)), is.na)) } #' @export draw_design.drawn_design_spread <- function(design, data) { fr <- spread_frame(design, data) - picked <- local_pivotal(fr$pi, fr$x) - reindex(data, fr$keep[picked], sort = TRUE) + if (!is.null(design$strata)) { + warn_empty_groups(fr$n_alloc, fr$sizes, fr$labels, fix = paste0( + if (has_counts(design)) "Give " else "Raise `n`, or give ", + "each stratum a count of at least 1 in `allocation` (or 2, so each ", + "stratum also supports a variance).")) + } + # Strata are drawn one after another in key order, each by its own + # pivotal walk. + picked <- unlist(lapply(fr$idx, function(i) { + i[local_pivotal(fr$pi[i], fr$x[i, , drop = FALSE])] + }), use.names = FALSE) + r <- reserve_size(design) + if (r == 0L) return(reindex(data, fr$keep[picked], sort = TRUE)) + + # The reserves are a second pivotal sample, of `reserve` rows at equal + # probability from the rows the main sample left, so they are spread over + # the space too. They are used in random order. + left <- setdiff(seq_along(fr$keep), picked) + spare <- left[local_pivotal(rep(r / length(left), length(left)), + fr$x[left, , drop = FALSE])] + spare <- spare[sample.int(length(spare))] + out <- reindex(data, fr$keep[c(sort(picked), spare)]) + with_reserve(out, design$n, r) } #' The local pivotal method, LPM2 @@ -182,13 +422,18 @@ draw_design.drawn_design_spread <- function(design, data) { #' therefore exactly its target, while neighbours rarely end up in the sample #' together. Ties for nearest neighbour are broken at random. #' +#' Every row with a target above 0 competes, however small the target. Each +#' step settles one of the pair at exactly 0 or 1, so the loop ends after at +#' most one step per row. A pooled probability less than `eps` below 1 is +#' the rounding error of a sum that is 1 in exact arithmetic and is settled +#' at 1, and a remainder less than `eps` above 1 is settled at 0 for the same +#' reason. A small pooled probability is kept, so two rows of `1e-13` pool to +#' `2e-13` and not to 0. +#' #' @noRd -local_pivotal <- function(pi, x, eps = 1e-9) { +local_pivotal <- function(pi, x, eps = 1e-12) { p <- pi - p[p < eps] <- 0 - p[p > 1 - eps] <- 1 - open <- p > 0 & p < 1 - idx <- which(open) + idx <- which(p > 0 & p < 1) while (length(idx) > 1L) { i <- idx[sample.int(length(idx), 1L)] others <- idx[idx != i] @@ -198,22 +443,20 @@ local_pivotal <- function(pi, x, eps = 1e-9) { else nearest s <- p[i] + p[j] if (s < 1) { + pooled <- if (s > 1 - eps) 1 else s if (stats::runif(1) < p[j] / s) { - p[j] <- s; p[i] <- 0 + p[j] <- pooled; p[i] <- 0 } else { - p[i] <- s; p[j] <- 0 + p[i] <- pooled; p[j] <- 0 } } else { + left <- if (s - 1 < eps) 0 else s - 1 if (stats::runif(1) < (1 - p[j]) / (2 - s)) { - p[i] <- 1; p[j] <- s - 1 + p[i] <- 1; p[j] <- left } else { - p[j] <- 1; p[i] <- s - 1 + p[j] <- 1; p[i] <- left } } - for (k in c(i, j)) { - if (p[k] < eps) p[k] <- 0 - if (p[k] > 1 - eps) p[k] <- 1 - } idx <- idx[p[idx] > 0 & p[idx] < 1] } # A single row left over only when the probabilities did not sum to a whole @@ -238,9 +481,8 @@ exact_inclusion.drawn_design_spread <- function(design, data) { joint_inclusion.drawn_design_spread <- function(design, data, rows) { no_joint_form( "`design_spread()`", - paste0("The local pivotal method has no closed-form joint inclusion ", - "probability. Pass\nsimulate = TRUE to estimate them; ht_total() ", - "uses the local mean variance\nestimator instead.") + paste0("ht_total() uses the local mean variance estimator, which needs ", + "no joint probabilities.") ) } @@ -259,37 +501,123 @@ joint_inclusion.drawn_design_spread <- function(design, data, rows) { #' but left smooth ones understated by about a quarter at a 20-40% sampling #' fraction, and understating is the worse failure. #' +#' `nb` is `local_neighbours(x, k)` when the caller has it already, as the +#' domains of one sample do. +#' #' @noRd -local_mean_variance <- function(x, y, pi_i, k = 4L) { +local_mean_variance <- function(x, y, pi_i, k = 4L, nb = NULL) { n <- length(y) if (n < 2L) { return(list(variance = NA_real_, method = "local mean", note = "A variance needs at least two sampled rows.")) } u <- y / pi_i - x <- as.matrix(x) - k <- min(k, n) - dev <- vapply(seq_len(n), function(i) { - d <- colSums((t(x) - x[i, ])^2) - d[i] <- -Inf # itself first - nb <- order(d)[seq_len(k)] - kk <- length(nb) - kk / (kk - 1) * (u[i] - mean(u[nb]))^2 - }, numeric(1)) + nb <- nb %||% local_neighbours(x, k) + kk <- ncol(nb) + local <- rowMeans(matrix(u[nb], nrow = n)) + dev <- kk / (kk - 1) * (u - local)^2 list(variance = sum(dev), method = "local mean", note = paste0("Local mean approximation for a spatially balanced ", "sample: the local pivotal method has no closed-form ", "joint inclusion probabilities.")) } +#' Each sampled row's neighbourhood for the local mean +#' +#' Row `i` of the result holds the row itself and its `k - 1` nearest rows of +#' `x`, by squared distance, `k` at most the number of rows. The +#' neighbourhoods depend on where the rows lie and not on `y`. +#' #' @noRd -ht_variance.drawn_design_spread <- function(design, data, rows, y, pi_i) { - fr <- spread_frame(design, data) +local_neighbours <- function(x, k = 4L) { + x <- as.matrix(x) + n <- nrow(x) + k <- min(k, n) + nb <- vapply(seq_len(n), function(i) { + d <- colSums((t(x) - x[i, ])^2) + d[i] <- -Inf # itself first + order(d)[seq_len(k)] + }, integer(k)) + matrix(nb, nrow = n, ncol = k, byrow = TRUE) +} + +#' Variance of a spread sample +#' +#' Rows taken with certainty, in a census or because a `size` column puts them +#' past it, are in every possible sample and add no variance. Kept in, each +#' one's distance from its neighbours' mean counted as sampling variation. A +#' census then reported a standard error of about 5% of its exact total, and +#' on a frame with three dominant sizes the estimate averaged 1,270 times the +#' true variance. They are left out, both as rows and as neighbours, and the +#' estimator runs over the rest. +#' +#' With `strata`, each stratum is a spread sample of its own, drawn +#' independently of the others, so the variance is the sum of the strata's +#' local mean variances, with neighbours found within each stratum. +#' +#' @noRd +ht_variance.drawn_design_spread <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + fr <- from_context(ctx, "spread", spread_frame(design, data)) pos <- match(rows, fr$keep) if (anyNA(pos)) { return(list(variance = NA_real_, note = paste0( "Some sampled rows were dropped by this design's `na_rm`, so they have ", "no place in the space the variance is computed over."))) } - local_mean_variance(fr$x[pos, , drop = FALSE], y, pi_i) + free <- !is_certain(pi_i) + if (!any(free)) return(all_certain()) + if (!is.null(design$strata)) { + return(spread_strata_variance(design, data, fr, rows, pos, y, pi_i, free, + domain, ctx)) + } + if (sum(free) < 2L) { + return(list(variance = NA_real_, method = "local mean", note = paste0( + "Only one sampled row was not taken with certainty, so the local mean ", + "estimator has no neighbour to compare it with. Draw a larger `n`."))) + } + x <- fr$x[pos[free], , drop = FALSE] + local_mean_variance(x, y[free], pi_i[free], + nb = from_context(ctx, "neighbours", local_neighbours(x))) +} + +#' The local mean variance of a spread sample with strata +#' +#' The sum over strata of `local_mean_variance()` on each stratum's sampled +#' rows below certainty. A stratum with one such row has no neighbour to +#' compare it with, and is refused by `lonely_note()`, unless `domain` shows +#' it holds no unit of the domain, when it adds 0. `fr` is `spread_frame()` +#' of the frame `data`, `pos` the sampled rows' positions in `fr$keep`, and +#' `free` marks the sampled rows below certainty. +#' +#' @noRd +spread_strata_variance <- function(design, data, fr, rows, pos, y, pi_i, + free, domain = NULL, ctx = NULL) { + k <- length(fr$sizes) + # Each frame row's stratum, counting only the rows below certainty. + code <- rep(NA_integer_, nrow(data)) + open <- !is_certain(fr$pi) + code[fr$keep[open]] <- fr$code[open] + group <- structure(code, levels = fr$labels, class = "factor") + note <- lonely_note(group, rows, c("stratum", "strata"), lonely_fix(design), + domain) + if (!is.null(note)) { + return(list(variance = NA_real_, method = "local mean", note = note)) + } + h <- fr$code[pos] + by_stratum <- lapply(seq_len(k), function(g) which(free & h == g)) + nb <- from_context(ctx, "neighbours", lapply(by_stratum, function(i) { + if (length(i) >= 2L) local_neighbours(fr$x[pos[i], , drop = FALSE]) + })) + v <- 0 + for (g in seq_len(k)) { + i <- by_stratum[[g]] + if (length(i) < 2L) next + v <- v + local_mean_variance(fr$x[pos[i], , drop = FALSE], y[i], + pi_i[i], nb = nb[[g]])$variance + } + list(variance = v, method = "local mean", + note = paste0("Local mean approximation for a spatially balanced ", + "sample, summed over strata: the local pivotal method ", + "has no closed-form joint inclusion probabilities.")) } diff --git a/R/design-stratified.R b/R/design-stratified.R index 13771e6..70ceb38 100644 --- a/R/design-stratified.R +++ b/R/design-stratified.R @@ -6,19 +6,47 @@ #' #' @param strata One or more column names defining the strata. Several columns #' are cross-classified. -#' @param n Total rows to draw across all strata, under either allocation. -#' @param allocation How `n` is split across strata. `"proportional"` gives each -#' stratum a share of `n` in proportion to its size; `"equal"` splits `n` -#' evenly; `"neyman"` gives shares proportional to `size * sd`, using the -#' column named by `allocation_by` (Neyman 1934). Neyman minimises the -#' variance of a total for a fixed `n` by putting more rows where the values -#' vary most, and is the right choice when you have a frame variable -#' correlated with what you are measuring. Under any rule, a stratum that -#' would be allocated more rows than it holds is taken whole and the rest of -#' `n` re-split over the others by the same rule (Cochran 1977, section 5.9). -#' @param allocation_by Column whose within-stratum standard deviation drives -#' `allocation = "neyman"`. Ignored otherwise. -#' @param min_per_stratum Minimum rows from each stratum. With the default of +#' @param n Total rows to draw across all strata, under any allocation, or a +#' plan from [plan_size()]. With counts in `allocation` it can be left out +#' and is their sum; when given, it must equal that sum. +#' @param allocation How `n` is split across strata: a rule, or the count for +#' each stratum. Of the rules, `"proportional"` gives each stratum a share +#' of `n` in proportion to its size; `"equal"` splits `n` evenly; +#' `"neyman"` gives shares proportional to `size * sd`, with the standard +#' deviation of each stratum from `allocation_by` (Neyman 1934). Neyman +#' minimises the variance of a total for a fixed `n` by putting more rows +#' where the values vary most, and is the right choice when you have a +#' frame variable correlated with what you are measuring, or estimates of +#' each stratum's standard deviation from a pilot or an earlier survey. +#' Under any rule, a stratum that would be +#' allocated more rows than it holds is taken whole, one that would get +#' fewer than `min_per_stratum` gets that many, and the rest of `n` is +#' re-split over the others by the same rule (Cochran 1977, section 5.9). +#' +#' Counts are a named vector, such as `c(north = 10, south = 5, east = 5)`, +#' when `strata` is one column, its names matched to that column's values +#' as text; or a data frame holding the `strata` columns and a column `n`, +#' matched on the values themselves. Every stratum of the frame needs a +#' count, 0 included, and a count for a stratum the frame does not have is +#' refused, so a misspelt name cannot quietly leave a stratum out. Without +#' replacement no count may exceed the rows in its stratum. The design then +#' draws exactly those counts, and the inclusion probabilities, variances +#' and [as_svydesign()] follow them. +#' @param allocation_by The standard deviation of each stratum, for +#' `allocation = "neyman"`. Ignored otherwise. Either a column of the +#' frame, whose standard deviation within each stratum is used, and which +#' needs a finite value on every row allocated over; or the standard +#' deviations themselves, so the frame needs no such column. Those are a +#' named vector, such as `c(north = 40, south = 15)`, when `strata` is one +#' column, its names matched to that column's values as text; or a data +#' frame holding the `strata` columns and a column `sd`, matched on the +#' values themselves. Every stratum of the frame needs one, and each must +#' be finite and 0 or more. A value for a stratum the frame does not have +#' is ignored, so the same values serve a part of the frame, such as the +#' `rest` of [design_certainty()] when every row of a stratum is above the +#' threshold. A stratum with a standard deviation of 0 gets no share. +#' @param min_per_stratum Minimum rows from each stratum, under an allocation +#' rule. With the default of #' `0`, a stratum smaller than about `N / n` can be allocated no rows at all; #' its rows then have inclusion probability 0 and a total estimated from the #' sample silently leaves them out, so [draw()] warns when that happens. `1` @@ -26,11 +54,87 @@ #' Horvitz-Thompson total needs, and `2` also lets every stratum contribute #' to the variance estimate. Over-sampling a small stratum this way does #' *not* bias an estimate made with the design weights, which correct for it; -#' it only moves precision around. +#' it only moves precision around. Without replacement a stratum smaller +#' than the floor is taken whole, so `n` must cover `min_per_stratum` rows +#' from each stratum, or all of a smaller one. With counts in `allocation`, +#' give each stratum its count there instead. #' @param replace Sample with replacement within each stratum? #' @param na_rm Drop rows whose stratum key is `NA` instead of raising an error. +#' @param cost The cost of sampling one row in each stratum, for +#' `allocation = "neyman"` only. In the same forms as standard deviations +#' given in `allocation_by`, with the column of a data frame named `cost`, +#' so one data frame of the `strata` columns, `sd` and `cost` can serve +#' both. Each must be finite and above 0. The shares become proportional to +#' `size * sd / sqrt(cost)`, which gives the smallest variance among the +#' splits of the same total cost, `sum(cost * n_h)` over strata (Cochran +#' 1977, section 5.5). Before any stratum is held at its floor or its +#' size, the `n` that spends a budget `C`, net of any fixed cost, is +#' `C * sum(N_h * S_h / sqrt(c_h)) / sum(N_h * S_h * sqrt(c_h))`, rounded +#' down. When no stratum has any spread, the shares are +#' proportional to `size / sqrt(cost)`, as for equal spreads, and without +#' `cost` to `size`. +#' @param within How rows are drawn inside each stratum: `NULL`, the +#' default, for a simple random sample, or [design_systematic()] without +#' `interval` or `n`, to walk each stratum in the order of its `order_by` +#' column, or in frame order without one. Each stratum gets the rows the +#' allocation gives it, at an even step from a random start of its own; +#' see "Systematic sampling within strata". Needs `replace = FALSE`. +#' +#' @section Rounding, ties and the order of strata: +#' Each stratum first gets the whole part of its share of `n`. The rows left +#' over go one at a time to the strata with the largest fractional parts. When +#' two strata tie, the one with more rows not yet allocated goes first, and +#' after that the one that comes first in key order. `min_per_stratum` and +#' the size of each stratum bound the shares before they are rounded, so the +#' rounding never takes a stratum below its floor or past its size. +#' +#' Key order is the order of the levels for a factor column and the sorted +#' values for any other column, with text sorted byte by byte as in the C +#' locale (`"B"` before `"a"`). With several `strata` columns the first varies +#' slowest. Strata are also drawn from in this order, so a seed selects the +#' same rows in every locale. Renaming a stratum, or reordering a factor's +#' levels, can move a tied row from one stratum to another; the inclusion +#' probabilities always follow the allocation used. +#' +#' An empty string is a stratum like any other, shown as `(blank)` in +#' messages. +#' +#' @section Systematic sampling within strata: +#' With `within = design_systematic(order_by = "x")`, the strata are +#' allocated as without it, each stratum is sorted on `x`, and the `n_h` +#' rows allocated to a stratum of `N_h` are taken as +#' `design_systematic(n = n_h)` takes them from a frame of `N_h` rows: a +#' start drawn from (0, 1) and a step of `N_h / n_h` rows, which need not be +#' whole. Strata draw their starts in key order. Every row has probability +#' `n_h / N_h`, as under simple random sampling within strata, so the +#' allocation, [allocation_table()] and the weights are the same; what +#' changes is which rows can be drawn together. Two rows of one stratum have +#' the joint probability of the systematic design there, which is 0 for +#' rows at most `N_h / n_h - 1` rows apart, and two rows of different strata +#' the product of their probabilities. Rows whose `x` is missing are refused, +#' or with the `na_rm = TRUE` of the systematic design left out of their +#' stratum before it is allocated. +#' +#' Each stratum has one random start, so when any stratum is walked at a +#' step of 2 rows or more no design-unbiased variance exists, as for +#' [design_systematic()] on its own. [ht_total()] and [ht_mean()] +#' add up the strata's successive-difference approximations, +#' `(1 - n_h / N_h) * n_h / (2 * (n_h - 1)) * sum(diff(y / pi)^2)` over each +#' stratum's sampled rows in the order it was walked (Wolter 2007), with +#' the degrees of freedom of a stratified sample, the sampled rows less the +#' strata. A stratum with one sampled row from several is refused, as +#' without `within`. So is the jackknife: a stratum's rows all come from one +#' start, and deleting them one at a time does not mirror the design. +#' [as_svydesign()] hands `survey` the strata, whose simple-random variance +#' differs. #' -#' @return A design object, for use with [draw()]. +#' Only [design_systematic()] is taken as `within`, with one start and no +#' `interval` or `n`: the allocation sets the size of each stratum. To walk +#' a stratum by several columns, give `order_by` a column of ranks, as in +#' the examples of [design_systematic()]. +#' +#' @return A design object, for use with [draw()]. [allocation_table()] shows +#' the rows it takes from each stratum of a frame before anything is drawn. #' #' @references #' Neyman, J. (1934). On the two different aspects of the representative @@ -38,6 +142,9 @@ #' #' Cochran, W. G. (1977). *Sampling Techniques*, 3rd ed. Wiley. #' +#' Wolter, K. M. (2007). *Introduction to Variance Estimation*, 2nd ed. +#' Springer. +#' #' @examples #' df <- data.frame(id = 1:100, site = rep(letters[1:4], each = 25)) #' table(draw(df, design_stratified("site", n = 20), seed = 1)$site) @@ -47,37 +154,302 @@ #' skewed <- data.frame(id = 1:1000, g = c(rep("common", 999), "rare")) #' draw(skewed, design_stratified("g", n = 10, min_per_stratum = 1), seed = 1)$g #' +#' # A count for each stratum, drawn as given; `n` is their sum +#' fixed <- design_stratified("site", allocation = c(a = 8, b = 4, c = 4, d = 4)) +#' table(draw(df, fixed, seed = 1)$site) +#' +#' # Neyman from standard deviations known from an earlier survey, with the +#' # cost of reaching a row in each stratum +#' pilot <- design_stratified("site", n = 20, allocation = "neyman", +#' allocation_by = c(a = 4, b = 1, c = 2, d = 8), +#' cost = c(a = 1, b = 1, c = 4, d = 4)) +#' allocation_table(df, pilot) +#' +#' # Each stratum walked in order of `size`, from a start of its own +#' df$size <- (df$id * 37) %% 101 +#' walked <- design_stratified("site", n = 20, +#' within = design_systematic(order_by = "size")) +#' draw(df, walked, seed = 1) +#' #' @family designs -#' @seealso [draw()] +#' @seealso [draw()], [allocation_table()] #' @export design_stratified <- function(strata, n, allocation = c("proportional", "equal", "neyman"), allocation_by = NULL, min_per_stratum = 0L, replace = FALSE, - na_rm = FALSE) { - allocation <- match.arg(allocation) - if (allocation == "neyman" && is.null(allocation_by)) { - stop("`allocation = \"neyman\"` needs `allocation_by`, the column whose ", - "within-stratum spread should drive the split.", call. = FALSE) + na_rm = FALSE, cost = NULL, within = NULL) { + if (!missing(n)) n <- plan_n(n) + if (is.numeric(allocation) || is.data.frame(allocation)) { + strata <- check_columns(strata, "strata") + allocation <- check_stratum_counts(allocation, strata) + n <- counts_n(if (!missing(n)) n, allocation) + min_per_stratum <- check_count(min_per_stratum, "min_per_stratum") + if (min_per_stratum > 0L) { + stop("`min_per_stratum` (", min_per_stratum, ") is a floor for an ", + "allocation rule, and `allocation` gives the counts. Give each ", + "stratum a count of at least ", min_per_stratum, " there ", + "instead.", call. = FALSE) + } + } else { + if (!is.null(allocation) && !is.character(allocation)) { + stop("`allocation` must be \"proportional\", \"equal\", \"neyman\" ", + "or the count for each stratum, not ", format_bad(allocation), ".", + call. = FALSE) + } + allocation <- check_choice(allocation, + c("proportional", "equal", "neyman"), + "allocation") + if (allocation == "neyman" && is.null(allocation_by)) { + stop("`allocation = \"neyman\"` needs `allocation_by`, the column ", + "whose within-stratum spread should drive the split.", + call. = FALSE) + } + strata <- check_columns(strata, "strata") + if (missing(n) || is.null(n)) { + stop("`n` is missing. Give the total number of rows to draw, or the ", + "count for each stratum in `allocation`.", call. = FALSE) + } + if (is.numeric(n) && length(n) > 1L) { + stop("`n` must be a single whole number, the total across strata, not ", + format_bad(n), ". Give the count for each stratum as ", + "`allocation`, as in allocation = c(north = 10, south = 5).", + call. = FALSE) + } + n <- check_count(n, "n") + } + if (!is.null(cost) && !identical(allocation, "neyman")) { + stop("`cost` applies only to allocation = \"neyman\", and ", + if (is.character(allocation)) { + paste0("`allocation` is \"", allocation, "\". Use allocation = ", + "\"neyman\" with `allocation_by`, or leave `cost` out.") + } else { + "`allocation` gives the count for each stratum. Leave `cost` out." + }, call. = FALSE) } new_design("stratified", list( - strata = check_columns(strata, "strata"), - n = check_count(n, "n"), + strata = strata, + n = n, allocation = allocation, - allocation_by = if (is.null(allocation_by)) NULL else - check_columns(allocation_by, "allocation_by", 1L), + allocation_by = check_allocation_by(allocation_by, strata), + cost = if (!is.null(cost)) { + check_stratum_values(cost, strata, "cost", "cost", positive = TRUE) + }, min_per_stratum = check_count(min_per_stratum, "min_per_stratum"), replace = check_flag(replace, "replace"), - na_rm = check_flag(na_rm, "na_rm") + na_rm = check_flag(na_rm, "na_rm"), + within = check_within(within, replace) )) } +#' Check `within`: `NULL`, or a systematic design the allocation can size +#' @noRd +check_within <- function(within, replace) { + if (is.null(within)) return(NULL) + if (!inherits(within, "drawn_design_systematic")) { + stop("`within` must be NULL, for a simple random sample in each ", + "stratum, or design_systematic(), to walk each stratum in order, ", + "not ", if (is_design(within)) design_label(within) else + format_bad(within), ".", call. = FALSE) + } + given <- c("interval", "n")[c(!is.null(within$interval), + !is.null(within$n))] + if (length(given)) { + stop("`within` takes design_systematic() without `interval` or `n`, ", + "and has `", given[1], "` (", within[[given[1]]], "). The ", + "allocation sets the size of each stratum. Leave it out, as in ", + "within = design_systematic(order_by = \"x\").", call. = FALSE) + } + if (isTRUE(replace)) { + stop("`within` cannot be combined with replace = TRUE: a systematic ", + "walk takes each row of a stratum at most once. Use replace = ", + "FALSE.", call. = FALSE) + } + within +} + +#' Does the design walk each stratum systematically? +#' @noRd +walks_strata <- function(design) { + inherits(design, "drawn_design_stratified") && !is.null(design$within) +} + +#' Check `allocation_by`: a column name, or a standard deviation per stratum +#' +#' Returns the column name, or the standard deviations in the form the +#' design stores per-stratum values. +#' +#' @noRd +check_allocation_by <- function(allocation_by, strata) { + if (is.null(allocation_by)) return(NULL) + if (is.character(allocation_by)) { + return(check_columns(allocation_by, "allocation_by", 1L)) + } + if (!is.numeric(allocation_by) && !is.data.frame(allocation_by)) { + stop("`allocation_by` must be a column name, or the standard deviation ", + "of each stratum as a named vector or a data frame of the `strata` ", + "columns and `sd`, not ", format_bad(allocation_by), ".", + call. = FALSE) + } + check_stratum_values(allocation_by, strata, "allocation_by", "sd") +} + +#' Check numbers given per stratum, such as standard deviations or costs +#' +#' Each must be finite and 0 or more, or above 0 with `positive`. Returns a +#' named double vector, or a plain data frame of the `strata` columns and the +#' `value` column. Whether every stratum has one is a question about the +#' frame, answered by `match_strata()` when the design meets one. +#' +#' @noRd +check_stratum_values <- function(spec, strata, arg, value, + positive = FALSE) { + what <- c(sd = "standard deviations", cost = "costs")[[value]] + out <- strata_frame(spec, strata, arg, value) + v <- out[[value]] + if (!is.numeric(v)) { + stop("The ", what, " in `", arg, "` must be numbers, not ", + class(v)[1], ".", call. = FALSE) + } + bad <- !is.finite(v) | if (positive) v <= 0 else v < 0 + if (any(bad)) { + h <- which(bad)[1] + stop("The ", what, " in `", arg, "` must be finite numbers ", + if (positive) "above 0" else "of 0 or more", ", and stratum ", + spec_label(out, strata, h), " has ", format(v[h]), ". Give every ", + "stratum ", if (positive) { + "the cost of sampling one row there." + } else { + "an estimate, such as one from a pilot or an earlier survey." + }, call. = FALSE) + } + if (is.data.frame(spec)) { + out[[value]] <- as.numeric(v) + return(out) + } + stats::setNames(as.numeric(v), names(spec)) +} + +#' One row of per-stratum values given by the user, named for a message +#' @noRd +spec_label <- function(spec, strata, h) { + quote_labels(do.call(paste, c( + lapply(spec[strata], function(v) as.character(v[h])), sep = "\r"))) +} + +#' Check the per-stratum counts given as `allocation` +#' +#' Returns them in the form the design stores: a named integer vector, or a +#' plain data frame of the `strata` columns and an integer `n`. Whether every +#' stratum has a count is a question about the frame, answered by +#' `match_strata()` when the design meets one. +#' +#' @noRd +check_stratum_counts <- function(allocation, strata) { + spec <- strata_frame(allocation, strata, "allocation", "n") + n <- spec$n + if (!is.numeric(n)) { + stop("The counts in `allocation` must be numbers, not ", + class(n)[1], ".", call. = FALSE) + } + bad <- is.na(n) | !is.finite(n) | n < 0 | n != trunc(n) + if (any(bad)) { + h <- which(bad)[1] + stop("The counts in `allocation` must be whole numbers of 0 or more; ", + "stratum ", spec_label(spec, strata, h), " has ", format(n[h]), ".", + call. = FALSE) + } + big <- n > .Machine$integer.max + if (any(big)) { + h <- which(big)[1] + stop("The counts in `allocation` must be at most ", .Machine$integer.max, + ", the largest integer R holds; stratum ", + spec_label(spec, strata, h), " has ", format(n[h]), ". Give ", + "that stratum a smaller count.", call. = FALSE) + } + if (is.data.frame(allocation)) { + spec$n <- as.integer(n) + return(spec) + } + stats::setNames(as.integer(n), names(allocation)) +} + +#' `n` for a design given per-stratum counts +#' +#' Their sum when `n` is `NULL`, and otherwise `n`, which must equal it. +#' +#' @noRd +counts_n <- function(n, allocation) { + total <- sum(as.numeric(stratum_counts(allocation))) + n <- check_count(n %||% total, "n") + if (n != total) { + stop("`n` (", n, ") is not the sum of the counts in `allocation` (", + total, "). Leave `n` out to draw the counts as given.", + call. = FALSE) + } + n +} + +#' The counts stored by a design built with counts, in the order given +#' @noRd +stratum_counts <- function(allocation) { + if (is.data.frame(allocation)) allocation$n else unname(allocation) +} + +#' Was the design given its per-stratum counts rather than a rule? +#' @noRd +has_counts <- function(design) { + !is.null(design$allocation) && !is.character(design$allocation) +} + +#' Per-stratum values for a design's printout and title +#' +#' Counts, standard deviations or costs, as the design stores them: a named +#' vector, or a data frame whose last column holds the values. +#' `c(north = 10, south = 5)` for up to six strata, with columns joined by +#' ` . ` and names that are not syntactic in backticks, and a count of the +#' strata beyond that. +#' +#' @noRd +fmt_counts <- function(x) { + v <- if (is.data.frame(x)) x[[ncol(x)]] else unname(x) + what <- if (is.integer(v)) "counts" else "values" + if (length(v) > 6L) { + return(paste0("<", what, " for ", length(v), " strata>")) + } + lab <- if (is.data.frame(x)) { + keys <- names(x)[-ncol(x)] + group_label(do.call(paste, c(lapply(x[keys], as.character), + sep = "\r"))) + } else { + group_label(names(x)) + } + plain <- lab == make.names(lab) + lab[!plain] <- paste0("`", lab[!plain], "`") + shown <- if (is.integer(v)) { + as.character(v) + } else { + trimws(formatC(v, format = "fg", digits = 6)) + } + paste0("c(", paste0(lab, " = ", shown, collapse = ", "), ")") +} #' Within-stratum spread for Neyman allocation +#' +#' One standard deviation per stratum, in the order of `idx_by_stratum` and +#' the levels of `key`: given in the design, or worked out from the column +#' `allocation_by`. A spread worked out on a smaller scale, because the +#' column's own overflows, carries that scale as the attribute `scale`. +#' #' @noRd -stratum_spread <- function(design, data, idx_by_stratum) { - if (design$allocation != "neyman") return(NULL) +stratum_spread <- function(design, data, idx_by_stratum, + key = group_key(data, design$strata)) { + if (!identical(design$allocation, "neyman")) return(NULL) col <- design$allocation_by + if (!is.character(col)) { + return(match_strata(col, data, design$strata, "allocation_by", + value = "sd", key = key, ignore_extra = TRUE)$sd) + } validate_data(data, required_columns = col) v <- data[[col]] if (!is.numeric(v)) { @@ -86,82 +458,434 @@ stratum_spread <- function(design, data, idx_by_stratum) { } # Only the rows that survive the design's own NA handling matter. Checking # the whole frame made a design that draws fine fail on inclusion_prob(). + # sd() of a stratum holding an infinite value is NaN, which would read as + # no spread and allocate that stratum nothing. used <- unlist(idx_by_stratum, use.names = FALSE) - if (anyNA(v[used])) { - stop(sum(is.na(v[used])), " value(s) of `", col, "` are missing; Neyman ", - "allocation needs it for every row it allocates over.", call. = FALSE) + bad <- !is.finite(v[used]) + if (any(bad)) { + stop(sum(bad), " value(s) of `", col, "` are missing or non-finite; ", + "Neyman allocation needs a finite value for every row it allocates ", + "over. Drop those rows, or set them to a finite value.", + call. = FALSE) + } + spread <- function(scale) { + vapply(idx_by_stratum, function(i) { + if (length(i) < 2L) 0 else stats::sd(v[i] / scale) + }, numeric(1), USE.NAMES = FALSE) + } + sp <- spread(1) + # Values near the largest double overflow inside sd(), which squares + # them. In the stratum's own largest value as the unit they do not, and + # the other strata keep the spreads sd() gives them. + big <- !is.finite(sp) + if (any(big)) { + sp[big] <- vapply(idx_by_stratum[big], function(i) { + unit <- max(abs(v[i])) + unit * stats::sd(v[i] / unit) + }, numeric(1), USE.NAMES = FALSE) } - vapply(idx_by_stratum, function(i) { - if (length(i) < 2L) 0 else stats::sd(v[i]) - }, numeric(1)) + # A spread beyond the largest double needs a smaller scale for all of + # them. The shares depend only on the ratios of the spreads, so the same + # spreads on a smaller scale give the same allocation. + if (!all(is.finite(sp))) { + scale <- max(abs(v[used])) + sp <- structure(spread(scale), scale = scale) + } + sp } -#' @export -draw_design.drawn_design_stratified <- function(design, data) { +#' The cost of one row in each stratum, in the order of the levels of `key` +#' @noRd +stratum_cost <- function(design, data, key = group_key(data, design$strata)) { + if (is.null(design$cost)) return(NULL) + match_strata(design$cost, data, design$strata, "cost", value = "cost", + key = key, ignore_extra = TRUE)$cost +} + +#' Strata, their sizes and their allocation +#' +#' The one place a stratified design's strata and per-stratum sample sizes are +#' worked out, so the draw, the inclusion probabilities and the joint +#' probabilities cannot disagree. Everything is by position: `code` is each +#' row's stratum as a position in `sizes`, `n_alloc` and `idx`, and `NA` for a +#' row with a missing key. +#' +#' It is also where an allocation the frame cannot supply is refused, on every +#' path, so [inclusion_prob()] does not report a census for an `n` larger than +#' the frame that [draw()] refuses. Counts given in `allocation` are matched +#' to the strata here and used as they are. `spread` is each stratum's +#' standard deviation under Neyman allocation, and `NULL` otherwise; `cost` +#' is each stratum's cost per row when the design has costs, and `NULL` +#' otherwise. +#' +#' [design_spread()] with `strata` splits its `n` here too. It has no +#' `replace`, `min_per_stratum`, `allocation_by` or `cost`, and is treated as +#' a design without replacement, with no floor. +#' +#' Under `within`, a row whose `order_by` is missing is refused, or with the +#' systematic design's `na_rm` left out like a row with a missing stratum +#' key. +#' +#' @noRd +stratum_allocation <- function(design, data) { validate_data(data, required_columns = design$strata) check_key_columns(data, design$strata, "strata") + key <- group_key(data, design$strata) + bad <- check_na_policy(is.na(key), design$na_rm, "a missing stratum key") + if (all(bad)) stop("Every row has a missing stratum key.", call. = FALSE) + if (walks_strata(design)) { + # A row with no place in its stratum's walk cannot be drawn, so it is + # left out before the strata are counted and allocated. + gone <- walk_missing(design$within, data, bad, key) + if (any(gone)) { + bad <- bad | gone + key[gone] <- NA + } + } + code <- as.integer(key) + idx <- split(seq_len(nrow(data))[!bad], key[!bad]) + sizes <- lengths(idx, use.names = FALSE) + spread <- NULL + cost <- NULL - keys <- data[design$strata] - bad <- Reduce(`|`, lapply(keys, is.na)) - if (any(bad)) { - data <- drop_na_rows(data, bad, design$na_rm, "a missing stratum key") - keys <- data[design$strata] + replace <- isTRUE(design$replace) + if (has_counts(design)) { + n_alloc <- match_strata(design$allocation, data, design$strata, + "allocation", key = key)$n + over <- which(n_alloc > sizes) + if (!replace && length(over)) { + h <- over[1] + stop("Stratum `", group_label(levels(key)[h]), "` has ", sizes[h], + " row(s) but `allocation` asks for ", n_alloc[h], ". Lower its ", + "count", if (!is.null(design$replace)) ", or use replace = TRUE", + ".", call. = FALSE) + } + } else { + check_draw_size(design$n, sum(!bad), replace) + spread <- stratum_spread(design, data, idx, key) + cost <- stratum_cost(design, data, key) + n_alloc <- unname(allocate(design$n, sizes, design$allocation, + design$min_per_stratum %||% 0L, cap = !replace, + spread = spread, cost = cost)) + if (!replace) { + over <- which(n_alloc > sizes) + if (length(over)) { + h <- over[1] + stop("Stratum `", group_label(levels(key)[h]), "` has ", sizes[h], + " row(s) but ", n_alloc[h], " were requested. ", + "Use replace = TRUE or lower `n`.", call. = FALSE) + } + if (sum(n_alloc) != design$n) { + stop("`n` (", design$n, ") cannot be allocated ", + if (length(sizes) == 1L) { + "in the one stratum" + } else { + paste0("across these ", length(sizes), " strata") + }, " with min_per_stratum = ", + design$min_per_stratum, "; the allocation totals ", + sum(n_alloc), " row(s).", call. = FALSE) + } + } } - idx_by_stratum <- split(seq_len(nrow(data)), - group_key(data, design$strata)) - sizes <- lengths(idx_by_stratum) + list(code = code, labels = levels(key), idx = unname(idx), sizes = sizes, + n_alloc = n_alloc, spread = spread, cost = cost) +} - check_draw_size(design$n, nrow(data), design$replace) +#' How a design splits its sample over the strata of a frame +#' +#' The rows [draw()] takes from each stratum, the inclusion probability that +#' gives each row there, and the reason for any stratum held at the floor, +#' capped at its size or left with no rows, all before anything is drawn. +#' Under Neyman allocation it also shows the standard deviation of each +#' stratum the split used, and the cost per row when the design has costs. +#' The numbers come from the same computation as [draw()] and +#' [inclusion_prob()], so they always agree with both. +#' +#' @param data A data frame. +#' @param design [design_stratified()], [design_spread()] or +#' [design_weighted()] with `strata`, or [design_certainty()] whose `rest` +#' is one of these. For the last the +#' table describes `rest` over the rows below the threshold, and the rows +#' at or above it, which are taken with certainty, are not counted in any +#' stratum. Other designs are refused. +#' +#' @return A data frame with one row per stratum of `data`, in key order (see +#' [design_stratified()]): the `strata` columns, then +#' \describe{ +#' \item{`N`}{Rows in the stratum.} +#' \item{`n`}{Rows drawn from it.} +#' \item{`prob`}{The inclusion probability of each of its rows, as +#' [inclusion_prob()] gives it. `NA` for [design_spread()] with `size` +#' and for [design_weighted()], whose rows in one stratum have +#' different probabilities; there [inclusion_prob()] gives them row by +#' row.} +#' \item{`sd`}{Under Neyman allocation, the stratum's standard deviation +#' that the split used: of the `allocation_by` column within the +#' stratum, or as given. `NA` under other allocations.} +#' \item{`cost`}{The cost of one row, when the design has `cost`, and +#' `NA` otherwise.} +#' \item{`status`}{Why the stratum got `n`: `"rule"` for its share under +#' the allocation rule, rounded; `"count"` for a count given in +#' `allocation`; `"floor"` for a stratum raised to `min_per_stratum` +#' from a smaller share; `"capped"` for one the rule asked more rows of +#' than it holds, so it is taken whole and the rows it could not give +#' go to the other strata; `"take-all"` for one taken whole for another +#' reason, such as a size below `min_per_stratum` or a count equal to +#' its size; and `"empty"` for one allocated no rows, whose rows can +#' never be drawn. With `replace = TRUE` no stratum is capped or taken +#' whole.} +#' } +#' +#' @examples +#' df <- data.frame(id = 1:300, +#' site = rep(c("a", "b", "c", "d"), c(150, 100, 45, 5)), +#' v = c(1:150 %% 7, 1:100 %% 19, 1:45 %% 3, 1:5 * 40)) +#' d <- design_stratified("site", n = 30, allocation = "neyman", +#' allocation_by = "v", min_per_stratum = 2) +#' allocation_table(df, d) +#' +#' # The same counts as a draw, and the same probabilities as inclusion_prob() +#' table(draw(df, d, seed = 1)$site) +#' tapply(inclusion_prob(df, d), df$site, unique) +#' +#' @seealso [design_stratified()], [design_spread()], [inclusion_prob()] +#' @export +allocation_table <- function(data, design) { + design <- check_design(design, data, "allocation_table") + validate_data(data) + if (inherits(design, "drawn_design_certainty") && + has_strata(design$rest)) { + sp <- certainty_split(design, data) + validate_data(data, required_columns = design$rest$strata) + below <- sp$data[sp$rest, , drop = FALSE] + return(in_rest(design, length(sp$rest), + stratum_table(design$rest, below))) + } + if (!has_strata(design)) { + stop("`design` is ", design_label(design), ", which has no strata to ", + "allocate over. allocation_table() takes design_stratified(), ", + "design_spread() or design_weighted() with `strata`, or ", + "design_certainty() with one of those as `rest`.", call. = FALSE) + } + stratum_table(design, data) +} - n_alloc <- allocate(design$n, sizes, design$allocation, - design$min_per_stratum, cap = !design$replace, - spread = stratum_spread(design, data, idx_by_stratum)) - warn_empty_groups(n_alloc, sizes) +#' Does the design split `n` over strata? +#' @noRd +has_strata <- function(design) { + inherits(design, "drawn_design_stratified") || + (inherits(design, c("drawn_design_spread", "drawn_design_weighted")) && + !is.null(design$strata)) +} - if (!design$replace) { - over <- n_alloc > sizes - if (any(over)) { - stop("Stratum `", names(sizes)[over][1], "` has ", sizes[over][1], - " row(s) but ", n_alloc[over][1], " were requested. ", - "Use replace = TRUE or lower `n`.", call. = FALSE) - } - if (sum(n_alloc) != design$n) { - stop("`n` (", design$n, ") cannot be allocated across these ", - length(sizes), " strata with min_per_stratum = ", - design$min_per_stratum, "; the allocation totals ", sum(n_alloc), - " row(s).", call. = FALSE) +#' The table `allocation_table()` returns, for a design with strata +#' +#' A frame with no rows gives a table with no strata. Only a certainty +#' design with no rows below its threshold, where `rest` draws nothing, +#' passes one. The strata of a spread or weighted design hold the rows it +#' can draw, and have no floor. +#' +#' @noRd +stratum_table <- function(design, data) { + cols <- c("N", "n", "prob", "sd", "cost", "status") + clash <- intersect(design$strata, cols) + if (length(clash)) { + stop("`strata` column ", format_bad(clash[1]), " has the name of a ", + "column allocation_table() adds. Rename it in `data` and in the ", + "design.", call. = FALSE) + } + if (!nrow(data)) { + keys <- lapply(design$strata, function(col) data[[col]]) + return(table_frame(keys, design$strata, list( + N = integer(0), n = integer(0), prob = numeric(0), sd = numeric(0), + cost = numeric(0), status = character(0)))) + } + if (inherits(design, "drawn_design_spread")) { + fr <- spread_frame(design, data) + al <- list(idx = lapply(fr$idx, function(i) fr$keep[i]), + sizes = fr$sizes, n_alloc = fr$n_alloc) + prob <- if (is.null(design$size)) { + fr$n_alloc / fr$sizes + } else { + rep(NA_real_, length(fr$sizes)) } + } else if (inherits(design, "drawn_design_weighted")) { + st <- weighted_setup(design, data) + al <- list(idx = lapply(st$idx, function(i) st$keep[i]), + sizes = st$sizes, n_alloc = st$n_alloc) + # Rows of one stratum have probabilities proportional to their size. + prob <- rep(NA_real_, length(st$sizes)) + } else { + al <- stratum_allocation(design, data) + prob <- stratum_prob(design, al) + } + k <- length(al$sizes) + first <- vapply(al$idx, function(i) i[1L], integer(1)) + keys <- lapply(design$strata, function(col) data[[col]][first]) + cap <- !isTRUE(design$replace) + status <- if (has_counts(design)) { + out <- rep("count", k) + if (cap) out[al$n_alloc == al$sizes] <- "take-all" + out[al$n_alloc == 0L] <- "empty" + out + } else { + allocation_status( + design$n, al$n_alloc, al$sizes, + share = allocation_share(design$allocation, al$sizes, al$spread, + al$cost), + lower = group_floor(design$min_per_stratum %||% 0L, al$sizes, cap), + cap = cap) } + sd <- if (is.null(al$spread)) { + rep(NA_real_, k) + } else { + as.numeric(al$spread) * (attr(al$spread, "scale") %||% 1) + } + table_frame(keys, design$strata, list( + N = as.integer(al$sizes), + n = as.integer(al$n_alloc), + prob = prob, + sd = sd, + cost = if (is.null(al$cost)) rep(NA_real_, k) else as.numeric(al$cost), + status = status)) +} - reindex(data, take_within(idx_by_stratum, n_alloc, design$replace), sort = TRUE) +#' A plain data frame of key columns followed by value columns +#' @noRd +table_frame <- function(keys, strata, values) { + out <- c(stats::setNames(keys, strata), values) + structure(out, class = "data.frame", row.names = seq_along(out[[1L]])) +} + +#' @export +draw_design.drawn_design_stratified <- function(design, data) { + al <- stratum_allocation(design, data) + # Neyman allocation gives no share to a stratum whose `allocation_by` does + # not vary, unless no stratum varies and it falls back to proportional. + flat <- if (!is.null(al$spread) && sum(al$sizes * al$spread) > 0) { + al$spread == 0 + } + by <- design$allocation_by + warn_empty_groups( + al$n_alloc, al$sizes, al$labels, flat = flat, + by = if (is.character(by)) by, + fix = if (has_counts(design)) { + paste0("Give each stratum a count of at least 1 in `allocation` (or ", + "2, so each stratum also supports a variance).") + }) + if (walks_strata(design)) { + return(reindex(data, take_walks(design, data, al), sort = TRUE)) + } + reindex(data, take_within(al$idx, al$n_alloc, design$replace), sort = TRUE) +} + +# ---- systematic sampling within strata -------------------------------------- + +#' Rows `within` cannot place on its walk +#' +#' A missing `order_by` among the rows that have a stratum, `bad` marking the +#' others and `key` giving each row's stratum. Refused unless the systematic +#' design has `na_rm = TRUE`, and refused even then for a stratum that would +#' be left with no rows to walk. +#' +#' @noRd +walk_missing <- function(within, data, bad, key) { + col <- within$order_by + if (is.null(col)) return(rep(FALSE, nrow(data))) + if (!col %in% names(data)) { + stop("`data` is missing column: `", col, "`.", call. = FALSE) + } + check_key_columns(data, col, "order_by") + what <- paste0("a missing `", col, "`") + gone <- check_na_policy(is.na(data[[col]]) & !bad, within$na_rm, what) + code <- as.integer(key) + k <- nlevels(key) + emptied <- tabulate(code[!bad], k) > 0L & + tabulate(code[!bad & !gone], k) == 0L + if (any(emptied)) { + one <- sum(emptied) == 1L + stop(if (one) "Stratum " else "Strata ", + quote_labels(levels(key)[emptied]), if (one) " has " else " have ", + what, " in every row, so `within` has nothing to walk there. Give ", + "those rows a `", col, "`, or leave ", if (one) "the stratum" else + "those strata", " out of `data`.", call. = FALSE) + } + gone +} + +#' The frame rows of every stratum, in the order the design walks them +#' +#' Stratum by stratum in key order, each sorted on the `order_by` of +#' `within`, or left in frame order without one. Text is sorted byte by byte +#' and ties keep frame order, as in [design_systematic()]. `code` is each +#' row's stratum from `stratum_allocation()`, `NA` for a row in none. +#' +#' @noRd +stratum_walk <- function(design, data, code) { + kept <- which(!is.na(code)) + col <- design$within$order_by + if (!is.null(col)) kept <- kept[key_order(data[[col]][kept])] + # Radix ordering is stable, so each stratum keeps the order of its key. + kept[order(code[kept], method = "radix")] +} + +#' Each frame row's position in its stratum's walk, `NA` for a row in none +#' +#' `k` is the number of strata that `code` indexes. +#' +#' @noRd +walk_positions <- function(design, data, code, k) { + walk <- stratum_walk(design, data, code) + before <- c(0L, cumsum(tabulate(code, k))) + pos <- rep(NA_integer_, length(code)) + pos[walk] <- seq_along(walk) - before[code[walk]] + pos +} + +#' The rows a stratified design with `within` draws +#' +#' Stratum `h`, in key order, takes the walk positions `fractional_walk()` +#' gives for `n_h` of `N_h` rows, from one `stats::runif()` of its own. A +#' stratum allocated no rows draws no start. +#' +#' @noRd +take_walks <- function(design, data, al) { + walk <- stratum_walk(design, data, al$code) + before <- c(0L, cumsum(al$sizes)) + unlist(lapply(which(al$n_alloc > 0L), function(h) { + walk[before[h] + fractional_walk(stats::runif(1L), al$n_alloc[h], + al$sizes[h])] + })) } # ---- inclusion probability ------------------------------------------------ #' @noRd exact_inclusion.drawn_design_stratified <- function(design, data) { - validate_data(data, required_columns = design$strata) - check_key_columns(data, design$strata, "strata") - keys <- data[design$strata] - bad <- check_na_policy(Reduce(`|`, lapply(keys, is.na)), design$na_rm, - "a missing stratum key") - group <- group_key(data, design$strata) - - idx_by_stratum <- split(seq_len(nrow(data))[!bad], group[!bad]) - sizes <- lengths(idx_by_stratum) - n_alloc <- allocate(design$n, sizes, design$allocation, - design$min_per_stratum, cap = !design$replace, - spread = stratum_spread(design, data, idx_by_stratum)) - - out <- numeric(nrow(data)) - for (h in names(idx_by_stratum)) { - idx <- idx_by_stratum[[h]] - out[idx] <- if (design$replace) { - 1 - (1 - 1 / length(idx))^n_alloc[[h]] - } else { - n_alloc[[h]] / length(idx) - } - } + stratum_pi(design, stratum_allocation(design, data)) +} + +#' Each row's inclusion probability, from `stratum_allocation()` +#' +#' Linear in the rows, whatever the number of strata. A row with no stratum +#' gets 0. +#' +#' @noRd +stratum_pi <- function(design, al) { + p <- stratum_prob(design, al) + out <- numeric(length(al$code)) + keep <- !is.na(al$code) + out[keep] <- p[al$code[keep]] out } + +#' The inclusion probability of a row in each stratum of `stratum_allocation()` +#' @noRd +stratum_prob <- function(design, al) { + if (design$replace) { + 1 - (1 - 1 / al$sizes)^al$n_alloc + } else { + al$n_alloc / al$sizes + } +} diff --git a/R/design-systematic.R b/R/design-systematic.R index bf134d1..5787e8d 100644 --- a/R/design-systematic.R +++ b/R/design-systematic.R @@ -1,26 +1,87 @@ #' Systematic sampling #' -#' Takes every `interval`-th row, beginning at `start`. The number of rows drawn -#' follows from the interval and the size of the data, so there is no `n`. -#' -#' @param interval Sampling interval. A whole number of 1 or more. Fractional -#' intervals are rejected: they produce uneven gaps, which is not a systematic -#' design. -#' @param start Starting row, in `1:interval`. Drawn at random from that range -#' when `NULL`. +#' Walks the rows at a fixed step. Give `interval` to take every +#' `interval`-th row, beginning at `start`, which is drawn at random unless +#' given; the number of rows drawn then follows from the interval and the size +#' of the data. Give `n` instead to draw exactly `n` rows from a random start: +#' the step is the number of rows walked divided by `n`, and need not be a +#' whole number. With `n_starts`, several random starts are walked at a +#' longer step, which gives the sample a design-unbiased variance. Given +#' neither `interval` nor `n`, the design walks each stratum of +#' [design_stratified()] as its `within` argument. +#' +#' @param interval Sampling interval, a whole number of 1 or more: every +#' `interval`-th row of the walk is taken. Give `interval` or `n`, not both. +#' For a step that is not a whole number, give `n`. +#' @param start Position in the walk of the first row taken, in +#' `1:interval`. The walk is the frame's rows in their order, or sorted by +#' `order_by` when given, so with `order_by` a `start` of 3 takes the row +#' with the third smallest value, not the frame's third row. Drawn at +#' random from that range when `NULL`. A fixed start makes the design +#' deterministic: each row is selected with probability 0 or 1, so +#' [inclusion_prob()], +#' [sampling_weight()], [joint_prob()], `draw(weights = TRUE)`, +#' [ht_total()] and [ht_mean()] refuse it, while +#' `inclusion_prob(simulate = TRUE)` reports those 0s and 1s. Not used with +#' `n` or `n_starts`, whose starts are always random. #' @param order_by Optional column to sort by before walking the data. It #' changes which rows can appear together, so [inclusion_prob()] and -#' [joint_prob()] compute against the sorted order too. +#' [joint_prob()] compute against the sorted order too. Text is sorted byte +#' by byte, as in the C locale, so the walk is the same in every session; +#' ties keep frame order, so where the column has ties a seed is sure to +#' draw the same rows only from a frame with its rows in the same order. +#' Without ties the walk does not depend on frame order. One column: to +#' walk by several, add a column of ranks built from them and give its +#' name, as in the examples. #' @param na_rm When `order_by` is given, drop rows whose sort key is `NA` #' instead of raising an error. +#' @param n Number of rows to draw, in place of `interval`. With `N` rows +#' walked, each row covers a stretch of length `n / N` on a line from 0 to +#' `n`, a start `u` is drawn uniformly from (0, 1), and the rows under `u`, +#' `u + 1`, ..., `u + n - 1` are taken. The step is `N / n` rows, every row +#' has probability `n / N`, and the sample always holds `n` rows. When `n` +#' divides `N` the probabilities are those of `interval = N / n`. A plan +#' from [plan_size()] gives its `n`. +#' @param n_starts Number of random starts, 1 by default. With +#' `n_starts = m` and `interval = k`, `m` different starts are drawn from +#' `1:(m * k)` and each is walked at a step of `m * k` rows. Every row +#' still has probability `1 / k`, and the expected sample size is that of +#' one start at `interval`. Each start gives a replicate, a systematic +#' sample of its own, and two or more of them give a design-unbiased +#' variance (see "Variance"). Needs `interval`, and a random `start`. #' #' @section Variance: -#' A systematic sample has a single random start, so no design-unbiased +#' A systematic sample has a single random start. At a step of 2 rows or +#' more, which is every `interval` above 1 and every `n` up to half the rows +#' walked, neighbouring rows are never drawn together, so no design-unbiased #' variance estimator exists. [ht_total()] uses the successive-difference #' approximation (Wolter 2007), which compares neighbouring sampled rows in -#' the order the design walked. Sorting on a variable related to what you +#' the order the design walked. With `n` above half the rows walked, every +#' pair of rows can be drawn together (see [joint_prob()]), and [ht_total()] +#' uses the same approximation. Sorting on a variable related to what you #' measure (`order_by`) is what makes systematic sampling efficient, and this #' estimator is the one that can see it; see [ht_total()] for its limits. +#' When `interval` does not divide the number of rows walked, the sample size +#' is random, and a term for that is added to the variance. A design given +#' `n` has a fixed size and needs no such term. +#' +#' With `n_starts = m` of 2 or more, the `m` starts are a simple random +#' sample of the `m * k` possible ones, and each replicate `r` gives a total +#' of its own, `t_r`, which is `m` times the sum of `y / pi` over its rows. +#' The sample's total is their mean, and [ht_total()] uses the random group +#' variance (Wolter 2007), `(1 - 1 / k) * var(t_r) / m`, on `m - 1` degrees +#' of freedom. It is design-unbiased whether or not `m * k` divides the rows +#' walked, a replicate that drew no rows counting with a total of 0. +#' [as_svydesign()] gives the same standard error with each replicate as a +#' primary sampling unit, and refuses a sample with a replicate that drew no +#' rows, which `survey` would leave out of its count of replicates. The price +#' is precision: `m` starts spread the sample over the walk less evenly than +#' one start at `interval` does, and few replicates give few degrees of +#' freedom and a wide interval. +#' +#' Within strata, as `design_stratified(within = design_systematic())`, each +#' stratum has a start of its own and the variance is the sum of the +#' strata's successive-difference approximations; see [design_stratified()]. #' #' @return A design object, for use with [draw()]. #' @@ -32,61 +93,183 @@ #' Springer. #' #' @examples -#' df <- data.frame(id = 1:100, value = (1:100) / 10) +#' df <- data.frame(id = 1:100, value = (1:100) / 10, +#' site = rep(c("b", "a"), each = 50)) #' draw(df, design_systematic(interval = 10, start = 3)) #' draw(df, design_systematic(interval = 25, order_by = "value"), seed = 1) #' +#' # 30 rows from 100, a step of 3.33 +#' draw(df, design_systematic(n = 30), seed = 1)$id +#' +#' # Four starts from 1:40, each walked at a step of 40: ten rows on +#' # average, as with one start, and a variance from the spread of the four +#' # replicates +#' s <- draw(df, design_systematic(interval = 10, n_starts = 4), seed = 1, +#' weights = TRUE) +#' ht_total(s, "value") +#' +#' # Walking by two columns: rank the rows by both, then walk the ranks +#' df$walk <- order(order(df$site, -df$value, method = "radix")) +#' draw(df, design_systematic(interval = 20, order_by = "walk"), seed = 1) +#' #' @family designs -#' @seealso [draw()] +#' @seealso [draw()], [design_stratified()] #' @export -design_systematic <- function(interval, start = NULL, order_by = NULL, - na_rm = FALSE) { - interval <- check_count(interval, "interval", allow_zero = FALSE) +design_systematic <- function(interval = NULL, start = NULL, order_by = NULL, + na_rm = FALSE, n = NULL, n_starts = 1L) { + n <- plan_n(n) + n_starts <- check_count(n_starts, "n_starts", allow_zero = FALSE) + if (!is.null(interval) && !is.null(n)) { + stop("`design_systematic()` takes `interval` or `n`, not both. ", + "Give `interval` for every k-th row, or `n` for a fixed sample size.", + call. = FALSE) + } + if (!is.null(n)) { + n <- check_count(n, "n") + if (!is.null(start)) { + stop("`start` cannot be fixed with `n`, whose start is drawn from ", + "(0, 1). Leave `start` as NULL, or give `interval` instead of `n`.", + call. = FALSE) + } + } else if (!is.null(interval)) { + if (is.numeric(interval) && length(interval) == 1L && + is.finite(interval) && interval > 1 && interval != trunc(interval)) { + stop("`interval` must be a single whole number, not ", interval, ". ", + "For a step that is not whole, give the sample size as `n`.", + call. = FALSE) + } + interval <- check_count(interval, "interval", allow_zero = FALSE) + } + if (n_starts > 1L) { + if (is.null(interval)) { + stop("`n_starts` (", n_starts, ") needs `interval`: the starts are ", + "drawn from 1:(n_starts * interval) and walked at that step. ", + if (is.null(n)) { + "Give `interval`." + } else { + "Give `interval` in place of `n`, or leave `n_starts` at 1." + }, call. = FALSE) + } + if (!is.null(start)) { + stop("`start` cannot be fixed with `n_starts` (", n_starts, "), whose ", + "starts are drawn at random. Leave `start` as NULL.", + call. = FALSE) + } + if (as.numeric(n_starts) * interval > .Machine$integer.max) { + stop("`n_starts * interval` (", + format(as.numeric(n_starts) * interval, scientific = FALSE), + ") must be at most ", .Machine$integer.max, ". Lower `n_starts` ", + "or `interval`.", call. = FALSE) + } + } if (!is.null(start)) { + if (is.null(interval)) { + stop("`start` needs `interval`, and it has none. Give `interval`, or ", + "leave `start` as NULL.", call. = FALSE) + } start <- check_count(start, "start", allow_zero = FALSE) if (start > interval) { stop("`start` (", start, ") must lie in 1:interval (1:", interval, ").", call. = FALSE) } } + if (is.character(order_by) && length(order_by) > 1L) { + stop("`order_by` names one column, not ", length(order_by), ". To walk ", + "by several, add a column of ranks built from them, such as ", + "data$walk <- order(order(data$", order_by[1], ", data$", + order_by[2], ", method = \"radix\")), and give order_by = \"walk\".", + call. = FALSE) + } new_design("systematic", list( interval = interval, + n = n, start = start, order_by = if (is.null(order_by)) NULL else check_columns(order_by, "order_by", 1L), - na_rm = check_flag(na_rm, "na_rm") + na_rm = check_flag(na_rm, "na_rm"), + n_starts = n_starts )) } +#' The number of random starts of a systematic design +#' +#' A design saved before `n_starts` existed has one. +#' +#' @noRd +systematic_starts <- function(design) design$n_starts %||% 1L + +#' Does the design draw several random starts? +#' @noRd +replicated <- function(design) { + inherits(design, "drawn_design_systematic") && + systematic_starts(design) > 1L +} + #' @export draw_design.drawn_design_systematic <- function(design, data) { - validate_data(data, required_columns = design$order_by) + validate_data(data) # The walk visits rows in `walk` order; the result comes back in frame order # like every other design that selects a set of rows. - walk <- seq_len(nrow(data)) - if (!is.null(design$order_by)) { - check_key_columns(data, design$order_by, "order_by") - key <- data[[design$order_by]] - if (anyNA(key)) { - data <- drop_na_rows(data, is.na(key), design$na_rm, - paste0("a missing `", design$order_by, "`")) - key <- data[[design$order_by]] - } - walk <- order(key) + pos <- systematic_positions(design, data) + if (anyNA(pos)) { + keep <- which(!is.na(pos)) + data <- reindex(data, keep) + pos <- pos[keep] } + walk <- order(pos) - start <- design$start %||% sample.int(design$interval, 1L) + if (!is.null(design$n)) { + if (design$n == 0L) return(empty_like(data)) + taken <- fractional_walk(stats::runif(1L), design$n, nrow(data)) + return(reindex(data, walk[taken], sort = TRUE)) + } - if (start > nrow(data)) { - warning("`start` (", start, ") is past the last row (", nrow(data), - "); returning no rows.", call. = FALSE) + # Each of the `m` starts is walked at a step of `m * interval`. One start + # is sample.int(interval, 1), as it always was, so a seed draws the same + # rows. + m <- systematic_starts(design) + step <- m * design$interval + starts <- design$start %||% sort(sample.int(step, m)) + live <- starts[starts <= nrow(data)] + if (!length(live)) { + warn_drawn(if (!is.null(design$start)) { + paste0("`start` (", starts, ") is past the last row (", nrow(data), + "); returning no rows.") + } else if (m == 1L) { + paste0("The random start (", starts, ") is past the last row (", + nrow(data), "), so the sample is empty. `interval` (", + design$interval, ") is larger than the number of rows, so ", + "a start above ", nrow(data), " draws nothing.") + } else { + paste0("Every random start (", format_rows(starts), ") is past the ", + "last row (", nrow(data), "), so the sample is empty. The ", + "starts are drawn from 1:", step, ", `n_starts * interval`, ", + "and a start above ", nrow(data), " draws nothing.") + }, "drawn_empty_start") return(empty_like(data)) } - picked <- walk[seq.int(from = start, to = nrow(data), by = design$interval)] + picked <- walk[unlist(lapply(live, function(s) { + seq.int(from = s, to = nrow(data), by = step) + }))] reindex(data, picked, sort = TRUE) } +#' Walk positions a fixed-size systematic sample takes +#' +#' Walk position `j` covers `[(j - 1) * n / N, j * n / N)` on a line from 0 to +#' `n`, and the positions under `u`, `u + 1`, ..., `u + n - 1` are taken. No +#' stretch is longer than 1, so no position is hit twice and exactly `n` are +#' taken. Each break is `j * n / N` with one rounding, rather than a running +#' sum, so the last one is `n` exactly. +#' +#' @noRd +fractional_walk <- function(u, n, N) { + breaks <- as.double(seq_len(N)) * n / N + # A point that rounds up to `n` lies in the last stretch. + pmin(findInterval(u + seq.int(0L, n - 1L), breaks) + 1L, N) +} + # ---- inclusion probability ------------------------------------------------ #' Where each row of `data` sits in the order the design walks @@ -96,30 +279,91 @@ draw_design.drawn_design_systematic <- function(design, data) { #' probabilities have to be computed against the order `draw_design()` actually #' uses -- the sorted, NA-dropped frame -- not against frame order. #' +#' It is also the design's one set of checks, shared by the draw, the +#' probabilities and the successive-difference variance: a design with no +#' `interval` or `n`, which only `design_stratified(within =)` can size, an +#' `order_by` column the frame lacks, which gave every row a probability of +#' 0, the `na_rm` policy, a key missing in every row, and an `n` larger than +#' the rows walked. +#' #' @noRd systematic_positions <- function(design, data) { + if (is.null(design$interval) && is.null(design$n)) { + stop("`design_systematic()` has no `interval` or `n`, so it sets no ", + "sample size. Give `interval` or `n` to draw it on its own, or use ", + "it as `within` in design_stratified(), which sets the size of ", + "each stratum.", call. = FALSE) + } n <- nrow(data) - if (is.null(design$order_by)) return(seq_len(n)) - check_key_columns(data, design$order_by, "order_by") - key <- data[[design$order_by]] - bad <- check_na_policy(is.na(key), design$na_rm, - paste0("a missing `", design$order_by, "`")) - out <- rep(NA_integer_, n) - kept <- which(!bad) - if (!length(kept)) return(out) - out[kept[order(key[kept])]] <- seq_along(kept) + out <- seq_len(n) + if (!is.null(design$order_by)) { + col <- design$order_by + if (!col %in% names(data)) { + stop("`data` is missing column: `", col, "`.", call. = FALSE) + } + check_key_columns(data, col, "order_by") + key <- data[[col]] + what <- paste0("a missing `", col, "`") + bad <- check_na_policy(is.na(key), design$na_rm, what) + if (n > 0L && all(bad)) stop("Every row has ", what, ".", call. = FALSE) + out <- rep(NA_integer_, n) + kept <- which(!bad) + # Byte order for text, so the walk is the same in every locale. Ties keep + # frame order. + out[kept[key_order(key[kept])]] <- seq_along(kept) + } + if (!is.null(design$n)) { + walked <- sum(!is.na(out)) + if (design$n > walked) { + stop("`n` (", design$n, ") cannot exceed the number of rows walked (", + walked, "). Give `n` of at most ", walked, ".", call. = FALSE) + } + } out } +#' Refuse a fixed start on every probability and variance path +#' +#' A fixed start makes the design deterministic. Its probabilities of 0 and 1 +#' are true, and the simulation reports them, but as weights they would make +#' the sum over the sample a total of the frame. +#' #' @noRd -exact_inclusion.drawn_design_systematic <- function(design, data) { +refuse_fixed_start <- function(design) { if (!is.null(design$start)) { - stop("A systematic design with a fixed `start` is not a probability ", - "sample: each row is selected with probability 0 or 1. Leave `start` ", - "as NULL for a random start.", call. = FALSE) + stop_declined(paste0( + "A systematic design with a fixed `start` is not a probability sample: ", + "each row is selected with probability 0 or 1. Leave `start` as NULL ", + "for a random start.")) } - # Row j is selected exactly when start == ((j - 1) %% interval) + 1, which is - # one of the `interval` equally likely starts. Exact for any N. + invisible(design) +} + +#' @noRd +exact_inclusion.drawn_design_systematic <- function(design, data) { + refuse_fixed_start(design) pos <- systematic_positions(design, data) + if (!is.null(design$n)) { + # Each walked row covers a stretch of length n / N, and the start is + # uniform on (0, 1). + return(ifelse(is.na(pos), 0, design$n / sum(!is.na(pos)))) + } + # With `m` starts from 1:(m * interval), row j is selected exactly when + # ((j - 1) %% (m * interval)) + 1 is one of them, which happens m times in + # m * interval. One start is the case m = 1. Exact for any N. ifelse(is.na(pos), 0, 1 / design$interval) } + +#' The replicate each sampled row of a systematic design belongs to +#' +#' A row at walk position `p` is taken by the start +#' `((p - 1) %% (m * interval)) + 1`, so that number names its replicate. +#' `walk` is `systematic_positions()` over the frame and `rows` the sampled +#' frame rows. With one start every row is in replicate 1. +#' +#' @noRd +systematic_replicates <- function(design, walk, rows) { + if (!replicated(design)) return(rep(1L, length(rows))) + step <- systematic_starts(design) * design$interval + as.integer((walk[rows] - 1L) %% step) + 1L +} diff --git a/R/design-temporal.R b/R/design-temporal.R index 39ad097..2aedf65 100644 --- a/R/design-temporal.R +++ b/R/design-temporal.R @@ -1,26 +1,62 @@ #' Temporal sampling #' -#' Divides a time window into equal intervals and samples within each one. -#' `per_interval` is named for what it is: unlike `n` elsewhere in the package, -#' it is a per-group figure, not a total. -#' -#' Buckets are assigned arithmetically in a single pass rather than by -#' re-filtering the data per interval, so cost scales with the data rather than -#' with the number of intervals. -#' -#' @param time Column of timestamps. `POSIXct` and `Date` columns are used as -#' they are; character columns are parsed with [lubridate::ymd_hms()]. -#' @param from,to Window bounds, as timestamps or strings. The window is -#' half-open: `[from, to)`. Trailing partial intervals are dropped. +#' Divides a time window into intervals of `interval` units and samples within +#' each one. `per_interval` is named for what it is: unlike `n` elsewhere in +#' the package, it is a per-group figure, not a total. +#' +#' Each row's interval is found in a single pass over the data, so the draw +#' and the inclusion probabilities take time that grows with the number of +#' rows rather than with rows times intervals. +#' +#' @section Time zones and calendar steps: +#' The window and the intervals are laid out in one time zone: `tz` when it +#' is given, otherwise the zone of a `POSIXct` `time` column, otherwise UTC. +#' A `POSIXct` column with an empty `tzone`, which R shows in the session's +#' zone, also gets UTC, so a design gives the same intervals on every +#' machine. +#' +#' A `Date`, in the column or as a bound, is its midnight in that zone, and a +#' string without an offset is a clock time there. A clock time that a +#' daylight-saving change skips moves to the moment the clocks jump, and one +#' that happens twice takes its first occurrence, so a `Date` stands for the +#' first instant of its day: 01:00 where the change skips midnight, as in +#' Santiago or Cairo, and the first of two midnights where it repeats one, as +#' in the Azores. A string ending in `Z` or an offset such as `+01:00` keeps +#' the instant it names. +#' +#' `"seconds"`, `"minutes"` and `"hours"` are fixed durations counted from +#' `from`, so hourly intervals ignore the clock change. `"days"` and +#' `"weeks"` step by calendar days, so each interval starts at the same +#' clock time as `from` and lasts 23 or 25 hours across a change. +#' `"months"` and `"years"` step by calendar units counted from `from`, and a +#' day the month lacks moves to its last day: a window starting on 31 +#' January 2024 has intervals starting on 29 February, 31 March and 30 April. +#' +#' @param time Column of timestamps: `POSIXct`, `POSIXlt`, `Date`, character +#' or factor. Strings are read as year-month-day with an optional time, in +#' the forms [lubridate::ymd_hms()] accepts, such as `"2024-03-01 14:30:00"` +#' or `"2024-03-01T14:30:00Z"`, and also `"2024-03-01 14:30"`, +#' `"2024-03-01 14"` and `"2024-03-01"`. +#' @param from,to Window bounds, each a single `POSIXct`, `Date` or string +#' read as `time` is. The window is half-open: `[from, to)`. Trailing +#' partial intervals are dropped. Both are checked when the design is +#' built, and `to` must come after `from`. Without `tz`, a bound that names +#' an instant (a `POSIXct`, or a string ending in `Z` or an offset) paired +#' with a clock time (a `Date`, or a string without an offset) can fall in +#' either order depending on the zone. Such a pair is refused when the +#' design is built if, with the clock time read in UTC, `to` comes a day or +#' more before `from`, since no zone's offset from UTC can undo that. +#' Otherwise its order is checked when the design is used, in the zone the +#' window is laid out in (see "Time zones and calendar steps"). #' @param interval Interval width, in units of `unit`. #' @param per_interval Rows to draw from each interval. Intervals holding fewer #' rows contribute all of them. #' @param unit One of `"seconds"`, `"minutes"`, `"hours"`, `"days"`, `"weeks"`, -#' `"months"` or `"years"`. `"months"` and `"years"` step by calendar units, -#' not by fixed 30.44-day durations. -#' @param tz Time zone the timestamps are expressed in. Applied when the column -#' *and* both bounds are parsed, so it genuinely shifts the window rather than -#' relabelling the output. +#' `"months"` or `"years"`. See "Time zones and calendar steps". +#' @param tz Time zone, a name from [OlsonNames()], in which the bounds, any +#' `Date` or string timestamps and the calendar steps are read. `NULL`, the +#' default, takes the zone of a `POSIXct` `time` column and UTC otherwise. +#' It shifts the window rather than relabelling the output. #' @param na_rm Drop rows whose timestamp is missing or unparseable instead of #' raising an error. #' @@ -42,169 +78,385 @@ design_temporal <- function(time, from, to, interval, per_interval, unit = c("hours", "seconds", "minutes", "days", "weeks", "months", "years"), tz = NULL, na_rm = FALSE) { - if (!is.null(tz) && (!is.character(tz) || length(tz) != 1L)) { - stop("`tz` must be a single time zone name, or NULL.", call. = FALSE) + if (!is.null(tz)) check_zone(tz) + time <- check_columns(time, "time", 1L) + interval <- check_count(interval, "interval", allow_zero = FALSE) + per_interval <- check_count(per_interval, "per_interval") + unit <- check_choice(unit, c("hours", "seconds", "minutes", "days", + "weeks", "months", "years"), "unit") + na_rm <- check_flag(na_rm, "na_rm") + # The bounds are read in `tz`, or in UTC until a column supplies the zone. + # Whether they parse does not depend on the zone. Their order does not + # either when both are instants or both are clock times, but it can for a + # pair that mixes the two. The clock time's instant then moves with the + # zone by the zone's offset from UTC, which is under a day in every zone, + # so such a pair is refused here only when it is a day or more out of + # order read in UTC, and otherwise when the window is laid out. + zone <- tz %||% "UTC" + lo <- time_bound(from, zone, "from") + hi <- time_bound(to, zone, "to") + if (!is.null(tz) || lo$instant == hi$instant) { + check_window(lo$at, hi$at) + } else { + check_window(lo$at, hi$at + 86400) } + # `from` and `to` are stored as given, so the design prints what was + # written, and are read again in the zone in force when it is used. new_design("temporal", list( - time = check_columns(time, "time", 1L), + time = time, from = from, to = to, - interval = check_count(interval, "interval", allow_zero = FALSE), - per_interval = check_count(per_interval, "per_interval"), - unit = match.arg(unit), + interval = interval, + per_interval = per_interval, + unit = unit, tz = tz, - na_rm = check_flag(na_rm, "na_rm") + na_rm = na_rm )) } #' @export draw_design.drawn_design_temporal <- function(design, data) { + tm <- temporal_setup(design, data) + keep <- which(!is.na(tm$bucket)) + if (!length(keep)) { + return(empty_like(data)) + } + idx_by_bucket <- split(keep, tm$bucket[keep]) + n_alloc <- pmin(lengths(idx_by_bucket), design$per_interval) + + reindex(data, take_within(idx_by_bucket, n_alloc, FALSE), sort = TRUE) +} + +#' The window, its intervals and each row's interval +#' +#' The checks and the parsing the draw, the probabilities and the variance +#' share, so [inclusion_prob()] refuses what [draw()] refuses, with the same +#' message: a timestamp missing under `na_rm = FALSE` or in every row, a +#' bound that is not one parseable date-time, a window that runs backwards, +#' and a window shorter than one interval. Returns `bucket`, each row's +#' interval as an integer, `NA` for a row outside the window or with no +#' timestamp, `breaks` and `tz`. +#' +#' @noRd +temporal_setup <- function(design, data) { validate_data(data, required_columns = design$time) col <- design$time - tz <- design$tz %||% "UTC" - - tv <- parse_time(data[[col]], tz, col) - if (anyNA(tv)) { - data <- drop_na_rows( - data, is.na(tv), design$na_rm, - paste0("a missing or unparseable timestamp in `", col, "`") - ) - tv <- parse_time(data[[col]], tz, col) - } - - from_dt <- parse_time(design$from, tz, "from") - to_dt <- parse_time(design$to, tz, "to") - if (length(from_dt) != 1L || length(to_dt) != 1L || - is.na(from_dt) || is.na(to_dt)) { - stop("`from` and `to` must each be a single parseable date-time.", - call. = FALSE) + win <- temporal_window(design, data) + + tv <- parse_time(data[[col]], win$tz, col) + what <- paste0("a missing or unparseable timestamp in `", col, "`") + if (is.character(data[[col]]) || is.factor(data[[col]])) { + what <- paste0(what, " (strings must be year-month-day with an optional ", + "time, such as \"2024-03-01\", \"2024-03-01 14:30\" or ", + "\"2024-03-01T14:30:00Z\")") } - check_window(from_dt, to_dt) + bad <- check_na_policy(is.na(tv), design$na_rm, what) + if (all(bad)) stop("Every row has ", what, ".", call. = FALSE) + + breaks <- win$breaks + bucket <- rep(NA_integer_, nrow(data)) + inw <- !bad & tv >= breaks[1] & tv < breaks[length(breaks)] + bucket[inw] <- findInterval(tv[inw], breaks) + list(bucket = bucket, breaks = breaks, tz = win$tz) +} - breaks <- make_breaks(from_dt, to_dt, design$interval, design$unit) +#' The time zone, bounds and interval boundaries of a temporal design +#' +#' The one place the zone is resolved: `tz` when the design has one, else the +#' zone of a `POSIXct` `time` column, else UTC. The bounds are read in that +#' zone and the breaks laid out from them. +#' +#' @noRd +temporal_window <- function(design, data) { + tz <- temporal_tz(design, data[[design$time]]) + from <- time_bound(design$from, tz, "from") + to <- time_bound(design$to, tz, "to") + check_window(from$at, to$at) + + breaks <- make_breaks(from$at, to$at, design$interval, design$unit, + clock = from$clock) if (length(breaks) < 2L) { - stop("The window (", format(difftime(to_dt, from_dt)), + stop("The window (", format(difftime(to$at, from$at)), ") is shorter than one interval of ", design$interval, " ", design$unit, "; no complete interval exists.", call. = FALSE) } + list(tz = tz, from = from$at, to = to$at, breaks = breaks) +} - in_window <- tv >= breaks[1] & tv < breaks[length(breaks)] - if (!any(in_window)) { - return(empty_like(data)) +#' The zone a design is laid out in +#' +#' `x` is the `time` column. A `POSIXct` column carries its zone in the +#' `tzone` attribute; an empty one means the session's zone, which differs +#' between machines, so it gets UTC like a column with no zone at all. +#' +#' @noRd +temporal_tz <- function(design, x) { + if (!is.null(design$tz)) return(design$tz) + zone <- if (inherits(x, "POSIXt")) attr(x, "tzone")[1L] + if (is.null(zone) || is.na(zone) || !nzchar(zone)) return("UTC") + if (!known_zone(zone)) { + stop("`", design$time, "` is in time zone \"", zone, "\", which R does ", + "not know. Set `tz` in design_temporal() to a name from ", + "OlsonNames().", call. = FALSE) } + zone +} - keep <- which(in_window) - bucket <- findInterval(tv[keep], breaks) - idx_by_bucket <- split(keep, bucket) - n_alloc <- pmin(lengths(idx_by_bucket), design$per_interval) +#' @noRd +known_zone <- function(tz) tz %in% c("UTC", "GMT") || tz %in% OlsonNames() - reindex(data, take_within(idx_by_bucket, n_alloc, FALSE), sort = TRUE) +#' @noRd +check_zone <- function(tz) { + if (!is.character(tz) || length(tz) != 1L || is.na(tz)) { + stop("`tz` must be a single time zone name, or NULL.", call. = FALSE) + } + if (!known_zone(tz)) { + stop("`tz` is \"", tz, "\", which is not a time zone R knows. Use a name ", + "from OlsonNames(), such as \"Europe/London\" or \"UTC\".", + call. = FALSE) + } + invisible(tz) } -#' Parse a value to POSIXct, leaving date-time classes alone +#' One window bound, as an instant and as a clock reading #' -#' Running ymd_hms() over an already-parsed column round-trips it through -#' as.character(), and midnight values silently become NA. +#' `at` is the instant in `tz`. `clock` is the local clock time the bound +#' was written as, held in UTC so that calendar steps from it are free of +#' daylight-saving changes. A `Date` or a string without an offset keeps the +#' clock time as written, which can differ from `at` when that time does not +#' exist in `tz`; anything else reads its clock from `at`. `instant` is +#' `TRUE` for a bound that names its instant whatever the zone: a date-time, +#' or a string ending in `Z` or an offset. #' #' @noRd -parse_time <- function(x, tz, arg) { - if (inherits(x, "POSIXct")) { - return(lubridate::with_tz(x, tzone = tz)) +time_bound <- function(x, tz, arg) { + hint <- paste0("Give a POSIXct, a Date, or a string written year-month-day ", + "with an optional time, such as \"2024-03-01\" or ", + "\"2024-03-01 14:30\".") + if (length(x) != 1L) { + stop("`", arg, "` must be a single date-time, not ", length(x), + " values. ", hint, call. = FALSE) } - if (inherits(x, "POSIXlt")) { - return(lubridate::with_tz(as.POSIXct(x), tzone = tz)) + read <- if (!is.na(x)) read_time(x, tz, arg) + if (is.null(read) || is.na(read$at)) { + shown <- if (is.na(x)) { + "NA" + } else if (is.character(x) || is.factor(x)) { + paste0("\"", as.character(x), "\"") + } else { + format(x) + } + stop("`", arg, "` is ", shown, ", which does not read as a date-time. ", + hint, call. = FALSE) + } + clock <- read$clock + instant <- is.null(clock) || is.na(clock) + if (instant) clock <- lubridate::force_tz(read$at, "UTC") + list(at = read$at, clock = clock, instant = instant) +} + +#' Parse timestamps to instants in a time zone +#' +#' @noRd +parse_time <- function(x, tz, arg) read_time(x, tz, arg)$at + +#' Read timestamps as instants, keeping the clock times they were written as +#' +#' Returns `at`, `POSIXct` instants in `tz`, and `clock`: for a `Date` or a +#' string without an offset, the clock time as written, in UTC; `NA` for a +#' string with its own offset; `NULL` for a date-time, which is an instant +#' already. A clock time is placed in `tz` by `zone_time()`. +#' +#' Base `as.POSIXct()` reads an ISO 8601 string such as +#' "2024-03-01T14:30:00Z" by its date alone, and drops the PM of +#' "2024-03-01 02:30:00 PM", so strings go through lubridate. +#' +#' @noRd +read_time <- function(x, tz, arg) { + if (inherits(x, "POSIXt")) { + # A date-time is an instant; only its display zone changes. Running + # ymd_hms() over it would round-trip it through as.character(), and + # midnight values would become NA. + at <- as.POSIXct(x) + attr(at, "tzone") <- tz + return(list(at = at, clock = NULL)) } if (inherits(x, "Date")) { - return(as.POSIXct(format(x, "%Y-%m-%d 00:00:00"), tz = tz)) + clock <- .POSIXct(floor(unclass(x)) * 86400, tz = "UTC") + return(list(at = zone_time(clock, tz), clock = clock)) } if (is.character(x) || is.factor(x)) { - x <- as.character(x) - parsed <- suppressWarnings(lubridate::ymd_hms(x, tz = tz, quiet = TRUE)) - # Retry the date-only parser on whatever is still missing, rather than only - # when nothing parsed at all. A column mixing "2024-01-01" with - # "2024-01-01 05:00:00" otherwise silently loses every date-only row. - todo <- is.na(parsed) & !is.na(x) - if (any(todo)) { - parsed[todo] <- suppressWarnings( - lubridate::ymd(x[todo], tz = tz, quiet = TRUE)) + read <- read_strings(as.character(x)) + at <- zone_time(read$clock, tz) + if (any(read$own)) { + at[read$own] <- read$clock[read$own] + read$clock[read$own] <- NA } - return(parsed) + return(list(at = at, clock = read$clock)) } stop("`", arg, "` must hold date-times, dates or parseable strings, not ", class(x)[1], ".", call. = FALSE) } -#' Interval boundaries, calendar-aware for months and years +#' Parse strings as clock times in UTC +#' +#' Returns `clock`, each string read in UTC, and `own`, `TRUE` for a string +#' that names its own instant with `Z` or an offset. Such a string reads as +#' the same instant in any zone, which is how it is told apart: it is read a +#' second time an hour east of UTC. #' -#' lubridate::dmonths() is a fixed 30.4375-day duration, so "monthly" buckets -#' drift off month boundaries immediately. +#' Full date-times go through ymd_hms() and dates through ymd(). Whatever is +#' left is tried against "YYYY-mm-dd HH:MM" and "YYYY-mm-dd HH" exactly, with +#' a space or a `T` before the time. ymd_hms(truncated = 3) would also read +#' those, but it reads "01/02/2024" as 21 February 2001. #' #' @noRd -make_breaks <- function(from_dt, to_dt, interval, unit) { - breaks <- if (unit %in% c("months", "years")) { - seq(from_dt, to_dt, by = paste(interval, sub("s$", "", unit))) +read_strings <- function(x) { + clock <- suppressWarnings(lubridate::ymd_hms(x, tz = "UTC", quiet = TRUE)) + east <- suppressWarnings( + lubridate::ymd_hms(x, tz = "Etc/GMT-1", quiet = TRUE)) + own <- !is.na(clock) & clock == east + + # Retry the date-only parser on whatever is still missing, rather than only + # when nothing parsed at all. A column mixing "2024-01-01" with + # "2024-01-01 05:00:00" otherwise loses every date-only row. + todo <- is.na(clock) & !is.na(x) + if (any(todo)) { + clock[todo] <- suppressWarnings( + lubridate::ymd(x[todo], tz = "UTC", quiet = TRUE)) + } + todo <- is.na(clock) & !is.na(x) + if (any(todo)) { + clock[todo] <- suppressWarnings(lubridate::parse_date_time( + x[todo], c("%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y-%m-%d %H", + "%Y-%m-%dT%H"), + tz = "UTC", exact = TRUE, quiet = TRUE)) + } + list(clock = clock, own = own) +} + +#' Place clock times, held in UTC, in a time zone +#' +#' A clock time that a daylight-saving change skips moves to the moment the +#' clocks jump, and one that happens twice takes its first occurrence. A +#' `Date` thus becomes the first instant of its day, whatever the other rows +#' hold, and a day that a zone skipped altogether, as Samoa skipped +#' 2011-12-30, becomes the first instant of the next one. +#' +#' @noRd +zone_time <- function(clock, tz) { + if (identical(tz, "UTC")) { + attr(clock, "tzone") <- tz + return(clock) + } + lubridate::force_tz(clock, tzone = tz, roll_dst = c("boundary", "pre")) +} + +#' Interval boundaries +#' +#' Seconds, minutes and hours are fixed durations from `from_dt`. Days and +#' weeks step by calendar days and months and years by calendar units, each +#' counted from `clock`, the clock time of `from_dt` held in UTC, and then +#' placed in the zone of `from_dt`. Stepping the clock keeps each break at +#' the same local time across a daylight-saving change, where a fixed 86,400 +#' seconds would drift off midnight. Months and years are added to the +#' anchor rather than to the previous break, and a day the month lacks moves +#' to its last day, so a 31 January anchor gives 29 February, 31 March and +#' 30 April. lubridate::dmonths() would be a fixed 30.4375 days. +#' +#' Only complete intervals are used: a row counts only while +#' `tv < breaks[length(breaks)]`. +#' +#' @noRd +make_breaks <- function(from_dt, to_dt, interval, unit, clock = NULL) { + if (unit %in% c("seconds", "minutes", "hours")) { + step <- interval * c(seconds = 1, minutes = 60, hours = 3600)[[unit]] + return(seq(from_dt, to_dt, by = step)) + } + tz <- attr(from_dt, "tzone")[1L] %||% "" + if (!nzchar(tz)) tz <- "UTC" + clock <- clock %||% lubridate::force_tz(from_dt, "UTC") + end <- lubridate::force_tz(to_dt, "UTC") + + steps <- if (unit %in% c("days", "weeks")) { + days <- interval * c(days = 1, weeks = 7)[[unit]] + span <- as.numeric(difftime(end, clock, units = "days")) + clock + 86400 * days * seq_len(max(0, ceiling(span / days) + 1)) } else { - step <- interval * switch(unit, - seconds = 1, minutes = 60, hours = 3600, - days = 86400, weeks = 604800 - ) - seq(from_dt, to_dt, by = step) + a <- as.POSIXlt(clock) + b <- as.POSIXlt(end) + gap <- 12 * (b$year - a$year) + (b$mon - a$mon) + per <- interval * c(months = 1, years = 12)[[unit]] + k <- seq_len(max(0, gap %/% per + 1)) + lubridate::`%m+%`(clock, lubridate::period(month = per * k)) } - # seq() never emits a value past `to`, so no trimming is needed here. Only - # complete intervals are used, and that is enforced where the buckets are - # assigned: a row counts only while `tv < breaks[length(breaks)]`. - breaks + at <- zone_time(steps, tz) + # A day the zone skipped places two clock times at one instant; the empty + # interval between them is dropped. + unique(c(from_dt, at[at > from_dt & at <= to_dt])) } # ---- inclusion probability ------------------------------------------------ #' @noRd exact_inclusion.drawn_design_temporal <- function(design, data) { - validate_data(data, required_columns = design$time) - tz <- design$tz %||% "UTC" - tv <- parse_time(data[[design$time]], tz, design$time) - from_dt <- parse_time(design$from, tz, "from") - to_dt <- parse_time(design$to, tz, "to") - check_window(from_dt, to_dt) - check_na_policy(is.na(tv), design$na_rm, - paste0("a missing or unparseable timestamp in `", - design$time, "`")) - breaks <- make_breaks(from_dt, to_dt, design$interval, design$unit) - - out <- numeric(nrow(data)) - if (length(breaks) < 2L) return(out) - - in_window <- !is.na(tv) & tv >= breaks[1] & tv < breaks[length(breaks)] - if (!any(in_window)) return(out) - - keep <- which(in_window) - bucket <- findInterval(tv[keep], breaks) - for (b in unique(bucket)) { - idx <- keep[bucket == b] - out[idx] <- min(1, design$per_interval / length(idx)) - } + temporal_pi(design, temporal_setup(design, data)$bucket) +} + +#' Inclusion probabilities from each row's interval +#' +#' One count per interval, so the work grows with the number of rows rather +#' than with rows times intervals. +#' +#' @noRd +temporal_pi <- function(design, bucket) { + out <- numeric(length(bucket)) + inw <- !is.na(bucket) + if (!any(inw)) return(out) + sizes <- tabulate(bucket[inw]) + out[inw] <- pmin(1, design$per_interval / sizes[bucket[inw]]) out } #' Which sampling interval each row falls in #' -#' `NA` for a row outside the window, which the design can never select. Shared -#' by the joint-probability and `survey` mappings so the three views of a -#' temporal design cannot drift apart. +#' A factor whose levels are every interval of the window in time order, +#' named by its start (see `interval_labels()`), and `NA` for a row outside +#' the window, which the design can never select. The variance, the +#' jackknife, `survey`'s strata and `sample_summary()` all read the intervals +#' from here, so they name them alike. #' #' @noRd temporal_bucket <- function(design, data) { - validate_data(data, required_columns = design$time) - tz <- design$tz %||% "UTC" - tv <- parse_time(data[[design$time]], tz, design$time) - from_dt <- parse_time(design$from, tz, "from") - to_dt <- parse_time(design$to, tz, "to") - check_window(from_dt, to_dt) - breaks <- make_breaks(from_dt, to_dt, design$interval, design$unit) - out <- rep(NA_character_, nrow(data)) - if (length(breaks) >= 2L) { - inw <- !is.na(tv) & tv >= breaks[1] & tv < breaks[length(breaks)] - out[inw] <- as.character(findInterval(tv[inw], breaks)) + tm <- temporal_setup(design, data) + structure(tm$bucket, levels = interval_labels(tm$breaks, tm$tz), + class = "factor") +} + +#' Each interval's start, as a label +#' +#' "2024-01-03 00:00" in the design's zone, with seconds when a start has +#' them, so the labels are unique and sort in time order. A clock time that +#' a daylight-saving change repeats starts two intervals, and both get the +#' zone's abbreviation, or failing that its UTC offset, to tell them apart. +#' +#' @noRd +interval_labels <- function(breaks, tz) { + start <- breaks[-length(breaks)] + sec <- as.POSIXlt(start, tz = tz)$sec + fmt <- if (all(sec == 0)) { + "%Y-%m-%d %H:%M" + } else if (all(sec == floor(sec))) { + "%Y-%m-%d %H:%M:%S" + } else { + "%Y-%m-%d %H:%M:%OS3" + } + out <- format(start, fmt, tz = tz) + for (zone in c("%Z", "%z")) { + twice <- out %in% out[duplicated(out)] + if (!any(twice)) break + out[twice] <- paste(format(start[twice], fmt, tz = tz), + format(start[twice], zone, tz = tz)) } out } @@ -213,7 +465,6 @@ temporal_bucket <- function(design, data) { #' #' `make_breaks()` hands a backwards window to `seq()`, which fails with "wrong #' sign in 'by' argument" -- a base-R message that says nothing about the design. -#' `draw_design()` guarded this; the probability paths did not. #' #' @noRd check_window <- function(from_dt, to_dt) { diff --git a/R/design-weighted.R b/R/design-weighted.R index 252269e..41821fe 100644 --- a/R/design-weighted.R +++ b/R/design-weighted.R @@ -15,7 +15,8 @@ #' proportional to the weights. How far off depends on the weights: with a #' single dominant unit the two nearly coincide (about 1% apart), but with a #' moderate spread the gap is large — weights `1:10` at `n = 5` give -#' inclusion probabilities up to 35% away from proportional. Treating them as +#' inclusion probabilities up to about 36% away from proportional, by +#' exact enumeration of the ordered draws. Treating them as #' if they were proportional biases a Horvitz-Thompson total by around 1% at #' `n = 15` out of 30 in simulation, small in size but unmistakable in sign. #' There is no closed form for `pi`, so [inclusion_prob()] refuses to give @@ -31,22 +32,81 @@ #' form, so [ht_total()] uses Deville's approximation for the variance, #' which needs only the first-order probabilities.} #' \item{`"poisson"`}{Each row is included independently with probability -#' `pi_i = n * p_i`, capped at 1. Inclusion probabilities are exactly -#' proportional to size and every pair can co-occur, at the cost of a -#' **random sample size** averaging `n`.} +#' `pi_i = n * p_i`. Rows heavy enough that `n * p_i > 1` are taken with +#' certainty and the rest rescaled, repeatedly, as for `"systematic"`, so +#' the probabilities still sum to `n`. Inclusion probabilities are exactly +#' proportional to size among the rows below certainty, and every pair can +#' co-occur, at the cost of a **random sample size** averaging `n`.} #' } #' #' `replace = TRUE` is with-replacement PPS and applies only to #' `method = "successive"`. #' -#' @param weights Column of positive, finite weights. -#' @param n Number of rows to draw. Under `method = "poisson"` this is the -#' expected number, not a guarantee. +#' @section Strata: +#' With `strata`, `n` is split over the strata by `allocation`, as +#' [design_stratified()] splits it over the rows in each stratum, and each +#' stratum is then sampled in proportion to size on its own: a row of stratum +#' `h` gets `n_h * w_i / sum(w)`, the sum running over the stratum, with rows +#' past certainty taken with certainty within it. Under `"systematic"` each +#' stratum is shuffled and walked from a start of its own, in key order; +#' under `"poisson"` every row is included independently with the probability +#' its stratum gives it, so the size of each stratum's sample is random. +#' `"successive"` has no closed-form inclusion probability and is refused with +#' `strata`. To split `n` in proportion to each stratum's total size rather +#' than its rows, work out the counts and give them as `allocation`. +#' +#' The strata are sampled independently. [ht_total()] and [ht_mean()] add up +#' Deville's approximation over the strata for `"systematic"`, and the +#' Poisson variance needs no change. The degrees of freedom are the sampled +#' rows below certainty less the strata that hold them. A stratum with one +#' sampled row below certainty has nothing to compare it with, and the +#' variance is refused with the stratum named; draw at least two in each. +#' +#' In simulations of 2,000 draws each from frames of 600 rows in four strata, +#' drawing 24 or 60 rows by `"systematic"`, the variance averaged 0.94 to +#' 1.04 times the true variance of the total, and 95% intervals covered 89% +#' to 96% of the time. The low coverage came where `y / pi` was skewed, so +#' that samples with a low total also had a low estimated variance; the same +#' frames without strata covered 92% to 94%. +#' +#' [as_svydesign()] hands the strata to `survey`, with Brewer's approximation +#' within each, [allocation_table()] shows the split before anything is +#' drawn, and [sample_summary()] counts the rows drawn from each stratum. +#' +#' Drawing each stratum with a design of its own and binding the samples with +#' [rbind()] does not give a sample to estimate from. The bound sample keeps +#' the first draw's frame and design, so [ht_total()] refuses it; use +#' `strata` instead. +#' +#' @param weights Column of positive, finite, numeric weights. A weight of 0 +#' is refused under every method, not given a probability of 0; drop such +#' rows from the frame first, since a design that selects in proportion to +#' size could never select them. +#' @param n Number of rows to draw, the total across `strata` when given, or +#' a plan from [plan_size()]. +#' Under `method = "poisson"` this is the expected number, not a guarantee. +#' With counts in `allocation` it can be left out and is their sum; when +#' given, it must equal that sum. #' @param replace Sample with replacement? Only available for #' `method = "successive"`. #' @param method One of `"successive"`, `"systematic"` or `"poisson"`. See #' "Choosing a method". -#' @param na_rm Drop rows whose weight is `NA` instead of raising an error. +#' @param na_rm Drop rows whose weight or stratum key is `NA` instead of +#' raising an error. +#' @param strata Optional column name(s) defining strata, to sample in +#' proportion to size within each one. Several columns are +#' cross-classified. Needs `method = "systematic"` or `"poisson"`. See +#' "Strata". +#' @param allocation How `n` is split across `strata`: `"proportional"` to +#' the number of rows in each stratum, or `"equal"`, by the +#' largest-remainder method of [design_stratified()], with a stratum that +#' would get more rows than it holds taken whole; or the count for each +#' stratum, as a named vector such as `c(north = 10, south = 5)` when +#' `strata` is one column, or a data frame of the `strata` columns and `n`. +#' Counts follow the rules of [design_stratified()]: every stratum of the +#' frame needs one, a count for a stratum the frame does not have is +#' refused, and no count may exceed the rows in its stratum. Only with +#' `strata`. #' #' @return A design object, for use with [draw()]. #' @@ -75,66 +135,188 @@ #' s <- draw(df, d, seed = 1, weights = TRUE) #' sum(s$w * s$.weight) # estimates sum(df$w) = 210 #' +#' # In proportion to size within each of two regions +#' df$region <- rep(c("east", "west"), each = 10) +#' by_region <- design_weighted("w", n = 8, method = "systematic", +#' strata = "region") +#' allocation_table(df, by_region) +#' round(inclusion_prob(df, by_region), 3) +#' #' @family designs -#' @seealso [draw()], [inclusion_prob()], [design_spread()] to select in +#' @seealso [draw()], [inclusion_prob()], [certainty_set()] for the rows +#' taken with certainty, [design_spread()] to select in #' proportion to size *and* spread the sample across a map. The `sampling` #' package implements further fixed-size unequal-probability algorithms #' (Brewer, Sampford, Tillé, maximum entropy) as vector functions. #' @export design_weighted <- function(weights, n, replace = FALSE, method = c("successive", "systematic", "poisson"), - na_rm = FALSE) { - method <- match.arg(method) + na_rm = FALSE, strata = NULL, + allocation = c("proportional", "equal")) { + if (!missing(n)) n <- plan_n(n) + method <- check_choice(method, c("successive", "systematic", "poisson"), + "method") replace <- check_flag(replace, "replace") if (replace && method != "successive") { stop("`replace = TRUE` is with-replacement PPS and cannot be combined with ", "method = \"", method, "\". Use method = \"successive\", or set ", "replace = FALSE.", call. = FALSE) } + if (is.null(strata)) { + if (!missing(allocation) && !is.null(allocation)) { + stop("`allocation` splits `n` over strata, and `strata` is NULL. Name ", + "the strata columns in `strata`, or leave `allocation` out.", + call. = FALSE) + } + allocation <- NULL + n <- check_count(n, "n") + } else { + strata <- check_columns(strata, "strata") + if (method == "successive") { + stop("`strata` cannot be combined with method = \"successive\", whose ", + "inclusion probabilities have no closed form, so a total could not ", + "be estimated from the strata. Use method = \"systematic\" or ", + "\"poisson\".", call. = FALSE) + } + if (is.numeric(allocation) || is.data.frame(allocation)) { + allocation <- check_stratum_counts(allocation, strata) + n <- counts_n(if (!missing(n)) n, allocation) + } else { + if (!is.null(allocation) && !is.character(allocation)) { + stop("`allocation` must be \"proportional\", \"equal\" or the count ", + "for each stratum, not ", format_bad(allocation), ".", + call. = FALSE) + } + allocation <- check_choice(allocation, c("proportional", "equal"), + "allocation") + if (missing(n) || is.null(n)) { + stop("`n` is missing. Give the total number of rows to draw, or the ", + "count for each stratum in `allocation`.", call. = FALSE) + } + n <- check_count(n, "n") + } + } new_design("weighted", list( weights = check_columns(weights, "weights", 1L), - n = check_count(n, "n"), + n = n, replace = replace, method = method, - na_rm = check_flag(na_rm, "na_rm") + na_rm = check_flag(na_rm, "na_rm"), + strata = strata, + allocation = allocation )) } -#' @export -draw_design.drawn_design_weighted <- function(design, data) { - validate_data(data, required_columns = design$weights) - +#' Weights a weighted design can use, and a size the frame can supply +#' +#' The checks the draw and the probabilities share, so [inclusion_prob()] +#' refuses what [draw()] refuses, with the same message: weights that are not +#' numeric, missing under `na_rm = FALSE`, missing in every row, not finite or +#' not positive, and an `n` above the rows left. Returns `keep`, the rows the +#' design uses, and `w`, their weights. +#' +#' With `strata`, a row with a missing stratum key is refused or dropped as a +#' missing weight is, and `n` is split over the strata of the rows kept by +#' `stratum_allocation()`. The result then also holds `code`, each kept +#' row's stratum as a position in `labels`, `sizes` and `n_alloc`, and `idx`, +#' the positions in `keep` of each stratum's rows, in key order. +#' +#' @noRd +weighted_setup <- function(design, data) { col <- design$weights + strata <- design$strata + validate_data(data, required_columns = c(col, strata)) check_key_columns(data, col, "weights") + if (!is.null(strata)) check_key_columns(data, strata, "strata") w <- data[[col]] - if (!is.numeric(w)) { - stop("`", col, "` must be numeric, not ", class(w)[1], ".", call. = FALSE) + check_weights(w, col) + what <- paste0("a missing weight in `", col, "`") + bad <- check_na_policy(is.na(w), design$na_rm, what) + if (all(bad)) stop("Every row has ", what, ".", call. = FALSE) + if (!is.null(strata)) return(weighted_strata(design, data, w, bad)) + keep <- which(!bad) + n_rows <- length(keep) + if (design$method == "successive") { + check_draw_size(design$n, n_rows, design$replace) + } else if (design$n > n_rows) { + stop("`n` (", design$n, ") cannot exceed the number of rows (", n_rows, + ") for method = \"", design$method, "\".", call. = FALSE) } - if (anyNA(w)) { - data <- drop_na_rows(data, is.na(w), design$na_rm, - paste0("a missing weight in `", col, "`")) - w <- data[[col]] + list(keep = keep, w = w[keep]) +} + +#' The strata of a weighted design, and its split of `n` over them +#' +#' `bad` marks the rows dropped for a missing weight. The allocation runs +#' over the rows left, so a stratum's size counts only rows the design can +#' draw. +#' +#' @noRd +weighted_strata <- function(design, data, w, bad) { + strata <- design$strata + key <- group_key(data, strata) + gone <- check_na_policy(is.na(key) & !bad, design$na_rm, + "a missing stratum key") + keep <- which(!bad & !gone) + if (!length(keep)) { + stop("Every row has a missing weight in `", design$weights, "` or a ", + "missing stratum key.", call. = FALSE) } - check_weights(w, col) + refuse_emptied_counts(design, data, key, keep, + paste0("a missing weight in `", design$weights, "`")) + # These methods have no `replace`, so a count above its stratum's rows is + # refused without offering one. + split_by <- design + split_by$replace <- NULL + al <- stratum_allocation(split_by, table_frame( + lapply(strata, function(col) data[[col]][keep]), strata, list())) + list(keep = keep, w = w[keep], code = al$code, labels = al$labels, + idx = al$idx, sizes = al$sizes, n_alloc = al$n_alloc) +} + +#' Each kept row's inclusion probability under a PPS method +#' +#' `st` is `weighted_setup()`. Without strata, `pps_pi()` over all the rows; +#' with them, `pps_pi()` within each stratum, for its share of `n`. +#' +#' @noRd +weighted_pi <- function(design, st) { + if (is.null(design$strata)) return(pps_pi(st$w, design$n)) + pi <- numeric(length(st$keep)) + for (h in seq_along(st$idx)) { + i <- st$idx[[h]] + pi[i] <- pps_pi(st$w[i], st$n_alloc[h]) + } + pi +} +#' @export +draw_design.drawn_design_weighted <- function(design, data) { + st <- weighted_setup(design, data) + if (length(st$keep) < nrow(data)) data <- reindex(data, st$keep) + w <- st$w n_rows <- nrow(data) if (design$method == "successive") { - check_draw_size(design$n, n_rows, design$replace) idx <- sample.int(n_rows, size = design$n, replace = design$replace, - prob = w) + prob = finite_total(w)) return(reindex(data, idx)) } - if (design$n > n_rows) { - stop("`n` (", design$n, ") cannot exceed the number of rows (", n_rows, - ") for method = \"", design$method, "\".", call. = FALSE) + if (!is.null(design$strata)) { + warn_empty_groups(st$n_alloc, st$sizes, st$labels, fix = paste0( + if (has_counts(design)) "Give " else "Raise `n`, or give ", + "each stratum a count of at least 1 in `allocation` (or 2, so each ", + "stratum also supports a variance).")) } - - pi <- pps_pi(w, design$n) + pi <- weighted_pi(design, st) idx <- if (design$method == "poisson") { which(stats::runif(n_rows) < pi) + } else if (!is.null(design$strata)) { + # Each stratum is shuffled and walked on its own, in key order. + unlist(lapply(st$idx, function(i) i[systematic_pps(pi[i])]), + use.names = FALSE) } else { systematic_pps(pi) } @@ -149,8 +331,12 @@ draw_design.drawn_design_weighted <- function(design, data) { #' redistribute the remaining sample size over the rest -- repeating, because #' removing units raises everyone else's share. #' +#' A share that rounds to slightly below 1 is certain too, and gets exactly 1, +#' so every check on `.prob` sees the same certainty units as the draw. +#' #' @noRd pps_pi <- function(w, n) { + w <- finite_total(w) pi <- rep(0, length(w)) certain <- rep(FALSE, length(w)) @@ -158,9 +344,12 @@ pps_pi <- function(w, n) { free <- !certain n_free <- n - sum(certain) if (n_free <= 0 || !any(free)) break + # Positive weights can still divide to 0 against the largest, when they + # span more orders of magnitude than a double holds; see the check below. + if (!(sum(w[free]) > 0)) break p <- w[free] / sum(w[free]) cand <- n_free * p - over <- cand >= 1 + over <- is_certain(cand) if (!any(over)) { pi[free] <- cand break @@ -170,9 +359,30 @@ pps_pi <- function(w, n) { } pi[certain] <- 1 + if (!isTRUE(abs(sum(pi) - n) <= 1e-6 * max(n, 1))) { + stop("The size measure gives inclusion probabilities summing to ", + format(sum(pi)), ", where `n` is ", n, ", because its values span ", + "more orders of magnitude than double precision holds. Take the ", + "largest units with design_certainty() and sample the rest.", + call. = FALSE) + } pi } +#' Weights whose sum is finite +#' +#' A probability proportional to size does not depend on the scale of the +#' sizes. Positive weights near `1e306` sum to `Inf`, which made every +#' probability 0, so such weights are divided by the largest of them. Weights +#' with a finite sum are returned as they are, which keeps their +#' probabilities, and the rows a seed selects, unchanged. +#' +#' @noRd +finite_total <- function(w) { + if (length(w) && !is.finite(sum(w))) w <- w / max(w) + w +} + #' Systematic PPS selection given inclusion probabilities #' #' Walks the cumulative probabilities with a fixed step of 1 from a random start @@ -196,6 +406,7 @@ systematic_pps <- function(pi) { #' @noRd exact_inclusion.drawn_design_weighted <- function(design, data) { + st <- weighted_setup(design, data) if (design$method == "successive") { no_closed_form( "`design_weighted(method = \"successive\")`", @@ -205,30 +416,33 @@ exact_inclusion.drawn_design_weighted <- function(design, data) { "are proportional to the weights.") ) } - validate_data(data, required_columns = design$weights) - col <- design$weights - check_key_columns(data, col, "weights") - w <- data[[col]] - keep <- !check_na_policy(is.na(w), design$na_rm, - paste0("a missing weight in `", col, "`")) - # pps_pi()'s rescaling loop runs off the rails on a non-positive weight -- - # `n_free` goes negative and it returns a vector of 0s and 1s summing to the - # wrong total. draw_design() rejects these; so must this. - check_weights(w[keep], col) out <- numeric(nrow(data)) - out[keep] <- pps_pi(w[keep], design$n) + out[st$keep] <- weighted_pi(design, st) out } -#' Weights a probability-proportional-to-size design can actually use +#' Weights a probability-proportional-to-size design can use +#' +#' Numeric, finite and positive. Missing values are left to the design's +#' `na_rm`. A negative weight sends the rescaling in `pps_pi()` to a vector of +#' 0s and 1s summing to the wrong total. A weight of 0 is refused too, on +#' every path, and the message says to drop such rows from the frame. Every +#' message names the column. +#' #' @noRd check_weights <- function(w, col) { + if (!is.numeric(w)) { + stop("`", col, "` must be numeric, not ", class(w)[1], ".", call. = FALSE) + } + w <- w[!is.na(w)] if (any(!is.finite(w))) { stop("`", col, "` contains ", sum(!is.finite(w)), " non-finite weight(s).", call. = FALSE) } if (any(w <= 0)) { - stop("All weights must be positive; ", sum(w <= 0), " are not.", + stop("`", col, "` must be positive, but ", sum(w <= 0), " weight(s) are ", + "0 or negative. Drop those rows from `data` first; a design that ", + "selects in proportion to size can never select them.", call. = FALSE) } invisible(w) diff --git a/R/design.R b/R/design.R index 4eba322..56365c8 100644 --- a/R/design.R +++ b/R/design.R @@ -8,11 +8,15 @@ #' @section The designs: #' \describe{ #' \item{[design_simple()]}{Rows uniformly at random.} -#' \item{[design_stratified()]}{A share of each stratum.} -#' \item{[design_systematic()]}{Every *k*-th row.} +#' \item{[design_stratified()]}{A share of each stratum, at random or +#' walked in order.} +#' \item{[design_systematic()]}{Every *k*-th row, or `n` rows at an even +#' step, from one random start or several.} #' \item{[design_cluster()]}{Whole clusters.} -#' \item{[design_multistage()]}{Clusters, then rows within them.} -#' \item{[design_weighted()]}{Rows with probability governed by a weight.} +#' \item{[design_multistage()]}{Clusters, at random or in proportion to +#' size, then rows within them.} +#' \item{[design_weighted()]}{Rows with probability governed by a weight, +#' within strata if asked.} #' \item{[design_certainty()]}{Everything above a threshold, plus a sample of #' the rest.} #' \item{[design_reservoir()]}{A fixed-size sample from a stream.} @@ -20,7 +24,7 @@ #' \item{[design_temporal()]}{A share of each time interval.} #' \item{[design_spatial()]}{Rows inside a region.} #' \item{[design_spread()]}{A sample spread evenly across a map or across -#' auxiliary variables.} +#' auxiliary variables, within strata if asked.} #' } #' #' @section What every design guarantees: @@ -29,43 +33,78 @@ #' * `n` is always the **total** number of rows drawn, never a per-group figure. #' [design_temporal()] uses `per_interval` precisely because that one *is* per #' group, and [design_cluster()] has no `n` at all because the row count -#' follows from which clusters were selected. -#' * `allocation` always says how a total is split across groups, either -#' `"proportional"` or `"equal"`. Splitting is exact: the largest-remainder -#' method is used, so a request for 60 rows returns 60 rather than drifting -#' with per-group rounding. +#' follows from which clusters were selected. A plan from [plan_size()] can +#' be given as `n`, and its `n` is used. +#' * `allocation` always says how a total is split across groups: +#' `"proportional"`, `"equal"` or, in [design_stratified()] only, +#' `"neyman"`. [design_stratified()], [design_spread()] and +#' [design_weighted()] also take the count for each stratum in place of a +#' rule, and `n` is then their total. +#' Splitting is exact: the largest-remainder method is used, so a request +#' for 60 rows returns 60 rather than drifting with per-group rounding. #' * `na_rm` always decides whether rows with a missing key are dropped or raise #' an error. It is never silently assumed either way. +#' * Groups always come in key order, whether strata, `by` domains or the +#' rows of [sample_summary()]: a factor's levels, or the sorted values of any +#' other column, with text sorted byte by byte as in the C locale. A seed +#' therefore draws the same rows in every locale, and an `order_by` column +#' of text is walked in the same order everywhere. #' * `replace` always means sampling with replacement within whatever group the #' design works on, and always rules out `draw(weights = TRUE)`: an inclusion #' probability describes distinct units, and a sample holding duplicates #' cannot be weighted by one. -#' * [draw()] always restores the caller's random number stream before -#' returning, and always gives back a data frame with the input's class and -#' column order. +#' * With a `seed`, [draw()] always restores the caller's random number +#' stream and generator before returning, and a seed draws the same sample +#' whatever generator the session has selected. With `seed = NULL` it draws +#' from, and advances, the caller's stream. See "Seeding" in [draw()]. +#' * [draw()] always gives back a data frame with the input's class and +#' column order, and the frame's own row names on the rows drawn. +#' [design_bootstrap()] with `output = "indices"` or +#' `"weights"` gives a matrix instead, and [design_reservoir()] a list +#' when `data` is not a data frame, unless `batches = TRUE`. #' * Rows come back in frame order for every design that selects a set of rows, -#' including [design_systematic()] with `order_by`. -#' The two exceptions are the ones where draw order is meaningful: -#' [design_simple()] and [design_weighted()] return rows in the order they -#' were drawn, and [design_bootstrap()] returns replicates in order with a -#' leading `.replicate` column. +#' including [design_systematic()] with `order_by` and [design_weighted()] +#' with `method = "systematic"` or `"poisson"`. +#' The exceptions are the ones where draw order is meaningful: +#' [design_simple()] and `design_weighted(method = "successive")` return +#' rows in the order they were drawn, and [design_bootstrap()] returns +#' replicates in order with a leading `.replicate` column. A design with +#' `reserve` returns its main sample and then its reserves, in the order +#' they are used, with a leading `.reserve` column. #' #' @section Estimating from a sample: #' Because a design is a value, it can report its own inclusion probabilities #' before any sampling happens. [inclusion_prob()] gives first-order #' probabilities and [sampling_weight()] their reciprocals — the number of -#' population rows each sampled row stands for. [joint_prob()] gives +#' population rows each sampled row stands for, and [certainty_set()] the rows +#' a design that selects in proportion to size takes with certainty. +#' [allocation_table()] shows how a design with strata splits `n` over the +#' strata of a frame, and which strata it holds at the floor, takes whole or +#' leaves empty. [joint_prob()] gives #' second-order probabilities, and [ht_total()] and [ht_mean()] turn a sample -#' into a population total, mean or proportion — overall or by domain — with a -#' standard error from the variance estimator suited to the design and a -#' confidence interval on the design's degrees of freedom. [deff()] reports +#' into a population total, mean or proportion, overall or by domain and for +#' one variable or several, with a standard error from the variance +#' estimator suited to the design and a confidence interval on the design's +#' degrees of freedom. A factor `y` gives the count or share of each level. +#' [ht_ratio()] estimates a ratio of two totals the same way, +#' `ht_total(ratio =)` the ratio estimator of a total, and [ht_quantile()] +#' medians and other quantiles with Woodruff intervals. [deff()] reports #' what the design cost in precision against simple random sampling, and #' [sample_summary()] reports what was actually drawn against what was in the -#' frame. +#' frame. [add_fieldwork()] joins fieldwork results to a sample by an id, +#' [use_reserves()] replaces the units of a list from [design_simple()] or +#' [design_spread()] with `reserve` that were found unavailable, +#' [as_drawn()] rebuilds a sample read back from a file or a database, and +#' [compact_sample()] drops the frame columns its design does not read before +#' it is saved or shared. #' #' Going the other way, [plan_size()] solves for the sample size a given margin -#' of error requires — the step *before* choosing a design. For analysis this -#' package does not do, [as_svydesign()] hands a sample to the `survey` package. +#' of error requires — the step *before* choosing a design. It plans a sample +#' overall or split over strata, and [deff_cluster()] gives the design effect +#' of a cluster sample to plan with. For analysis this package does not do, +#' [as_svydesign()] hands a sample to the `survey` package, +#' [replicate_weights()] builds replicate weights for it from the design, and +#' [frame_totals()] gives the frame's totals to calibrate it to. #' #' Not every design has a closed form for these — see [inclusion_prob()] for #' which, why, and what to do instead. Those that do not say so rather than @@ -80,9 +119,12 @@ #' `min_per_stratum` if rare groups must appear.} #' \item{Fieldwork cost matters more than efficiency}{[design_cluster()] or #' [design_multistage()] — visiting five sites is cheaper than visiting -#' fifty, at the cost of precision.} +#' fifty, at the cost of precision. With `size`, [design_multistage()] +#' selects the sites in proportion to size and takes the same number of +#' rows from each.} #' \item{Large units matter more}{[design_weighted()], with -#' `method = "systematic"` or `"poisson"` if you intend to estimate.} +#' `method = "systematic"` or `"poisson"` if you intend to estimate, and +#' `strata` to sample in proportion to size within each stratum.} #' \item{A few units dominate the total}{[design_certainty()] — take those #' with certainty and sample the tail, which removes them from the variance #' entirely.} @@ -130,25 +172,53 @@ design_type <- function(x) { print.drawn_design <- function(x, ...) { cat("\n", sep = "") params <- unclass(x) - params <- params[!vapply(params, is.null, logical(1))] - if (length(params) == 0L) { + shown <- Map(function(v, nm) if (!is.null(v)) fmt_param(v, nm), + params, names(params)) + # A NULL that stands for a default worked out later is shown by what it + # means. A temporal design without `tz` takes its zone from the data. + if (inherits(x, "drawn_design_temporal") && is.null(params$tz)) { + shown$tz <- "from the time column, else UTC" + } + if (inherits(x, "drawn_design_systematic") && is.null(params$start)) { + shown$start <- "random" + } + if (inherits(x, "drawn_design_bootstrap")) { + if (is.null(params$n)) shown$n <- "nrow(data)" + if (is.null(params$block_length) && !identical(params$method, "simple")) { + shown$block_length <- "nrow(data)^(1/3), rounded down" + } + } + shown <- shown[!vapply(shown, is.null, logical(1))] + if (length(shown) == 0L) { return(invisible(x)) } - width <- max(nchar(names(params))) - for (nm in names(params)) { - cat(" ", formatC(nm, width = -width), " ", fmt_param(params[[nm]]), "\n", - sep = "") + width <- max(nchar(names(shown))) + for (nm in names(shown)) { + cat(" ", formatC(nm, width = -width), " ", shown[[nm]], "\n", sep = "") } invisible(x) } +#' Is a design parameter a value per stratum? +#' +#' Counts, standard deviations or costs given per stratum, as `allocation`, +#' `allocation_by` or `cost`. Other named numbers, such as a `threshold` +#' taken from quantile(), are shown by value alone. +#' +#' @noRd +is_per_stratum <- function(v, name) { + isTRUE(name %in% c("allocation", "allocation_by", "cost")) && + (is.data.frame(v) || (is.numeric(v) && !is.null(names(v)))) +} + #' @noRd -fmt_param <- function(v) { +fmt_param <- function(v, name = NULL) { if (inherits(v, c("sf", "sfc"))) { return(paste0("<", class(v)[1], ">")) } if (is.function(v)) return("") if (is_design(v)) return(design_label(v)) + if (is_per_stratum(v, name)) return(fmt_counts(v)) if (inherits(v, "POSIXt") || inherits(v, "Date")) return(format(v)) if (is.character(v)) { return(paste0("\"", v, "\"", collapse = ", ")) diff --git a/R/draw.R b/R/draw.R index 919ec3b..c3c8a48 100644 --- a/R/draw.R +++ b/R/draw.R @@ -4,47 +4,128 @@ #' #' @section What you get back: #' A data frame with the same class and the same columns, in the same order, as -#' `data`. Two designs qualify that: +#' `data`. `weights = TRUE` prepends three columns (see "Design weights"), and +#' some designs qualify it further: #' #' * [design_bootstrap()] prepends a `.replicate` column identifying which #' replicate each row belongs to, so all replicates come back in one frame. -#' Split them with `split(out, out$.replicate)` if you need a list. -#' * [design_reservoir()] returns a list when `data` is a stream rather than a -#' data frame, because there is nothing to make a data frame out of. +#' Split them with `split(out, out$.replicate)` if you need a list. With +#' `output = "indices"` or `"weights"` it returns a matrix of row numbers or +#' counts instead, with a column per replicate. +#' * [design_reservoir()] returns a list when `data` is a list or a stream +#' rather than a data frame, because there is nothing to make a data frame +#' out of. With `batches = TRUE` it returns the rows sampled from a +#' function's data frames as one data frame. +#' * [design_simple()] and [design_spread()] with `reserve` return a list: +#' the main sample, then the reserves, with a leading integer `.reserve` +#' column that is 0 for the main sample and numbers the reserves 1, 2, ... +#' in the order they are used. With `weights = TRUE` it follows `.row`, +#' and `.prob` is the main sample's probability for every row. +#' [use_reserves()] turns the list into the sample to estimate from. +#' +#' Row names of the frame's own, such as the car names of `mtcars`, stay with +#' their rows. A row drawn more than once, by a design with `replace = TRUE` +#' or by [design_bootstrap()], gets names made unique by [make.unique()]: +#' `"Mazda RX4"`, then `"Mazda RX4.1"`. The automatic row names 1, 2, ... +#' number the sample's rows afresh, and `weights = TRUE` records each row's +#' place in `data` in `.row`. A tibble has no row names to keep. #' #' @section Design weights: -#' `weights = TRUE` prepends two columns: `.prob`, the probability that the row -#' was included in the sample, and `.weight`, its reciprocal — the number of -#' population units the row stands for. Those are what an unbiased estimate -#' needs: a Horvitz-Thompson total is `sum(y * .weight)`. +#' `weights = TRUE` prepends three columns: `.prob`, the probability that the +#' row was included in the sample; `.weight`, its reciprocal, the number of +#' population units the row stands for; and `.row`, the row of `data` it came +#' from. `.prob` and `.weight` are what an unbiased estimate needs: a +#' Horvitz-Thompson total is `sum(y * .weight)`. #' #' They come from the design applied to the population, not from the drawn #' sample, and some designs have no closed form for them. [inclusion_prob()] #' documents which, why, and what to do instead. #' -#' The sample also carries its design, the frame rows it came from and the -#' frame itself as attributes, which is what lets [ht_total()], [ht_mean()], -#' [sample_summary()] and [as_svydesign()] work from the sample alone. Two -#' consequences: estimate before subsetting (use `by` for groups), since -#' `[` drops the attributes; and saving the sample with [saveRDS()] saves the -#' frame with it. +#' Two kinds of design are weighted conditional on the clusters the draw +#' selected: [design_cluster()] with `balanced = TRUE`, and +#' [design_multistage()] without `size` when the rows taken from a cluster +#' depend on which other clusters were selected. With `a` of `A` clusters +#' selected and `m_i` of the `N_i` rows of cluster `i` taken, `.prob` is +#' `(a / A) * m_i / N_i`, the chance of the cluster being selected times the +#' chance of the row being drawn given these clusters. The total estimated +#' from it is unbiased given the clusters selected, and so over every +#' selection. [sample_summary()] says when a sample is weighted this way. +#' +#' Keep `.prob` as it is: [ht_total()], [ht_mean()] and [as_svydesign()] refuse +#' a sample whose `.prob` was changed. Weights adjusted after the draw, for +#' nonresponse say, go in `.weight`, and [as_svydesign()] is the way to +#' estimate from them; [ht_total()] and [ht_mean()] keep to `.prob` and warn +#' when `.weight` no longer matches it. +#' +#' The sample also carries its design, the frame rows it came from and a copy +#' of the frame as attributes, which is what lets [ht_total()], [ht_mean()], +#' [sample_summary()] and [as_svydesign()] work from the sample alone. +#' +#' * The frame is copied when the sample is drawn, every column of it. Later +#' edits to `data`, including data.table's in-place `:=`, `setorder()` and +#' `setkey()`, do not reach the sample. Each sample holds its own copy, in +#' memory and in every file it is saved to with [saveRDS()], so a list of +#' samples from a large frame holds the frame once per sample, and a +#' sample sent to someone sends them the frame, with any personal data in +#' it. [compact_sample()] keeps only the columns the design reads. +#' * Reordering the sample by `[`, `dplyr::arrange()` or +#' `data.table::setorder()` is safe, because each row finds its frame row +#' through `.row`. +#' * Estimate from the whole sample and use `by` for groups. Row subsets +#' (`head()`, `s[cond, ]`, `dplyr::filter()`), [rbind()] of samples and joins +#' that repeat rows keep the attributes but no longer match the rows that +#' were drawn, and the functions above refuse them. [merge()], column +#' selection (`s[, cols]`), [subset()] and [transform()] drop the attributes +#' altogether. Add fieldwork results with [add_fieldwork()], which matches +#' them on an id, or with `s$col <- value`. +#' * A CSV or spreadsheet file and a database table keep the rows and the +#' `.row` column but not the attributes. [as_drawn()] rebuilds the sample +#' from them, the design and the frame. #' #' `weights = TRUE` is not available for a design that samples **with -#' replacement**. `.prob` there is the probability of being selected *at least -#' once*, but the sample holds duplicates, so `sum(y * .weight)` over it counts -#' each duplicate at the distinct-unit weight and comes out around 15% high. -#' Use `replace = FALSE`, or the Hansen-Hurwitz form `N / n * sum(y)`. +#' replacement**, or a [design_certainty()] whose `rest` does. `.prob` there +#' is the probability of being selected *at least once*, but the sample holds +#' duplicates, so `sum(y * .weight)` over it counts each duplicate at the +#' distinct-unit weight. The total comes out high by a factor of +#' `(n / N) / (1 - (1 - 1 / N)^n)`, which is about 5% at `n = N / 10`, 15% at +#' `n = 0.3 * N`, 58% at `n = N` and more beyond, applied within each stratum +#' of a stratified design. Use `replace = FALSE`, or the Hansen-Hurwitz form +#' `N / n * sum(y)`, summed over strata as `N_h / n_h * sum(y_h)` for a +#' stratified design. #' #' @section Seeding: -#' `seed` is saved, applied, and unwound: `.Random.seed` is restored on exit, so -#' drawing a sample inside a simulation does not shift the simulation's own -#' random number stream. Leave it `NULL` to draw from the current stream. +#' With a `seed`, `draw()` saves the caller's random number state, seeds, +#' draws, and restores the state on exit, so drawing a sample inside a +#' simulation does not shift the simulation's own random number stream. With +#' `seed = NULL` it draws from the caller's stream and advances it, as any +#' function that draws random numbers does. +#' +#' A seed is applied with R's default generator, +#' `set.seed(seed, kind = "Mersenne-Twister", normal.kind = "Inversion", +#' sample.kind = "Rejection")`, whatever generator the session has selected, +#' and the session's generator is restored on exit with its state. A seed +#' therefore draws the same sample after `RNGkind("L'Ecuyer-CMRG")`, which +#' parallel code often selects, or under `sample.kind = "Rounding"` as it +#' does in a session left at R's defaults. It must be a whole number from +#' `-.Machine$integer.max` to `.Machine$integer.max`. The same holds for the +#' `seed` of [inclusion_prob()], [joint_prob()] and [plot()][plot.drawn_design]. +#' Most designs select rows by their position in `data`, so a seed is sure +#' to draw the same rows again only from a frame with the same rows in the +#' same order. +#' +#' With `weights = TRUE` the sample records how it was drawn in its +#' `drawn_meta` attribute: `seed` (`NULL` without one), `rng_kind` (the +#' generator used, as [RNGkind()] gives it), `version` (of drawn), `time`, +#' `frame_rows` (the rows of `data`) and `made_by` (`"draw()"`, or +#' `"as_drawn()"` for a sample rebuilt from a file). [sample_summary()] +#' prints it. #' #' @param data A data frame. [design_reservoir()] also accepts a list, a #' connection, or a zero-argument generator function. #' @param design A design built by one of the [design_simple()] family. -#' @param seed Optional seed, applied only for this draw. -#' @param weights Attach `.prob` and `.weight` columns. See "Design weights". +#' @param seed Optional seed, applied only for this draw. See "Seeding". +#' @param weights Attach `.prob`, `.weight` and `.row` columns. See "Design +#' weights". #' #' @return The sampled rows. See "What you get back". #' @@ -68,23 +149,29 @@ #' total with a standard error. #' @export draw <- function(data, design, seed = NULL, weights = FALSE) { - if (!is_design(design)) { - stop("`design` must come from one of the design_*() constructors, not a ", - class(design)[1], ". See ?designs.", call. = FALSE) - } + design <- check_design(design, data, "draw") + check_seed(seed) check_flag(weights, "weights") + warn_region(design, data) if (!isTRUE(weights)) { - return(with_seed(seed, draw_design(design, data))) + out <- with_seed(seed, draw_design(design, data)) + return(table_ready(drop_selection(out))) } if (!is.data.frame(data)) { - stop("`weights = TRUE` needs a data frame, not a ", class(data)[1], ".", + stop("`weights = TRUE` needs a data frame, not ", a_class(data), ".", call. = FALSE) } - clash <- intersect(c(".prob", ".weight"), names(data)) + added <- c(".prob", ".weight", ".row") + clash <- intersect(added, names(data)) if (length(clash) > 0L) { - stop("`data` already has ", paste0("`", clash, "`", collapse = " and "), + shown <- paste0("`", clash, "`") + stop("`data` already has ", + if (length(shown) > 1L) { + paste(paste(shown[-length(shown)], collapse = ", "), "and", + shown[length(shown)]) + } else shown, "; weights = TRUE would overwrite ", if (length(clash) == 1L) "it" else "them", ".", call. = FALSE) } @@ -94,18 +181,24 @@ draw <- function(data, design, seed = NULL, weights = FALSE) { format_bad(dup), ". Rename them before drawing with weights, which ", "cannot tell them apart.", call. = FALSE) } - if (isTRUE(design$replace)) { - stop("`weights = TRUE` is not available for a with-replacement design.\n", - "`.prob` would be the chance of being selected *at least once*, but ", - "the sample holds\nduplicates, so summing `y * .weight` over it ", - "double-counts and comes out roughly 15%\nhigh. Use replace = FALSE, ", - "or estimate with the Hansen-Hurwitz form, N / n * sum(y).", - call. = FALSE) + if (samples_with_replacement(design)) { + stop("`weights = TRUE` is not available for ", replacement_design(design), + ".\n", replacement_problem(design, "would be"), call. = FALSE) } # Probabilities first, so a design with no closed form fails before any - # sampling happens rather than after. - p_all <- exact_inclusion(design, data) + # sampling happens rather than after. A design weighted conditional on its + # clusters has probabilities only once they are selected, so it gets its + # checks here and its probabilities after the draw. + conditional <- conditional_design(design, data) + if (conditional) { + conditional_setup(design, data) + } else { + p_all <- exact_inclusion(design, data) + if (inherits(design, "drawn_design_certainty")) { + check_rest_reach(design, data, p_all) + } + } # Tag the population, draw from the tagged copy, then read the source row off # each drawn row. Matching on values afterwards would misattribute duplicate @@ -118,8 +211,14 @@ draw <- function(data, design, seed = NULL, weights = FALSE) { tagged <- data tagged[[key]] <- seq_len(nrow(data)) + # Read before the draw, since with_seed() changes the generator while the + # draw runs. + meta <- draw_meta(seed, nrow(data)) out <- with_seed(seed, draw_design(design, tagged)) - pos <- out[[key]] + selection <- attr(out, "drawn_selection", exact = TRUE) + out <- drop_selection(out) + if (conditional) p_all <- conditional_inclusion(design, data, selection) + pos <- as.integer(out[[key]]) out[[key]] <- NULL p <- p_all[pos] @@ -132,25 +231,172 @@ draw <- function(data, design, seed = NULL, weights = FALSE) { out <- reindex(out, seq_len(nrow(out))) out[[".prob"]] <- p out[[".weight"]] <- w - out <- out[, c(".prob", ".weight", setdiff(names(out), c(".prob", ".weight"))), - drop = FALSE] + out[[".row"]] <- pos + out <- out[, c(added, setdiff(names(out), added)), drop = FALSE] - # Carry the design and the source rows so ht_total() can recover the joint - # inclusion probabilities without being handed the population again. + # Carry the design, the source rows, the frame and its probabilities so + # ht_total() can recover the joint inclusion probabilities without being + # handed the population again. The frame is a copy, because a data.table + # edited in place after the draw would otherwise change the sample's + # estimates. attr(out, "drawn_design") <- design - attr(out, "drawn_rows") <- pos - attr(out, "drawn_population") <- data + # `.row` holds `pos` itself, so the attribute gets its own copy; an + # in-place data.table::setorder() of the sample would reorder both. + attr(out, "drawn_rows") <- copy_column(pos) + attr(out, "drawn_population") <- snapshot_frame(data) + attr(out, "drawn_pi") <- p_all + # The clusters selected, in the order selected, from which drawn_state() + # works out the conditional probabilities again. + if (conditional) attr(out, "drawn_selection") <- selection + attr(out, "drawn_meta") <- meta + table_ready(out) +} + +#' How a sample was drawn, for the record it carries +#' +#' The seed (`NULL` without one), the generator the draw used (the pinned +#' one with a seed, else the session's), the version of drawn, the time, the +#' number of frame rows, and the function that made the sample. A sample +#' rebuilt by as_drawn() records neither seed nor generator, which the file +#' it was read from does not hold. +#' +#' @noRd +draw_meta <- function(seed, frame_rows, made_by = "draw()") { + drawn_here <- identical(made_by, "draw()") + list( + seed = seed, + rng_kind = if (!drawn_here) { + NULL + } else if (is.null(seed)) { + RNGkind() + } else { + seed_kind() + }, + version = as.character(utils::packageVersion("drawn")), + time = Sys.time(), + frame_rows = as.integer(frame_rows), + made_by = made_by + ) +} + +#' Remove the clusters a cluster or multistage draw records +#' +#' Their draw_design() methods attach the codes of the clusters they selected +#' as `drawn_selection`. Only a sample weighted conditional on its clusters +#' keeps them, set by draw() itself. +#' +#' @noRd +drop_selection <- function(out) { + if (!is.null(attr(out, "drawn_selection", exact = TRUE))) { + attr(out, "drawn_selection") <- NULL + } + out +} + +#' Does a design put the same row in a sample more than once? +#' +#' A certainty design has no `replace` of its own; its `rest` decides. +#' +#' @noRd +samples_with_replacement <- function(design) { + isTRUE(design$replace) || + (inherits(design, "drawn_design_certainty") && + samples_with_replacement(design$rest)) +} + +#' A with-replacement design, named for a message +#' @noRd +replacement_design <- function(design) { + if (inherits(design, "drawn_design_certainty")) { + "a certainty design over a with-replacement `rest`" + } else { + "a with-replacement design" + } +} + +#' Why a with-replacement design gets no weights, and what to do instead +#' +#' draw() gives this reason when it refuses `weights = TRUE`, with `tense` +#' "would be", and drawn_state() when it refuses a sample that carries such +#' a design, with "is". A certainty design takes `replace` in its `rest`. +#' +#' @noRd +replacement_problem <- function(design, tense = "is") { + paste0( + "`.prob` ", tense, " the chance of being selected *at least once*, but ", + "the sample holds\nduplicates, so summing `y * .weight` over it ", + "overstates the total by a factor of\n(n / N) / (1 - (1 - 1 / N)^n), ", + "about 5% at n = N / 10, 15% at n = 0.3 * N, 58% at\nn = N and more ", + "beyond, within each stratum of a stratified design. Use\n", + if (inherits(design, "drawn_design_certainty")) { + paste0("replace = FALSE in `rest`, or estimate with the Hansen-Hurwitz ", + "form,\nN / n * sum(y), summed over strata as ", + "N_h / n_h * sum(y_h).") + } else { + paste0("replace = FALSE, or estimate with the Hansen-Hurwitz form, ", + "N / n * sum(y), summed\nover strata as N_h / n_h * sum(y_h).") + }) +} + +#' Let `:=` work on a data.table built by base subsetting +#' +#' Base `[` and `[[<-` return a data.table without the spare column slots +#' data.table allocates, so the first `:=` on it warns about an invalid +#' self-reference and copies. setalloccol() restores the slots. It runs last, +#' because `attr<-` would copy the table again. +#' +#' @noRd +table_ready <- function(out) { + if (inherits(out, "data.table") && + requireNamespace("data.table", quietly = TRUE)) { + out <- data.table::setalloccol(out) + } out } -#' Design-specific draw method +#' Draw method for a design class +#' +#' The generic [draw()] calls to make a sample from a design. Each design in +#' the package has a method, and a design of your own can have one too. +#' +#' @section Writing a design of your own: +#' A design is a list with a class vector ending in `"drawn_design"`, so that +#' [is_design()] accepts it, such as +#' `structure(list(n = 5), class = c("first_rows", "drawn_design"))`. Its +#' method takes `design` and `data` and returns rows of `data`, with every +#' column of `data`, as `data[idx, , drop = FALSE]` gives them. It draws its +#' random numbers from the current stream; [draw()] applies the seed around +#' it. A package registers the method with `@exportS3Method +#' drawn::draw_design`, and a script with [.S3method()]. +#' +#' That is enough for [draw()] without weights, and for [inclusion_prob()] +#' and [joint_prob()] with `simulate = TRUE`, which count how often each row +#' is drawn and find the rows through a column they add to `data`. The exact +#' probabilities, `draw(weights = TRUE)` and the estimators need the +#' design's inclusion probabilities, which the package computes for its own +#' designs only, so they refuse a design of your own. #' #' @param design A design object. #' @param data The data to sample from. -#' @return The sampled rows. -#' @keywords internal +#' @return The sampled rows. The cluster and multistage methods attach the +#' codes of the clusters they selected as the attribute `drawn_selection`, +#' which [draw()] removes or, for a sample weighted conditional on its +#' clusters, keeps. +#' @examples +#' first_rows <- structure(list(n = 3), class = c("first_rows", "drawn_design")) +#' .S3method("draw_design", "first_rows", function(design, data) { +#' data[seq_len(design$n), , drop = FALSE] +#' }) +#' +#' df <- data.frame(id = 1:10) +#' draw(df, first_rows) +#' inclusion_prob(df, first_rows, simulate = TRUE, R = 20, seed = 1) #' @export draw_design <- function(design, data) { + # A design saved by drawn 0.2.0 lacks fields added since, and `$` would + # match some of them to others by partial name. + current <- legacy_design(design) + if (!identical(current, design)) return(draw_design(current, data)) UseMethod("draw_design") } diff --git a/R/drawn-package.R b/R/drawn-package.R index 35cd6f5..a218291 100644 --- a/R/drawn-package.R +++ b/R/drawn-package.R @@ -1,5 +1,6 @@ #' @keywords internal #' @importFrom graphics par plot points mtext abline +#' @importFrom stats coef confint vcov "_PACKAGE" ## usethis namespace: start diff --git a/R/estimate.R b/R/estimate.R index 8dfad9f..09f040a 100644 --- a/R/estimate.R +++ b/R/estimate.R @@ -6,23 +6,63 @@ #' denominator together and they partly cancel. `estimator = "ht"` divides by #' the true `N` instead. #' +#' @section Proportions: #' For a 0/1 or logical variable either one estimates a proportion, and the #' confidence interval is then formed on the logit scale and transformed back #' (Korn and Graubard 1999, section 5.3). A symmetric interval around a small #' proportion runs below zero; this one cannot, and matches #' `survey::svyciprop(method = "xlogit")`. #' +#' Whether `y` is a proportion is read from what `y` is, not from the values +#' the sample happened to draw. A logical `y` is one, and so is a column of +#' the frame whose values are all 0 or 1. A count that came out 0 or 1 in +#' every sampled row is not: a logit interval cannot pass 1, so it would never +#' cover a mean of 1.2. A numeric vector, or a column added to the sample after +#' the draw, such as a 0/1 result recorded in fieldwork, has no column of the +#' frame to read. It is taken for a proportion when it is 0 or 1 in every +#' sampled row, and `note` says the choice came from the sample. +#' `proportion = FALSE` asks for the symmetric interval whatever `y` is, and +#' is the choice for a count. +#' +#' `ci_method = "beta"` gives the Korn and Graubard (1998) interval instead, +#' a Clopper-Pearson interval at an effective sample size of `p(1 - p) / v`, +#' with `p` the estimate and `v` its variance, capped at `n` and then scaled +#' by `(qt(a, n - 1) / qt(a, df))^2` for the design's degrees of freedom. +#' Here `n` is the number of sampled rows below certainty behind the estimate +#' and `a` the tail probability of the interval. The scaled size is capped at +#' `n` too, so a domain whose design has more degrees of freedom than the +#' domain has rows gets no narrower an interval than Clopper-Pearson's over +#' those rows. With no rows taken with certainty it matches +#' `survey::svyciprop(method = "beta")` whenever neither cap binds. It +#' ignores the finite population correction, so it errs wide when the sample +#' is a large share of the frame. +#' +#' An estimate of exactly 0 or 1, such as no deviations found in 60 sampled +#' invoices, has a variance of 0, and a logit interval around it has no +#' width. It gets the beta interval whatever `ci_method` says, with the +#' effective sample size set to `n`, and `note` says so. For 0 of 60 from a +#' simple random sample, the 95% upper bound (`alternative = "less"`) is +#' 4.87%. The interval needs no variance, so a design that leaves 0 degrees of +#' freedom, such as a Poisson sample of one row, gets Clopper-Pearson's over +#' the sampled rows. When every sampled row behind the estimate was taken +#' with certainty, the estimate is exact and the interval has no width. +#' #' @section When the two differ, and which to use: #' They coincide **exactly** whenever the design weights of the rows you drew -#' sum to `N` — which covers every fixed-size equal-probability design and every -#' [design_stratified()] without replacement, because each stratum contributes -#' `n_h * N_h / n_h = N_h`. There is nothing to choose between them there. +#' sum to `N` — which covers every fixed-size equal-probability design that +#' can reach every row of the frame, and every [design_stratified()] without +#' replacement that draws from every stratum, because each stratum +#' contributes `n_h * N_h / n_h = N_h`. There is nothing to choose between +#' them there. A [design_spatial()] sample from a region, or a +#' [design_reservoir()] sample whose stream ran past `max_items`, is a simple +#' random sample of the rows it can reach, and its weights sum to their +#' number instead; see the caveat on `"ht"` below. #' #' They differ when that sum is random or uneven: #' #' * the sample size itself is random — [design_weighted()] with #' `method = "poisson"`, [design_cluster()] over clusters of unequal size, or -#' [design_systematic()] where the interval does not divide `N`; +#' [design_systematic()] with an `interval` that does not divide `N`; #' * the weights vary within a fixed-size sample — probability-proportional-to- #' size selection. #' @@ -31,13 +71,19 @@ #' knowing: when `y` is close to proportional to the size measure that drove #' selection, `y / pi` is nearly constant, the Horvitz-Thompson numerator #' barely moves, and dividing it by the known `N` beats dividing by an -#' estimate. +#' estimate. The Hajek mean's ratio bias, and a variance estimate that runs 11 +#' to 12% low, also lower the coverage of its interval there. Drawing with +#' `n = 30` from 240 rows by Poisson PPS, its 95% interval covered 91% of the +#' time and that of `"ht"` 94%. By systematic PPS both covered about 90%. +#' "Confidence intervals" in [ht_total()] gives the figures and the reasons. #' #' One caveat on `"ht"`. It is unbiased for the frame mean *provided every row -#' could have been selected*. Rows with inclusion probability 0 — outside a time -#' window, outside a region, zero weight — sit inside the `N` it divides by but -#' can never enter the numerator, so the estimate is biased low by exactly their -#' share of the frame. [sample_summary()] reports how many such rows there are. +#' could have been selected*. Rows with inclusion probability 0, such as rows +#' outside a time window or a region, past `max_items` or dropped under +#' `na_rm = TRUE`, sit inside the `N` it divides by but can never enter the +#' numerator, so the estimate is biased low by exactly their share of the +#' frame. +#' [sample_summary()] reports how many such rows there are. #' The Hajek mean is unaffected, because it estimates the mean of the part of #' the frame the design can actually reach. #' @@ -45,22 +91,98 @@ #' The Hajek mean is a ratio, and its variance is the variance of the total of #' the linearised residuals `(y - mean) / N_hat` (Deville 1999), computed with #' whichever estimator suits the design — see [ht_total()], which also explains -#' the confidence interval's degrees of freedom and how `by` estimates domain -#' means from the whole sample rather than a subset of it. +#' the confidence interval's degrees of freedom, how `by` estimates domain +#' means from the whole sample rather than a subset of it, and what an empty +#' sample gives. +#' +#' The residuals sum to zero inside a primary sampling unit that holds every +#' sampled row of the domain, so a Hajek mean over one unit, such as a domain +#' with one sampled row or a Poisson sample of one row, gets no standard +#' error. The "Domains" section of [ht_total()] says more. +#' +#' With `estimator = "ht"` each domain's total is divided by the domain's +#' number of rows in the frame, read from the frame's `by` columns. A frame +#' row with a `by` value missing could be in any domain, so such a frame is +#' refused. +#' +#' `contrast` gives a weighted sum of domain means, such as the difference +#' between two, with its standard error; see "Contrasts" in [ht_total()]. +#' Its interval is symmetric whatever `proportion` and `ci_method` say. +#' +#' When `y` has the same value in every sampled row, the residuals are 0 and +#' the Hajek mean's variance is set to exactly 0, with a note, rather than +#' left to rounding error, which gave standard errors near `1e-16` and design +#' effects that changed from seed to seed. The design effect is then `NA`. +#' +#' @section Shares and counts of categories: +#' A factor or character column named as `y`, or a factor as long as +#' `sample`, gives the share of each of its levels: a `drawn_by` table led +#' by a `level` column, with a proportion's interval for each level and the +#' covariances between the shares in `vcov()`. [ht_total()] gives the +#' estimated number of frame rows at each level the same way; see +#' "Categories" there. The share of one level is also the mean of its +#' indicator, `ht_mean(s, s$habitat == "forest")`, which takes `contrast` +#' as any `y` does. #' -#' @param sample A data frame returned by [draw()] with `weights = TRUE`. -#' @param y The variable to average: a column name, or a numeric vector as long -#' as `sample`. +#' A single number as `y` stands for that value in every row, so +#' `ht_total(s, 1)` estimates the number of frame rows the design can +#' reach, and `ht_total(s, 1, by = "habitat")` the number in each domain. +#' +#' @section Missing values: +#' A missing `y` is refused unless `na_rm = TRUE`. Then the mean is the +#' Hajek mean over the rows with `y` present, treated as a domain of the +#' whole sample, with the design's own variance estimator, and equals +#' `survey::svymean(na.rm = TRUE)` on [as_svydesign()]. It assumes the values +#' are missing completely at random, and the printed result says so. `n` +#' counts the rows with `y` present, `n_missing` the others, and the design +#' effect is `NA`, as for a domain. With `by`, each domain is the rows of +#' its `by` values with `y` present. `estimator = "ht"` is refused, since +#' the number of frame rows that would have a `y` is unknown. See "Missing +#' values and nonresponse" in [ht_total()] for when the assumption fails and +#' what to do then. +#' +#' @param sample A data frame returned by [draw()] with `weights = TRUE`. It is +#' read as [ht_total()] reads it: `.prob` for the probabilities, and the +#' stored frame for the design's columns. See "Which columns are read" there. +#' @param y The variable to average: a column name, several column names, a +#' numeric vector as long as `sample`, or a single number, which stands +#' for that value in every row. A factor or character column, or a factor +#' as long as `sample`, gives the share of each level. See "Several +#' variables" and "Categories" in [ht_total()]. #' @param estimator `"hajek"` or `"ht"`. See above. -#' @param variance,level,by,df As for [ht_total()]. +#' @param variance,level,by,df,alternative,contrast As for [ht_total()]. +#' @param proportion Whether `y` is a proportion, which decides the shape of +#' the interval. `NULL` decides from `y`: a logical `y`, or a column of the +#' frame whose values are all 0 or 1, is a proportion, and a numeric vector +#' or a column added after the draw is one when it is 0 or 1 in every +#' sampled row. `TRUE` treats `y` as one, and needs it to be 0 or 1 in every +#' sampled row; `FALSE` gives the symmetric interval. See "Proportions". +#' @param ci_method The interval for a proportion: `"logit"`, or `"beta"` for +#' Korn and Graubard's. A proportion of exactly 0 or 1 gets `"beta"` either +#' way. See "Proportions". +#' @param na_rm `FALSE` refuses a missing `y`. `TRUE` estimates the mean over +#' the rows with `y` present, as a domain of the sample. See "Missing +#' values". #' #' @return A list with a `print()` method, holding `mean`, `estimator`, -#' `variance`, `se`, `ci`, `level`, `df`, `n`, `design`, `deff`, `method` and -#' `note`. See [ht_total()] for what `method`, `df` and `note` say, and -#' [deff()] for the design effect. With `by`, a data frame with one row per -#' domain. +#' `variable`, `variance`, `se`, `ci`, `level`, `alternative`, `df`, `n`, +#' `n_random`, `design`, `deff`, `method`, `note`, `ci_scale` (`"linear"`, +#' `"logit"` or `"beta"`), `unreachable` and `n_missing`, the sampled rows +#' with `y` missing that `na_rm = TRUE` left out. See [ht_total()] for what +#' `variable`, `n_random`, `method`, `df`, `note` and `unreachable` say, +#' and [deff()] for the design effect. With `by`, a data frame with one row +#' per domain, and with `contrast` a `drawn_contrast`, as for [ht_total()]. +#' With several column names as `y`, a `drawn_by` table with a row per +#' variable, and with a factor or character `y` one with a row per level, +#' as for [ht_total()]. Each has `coef()`, `vcov()`, `confint()`, +#' `as.data.frame()` and `tidy()` methods; see "Working with the result" in +#' [ht_total()]. #' #' @references +#' Korn, E. L. and Graubard, B. I. (1998). Confidence intervals for +#' proportions with small expected number of positive counts estimated from +#' survey data. *Survey Methodology*, 24, 193–201. +#' #' Korn, E. L. and Graubard, B. I. (1999). *Analysis of Health Surveys*. #' Wiley. #' @@ -90,9 +212,18 @@ #' # A mean for each site, estimated from the whole sample #' ht_mean(s, "spend", by = "site") #' +#' # The difference between the two sites' means +#' ht_mean(s, "spend", by = "site", contrast = c(a = 1, b = -1)) +#' #' # A proportion is the mean of a 0/1 variable #' ht_mean(s, s$spend > 250) #' +#' # The share of each level of a factor, with the covariances between them +#' s$band <- cut(s$spend, c(0, 100, 250, 500)) +#' shares <- ht_mean(s, "band") +#' shares +#' vcov(shares) +#' #' # Stratified without replacement: the weights sum to N, so the two agree #' all.equal(ht_mean(s, "spend", estimator = "ht")$mean, ht_mean(s, "spend")$mean) #' @@ -102,17 +233,94 @@ #' c(hajek = ht_mean(p, "spend", variance = "none")$mean, #' ht = ht_mean(p, "spend", "ht", variance = "none")$mean) #' -#' @seealso [ht_total()], [deff()], [sample_summary()] +#' @seealso [ht_total()], [ht_ratio()], [ht_quantile()], [deff()], +#' [sample_summary()] #' @export ht_mean <- function(sample, y, estimator = c("hajek", "ht"), variance = c("auto", "analytic", "jackknife", "none"), - level = 0.95, by = NULL, df = NULL) { - estimator <- match.arg(estimator) - variance <- match.arg(variance) - parts <- ht_prepare(sample, y, level, df) + level = 0.95, by = NULL, df = NULL, proportion = NULL, + ci_method = c("logit", "beta"), + alternative = c("two.sided", "less", "greater"), + contrast = NULL, na_rm = FALSE) { + estimator <- check_choice(estimator, c("hajek", "ht"), "estimator") + variance <- check_choice(variance, + c("auto", "analytic", "jackknife", "none"), + "variance") + ci_method <- check_choice(ci_method, c("logit", "beta"), "ci_method") + alternative <- check_choice(alternative, c("two.sided", "less", "greater"), + "alternative") + check_contrast_by(contrast, by) + check_flag(na_rm, "na_rm") + if (several_names(y)) { + return(estimate_several(sample, y, "mean", variance, level, by, df, + alternative, contrast, estimator = estimator, + proportion = proportion, ci_method = ci_method, + na_rm = na_rm)) + } + if (categorical(sample, y)) { + return(estimate_levels(sample, y, "mean", variance, level, by, df, + alternative, contrast, estimator = estimator, + proportion = proportion, ci_method = ci_method, + na_rm = na_rm)) + } + parts <- ht_prepare(sample, y, level, df, na_rm = na_rm) + parts <- mean_setup(parts, estimator, proportion, ci_method) if (!is.null(by)) { return(estimate_by(parts, by, variance, level, df, what = "mean", - estimator = estimator)) + estimator = estimator, ci_method = ci_method, + alternative = alternative, contrast = contrast)) + } + warn_grouped(sample, "ht_mean") + mean_one(parts, estimator, variance, level, df, ci_method, + alternative)$result +} + +#' Checks a mean makes of its `y`, and whether it is a proportion +#' +#' `label` names `y` in the messages, as the column it is when `y` names +#' several. +#' +#' @noRd +mean_setup <- function(parts, estimator, proportion, ci_method, + label = "`y`") { + n_missing <- sum(!parts$respond) + if (n_missing && estimator == "ht") { + stop("`estimator = \"ht\"` divides by the number of frame rows, and ", + "with ", label, " missing in ", n_missing, " sampled row", + if (n_missing > 1L) "s", " the number of frame rows the mean is ", + "over is unknown. Use the Hajek estimator, which estimates it from ", + "the sample.", call. = FALSE) + } + parts$proportion <- mean_is_proportion(parts, proportion) + parts$proportion_note <- if (sampled_proportion(parts, proportion)) { + sampled_proportion_note(parts$y_name) + } + if (ci_method == "beta" && !parts$proportion) { + stop("`ci_method = \"beta\"` gives an interval for a proportion, and ", + "the mean of ", label, " is not one. Pass `proportion = TRUE` if ", + "it is a 0/1 indicator; see \"Proportions\" in ?ht_mean.", + call. = FALSE) + } + parts +} + +#' One mean, as ht_mean() gives it without `by` +#' +#' Returns the estimate as `result`, with `z`, the variable whose total has +#' its variance, and `domain`, the `domain` its variance was run with, which +#' estimate_several() needs for the covariances between variables. +#' +#' @noRd +mean_one <- function(parts, estimator, variance, level, df, ci_method, + alternative, ctx = NULL) { + if (any(!parts$respond)) { + return(respondent_mean(parts, variance, level, df, ci_method, + alternative, ctx)) + } + if (!nrow(parts$sample) && estimator == "hajek") { + stop("`sample` has no rows, so the Hajek mean is 0 / 0. Use ", + "estimator = \"ht\", which divides the total, 0, by the size of the ", + "frame.", call. = FALSE) } pi_i <- parts$pi @@ -126,347 +334,2713 @@ ht_mean <- function(sample, y, estimator = c("hajek", "ht"), # Linearise: the variance of a ratio is the variance of a total of residuals. # For the HT mean there is no denominator to vary, so the residual is just y. z <- if (estimator == "hajek") (yv - est) / denom else yv / N + # A constant `y` has residuals of exactly 0. Computed, they come out a + # rounding error away from it, and so did the standard error. + constant <- estimator == "hajek" && length(yv) > 0L && all(yv == yv[1]) + if (constant) { + est <- yv[1] + z <- numeric(length(yv)) + } + declined <- if (estimator == "hajek") { + linear_declines(parts, rep(TRUE, length(yv)), variance) + } - estimate_one(parts, est, z, variance, level, df, what = "mean", - class = "drawn_mean", deff_y = yv, - extra = list(estimator = estimator), logit = parts$binary) + out <- estimate_one(parts, est, z, variance, level, df, what = "mean", + class = "drawn_mean", deff_y = yv, + extra = list(estimator = estimator), + proportion = parts$proportion, ci_method = ci_method, + alternative = alternative, var_out = declined$any, + divide_by = denom_rows(parts, estimator), ctx = ctx, + jk_decline = declined$jackknife) + if (constant && identical(out$variance, 0) && + !identical(out$ci_scale, "beta") && any(!is_certain(pi_i))) { + out$note <- paste(c(out$note, constant_note(yv[1], parts$proportion)), + collapse = " ") + } + out$n_missing <- 0L + list(result = out, z = z, domain = NULL) } -#' Estimates for each domain, from the whole sample +#' The Hajek mean over the rows with `y` present #' -#' A domain estimate uses the full sample with `y` zeroed outside the domain. -#' Subsetting first would treat the number of rows that happened to land in the -#' domain as fixed by design, which it is not, and would hand the variance -#' estimator a sample the design never drew. +#' Those rows are a domain of the whole sample, as a `by` domain is. The +#' estimate is the Hajek mean over them, and its variance that of the total +#' of the linearised residuals `(y - mean) / N_hat` over every sampled row, +#' 0 for a row with `y` missing, from the design's own estimator. Which frame +#' rows would have a `y` cannot be read from the frame, so `domain` is `NA`. +#' This is `survey::svymean(na.rm = TRUE)`. `n`, `n_random` and the beta +#' interval count the rows with `y` present. A domain's design effect is not +#' estimated, so `deff` is `NA`. Returns what mean_one() returns. #' #' @noRd -estimate_by <- function(parts, by, variance, level, df, what, - estimator = "hajek") { - if (!is.character(by) || !length(by) || anyNA(by) || - !all(by %in% names(parts$sample))) { - stop("`by` must name one or more columns of `sample`.", call. = FALSE) +respondent_mean <- function(parts, variance, level, df, ci_method, + alternative, ctx = NULL) { + r <- parts$respond + pi_i <- parts$pi + yv <- parts$y + n_hat <- sum(1 / pi_i[r]) + est <- sum(yv[r] / pi_i[r]) / n_hat + z <- numeric(length(yv)) + z[r] <- (yv[r] - est) / n_hat + constant <- all(yv[r] == yv[r][1]) + if (constant) { + est <- yv[r][1] + z[] <- 0 } - check_key_columns(parts$sample, by, "by") - if (any(vapply(parts$sample[by], anyNA, logical(1)))) { - stop("`by` columns must not contain missing values.", call. = FALSE) + declined <- linear_declines(parts, which(r), variance, NA, + subject = "The domain of rows with `y` present") + var_out <- declined$any %||% + ht_variance_dispatch(parts$design, parts$units, parts$pop, parts$rows, z, + pi_i, variance, domain = NA, ctx = ctx, + jk_decline = declined$jackknife) + df <- df %||% design_df(parts$design, parts$units, parts$pop, parts$rows, + pi_i) + # The interval's sample size and `n_random` count the rows behind the + # estimate. + held <- parts + held$pi <- pi_i[r] + out <- finish_estimate(est, var_out, held, level, df, what = "mean", + class = "drawn_mean", proportion = parts$proportion, + ci_method = ci_method, alternative = alternative) + out$estimator <- "hajek" + out$n <- sum(r) + out$n_missing <- sum(!r) + notes <- c(out$note, missing_note(sum(!r), length(r), parts$y_name)) + if (constant && identical(out$variance, 0) && + !identical(out$ci_scale, "beta") && any(!is_certain(pi_i[r]))) { + notes <- c(notes, constant_note(est, parts$proportion)) } - key <- as.character(group_key(parts$sample, by)) - pop_key <- if (all(by %in% names(parts$pop))) { - as.character(group_key(parts$pop, by)) - } else { - NULL + out$note <- paste(notes, collapse = " ") + list(result = out, z = z, domain = NA) +} + +#' What a mean over the rows with `y` present assumes +#' +#' `y_name` is the column `y` names, `NULL` for a vector. `blank` holds the +#' labels of the `by` domains whose sampled rows all have `y` missing, which +#' the table leaves out. +#' +#' @noRd +missing_note <- function(n_missing, n, y_name = NULL, blank = NULL) { + one <- n_missing == 1L + y <- paste0("`", y_name %||% "y", "`") + gap <- if (length(blank)) { + paste0(" Every sampled row of the domain", if (length(blank) > 1L) "s", + " ", paste0("`", blank, "`", collapse = ", "), " has ", y, + " missing, so the table has no row for ", + if (length(blank) > 1L) "them." else "it.") } - levels_in <- sort(unique(key)) - pi_i <- parts$pi - yv <- parts$y - df_use <- df %||% design_df(parts$design, parts$sample, parts$pop, - parts$rows) + paste0(n_missing, " of the ", n, " sampled rows ", if (one) "has" else + "have", " ", y, " missing and ", if (one) "is" else "are", + " left out.", gap, " The mean is over the rows with ", y, + " present, estimated as a domain of the whole sample, which assumes ", + "the values are missing completely at random, with no relation ", + "between whether ", y, " is missing and ", y, " itself. When ", + "response differs between groups whose ", y, " differs, adjust the ", + "weights within those groups and estimate with as_svydesign().") +} - rows <- lapply(levels_in, function(d) { - ind <- as.numeric(key == d) - if (what == "total") { - est <- sum(ind * yv / pi_i) - z <- ind * yv - } else { - denom <- if (estimator == "hajek") { - sum(ind / pi_i) - } else { - if (is.null(pop_key)) { - stop("estimator = \"ht\" needs the domain's population size, and ", - "the `by` columns are not in the population.", call. = FALSE) - } - sum(pop_key == d, na.rm = TRUE) - } - est <- sum(ind * yv / pi_i) / denom - z <- if (estimator == "hajek") ind * (yv - est) / denom else ind * yv / denom +#' What the mean divides its Horvitz-Thompson total by, for the design effect +#' +#' The Hajek mean estimates the mean over the rows the design can reach. The +#' Horvitz-Thompson mean divides by every row of the frame. +#' +#' @noRd +denom_rows <- function(parts, estimator) { + if (estimator == "ht") nrow(parts$pop) else parts$reach +} + +#' Why a Hajek mean of a constant `y` has a variance of 0 +#' @noRd +constant_note <- function(value, proportion, domains = NULL) { + hint <- if (!proportion && value %in% c(0, 1)) { + paste0(" If `y` is a 0/1 indicator, `proportion = TRUE` gives a ", + "proportion's interval, which allows for rows with the other value.") + } + if (is.null(domains)) { + return(paste0( + "`y` is ", format(value), " in every sampled row, so the Hajek mean's ", + "residuals are 0 and its estimated variance is 0. The interval has no ", + "width, though rows the sample did not draw may differ.", hint)) + } + paste0("`y` takes one value in every sampled row of the domain", + if (length(domains) > 1L) "s", " ", + paste0("`", domains, "`", collapse = ", "), ", so ", + if (length(domains) > 1L) "their Hajek means have" else + "its Hajek mean has", + " an estimated variance of 0 and an interval with no width, though ", + "rows the sample did not draw may differ.") +} + +#' Whether a mean is a proportion, for the shape of its interval +#' +#' Read from what `y` is rather than from the values the sample happened to +#' draw: a logical `y`, or a column of the frame whose values are all 0 or 1 +#' (a logical column of the frame counts too). A count that came out 0 or 1 +#' in every sampled row is not one, since a logit interval cannot pass 1 and +#' would never cover a mean above it. A numeric vector, and a column added to +#' the sample after the draw, have no frame column to read. They are +#' proportions when every sampled value is 0 or 1, as drawn 0.2.0 read every +#' `y`, and `sampled_proportion()` says so in a note. A single number stands +#' for a constant and is not one. +#' +#' @noRd +mean_is_proportion <- function(parts, proportion) { + y <- parts$y[parts$respond] + binary <- all(y == 0 | y == 1) + if (!is.null(proportion)) { + if (!is.logical(proportion) || length(proportion) != 1L || + is.na(proportion)) { + stop("`proportion` must be NULL, TRUE or FALSE, not ", + format_bad(proportion, value = TRUE), ".", call. = FALSE) } - v <- ht_variance_dispatch(parts$design, parts$sample, parts$pop, - parts$rows, z, pi_i, variance) - ci <- interval(est, v$variance, level, df_use, - logit = what == "mean" && parts$binary) - list(n = sum(ind), est = est, se = if (is.finite(v$variance) && - v$variance >= 0) - sqrt(v$variance) else NA_real_, - lo = ci[1], hi = ci[2], method = v$method %||% "analytic", - note = v$note) - }) + if (proportion && !binary) { + bad <- unique(y[!(y == 0 | y == 1)]) + stop("`proportion = TRUE` needs `y` to be 0 or 1 in every sampled row, ", + "and it takes ", length(bad), " other value", + if (length(bad) > 1L) "s", ", such as ", format(bad[1]), ". Leave ", + "`proportion` at NULL for the mean of a count or a measurement.", + call. = FALSE) + } + return(proportion) + } + if (!binary) return(FALSE) + if (parts$y_logical) return(TRUE) + if (isTRUE(parts$y_single)) return(FALSE) + col <- parts$y_name + if (!is.null(col)) { + if (col %in% names(parts$pop)) return(binary_column(parts$pop[[col]])) + # compact_sample() records which of the frame columns it dropped were 0/1. + if (col %in% parts$compact$dropped) return(col %in% parts$compact$binary) + } + TRUE +} - first <- match(levels_in, key) - out <- parts$sample[first, by, drop = FALSE] - out <- as.data.frame(out) - rownames(out) <- NULL - out$n <- vapply(rows, `[[`, numeric(1), "n") - out[[what]] <- vapply(rows, `[[`, numeric(1), "est") - out$se <- vapply(rows, `[[`, numeric(1), "se") - out$ci_lower <- vapply(rows, `[[`, numeric(1), "lo") - out$ci_upper <- vapply(rows, `[[`, numeric(1), "hi") - out$method <- vapply(rows, `[[`, character(1), "method") - notes <- unique(unlist(lapply(rows, `[[`, "note"))) - structure(out, class = c("drawn_by", "data.frame"), - what = what, estimator = if (what == "mean") estimator, - level = level, df = df_use, design = design_type(parts$design), - ci_scale = if (what == "mean" && parts$binary) "logit" else "linear", - notes = notes) +#' Whether a proportion was read from the sampled values alone +#' +#' True for a numeric `y` that `mean_is_proportion()` took for a proportion +#' with no frame column to read, which `proportion` did not settle. +#' +#' @noRd +sampled_proportion <- function(parts, proportion) { + is.null(proportion) && isTRUE(parts$proportion) && !parts$y_logical && + (is.null(parts$y_name) || !(parts$y_name %in% c(names(parts$pop), + parts$compact$dropped))) } -#' @export -print.drawn_by <- function(x, ...) { - what <- attr(x, "what") - label <- if (what == "total") "Horvitz-Thompson total" else - if (identical(attr(x, "estimator"), "ht")) "Horvitz-Thompson mean" else - "Hajek mean" - cat(label, " by domain (", attr(x, "design"), " design, ", - format(100 * attr(x, "level")), "% CI, ", - if (identical(attr(x, "ci_scale"), "logit")) "logit, ", - df_label(attr(x, "df")), ")\n", sep = "") - y <- x - attributes(y) <- attributes(x)[c("names", "row.names")] - class(y) <- "data.frame" - print(y, digits = 4, row.names = FALSE) - notes <- attr(x, "notes") - notes <- notes[nzchar(notes) & !grepl("^Variance not requested", notes)] - if (length(notes)) cat_note(notes) - invisible(x) +#' Why a `y` outside the frame was taken for a proportion +#' +#' `name` is the column `y` names, `NULL` for a vector. +#' +#' @noRd +sampled_proportion_note <- function(name = NULL) { + paste0(if (is.null(name)) "`y`" else paste0("`", name, "`"), " is not a ", + "column of the frame, so it was taken for a proportion because it ", + "is 0 or 1 in every sampled row. Pass `proportion = FALSE` for the ", + "symmetric interval of a count.") } -#' Design effect +#' Estimate a ratio of two population totals #' -#' How much precision the design costs against simple random sampling of the -#' same size (Kish 1965). `deff = 1` means the design is doing as well as a -#' coin flip over the frame; above 1 it is doing worse, which is the usual price -#' of clustering; below 1 it is doing better, which is what stratification and -#' probability-proportional-to-size buy you. +#' `ht_ratio()` estimates `R = Y / X`, the ratio of the population totals of +#' `y` and `x`, by `sum(y / pi) / sum(x / pi)`: audited value per unit of +#' book value, spend per visit, or yield per hectare. A Hajek mean is the +#' ratio with `x` equal to 1 in every row. [ht_total()] with `ratio` +#' multiplies the ratio by the frame's total of `x` to estimate the total of +#' `y`. #' -#' Read it as an exchange rate on sample size: at `deff = 2`, a sample of 400 -#' carries about as much information as 200 drawn at random. +#' @section Variance: +#' The ratio is linearised. Its variance is that of the Horvitz-Thompson +#' total of the residuals `(y - R x) / X_hat`, with `X_hat = sum(x / pi)` +#' (Särndal, Swensson and Wretman 1992; Deville 1999), and is computed with +#' the design's own estimator, as for a total: see "Variance" and +#' "Confidence intervals" in [ht_total()] for the estimators, the fallback +#' to the jackknife, the degrees of freedom and the notes. For the designs +#' [as_svydesign()] hands to `survey` with identical standard errors, the +#' standard error equals that of `survey::svyratio()` on its result. For +#' systematic, spread and systematic PPS samples it comes from the +#' estimator this package uses for their totals, which `survey` does not +#' have. +#' +#' The residuals sum to zero over the sample, weighted by `1 / pi`, so a +#' ratio whose sampled rows lie in one primary sampling unit, one row or one +#' cluster, gets no standard error, as a Hajek mean does. When `y` is +#' proportional to `x` in every sampled row the residuals are 0, the +#' variance is set to exactly 0 rather than left to rounding error, and +#' `note` says so. +#' +#' The ratio of two estimated totals is biased, by an amount of order +#' `1 / n`, which is small against its standard error except in small +#' samples. The design effect compares its variance with that of the same +#' ratio from a simple random sample of the same size, as +#' `survey::svyratio(deff = TRUE)` does. +#' +#' @section Domains: +#' `by` gives a ratio for each domain, `R_d = Y_d / X_d` over the rows of +#' the domain, estimated from the whole sample. Each domain's residuals, +#' `(y - R_d x) / X_hat_d`, are 0 outside it, as for the domain totals and +#' means described under "Domains" in [ht_total()], and the standard errors +#' are those of +#' `survey::svyby(~y, ~d, design, survey::svyratio, denominator = ~x)`. A +#' domain whose estimated total of `x` is 0 is refused by name. #' -#' `survey` has a `deff()` of its own, and attaching `survey` after this -#' package masks this one. Both work on an estimate from [ht_total()] or -#' [ht_mean()], so the masking is harmless. +#' A missing `y` or `x` is refused. `survey::svyratio(na.rm = TRUE)` on +#' [as_svydesign()] estimates the ratio over the rows that have both. #' -#' @param x A result from [ht_total()] or [ht_mean()]. +#' @inheritParams ht_total +#' @param y,x The numerator and the denominator: each a column name of +#' `sample`, or a numeric vector as long as `sample`. #' -#' @return A single number, or `NA` when the design has no variance estimate. +#' @return A list of class `drawn_ratio` with a `print()` method, holding +#' `ratio`, the estimate; `variable` and `x`, the names of `y` and `x` +#' when they are column names, else `NULL`; `total_y` and `total_x`, +#' their estimated totals; and `variance`, `se`, `ci`, `level`, +#' `alternative`, `df`, `n`, `n_random`, `ci_scale`, `design`, `deff`, +#' `method`, `note` and `unreachable` as for [ht_total()]. With `by`, a +#' `drawn_by` table with a row per domain and a `ratio` column, as for +#' [ht_total()]. Both have `coef()`, `vcov()`, `confint()`, +#' `as.data.frame()` and `tidy()` methods; see "Working with the result" +#' in [ht_total()]. #' #' @references -#' Kish, L. (1965). *Survey Sampling*. Wiley. +#' Deville, J.-C. (1999). Variance estimation for complex statistics and +#' estimators: linearization and residual techniques. *Survey Methodology*, +#' 25, 193–203. +#' +#' Särndal, C.-E., Swensson, B. and Wretman, J. (1992). *Model Assisted Survey +#' Sampling*. Springer. #' #' @examples #' set.seed(1) -#' # Sites differ from each other, and rows within a cluster are alike -- -#' # exactly the structure that makes stratifying pay and clustering cost. #' pop <- data.frame( -#' id = 1:400, -#' site = rep(c("a", "b", "c", "d"), each = 100), -#' cl = rep(paste0("c", 1:40), each = 10) +#' id = 1:300, +#' site = rep(c("a", "b", "c"), each = 100), +#' book = round(stats::rlnorm(300, 6, 1)) #' ) -#' pop$y <- rep(c(20, 60, 120, 200), each = 100) + round(stats::rnorm(400, 0, 8)) +#' pop$audited <- round(pop$book * stats::runif(300, 0.9, 1.05)) +#' s <- draw(pop, design_stratified("site", n = 45), seed = 1, weights = TRUE) #' -#' # Stratifying on something that matters buys precision (deff below 1) -#' deff(ht_total(draw(pop, design_stratified("site", n = 40), seed = 1, -#' weights = TRUE), "y")) +#' # Audited value per unit of book value +#' ht_ratio(s, "audited", "book") +#' sum(pop$audited) / sum(pop$book) # the truth #' -#' # Clustering usually costs it (deff above 1) -#' deff(ht_total(draw(pop, design_cluster("cl", n_clusters = 4), seed = 1, -#' weights = TRUE), "y")) +#' # For each site, from the whole sample +#' ht_ratio(s, "audited", "book", by = "site") #' -#' @seealso [ht_total()], [ht_mean()], [plan_size()], which takes a design -#' effect as an input. +#' # The ratio estimator of the total uses the frame's total of `book`, and +#' # is far more precise than the Horvitz-Thompson total here +#' ht_total(s, "audited", ratio = "book") +#' ht_total(s, "audited") +#' sum(pop$audited) +#' +#' @seealso [ht_total()], [ht_mean()], [as_svydesign()] #' @export -deff <- function(x) { - if (!inherits(x, c("drawn_ht", "drawn_mean"))) { - stop("`x` must come from ht_total() or ht_mean().", call. = FALSE) +ht_ratio <- function(sample, y, x, by = NULL, + variance = c("auto", "analytic", "jackknife", "none"), + level = 0.95, df = NULL, + alternative = c("two.sided", "less", "greater")) { + variance <- check_choice(variance, + c("auto", "analytic", "jackknife", "none"), + "variance") + alternative <- check_choice(alternative, c("two.sided", "less", "greater"), + "alternative") + parts <- prepare_sample(sample, level, df) + parts <- add_ratio_variables(parts, y, x) + parts <- finish_prepare(parts) + if (!is.null(by)) { + return(estimate_by(parts, by, variance, level, df, what = "ratio", + alternative = alternative)) } - x$deff + warn_grouped(sample, "ht_ratio") + ratio_one(parts, variance, level, df, alternative)$result } -# `survey` exports a `deff()` generic too, and attaching `survey` after this -# package masks ours. Registering methods for its generic means whichever -# `deff()` is found first still answers for an estimate made here, instead of -# failing with "non-numeric argument to mathematical function". +#' Read the `y` and `x` of a ratio into the parts of a sample +#' +#' Both must be present and finite in every sampled row. +#' +#' @noRd +add_ratio_variables <- function(parts, y, x) { + sample <- parts$sample + read <- function(v, arg) { + out <- read_variable(sample, v, arg) + gap <- is.na(out$values) & !is.nan(out$values) + if (any(gap)) { + stop("`", arg, "` is missing in ", sum(gap), " of the ", length(gap), + " sampled rows. A ratio needs `y` and `x` in every sampled row. ", + "survey::svyratio(na.rm = TRUE) on as_svydesign() estimates it ", + "over the rows that have both.", call. = FALSE) + } + need <- "A ratio needs a finite `y` and `x` for every sampled row." + check_finite_values(out$values, gap, paste0("`", arg, "`"), need) + out + } + yv <- read(y, "y") + xv <- read(x, "x") + parts$y <- yv$values + parts$respond <- rep(TRUE, length(yv$values)) + parts$y_name <- yv$name + parts$y_logical <- yv$logical + parts$x <- xv$values + parts$x_name <- xv$name + parts +} -#' @exportS3Method survey::deff -deff.drawn_ht <- function(object, quietly = FALSE, ...) object$deff +#' The ratio of `y` to `x`, and the residuals that carry its variance +#' +#' Returns `ratio`, `sum(y / pi) / sum(x / pi)`; `total_y` and `total_x`; +#' `z`, the residuals `(y - ratio * x) / total_x`; and `proportional`, +#' whether `y` is `ratio * x` in every row up to rounding. Then `z` is set +#' to exactly 0: the subtraction leaves a rounding error, which would give a +#' standard error a little above 0 and a design effect made of that error. +#' The caller refuses a `total_x` of 0. +#' +#' @noRd +ratio_fit <- function(y, x, pi_i) { + total_y <- sum(y / pi_i) + total_x <- sum(x / pi_i) + ratio <- total_y / total_x + e <- y - ratio * x + proportional <- length(y) > 0L && is.finite(ratio) && + all(abs(e) <= 1e-9 * pmax(abs(y), abs(ratio * x))) + z <- if (proportional) numeric(length(y)) else e / total_x + list(ratio = ratio, total_y = total_y, total_x = total_x, z = z, + proportional = proportional) +} -#' @exportS3Method survey::deff -deff.drawn_mean <- function(object, quietly = FALSE, ...) object$deff +#' A variable as a message names it: its column name, or `arg` for a vector +#' @noRd +ratio_name <- function(name, arg) paste0("`", name %||% arg, "`") -#' Shared argument handling for the estimators +#' Refuse a ratio whose estimated denominator is 0 #' @noRd -ht_prepare <- function(sample, y, level, df = NULL) { - if (!is.data.frame(sample)) { - stop("`sample` must be a data frame returned by draw().", call. = FALSE) - } - design <- attr(sample, "drawn_design") - rows <- attr(sample, "drawn_rows") - pop <- attr(sample, "drawn_population") - if (is.null(design) || is.null(rows) || is.null(pop)) { - stop("`sample` does not carry its design. Draw it with ", - "draw(..., weights = TRUE), and estimate from that result before ", - "subsetting it -- use `by` for estimates within groups.", - call. = FALSE) +check_ratio_denominator <- function(parts, total_x, name) { + if (!nrow(parts$sample)) { + stop("`sample` has no rows, so the ratio is 0 / 0.", call. = FALSE) } - if (!is.numeric(level) || length(level) != 1L || is.na(level) || - level <= 0 || level >= 1) { - stop("`level` must be a single number strictly between 0 and 1.", - call. = FALSE) - } - if (nrow(sample) == 0L) { - # Possible under Poisson sampling or a systematic start past the end. - stop("`sample` has no rows, so there is nothing to estimate from.", - call. = FALSE) - } - if (!is.null(df) && (!is.numeric(df) || length(df) != 1L || is.na(df) || - df <= 0)) { - stop("`df` must be a single positive number, Inf, or NULL.", call. = FALSE) + if (total_x == 0) { + stop("The estimated total of ", name, ", `sum(x / pi)` over the ", + "sampled rows, is 0, so the ratio is undefined. Use a denominator ", + "whose sampled values do not cancel out.", call. = FALSE) } + invisible(NULL) +} - yv <- if (is.character(y) && length(y) == 1L) { - if (!y %in% names(sample)) { - stop("`sample` has no column `", y, "`.", call. = FALSE) - } - sample[[y]] - } else { - y - } - if (is.logical(yv)) yv <- as.numeric(yv) - if (!is.numeric(yv) || length(yv) != nrow(sample)) { - stop("`y` must be a numeric column name or a numeric vector as long as ", - "`sample`.", call. = FALSE) - } - if (anyNA(yv)) { - stop(sum(is.na(yv)), " value(s) of `y` are missing.", call. = FALSE) - } - list(design = design, rows = rows, pop = pop, y = yv, pi = sample$.prob, - sample = sample, binary = all(yv == 0 | yv == 1)) +#' One ratio, as ht_ratio() gives it without `by` +#' +#' Returns what mean_one() returns. +#' +#' @noRd +ratio_one <- function(parts, variance, level, df, alternative, ctx = NULL) { + fit <- ratio_fit(parts$y, parts$x, parts$pi) + check_ratio_denominator(parts, fit$total_x, ratio_name(parts$x_name, "x")) + declined <- linear_declines(parts, rep(TRUE, length(parts$y)), variance, + estimate = "ratio") + out <- estimate_one(parts, fit$ratio, fit$z, variance, level, df, + what = "ratio", class = "drawn_ratio", deff_y = fit$z, + alternative = alternative, var_out = declined$any, + ctx = ctx, jk_decline = declined$jackknife) + out$x <- parts$x_name + out$total_y <- fit$total_y + out$total_x <- fit$total_x + out <- proportional_result(out, fit, parts) + list(result = out, z = fit$z, domain = NULL) } -#' A confidence interval from an estimate, a variance and degrees of freedom +#' The ratio estimator of a total, `R * X`, with `X` the frame's total of `x` +#' +#' Its variance is `X^2` times the ratio's, the variance of the total of +#' the residuals `X (y - R x) / X_hat`. +#' #' @noRd -interval <- function(est, v, level, df, logit = FALSE) { - if (!is.finite(v) || v < 0) return(c(NA_real_, NA_real_)) - q <- if (is.finite(df)) { - if (df < 1) return(c(NA_real_, NA_real_)) - stats::qt(1 - (1 - level) / 2, df) - } else { - stats::qnorm(1 - (1 - level) / 2) - } - if (logit && est > 0 && est < 1) { - # A proportion's interval on the logit scale, by the delta method, then - # back: it cannot leave [0, 1], and near 0 or 1 it is asymmetric the way - # the sampling distribution is. This is survey::svyciprop()'s "xlogit". - se_logit <- sqrt(v) / (est * (1 - est)) - return(stats::plogis(stats::qlogis(est) + c(-1, 1) * q * se_logit)) +ratio_total <- function(parts, variance, level, df, alternative, ctx = NULL) { + aux <- parts$ratio + fit <- ratio_fit(parts$y, aux$x, parts$pi) + check_ratio_denominator(parts, fit$total_x, ratio_name(aux$name, "x")) + z <- aux$total * fit$z + declined <- linear_declines(parts, rep(TRUE, length(parts$y)), variance, + estimate = "ratio estimator") + out <- estimate_one(parts, fit$ratio * aux$total, z, variance, level, df, + what = "total", class = "drawn_ht", deff_y = z, + alternative = alternative, var_out = declined$any, + ctx = ctx, jk_decline = declined$jackknife) + out$ratio <- fit$ratio + out$x <- aux$name + out$frame_total <- aux$total + out <- proportional_result(out, fit, parts) + list(result = out, z = z, domain = NULL) +} + +#' Add the note for a `y` proportional to `x`, when its variance is 0 +#' @noRd +proportional_result <- function(out, fit, parts) { + if (fit$proportional && identical(out$variance, 0) && + any(!is_certain(parts$pi))) { + out$note <- paste(c(out$note, proportional_note(fit$ratio)), + collapse = " ") } - est + c(-1, 1) * q * sqrt(v) + out } -#' Assemble an estimate, its interval, and its design effect +#' Why a ratio of a `y` proportional to `x` has a variance of 0 #' @noRd -finish_estimate <- function(est, var_out, level, df, n, design, y, pi_i, N, - what, class, logit = FALSE) { - v <- var_out$variance - se <- if (is.na(v) || v < 0) NA_real_ else sqrt(v) - logit <- isTRUE(logit && est > 0 && est < 1) - ci <- interval(est, v, level, df, logit) - note <- var_out$note - if (!is.na(se) && is.finite(df) && df < 1) { - note <- c(note, paste0("There are no degrees of freedom left for an ", - "interval: the sample has one primary sampling ", - "unit per stratum.")) - note <- paste(note, collapse = " ") +proportional_note <- function(value = NULL, domains = NULL) { + tail <- "though rows the sample did not draw may differ." + if (is.null(domains)) { + return(paste0( + "`y / x` is ", format(value), " in every sampled row, so the ", + "ratio's residuals are 0 and its estimated variance is 0. The ", + "interval has no width, ", tail)) } + several <- length(domains) > 1L + paste0("`y / x` takes one value in every sampled row of the domain", + if (several) "s", " ", paste0("`", domains, "`", collapse = ", "), + ", so ", if (several) "their ratios have" else "its ratio has", + " an estimated variance of 0 and an interval with no width, ", tail) +} - out <- list(variance = v, se = se, ci = ci, level = level, df = df, n = n, - ci_scale = if (logit) "logit" else "linear", - design = design_type(design), - deff = if (is.null(y)) NA_real_ else - deff_value(v, y, pi_i, N, n, what), - method = var_out$method %||% "analytic", note = note) - out[[what]] <- est - structure(out, class = class) +#' A ratio estimator of a total needs no domains +#' @noRd +check_ratio_by <- function(ratio, by) { + if (!is.null(ratio) && !is.null(by)) { + stop("`ratio` gives one ratio estimator of the total, and `by` asks for ", + "domains. For each domain's ratio use ht_ratio() with `by`, and ", + "multiply it by the domain's total of `", ratio[1], "` in the ", + "frame.", call. = FALSE) + } + invisible(NULL) } -#' Variance under simple random sampling of the same size, for comparison +#' The column `ratio` names, and its total over the frame #' -#' The population variance is estimated from the sample with design weights, so -#' this works from a sample of any design. -#' -#' The denominator is `sum(w) * (n - 1) / n`, not `sum(w) - 1`. Under simple -#' random sampling `sum(w * (y - mu)^2)` has expectation `(N/n)(n-1)S^2`, so -#' dividing by `N - 1` leaves the estimate short by a factor of `n(N-1)/(N(n-1))` -#' -- and the design effect, which divides by it, long by the reciprocal. That -#' put a plain simple random sample of 10 at a design effect of 1.11, printed as -#' "worse than simple random sampling". This form is exactly unbiased there. +#' The total is over the frame rows the design can reach, the population a +#' total estimates, read from the frame stored with the sample, as +#' frame_totals() reads it. Returns `NULL` without `ratio`, else its +#' `name`, the frame's value `x` for each sampled row and `total`. #' #' @noRd -deff_value <- function(v, y, pi_i, N, n, what) { - if (!is.finite(v) || v <= 0 || n < 2L || !is.finite(N) || N < 2L) { - return(NA_real_) +ratio_parts <- function(parts, ratio) { + if (is.null(ratio)) return(NULL) + if (!is.character(ratio) || length(ratio) != 1L || is.na(ratio)) { + stop("`ratio` must be the name of one column of the frame, not ", + format_bad(ratio), ".", call. = FALSE) } - w <- 1 / pi_i - mu <- sum(w * y) / sum(w) - s2 <- sum(w * (y - mu)^2) * n / (sum(w) * (n - 1)) - if (!is.finite(s2) || s2 <= 0) return(NA_real_) - fpc <- max(0, 1 - n / N) - v_srs <- if (what == "mean") s2 / n * fpc else N^2 * s2 / n * fpc - if (!is.finite(v_srs) || v_srs <= 0) return(NA_real_) - v / v_srs + pop <- parts$pop + if (!ratio %in% names(pop)) { + if (ratio %in% parts$compact$dropped) { + stop("`ratio` names `", ratio, "`, which compact_sample() dropped ", + "from the frame stored with `sample`. Name it in `keep` when ", + "compacting, or rebuild the sample from the full frame with ", + "as_drawn().", call. = FALSE) + } + stop("`ratio` names `", ratio, "`, which is not a column of the frame ", + "`sample` was drawn from. The ratio estimator needs its total over ", + "the frame, so name a column of that frame.", call. = FALSE) + } + x_all <- pop[[ratio]] + if (!is.numeric(x_all) && !is.logical(x_all)) { + stop("`ratio` names `", ratio, "`, ", a_class(x_all), " column of ", + "the frame. Name a numeric column.", call. = FALSE) + } + x_all <- as.numeric(x_all) + # A sample saved by drawn 0.2.0 records no probabilities, so they are + # worked out again from the design. + pi_all <- parts$pi_all %||% exact_inclusion(parts$design, pop) + reach <- reachable(pi_all) + vals <- x_all[reach] + gap <- is.na(vals) + if (any(gap)) { + stop("`", ratio, "` is missing in ", sum(gap), " of the ", length(vals), + " frame rows the design could reach, so its frame total is ", + "unknown. Name a column known for every row the design can reach, ", + "or estimate the ratio with ht_ratio() and multiply it by a total ", + "you know.", call. = FALSE) + } + if (any(!is.finite(vals))) { + stop("`", ratio, "` is infinite in ", sum(!is.finite(vals)), " of the ", + "frame rows the design could reach, so its frame total is not a ", + "number. Name a column with a finite value in every row.", + call. = FALSE) + } + list(name = ratio, x = x_all[parts$rows], total = sum(vals)) } #' @export -print.drawn_mean <- function(x, ...) { - print_estimate(x, "mean", if (identical(x$estimator, "ht")) - "Horvitz-Thompson mean" else "Hajek mean") +print.drawn_ratio <- function(x, ...) { + shown <- function(v) format(v, big.mark = ",") + print_estimate(x, "ratio", "Ratio of Horvitz-Thompson totals", lines = c( + ratio = paste(ratio_name(x$variable, "y"), "/", ratio_name(x$x, "x")), + totals = paste(shown(x$total_y), "/", shown(x$total_x)) + )) } +# ---- several variables at once --------------------------------------------- + +#' Whether `y` names several columns #' @noRd -df_label <- function(df) { - if (is.null(df) || !is.finite(df)) "normal" else - paste0("t, ", format(signif(df, 4)), " df") -} +several_names <- function(y) is.character(y) && length(y) > 1L +#' Whether a `by` table holds the estimates of several variables #' @noRd -method_label <- function(m) { - switch(m %||% "analytic", - deville = "Deville approximation", - `successive difference` = "successive-difference approximation", - `local mean` = "local-mean approximation", - m - ) +several_y <- function(x) length(attr(x, "variable")) > 1L + +#' Check the names in a `y` that names several columns +#' +#' A character vector that names no column of `sample`, or holds a missing +#' or empty name, is taken for data passed as `y`, and gets the message that +#' lists the forms `y` takes. +#' +#' @noRd +check_several_y <- function(sample, y) { + if (anyNA(y) || !all(nzchar(y)) || !any(y %in% names(sample))) { + stop(variable_forms(y, "y", TRUE, sample), call. = FALSE) + } + twice <- unique(y[duplicated(y)]) + if (length(twice)) { + stop("`y` names ", quote_names(twice), " more than once. Name each ", + "column once.", call. = FALSE) + } + absent <- setdiff(y, names(sample)) + if (length(absent)) { + stop("`sample` has no column", if (length(absent) > 1L) "s", " ", + quote_names(absent), ".", call. = FALSE) + } + kind <- vapply(y, function(v) { + col <- sample[[v]] + if (is.factor(col)) "factor" else if (is.character(col)) "character" else + "" + }, character(1)) + hit <- which(nzchar(kind)) + if (length(hit)) { + v <- y[hit[1]] + stop("`y` names `", v, "`, a ", kind[hit[1]], " column, among several. ", + "Estimate its levels in a call of their own, with `y = \"", v, + "\"`, which gives a row for each level.", call. = FALSE) + } + invisible(NULL) } +#' Estimates of several variables, as one table +#' +#' Each variable is estimated as a call for it alone estimates it, with one +#' `variance_context()` for them all, and the rows are stacked under a +#' `variable` column, which the table's `by` attribute leads, so that +#' coef(), confint() and the other methods name each row by its variable and +#' domain. +#' +#' The covariances between the variables come from polarisation. Every +#' variance estimator here is a quadratic form in the variable it totals, +#' `V(z) = z' A z` with `A` set by the design and the sampled rows, so +#' `Cov(a, b) = (V(z_a + z_b) - V(z_a) - V(z_b)) / 2`, one more run of the +#' same estimator for each pair. They are kept in the `vcov` attribute, +#' which vcov() reads. With `by` they are the covariances between the +#' variables within each domain. Between domains they are `NA`, as in the +#' vcov() of a `by` table of one variable, or 0 where domains_apart() shows +#' the domains were sampled independently. +#' #' @noRd -print_estimate <- function(x, field, label) { - cat(label, " (", x$design, " design, n = ", x$n, ")\n", sep = "") - cat(" estimate ", format(x[[field]], big.mark = ","), "\n", sep = "") - if (is.na(x$se)) { - cat(" se NA\n") - } else { - cat(" se ", format(x$se, big.mark = ","), " (", - method_label(x$method), ")\n", sep = "") - if (all(is.finite(x$ci))) { - cat(" ", format(100 * x$level), "% CI ", - format(x$ci[1], big.mark = ","), " to ", - format(x$ci[2], big.mark = ","), " (", - if (identical(x$ci_scale, "logit")) "logit, ", df_label(x$df), - ")\n", sep = "") - } - if (is.finite(x$deff)) { - cat(" deff ", signif(x$deff, 3), " (", - if (x$deff > 1.05) "worse than" else if (x$deff < 0.95) "better than" - else "about the same as", " simple random sampling)\n", sep = "") - } +estimate_several <- function(sample, y, what, variance, level, by, df, + alternative, contrast, estimator = "hajek", + proportion = NULL, ci_method = "logit", + na_rm = NULL, ratio = NULL) { + check_several_y(sample, y) + if (!is.null(contrast)) { + stop("`contrast` weighs the domains of one variable, and `y` names ", + length(y), " columns. Estimate each contrast with a call of its ", + "own.", call. = FALSE) } - if (!is.null(x$note) && (is.na(x$se) || !identical(x$method, "analytic"))) { - cat_note(x$note) + base <- prepare_sample(sample, level, df) + parts <- lapply(y, function(v) { + add_y(base, v, na_rm, label = paste0("`", v, "`, named in `y`,")) + }) + base <- finish_prepare(base) + if (what == "mean") { + parts <- lapply(seq_along(y), function(i) { + mean_setup(parts[[i]], estimator, proportion, ci_method, + label = paste0("`", y[i], "`")) + }) } - invisible(x) + stack_estimates(sample, base, parts, what, variance, level, by, df, + alternative, estimator, ci_method, ratio, + lead = "variable", values = y, variable = y) } -#' Print a note, wrapped and indented, after one blank line +#' Whether `y` is a factor or character column, or a factor vector +#' +#' A character vector is taken for column names, so a vector of categories +#' counts only as a factor. +#' #' @noRd -cat_note <- function(text) { - cat("\n", paste0(strwrap(text, prefix = " "), collapse = "\n"), "\n", - sep = "") +categorical <- function(sample, y) { + if (is.factor(y)) return(length(y) == nrow(sample)) + if (!is.character(y) || length(y) != 1L || is.na(y) || + !y %in% names(sample)) { + return(FALSE) + } + v <- sample[[y]] + is.factor(v) || is.character(v) +} + +#' The levels of a categorical `y`, in the order its table lists them +#' +#' A factor's levels, unused ones included, as `survey::svymean()` lists +#' them, kept as a factor of the same class; else the values present, sorted +#' byte by byte. +#' +#' @noRd +category_levels <- function(v) { + if (is.factor(v)) { + lev <- levels(v) + return(structure(seq_along(lev), levels = lev, class = class(v))) + } + key_values(v) +} + +#' Estimates for each level of a factor or character `y` +#' +#' Each level is a 0/1 indicator, missing where `y` is, estimated as one +#' variable of several: a count with ht_total(), a share with ht_mean(), +#' which reads the indicators as proportions. The table is led by a `level` +#' column. +#' +#' @noRd +estimate_levels <- function(sample, y, what, variance, level, by, df, + alternative, contrast, estimator = "hajek", + proportion = NULL, ci_method = "logit", + na_rm = NULL, ratio = NULL) { + name <- if (is.character(y)) y + v <- if (is.null(name)) y else sample[[name]] + shown <- ratio_name(name, "y") + values <- category_levels(v) + if (!is.null(contrast)) { + stop("`contrast` weighs the domains of one variable, and ", shown, + " has ", length(values), " levels, each estimated as a variable of ", + "its own. Pass the indicator of one level as `y`, such as `", + if (is.null(name)) "y" else paste0("sample$", name), " == \"", + values[1], "\"`, with `contrast`.", call. = FALSE) + } + if (!length(values)) { + stop(shown, " has no value in any sampled row, so it has no levels to ", + "estimate.", call. = FALSE) + } + base <- prepare_sample(sample, level, df) + codes <- if (is.factor(v)) as.integer(v) else match(v, values) + parts <- lapply(seq_along(values), function(k) { + add_y(base, codes == k, na_rm, label = shown) + }) + base <- finish_prepare(base) + if (what == "mean") { + parts <- lapply(parts, mean_setup, estimator = estimator, + proportion = proportion, ci_method = ci_method, + label = shown) + } + stack_estimates(sample, base, parts, what, variance, level, by, df, + alternative, estimator, ci_method, ratio, lead = "level", + values = values, variable = name) +} + +#' Estimates of several variables, stacked into one table +#' +#' `parts` holds one variable each. `lead` names the column that leads the +#' table, `"variable"` or `"level"`, `values` gives its value for each of +#' `parts`, and `variable` is the table's `variable` attribute: the column +#' names, or the name of the categorical `y`. +#' +#' @noRd +stack_estimates <- function(sample, base, parts, what, variance, level, by, + df, alternative, estimator, ci_method, ratio, + lead, values, variable) { + aux <- ratio_parts(base, ratio) + for (i in seq_along(parts)) parts[[i]]["ratio"] <- list(aux) + ctx <- variance_context() + if (is.null(by)) { + warn_grouped(sample, paste0("ht_", what)) + fits <- lapply(parts, function(p) { + if (what == "total") { + total_one(p, variance, level, df, alternative, ctx) + } else { + mean_one(p, estimator, variance, level, df, ci_method, alternative, + ctx) + } + }) + results <- lapply(fits, `[[`, "result") + pieces <- lapply(results, function(r) { + row <- data.frame(n = as.integer(r$n)) + row[[what]] <- r[[what]] + row$variance <- r$variance + row$se <- r$se + row$ci_lower <- r$ci[1] + row$ci_upper <- r$ci[2] + row$method <- r$method + row + }) + notes <- lapply(results, `[[`, "note") + n_random <- lapply(results, `[[`, "n_random") + df_use <- results[[1]]$df + } else { + fits <- lapply(parts, function(p) { + estimate_by(p, by, variance, level, df, what, estimator = estimator, + ci_method = ci_method, alternative = alternative, + ctx = ctx, reserved = lead, keep = TRUE) + }) + tables <- lapply(fits, `[[`, "table") + pieces <- lapply(tables, plain_frame) + notes <- lapply(tables, attr, "notes") + n_random <- lapply(tables, function(t) unname(attr(t, "n_random"))) + df_use <- attr(tables[[1]], "df") + } + sizes <- vapply(pieces, nrow, integer(1)) + out <- do.call(rbind, lapply(seq_along(parts), function(i) { + first <- stats::setNames(list(values[rep(i, sizes[i])]), lead) + cbind(data.frame(first, stringsAsFactors = FALSE), pieces[[i]]) + })) + rownames(out) <- NULL + out <- structure(out, class = c("drawn_by", "data.frame"), what = what, + estimator = if (what == "mean") estimator, level = level, + alternative = alternative, df = df_use, + design = design_type(base$design), + notes = several_notes(group_label(values), notes), + unreachable = base$unreachable, variable = variable, + by = c(lead, by), lead = lead) + attr(out, "unavailable") <- base$unavailable + if (!is.null(aux)) attr(out, "x") <- aux$name + nm <- domain_names(out) + # A proportion's interval is on the scale of `ci_method`, any other + # variable's on the linear scale; one scale for all is kept as one value. + scale <- rep(vapply(parts, function(p) { + if (isTRUE(p$proportion)) ci_method else "linear" + }, character(1)), sizes) + attr(out, "ci_scale") <- if (length(unique(scale)) > 1L) { + stats::setNames(scale, nm) + } else { + c(scale, "linear")[1] + } + attr(out, "n_random") <- stats::setNames(as.integer(unlist(n_random)), nm) + attr(out, "vcov") <- if (is.null(by)) { + several_vcov(base, fits, variance, nm, ctx) + } else { + several_vcov_by(base, by, fits, out, variance, nm, ctx) + } + out +} + +#' The notes of several variables: once if every variable has it, else +#' after the variable's name +#' @noRd +several_notes <- function(y, notes) { + notes <- lapply(notes, function(n) n[!is.na(n) & nzchar(n)]) + every <- unique(unlist(notes)) + shared <- every[vapply(every, function(n) { + all(vapply(notes, function(v) n %in% v, logical(1))) + }, logical(1))] + own <- unlist(lapply(seq_along(y), function(i) { + mine <- setdiff(notes[[i]], shared) + if (length(mine)) paste0("`", y[i], "`: ", mine) + })) + c(shared, own) +} + +#' A covariance by polarisation, or `NA` +#' +#' `va` and `vb` are the two variances and `ma` and `mb` the estimators +#' that gave them. `run(use)` gives the variance of the sum with `variance = +#' use`. The covariance is `NA` when either variance is missing or the +#' three did not come from one estimator, as when the design's own declined +#' for one of them and the jackknife stood in. +#' +#' @noRd +polarised <- function(va, vb, ma, mb, run) { + if (!is.finite(va) || !is.finite(vb) || !identical(ma, mb) || + identical(ma, "none")) { + return(NA_real_) + } + s <- run(if (ma == "jackknife") "jackknife" else "analytic") + if (!identical(s$method %||% "analytic", ma) || !is.finite(s$variance)) { + return(NA_real_) + } + (s$variance - va - vb) / 2 +} + +#' The covariance matrix of several variables' estimates, without `by` +#' @noRd +several_vcov <- function(base, fits, variance, nm, ctx) { + res <- lapply(fits, `[[`, "result") + v <- vapply(res, function(r) r$variance, numeric(1)) + m <- vapply(res, function(r) r$method %||% "analytic", character(1)) + k <- length(fits) + out <- diag(v, k) + for (a in seq_len(k - 1L)) { + for (b in seq.int(a + 1L, k)) { + # A mean over the rows with `y` present was run on a domain the frame + # cannot place, and the sum is run the same way. + domain <- if (anyNA(c(fits[[a]]$domain, fits[[b]]$domain))) NA + z <- fits[[a]]$z + fits[[b]]$z + out[a, b] <- out[b, a] <- polarised(v[a], v[b], m[a], m[b], + function(use) { + ht_variance_dispatch(base$design, base$units, base$pop, base$rows, z, + base$pi, use, domain, ctx) + }) + } + } + dimnames(out) <- list(nm, nm) + out +} + +#' The covariance matrix of several variables' domain estimates +#' +#' Each pair's sum is run over every domain at once, with the rows of each +#' domain whether or not they have each `y`; a row without one has a `z` of +#' 0 for it. +#' +#' @noRd +several_vcov_by <- function(base, by, fits, out, variance, nm, ctx) { + every <- base + every$respond <- rep(TRUE, nrow(base$sample)) + dom <- domain_keys(every, by) + v <- out$variance + codes <- unlist(lapply(fits, function(f) f$dom$levels_in)) + V <- between_domains(v, codes, domains_apart(every, dom), nm) + if (variance == "none") return(V) + start <- cumsum(c(0L, vapply(fits, function(f) nrow(f$table), + integer(1)))) + k <- length(fits) + for (a in seq_len(k - 1L)) { + for (b in seq.int(a + 1L, k)) { + vs <- domain_variances(every, dom, list(z = fits[[a]]$z + fits[[b]]$z), + variance, NULL, ctx) + for (j in seq_along(dom$levels_in)) { + ra <- start[a] + match(dom$levels_in[j], fits[[a]]$dom$levels_in) + rb <- start[b] + match(dom$levels_in[j], fits[[b]]$dom$levels_in) + if (is.na(ra) || is.na(rb)) next + V[ra, rb] <- V[rb, ra] <- polarised(v[ra], v[rb], out$method[ra], + out$method[rb], + function(use) vs[[j]]) + } + } + } + V +} + +#' Estimates for each domain, from the whole sample +#' +#' A domain estimate uses the full sample with `y` zeroed outside the domain. +#' Subsetting first would treat the number of rows that happened to land in the +#' domain as fixed by design, which it is not, and would hand the variance +#' estimator a sample the design never drew. +#' +#' Every domain's variance is computed against one `variance_context()`, so +#' the strata, clusters and other pieces read from the frame are worked out +#' once per call rather than once per domain. With `contrast`, the domains' +#' estimates are combined by `estimate_contrast()` instead. +#' +#' `what` is `"total"`, `"mean"` or `"ratio"`. `ctx` is the context to share +#' with other calls on the same sample, `reserved` names further columns the +#' table uses, which `by` must not name, and `keep = TRUE` returns the table +#' with the domains and their variable `z`, as estimate_several() needs them. +#' +#' @noRd +estimate_by <- function(parts, by, variance, level, df, what, + estimator = "hajek", ci_method = "logit", + alternative = "two.sided", contrast = NULL, + ctx = variance_context(), reserved = NULL, + keep = FALSE) { + dom <- domain_keys(parts, by) + est <- domain_estimates(parts, dom, what, estimator) + pi_i <- parts$pi + df_use <- df %||% design_df(parts$design, parts$units, parts$pop, + parts$rows, pi_i) + if (!is.null(contrast)) { + return(estimate_contrast(parts, dom, est, contrast, variance, level, + df_use, what, estimator, alternative, ctx)) + } + # The table's own columns would overwrite a `by` column of the same name. + check_table_names(by, c(reserved, "n", what, "variance", "se", + "ci_lower", "ci_upper", "method")) + linearised <- if (what == "ratio") { + "ratio" + } else if (what == "mean" && estimator == "hajek") { + "Hajek mean" + } + vars <- domain_variances(parts, dom, est, variance, linearised, ctx = ctx) + proportion <- what == "mean" && isTRUE(parts$proportion) + labels <- dom$labels + levels_in <- dom$levels_in + + rows <- lapply(seq_along(levels_in), function(j) { + v <- vars[[j]] + ci <- ci_for(est$est[j], v$variance, level, df_use, alternative, + proportion, ci_method, pi_i[dom$idx[[j]]]) + list(variance = v$variance, + se = if (is.finite(v$variance) && v$variance >= 0) + sqrt(v$variance) else NA_real_, + lo = ci$ci[1], hi = ci$ci[2], method = v$method %||% "analytic", + note = v$note, edge = ci$edge, + constant = est$constant[j] && identical(v$variance, 0) && + !ci$edge && !ci$exact) + }) + + first <- match(levels_in, dom$key) + out <- data.frame(stats::setNames(lapply(by, function(b) { + parts$sample[[b]][first] + }), by), check.names = FALSE) + out$n <- lengths(dom$idx) + out[[what]] <- est$est + out$variance <- vapply(rows, `[[`, numeric(1), "variance") + out$se <- vapply(rows, `[[`, numeric(1), "se") + out$ci_lower <- vapply(rows, `[[`, numeric(1), "lo") + out$ci_upper <- vapply(rows, `[[`, numeric(1), "hi") + out$method <- vapply(rows, `[[`, character(1), "method") + notes <- unique(unlist(lapply(rows, `[[`, "note"))) + if (any(is.na(out$variance) & out$n > 1L)) { + notes <- c(notes, compact_domain_note(parts, dom)) + } + if (any(is.finite(out$se) & (is.na(out$ci_lower) | is.na(out$ci_upper)))) { + notes <- c(notes, df_note(df_use)) + } + if (proportion && !is.null(parts$proportion_note)) { + notes <- c(notes, parts$proportion_note) + } + edge <- vapply(rows, `[[`, logical(1), "edge") + if (any(edge)) { + notes <- c(notes, edge_note(domains = labels[levels_in[edge]], + ci_method = ci_method, + certain = any(is_certain(pi_i)))) + } + if (is.null(linearised) && variance != "none") { + held <- certain_only_domains(parts, dom, out$variance) + if (length(held)) { + notes <- c(notes, certain_total_note(labels[levels_in[held]])) + } + } + constant <- vapply(rows, `[[`, logical(1), "constant") + if (any(constant)) { + shown <- labels[levels_in[constant]] + notes <- c(notes, if (what == "ratio") { + proportional_note(domains = shown) + } else { + constant_note(NA, TRUE, domains = shown) + }) + } + if (any(!parts$respond)) { + notes <- c(notes, missing_note(sum(!parts$respond), + length(parts$respond), parts$y_name, + blank = labels[dom$blank])) + } + out <- structure(out, class = c("drawn_by", "data.frame"), + what = what, estimator = if (what == "mean") estimator, + level = level, alternative = alternative, df = df_use, + design = design_type(parts$design), + ci_scale = if (proportion) ci_method else "linear", + notes = notes, unreachable = parts$unreachable, + variable = parts$y_name, by = by) + attr(out, "unavailable") <- parts$unavailable + if (what == "ratio") attr(out, "x") <- parts$x_name + # The beta interval's sample size, kept by domain name rather than by + # position so that it still matches after rows are selected. + attr(out, "n_random") <- stats::setNames( + vapply(dom$idx, function(i) sum(!is_certain(pi_i[i])), integer(1)), + domain_names(out)) + attr(out, "vcov") <- between_domains(out$variance, levels_in, + domains_apart(parts, dom), + domain_names(out)) + if (keep) return(list(table = out, z = est$z, dom = dom)) + out +} + +#' Which pairs of domains a stratified design samples independently +#' +#' Strata are sampled independently, and every variance estimator here sums +#' over them, so two domains whose sampled rows share no stratum have +#' estimates with a covariance of exactly 0. Returns a logical matrix over +#' the codes of `dom$labels`, `TRUE` for such a pair, or `NULL` for a design +#' other than [design_stratified()], whose covariances between domains are +#' not known. +#' +#' @noRd +domains_apart <- function(parts, dom) { + if (!inherits(parts$design, "drawn_design_stratified")) return(NULL) + k <- length(dom$labels) + stratum <- as.integer(group_key(parts$units, parts$design$strata)) + # A row with `y` missing under `na_rm = TRUE` is in no domain. + use <- !is.na(dom$pos) + held <- table(factor(dom$key[use], levels = seq_len(k)), + factor(stratum[use], levels = seq_len(max(stratum)))) + shared <- (unclass(held) > 0) %*% t(unclass(held) > 0) + shared == 0 +} + +#' A covariance matrix with the variances of a `by` table's rows +#' +#' `codes` are the rows' domain codes. Rows of two domains that +#' domains_apart() shows were sampled independently get a covariance of 0, +#' and any other pair `NA`, which estimate_several() fills in where it +#' estimates a covariance. +#' +#' @noRd +between_domains <- function(variance, codes, apart, nm) { + out <- matrix(NA_real_, length(variance), length(variance)) + if (!is.null(apart)) out[apart[codes, codes, drop = FALSE]] <- 0 + diag(out) <- variance + dimnames(out) <- list(nm, nm) + out +} + +#' Refuse `by` columns that the table of estimates uses for its own +#' @noRd +check_table_names <- function(by, own) { + clash <- intersect(by, own) + if (length(clash)) { + stop("`by` names ", paste0("`", clash, "`", collapse = ", "), ", which ", + "the table of domain estimates uses for its own column", + if (length(clash) > 1L) "s", ". Rename ", + if (length(clash) > 1L) "them" else "it", " in `sample` before ", + "estimating.", call. = FALSE) + } + invisible(NULL) +} + +#' The domains of `by`, keyed in the sample and, where it can be, the frame +#' +#' Returns `key`, each sampled row's domain as a code into `labels`; +#' `pop_key`, each frame row's, or `NULL` when the frame lacks a `by` column; +#' `pop_pos`, each frame row's position in `levels_in`, 0 for a row of no +#' domain there and `NA` where `pop_key` is, or `NULL` with `pop_key`; +#' `levels_in`, the codes of the domains with a sampled row, in key order; +#' `blank`, the codes of those whose sampled rows all have `y` missing under +#' `na_rm = TRUE`, which `levels_in` leaves out; `pos`, each sampled row's +#' position in `levels_in`, `NA` for a row with `y` missing under +#' `na_rm = TRUE`; `idx`, the sampled rows of each domain in `levels_in`, +#' without those; and `aligned`, whether the frame's `by` +#' columns agree with the sample's on the sampled rows, so that the frame can +#' say which of its rows each domain holds. +#' +#' @noRd +domain_keys <- function(parts, by) { + if (!is.character(by) || !length(by) || anyNA(by)) { + stop("`by` must name one or more columns of `sample`.", call. = FALSE) + } + absent <- setdiff(by, names(parts$sample)) + if (length(absent)) { + stop("`by` names ", paste0("`", absent, "`", collapse = ", "), ", which ", + "`sample` does not have.", call. = FALSE) + } + check_key_columns(parts$sample, by, "by") + # Columns are read one at a time, so an sf sample's geometry stays out. + if (any(vapply(by, function(b) anyNA(parts$sample[[b]]), logical(1)))) { + stop("`by` columns must not contain missing values.", call. = FALSE) + } + # Domains come out in key order: factor levels, else sorted values, with + # text in byte order whatever the locale. + if (all(by %in% names(parts$pop))) { + keys <- group_key2(parts$sample, parts$pop, by) + key <- as.integer(keys$x) + pop_key <- as.integer(keys$table) + labels <- group_label(levels(keys$x)) + } else { + k <- group_key(parts$sample, by) + key <- as.integer(k) + pop_key <- NULL + labels <- group_label(levels(k)) + } + # Rows with `y` missing, left out by `na_rm = TRUE`, belong to no domain, + # so each domain is the rows of its `by` values with `y` present. + use <- parts$respond %||% rep(TRUE, length(key)) + levels_in <- which(tabulate(key[use], length(labels)) > 0L) + blank <- setdiff(which(tabulate(key, length(labels)) > 0L), levels_in) + pos <- match(key, levels_in) + pos[!use] <- NA_integer_ + idx <- split(seq_along(key)[use], + structure(pos[use], levels = as.character(seq_along(levels_in)), + class = "factor")) + # Each frame row's position in `levels_in`, 0 for a domain with no + # sampled row and `NA` for a row whose `by` value is missing, so that + # domain_frame() marks one domain with a single comparison. + pop_pos <- if (!is.null(pop_key)) { + out <- match(pop_key, levels_in, nomatch = 0L) + out[is.na(pop_key)] <- NA_integer_ + out + } + list(by = by, key = key, pop_key = pop_key, pop_pos = pop_pos, + labels = labels, levels_in = levels_in, blank = blank, pos = pos, + idx = unname(idx), + aligned = !is.null(pop_key) && identical(pop_key[parts$rows], key)) +} + +#' Say that compact_sample() dropped the `by` columns a variance needed +#' +#' A stratum with one sampled row adds nothing to a domain's variance when +#' the frame shows it holds no row of the domain. Without the `by` columns +#' the frame cannot show that, and the variance is declined. Called when a +#' domain of more than one row has no variance; `NULL` unless the stored +#' frame lacks `by` columns that compact_sample() dropped. +#' +#' @noRd +compact_domain_note <- function(parts, dom) { + gone <- intersect(dom$by, parts$compact$dropped) + if (!length(gone) || dom$aligned) return(NULL) + paste0("compact_sample() dropped ", quote_names(gone), " from the frame ", + "stored with `sample`, so the frame cannot show which of its rows ", + "each domain holds, and a standard error that depends on it is ", + "missing. Compact the sample from draw() with `keep = ", + deparse(if (length(gone) > 1L) gone else gone[[1]]), "` instead.") +} + +#' Which frame rows the domains at positions `j` of `levels_in` hold +#' +#' Read from the frame's own `by` columns: `TRUE` for a row in one of the +#' domains and `FALSE` for a row outside them. A row with a `by` value +#' missing in the frame may belong to any domain and is `NA`. Where the frame +#' lacks a `by` column, or its values disagree with the sample's for the +#' sampled rows, the frame cannot say for any row and the result is a single +#' `NA`. +#' +#' @noRd +domain_frame <- function(dom, j) { + if (!dom$aligned) return(NA) + if (length(j) == 1L) return(dom$pop_pos == j) + out <- dom$pop_pos %in% j + out[is.na(dom$pop_pos)] <- NA + out +} + +#' Each domain's estimate, and the variable whose total has its variance +#' +#' For a total that variable is `y` on the domain's rows; for a Hajek mean, +#' the linearised residual `(y - mean) / N_hat` of the domain; for a +#' Horvitz-Thompson mean, `y / N_d` with `N_d` the domain's rows in the frame; +#' and for a ratio, `(y - R_d x) / X_hat_d` with `R_d` the domain's ratio and +#' `X_hat_d` its estimated total of `x`. +#' Each is 0 outside its domain, so one vector `z` holds them all: each +#' sampled row's value in its own domain. A Hajek mean of a `y` constant over +#' the domain, and a ratio of a `y` proportional to `x` there, have residuals +#' of exactly 0, not the rounding error the subtraction leaves, and +#' `constant` marks them. +#' +#' @noRd +domain_estimates <- function(parts, dom, what, estimator) { + yv <- parts$y + pi_i <- parts$pi + k <- length(dom$levels_in) + est <- numeric(k) + constant <- logical(k) + z <- numeric(length(yv)) + if (what == "ratio") { + zero <- logical(k) + for (j in seq_len(k)) { + i <- dom$idx[[j]] + fit <- ratio_fit(yv[i], parts$x[i], pi_i[i]) + zero[j] <- fit$total_x == 0 + est[j] <- fit$ratio + constant[j] <- fit$proportional + z[i] <- fit$z + } + if (any(zero)) { + shown <- dom$labels[dom$levels_in[zero]] + several <- length(shown) > 1L + stop("The estimated total of ", ratio_name(parts$x_name, "x"), + " is 0 in the domain", if (several) "s", " ", + quote_labels(shown), ", so ", if (several) "their ratios are" else + "its ratio is", " undefined. Merge ", + if (several) "those domains" else "that domain", + " with another in the `by` columns.", call. = FALSE) + } + return(list(est = est, z = z, constant = constant)) + } + size <- NULL + if (what == "mean" && estimator == "ht") { + if (is.null(dom$pop_key)) { + gone <- intersect(dom$by, parts$compact$dropped) + if (length(gone)) { + stop("estimator = \"ht\" needs each domain's size in the frame, ", + "and compact_sample() dropped ", quote_names(gone), " from the ", + "frame stored with `sample`. Name the `by` columns in `keep` ", + "when compacting, or rebuild the sample from the full frame ", + "with as_drawn().", call. = FALSE) + } + stop("estimator = \"ht\" needs the domain's population size, and ", + "the `by` columns are not in the population.", call. = FALSE) + } + # A frame row with a `by` value missing could be in any domain, so no + # domain's size is known. Counting without it overstated the mean. + gap <- sum(is.na(dom$pop_key)) + if (gap) { + several <- length(dom$by) > 1L + stop("estimator = \"ht\" divides each domain's total by its number ", + "of frame rows, and the `by` column", if (several) "s", " ", + quote_names(dom$by), + if (several) " have a missing value" else " is missing", + " in ", gap, " of the frame's ", length(dom$pop_key), + " rows, which could be in any domain. Fill in the frame's `by` ", + "values, or use estimator = \"hajek\", which needs no domain ", + "sizes.", call. = FALSE) + } + size <- tabulate(dom$pop_key, length(dom$labels))[dom$levels_in] + } + for (j in seq_len(k)) { + i <- dom$idx[[j]] + total <- sum(yv[i] / pi_i[i]) + if (what == "total") { + est[j] <- total + z[i] <- yv[i] + next + } + denom <- if (estimator == "hajek") sum(1 / pi_i[i]) else size[j] + est[j] <- total / denom + in_d <- yv[i] + if (estimator == "hajek" && all(in_d == in_d[1])) { + constant[j] <- TRUE + est[j] <- in_d[1] + } else { + z[i] <- if (estimator == "hajek") (in_d - est[j]) / denom else + in_d / denom + } + } + list(est = est, z = z, constant = constant) +} + +#' The variance of every domain's estimate +#' +#' A Hajek mean or a ratio over one primary sampling unit is declined first, +#' with `linear_declines()`; `linearised` names the estimate in its note, and is +#' `NULL` for an estimate that has no such decline. A domain over one cluster of +#' a census of clusters is declined only where the jackknife would give its +#' variance. Where the design's analytic estimator is `srs_variance()` over +#' strata, intervals or one group, every other domain is estimated in one pass +#' with `srs_variance_by()`. A domain that pass cannot settle, because a lonely +#' group holds some of its units or its variance overflowed, goes through +#' `ht_variance_dispatch()` as every domain of the other designs does, with the +#' shared `ctx`, and gets the same note and fallback as an estimate of its own. +#' +#' @noRd +domain_variances <- function(parts, dom, est, variance, linearised, ctx) { + k <- length(dom$levels_in) + out <- vector("list", k) + jk_out <- vector("list", k) + if (!is.null(linearised) && variance != "none") { + psu <- sample_units(parts$design, parts$units, parts$pop, parts$rows, + parts$pi) + jk_psu <- jackknife_units(parts, psu, variance) + for (j in seq_len(k)) { + d <- linear_declines(parts, dom$idx[[j]], variance, domain_frame(dom, j), + dom$labels[dom$levels_in[j]], estimate = linearised, + psu = psu, jk_psu = jk_psu) + out[j] <- list(d$any) + jk_out[j] <- list(d$jackknife) + } + } + open <- which(vapply(out, is.null, logical(1))) + if (length(open) && variance %in% c("auto", "analytic")) { + v <- srs_domains(parts, dom, est$z, ctx) + for (j in open[!is.na(v[open])]) { + out[[j]] <- list(variance = v[[j]], note = NULL, method = "analytic") + } + open <- which(vapply(out, is.null, logical(1))) + } + for (j in open) { + i <- dom$idx[[j]] + z <- numeric(length(est$z)) + z[i] <- est$z[i] + out[[j]] <- ht_variance_dispatch(parts$design, parts$units, parts$pop, + parts$rows, z, parts$pi, variance, + domain_frame(dom, j), ctx, jk_out[[j]]) + } + out +} + +#' Every domain's `srs_variance()` in one pass, or `NA` where it cannot say +#' +#' One variance per domain. Every domain gets `NA` when the design's analytic +#' estimator is not `srs_variance()` over groups (see `srs_layout()`), or when +#' a lonely group exists and the frame cannot say which domains it holds. A +#' domain with units in a lonely group, and a variance that overflowed, get +#' `NA` too. +#' +#' @noRd +srs_domains <- function(parts, dom, z, ctx) { + lay <- srs_layout(parts$design, parts$pop, parts$rows, ctx) + k <- length(dom$levels_in) + if (is.null(lay)) return(rep(NA_real_, k)) + keep <- !is.na(lay$group) + # A row with `y` missing is in no domain. It still counts among its + # group's sampled rows, so it goes in a domain of its own, left out of the + # result, where its `z` of 0 adds nothing. + pos <- dom$pos + pos[is.na(pos)] <- k + 1L + v <- srs_variance_by(z[keep], lay$group[keep], pos[keep], k + 1L, lay$n_g, + lay$N_g)[seq_len(k)] + if (length(lay$lonely_rows)) { + keys <- dom$pop_key[lay$lonely_rows] + # A frame row with a `by` value missing may belong to any domain. + hit <- if (dom$aligned && !anyNA(keys)) { + match(keys, dom$levels_in) + } else { + seq_len(k) + } + v[hit[!is.na(hit)]] <- NA_real_ + } + v[!is.finite(v)] <- NA_real_ + v +} + +#' A weighted sum of domain estimates, with its standard error +#' +#' Each domain's estimate comes from the whole sample, with the variable +#' `domain_estimates()` gives it, so a weighted sum of the estimates is +#' estimated by the same sum of those variables, and its variance is that of +#' one total. One run of the design's estimator gives it, covariances between +#' domains included. The interval is symmetric, since a difference of +#' proportions can be negative. A Hajek mean over one primary sampling unit +#' has no measurable variance, so a contrast that weighs one has none either. +#' +#' @noRd +estimate_contrast <- function(parts, dom, est, contrast, variance, level, df, + what, estimator, alternative, ctx) { + w <- contrast_weights(contrast, dom, parts$y_name) + used <- which(w != 0) + value <- sum(w[used] * est$est[used]) + w_row <- w[dom$pos] + w_row[is.na(w_row)] <- 0 + z <- w_row * est$z + labels <- dom$labels[dom$levels_in[used]] + var_out <- jk_decline <- NULL + if (what == "mean" && estimator == "hajek" && variance != "none") { + psu <- sample_units(parts$design, parts$units, parts$pop, parts$rows, + parts$pi) + jk_psu <- jackknife_units(parts, psu, variance) + declines <- lapply(seq_along(used), function(u) { + linear_declines(parts, dom$idx[[used[u]]], variance, + domain_frame(dom, used[u]), labels[u], psu = psu, + jk_psu = jk_psu) + }) + weighs <- function(notes) { + if (!length(notes)) return(NULL) + list(variance = NA_real_, method = "none", note = paste( + c(notes, paste0("The contrast weighs ", + if (length(notes) > 1L) "these domains" else + "this domain", + ", so it has no standard error either.")), + collapse = " ")) + } + var_out <- weighs(unlist(lapply(declines, function(d) d$any$note))) + jk_decline <- weighs(unlist(lapply(declines, + function(d) d$jackknife$note))) + } + var_out <- var_out %||% + ht_variance_dispatch(parts$design, parts$units, parts$pop, parts$rows, z, + parts$pi, variance, domain_frame(dom, used), ctx, + jk_decline) + out <- finish_estimate(value, var_out, parts, level, df, what = "contrast", + class = "drawn_contrast", alternative = alternative) + gap <- if (is.na(out$variance)) compact_domain_note(parts, dom) + if (!is.null(gap)) out$note <- paste(c(out$note, gap), collapse = " ") + if (any(!parts$respond)) { + out$note <- paste(c(out$note, missing_note(sum(!parts$respond), + length(parts$respond), + parts$y_name)), + collapse = " ") + } + out$weights <- stats::setNames(w[used], labels) + out$estimates <- stats::setNames(est$est[used], labels) + out$what <- what + out$estimator <- if (what == "mean") estimator + out$by <- dom$by + out +} + +#' A contrast weighs `by` domains, so it needs `by` +#' @noRd +check_contrast_by <- function(contrast, by) { + if (!is.null(contrast) && is.null(by)) { + stop("`contrast` weighs the domains of `by`, and `by` is NULL. Pass the ", + "column or columns that define the domains as `by`.", call. = FALSE) + } + invisible(NULL) +} + +#' Check a contrast against the domains, and spread it over them +#' +#' Returns one weight per domain in `dom$levels_in`, 0 for a domain the +#' contrast leaves out. `y_name` is the column `y` names, for the message +#' about a domain with `y` missing in every sampled row, `NULL` for a vector. +#' +#' @noRd +contrast_weights <- function(contrast, dom, y_name = NULL) { + ticks <- function(x) paste0("`", x, "`", collapse = ", ") + if (!is.numeric(contrast) || !length(contrast) || is.null(names(contrast))) { + stop("`contrast` must be a named numeric vector of weights, one per ", + "`by` domain, not ", format_bad(contrast), ". Name each weight ", + "after its domain, as in `contrast = c(a = 1, b = -1)`.", + call. = FALSE) + } + nm <- names(contrast) + if (anyNA(nm) || !all(nzchar(nm))) { + stop("`contrast` has a weight with no name. Name each weight after the ", + "`by` domain it applies to.", call. = FALSE) + } + twice <- unique(nm[duplicated(nm)]) + if (length(twice)) { + stop("`contrast` names ", ticks(twice), " more than once. Give each ", + "domain one weight.", call. = FALSE) + } + bad <- which(!is.finite(contrast)) + if (length(bad)) { + stop("`contrast` gives ", ticks(nm[bad[1]]), " a weight of ", + format(contrast[[bad[1]]]), ". Give every domain a finite weight.", + call. = FALSE) + } + shown <- dom$labels[dom$levels_in] + at <- match(nm, shown) + if (anyNA(at)) { + miss <- nm[is.na(at)] + several <- length(miss) > 1L + blank <- miss[miss %in% dom$labels[dom$blank]] + if (length(blank)) { + stop("`contrast` names ", ticks(blank), ", whose sampled rows all ", + "have ", ticks(y_name %||% "y"), " missing, so ", + if (length(blank) > 1L) "they have" else "it has", + " no estimate under `na_rm = TRUE`. Leave ", + if (length(blank) > 1L) "them" else "it", " out of `contrast`.", + call. = FALSE) + } + empty <- miss[miss %in% dom$labels] + if (length(empty)) { + stop("`contrast` names ", ticks(empty), ", which ", + if (length(empty) > 1L) "have" else "has", " no sampled row and ", + "so no estimate. Leave ", if (length(empty) > 1L) "them" else "it", + " out of `contrast`.", call. = FALSE) + } + stop("`contrast` names ", ticks(miss), ", which ", + if (several) "are not domains" else "is not a domain", " of `by`. ", + "Name the weights after the domains, which are ", + ticks(utils::head(shown, 5L)), more_text(shown), ".", call. = FALSE) + } + if (all(contrast == 0)) { + stop("`contrast` gives every domain a weight of 0. Give at least one ", + "domain a weight other than 0.", call. = FALSE) + } + w <- numeric(length(shown)) + w[at] <- as.numeric(contrast) + w +} + +#' @export +print.drawn_by <- function(x, ...) { + what <- attr(x, "what") + if (is.null(what)) { + # Selecting columns with `[` or subset() keeps the class but drops the + # attributes the heading reads, and the columns it describes may be gone. + print(plain_frame(x), ...) + return(invisible(x)) + } + lead <- attr(x, "lead") %||% if (several_y(x)) "variable" + y_name <- ratio_name(attr(x, "variable"), "y") + label <- if (what == "quantile") { + paste("Quantiles of", y_name) + } else if (what == "ratio") { + paste("Ratio", y_name, "/", ratio_name(attr(x, "x"), "x")) + } else if (what == "total") { + if (is.null(attr(x, "x"))) "Horvitz-Thompson total" else + paste0("Ratio estimate of the total, to `", attr(x, "x"), "`,") + } else if (identical(attr(x, "estimator"), "ht")) { + "Horvitz-Thompson mean" + } else { + "Hajek mean" + } + if (identical(lead, "level")) label <- paste(label, "of", y_name) + # The `by` columns that are domains, and not the variable, level or + # probability each row is for. + domains <- setdiff(attr(x, "by"), + c(lead, if (what == "quantile") "prob")) + rows <- if (is.null(lead)) { + if (length(domains)) "domain" + } else if (length(domains)) { + paste(lead, "and domain") + } else { + lead + } + scale <- unique(attr(x, "ci_scale") %||% "linear") + shown <- if (length(scale) > 1L) { + paste0(setdiff(scale, "linear")[1], " for proportions, ") + } else { + scale_label(scale) + } + cat(label, if (!is.null(rows)) paste0(" by ", rows), " (", + attr(x, "design"), " design, ", + ci_label(attr(x, "level"), attr(x, "alternative")), ", ", + shown, df_label(attr(x, "df")), ")\n", sep = "") + # The standard error is shown; its square adds width and nothing else. + y <- plain_frame(x) + y$variance <- NULL + print(y, digits = 4, row.names = FALSE) + print_unreachable(attr(x, "unreachable"), "these estimates", + attr(x, "unavailable")) + notes <- attr(x, "notes") + notes <- notes[nzchar(notes) & + !grepl("^Variance not requested", notes, useBytes = TRUE)] + if (length(notes)) cat_note(notes) + invisible(x) +} + +#' @export +print.drawn_contrast <- function(x, ...) { + what <- if (identical(x$what, "total")) "Horvitz-Thompson totals" else + if (identical(x$estimator, "ht")) "Horvitz-Thompson means" else + "Hajek means" + est <- vapply(x$estimates, format, character(1), big.mark = ",") + print_estimate(x, "contrast", paste("Contrast of", what), lines = c( + contrast = contrast_label(x$weights), + domains = paste0("`", names(est), "` ", est, collapse = ", ") + )) +} + +#' A contrast's weights as a sum, such as "`a` - `b`", or "a - b" without +#' `quote` +#' @noRd +contrast_label <- function(w, quote = TRUE) { + tick <- if (quote) "`" else "" + terms <- vapply(seq_along(w), function(i) { + a <- abs(w[[i]]) + paste0(if (a != 1) paste0(format(a), " "), tick, names(w)[i], tick) + }, character(1)) + out <- paste0(ifelse(w < 0, "- ", "+ "), terms, collapse = " ") + sub("^- ", "-", sub("^\\+ ", "", out, useBytes = TRUE), useBytes = TRUE) +} + +#' "95% CI", or "95% upper bound" for a one-sided interval +#' @noRd +ci_label <- function(level, alternative) { + paste0(format(100 * level), "% ", switch(alternative %||% "two.sided", + less = "upper bound", + greater = "lower bound", + "CI" + )) +} + +#' The interval's scale, as it leads the bracket after an interval +#' @noRd +scale_label <- function(scale) { + switch(scale %||% "linear", logit = "logit, ", beta = "beta, ", + woodruff = "Woodruff, ", "") +} + +#' A line for frame rows the design could never select +#' +#' `draw()` warns about them by name; this keeps them in view on the +#' estimate, which says nothing about them. `found` is the number of them +#' use_reserves() found unavailable, `NULL` for a sample that used no +#' reserves. Its weights count every frame row not found unavailable as +#' available, those nobody visited included, and a second line says so. +#' +#' @noRd +print_unreachable <- function(n, what, found = NULL) { + if (!isTRUE(n > 0)) return(invisible(NULL)) + cat(" unreachable ", fmt_n(n), " frame row", if (n > 1) "s", + " at probability 0, not covered by ", what, "\n", sep = "") + if (isTRUE(found > 0)) { + cat(" (", fmt_n(found), " found unavailable; rows not ", + "visited are taken as available)\n", sep = "") + } +} + +#' Design effect +#' +#' How much precision the design costs against simple random sampling of the +#' same size (Kish 1965). `deff = 1` means the design is doing as well as a +#' simple random sample from the rows it can reach; above 1 it is doing worse, +#' which is the usual price of clustering; below 1 it is doing better, which is +#' what stratification and probability-proportional-to-size buy you. +#' +#' Read it as an exchange rate on sample size: at `deff = 2`, a sample of 400 +#' carries about as much information as 200 drawn at random. +#' +#' The simple random sample it is measured against is drawn from the rows the +#' design gives a probability above 0, `sum(inclusion_prob(design, frame) > 0)` +#' of them, because those are the rows a total or a Hajek mean estimates +#' over. Rows past `max_items`, outside a region or time window, dropped by +#' `na_rm` or in a stratum allocated no rows are left out. Counting them set +#' an equal-probability sample of 20 from the first 100 rows of a 400-row +#' frame at a design effect of 0.05 for a total, "better than simple random +#' sampling", where the right figure is 1. +#' `survey` measures against the sum of the weights, which is that count for +#' an equal-probability design, and gives the same design effect there. A +#' Horvitz-Thompson mean +#' (`estimator = "ht"`) divides the total by the frame's row count, so its +#' design effect is the total's. +#' +#' The design effect is `NA` when there is no variance, and when `y` takes +#' one value in every sampled row, where there is no spread for a simple +#' random sample to be measured by. It is `NA` too for a mean from +#' `ht_mean(na_rm = TRUE)` with `y` missing in some sampled rows, since the +#' rows with `y` are a domain of the sample, and a domain's design effect is +#' not estimated. +#' +#' A table of domain estimates from `by`, of several variables, of the +#' levels of a factor or of quantiles carries no design effect, and `deff()` +#' refuses it with a message saying so. A contrast's design effect is `NA`, +#' and so is a quantile's from [ht_quantile()]. A ratio from [ht_ratio()], +#' and a total from the ratio estimator, are measured against the same +#' estimator from a simple random sample, through the variance of its +#' linearised residuals, as `survey::svyratio(deff = TRUE)` measures a +#' ratio. +#' +#' `survey` has a `deff()` of its own, and whichever of the two packages is +#' attached last masks the other's. Either one answers for both. This +#' `deff()` is a generic that passes an object it has no method for, such as +#' `survey::svymean(..., deff = TRUE)`, to `survey::deff()`, and `survey`'s +#' generic finds the methods for the estimates made here. +#' +#' @param object A result from [ht_total()], [ht_mean()], [ht_ratio()] or +#' [ht_quantile()], or an object from `survey` that holds a design effect. +#' @param ... Passed to `survey::deff()` for an object from `survey`, such as +#' its `quietly`. Not used for an estimate made here. +#' +#' @return A single number, or `NA` when the design has no variance +#' estimate, `y` is constant in the sample, or the estimate is a mean from +#' `ht_mean(na_rm = TRUE)` with `y` missing in some sampled rows. For an +#' object from `survey`, what `survey::deff()` returns. +#' +#' @references +#' Kish, L. (1965). *Survey Sampling*. Wiley. +#' +#' @examples +#' set.seed(1) +#' # Sites differ from each other, and rows within a cluster are alike -- +#' # exactly the structure that makes stratifying pay and clustering cost. +#' pop <- data.frame( +#' id = 1:400, +#' site = rep(c("a", "b", "c", "d"), each = 100), +#' cl = rep(paste0("c", 1:40), each = 10) +#' ) +#' pop$y <- rep(c(20, 60, 120, 200), each = 100) + round(stats::rnorm(400, 0, 8)) +#' +#' # Stratifying on something that matters buys precision (deff below 1) +#' deff(ht_total(draw(pop, design_stratified("site", n = 40), seed = 1, +#' weights = TRUE), "y")) +#' +#' # Clustering usually costs it (deff above 1) +#' deff(ht_total(draw(pop, design_cluster("cl", n_clusters = 4), seed = 1, +#' weights = TRUE), "y")) +#' +#' @seealso [ht_total()], [ht_mean()], [plan_size()], which takes a design +#' effect as an input. +#' @export +deff <- function(object, ...) UseMethod("deff") + +# Each method is registered twice: for the generic above, and for `survey`'s, +# so whichever `deff()` is found first answers for an estimate made here. + +#' @export +#' @exportS3Method survey::deff +deff.drawn_ht <- function(object, quietly = FALSE, ...) object$deff + +#' @export +#' @exportS3Method survey::deff +deff.drawn_mean <- function(object, quietly = FALSE, ...) object$deff + +#' @export +#' @exportS3Method survey::deff +deff.drawn_contrast <- function(object, quietly = FALSE, ...) object$deff + +#' @export +#' @exportS3Method survey::deff +deff.drawn_ratio <- function(object, quietly = FALSE, ...) object$deff + +#' @export +#' @exportS3Method survey::deff +deff.drawn_by <- function(object, quietly = FALSE, ...) { + if (identical(attr(object, "what"), "quantile")) { + stop("`object` is a table of quantiles, which carry no design effect.", + call. = FALSE) + } + if (identical(attr(object, "lead"), "level")) { + stop("`object` is a table of estimates for the levels of `y`, which ", + "carries no design effect. Call deff() on ht_total() or ht_mean() ", + "with the indicator of one level as `y`.", call. = FALSE) + } + if (several_y(object)) { + stop("`object` is a table of estimates for several variables, which ", + "carries no design effect. Call deff() on ht_total() or ht_mean() ", + "for one variable without `by`.", call. = FALSE) + } + stop("`object` is a table of domain estimates from `by`, which carries ", + "no design effect. Call deff() on ht_total() or ht_mean() without ", + "`by` for the design effect of the whole sample.", call. = FALSE) +} + +#' @export +deff.default <- function(object, ...) { + if (!requireNamespace("survey", quietly = TRUE)) { + stop("`object` has class `", class(object)[1], "`, and deff() reads ", + "the design effect of a result from ht_total() or ht_mean(). For an ", + "object from `survey`, install it with install.packages(\"survey\").", + call. = FALSE) + } + # survey::deff() dispatches from where it is called. Called here, it would + # find this method before its own default and call it again, without end; + # called from an environment over the base one, it finds only its own + # methods. `object` is passed by name, so a warning from `survey` shows + # `object` in its call rather than the whole object deparsed. + env <- new.env(parent = baseenv()) + env$object <- object + do.call(survey::deff, c(list(quote(object)), list(...)), envir = env) +} + +#' Shared argument handling for the estimators +#' +#' `na_rm` is `NULL` for ht_total(), which refuses a missing `y`, and the +#' `na_rm` of ht_mean() otherwise. With `na_rm = TRUE` a missing `y` is +#' allowed: `respond` marks the rows with `y` present, and `y` holds 0 in +#' the others, so a sum over every row is a sum over those rows. +#' +#' The work is split in three so that estimate_several() and ht_ratio() can +#' read the sample's state once and then one or more variables: +#' `prepare_sample()` reads the state and checks `level` and `df`, `add_y()` +#' reads one `y`, and `finish_prepare()` checks `.weight`. +#' +#' @noRd +ht_prepare <- function(sample, y, level, df = NULL, na_rm = FALSE) { + parts <- prepare_sample(sample, level, df) + finish_prepare(add_y(parts, y, na_rm)) +} + +#' The sample's state, before any variable is read +#' @noRd +prepare_sample <- function(sample, level, df = NULL) { + state <- drawn_state(sample) + if (!is.numeric(level) || length(level) != 1L || is.na(level) || + level <= 0 || level >= 1) { + stop("`level` must be a single number strictly between 0 and 1.", + call. = FALSE) + } + if (nrow(sample) == 0L) { + # Possible under Poisson sampling or a systematic start past the end, and + # then a total of 0 (see empty_sample()). A design that reaches no row of + # the frame, and a sample that records no probabilities, give nothing to + # estimate from. + if (is.null(state$pi_all)) { + stop("`sample` has no rows, so there is nothing to estimate from.", + call. = FALSE) + } + if (!any(reachable(state$pi_all))) { + stop("`sample` has no rows, and its design gives every row of the ", + "frame a probability of 0, so there is nothing to estimate from. ", + "Give the design a sample size above 0.", call. = FALSE) + } + } + if (!is.null(df) && (!is.numeric(df) || length(df) != 1L || is.na(df) || + df < 1)) { + stop("`df` must be NULL, Inf or a single number of 1 or more, not ", + format_bad(df, value = TRUE), ". A t interval needs at least one ", + "degree of freedom.", call. = FALSE) + } + # The rows the design can reach: those with a probability above 0 at draw + # time, or none recorded because the sample is conditional on clusters + # that left them out. A sample saved by drawn 0.2.0 has no such record, so + # its count is read from the design's columns and the unreachable rows are + # unknown. `unavailable` counts the rows among them that use_reserves() + # found unavailable, and is NULL for a sample that used no reserves. + pi_all <- state$pi_all + gone <- length(state$design[["unavailable"]]) + list(design = state$design, rows = state$rows, pop = state$pop, + units = state$units, pi_all = pi_all, pi = sample$.prob, + sample = sample, compact = state$compact, + reach = if (is.null(pi_all)) { + reachable_rows(state$design, state$pop) + } else { + sum(reachable(pi_all)) + }, + unreachable = if (is.null(pi_all)) { + NA_integer_ + } else { + sum(!reachable(pi_all)) + }, + unavailable = if (gone > 0L) gone) +} + +#' Read one `y` into the parts of a sample +#' +#' `label` names `y` in the messages: "`y`", or the column with the `y` it +#' came from when `y` names several. +#' +#' @noRd +add_y <- function(parts, y, na_rm, label = "`y`") { + v <- read_variable(parts$sample, y, "y", several = TRUE) + yv <- v$values + missing_y <- is.na(yv) & !is.nan(yv) + if (any(missing_y) && !isTRUE(na_rm)) { + stop(missing_y_message(parts$sample, missing_y, na_rm, label), + call. = FALSE) + } + if (length(missing_y) && all(missing_y)) { + stop(label, " is missing in every one of the ", length(missing_y), " ", + "sampled rows, so there is no mean to estimate.", call. = FALSE) + } + need <- "A total or mean needs a finite `y` for every sampled row." + check_finite_values(yv, missing_y, label, need) + yv[missing_y] <- 0 + parts$y <- yv + parts$respond <- !missing_y + parts$y_name <- v$name + parts$y_logical <- v$logical + parts$y_single <- v$single + parts +} + +#' Check `.weight` once the variables are read +#' @noRd +finish_prepare <- function(parts) { + # drawn_state() has checked `.prob`, against the probabilities recorded at + # draw time or, for a sample saved by drawn 0.2.0, against the design. + warn_weight_edited(parts$sample) + parts +} + +#' A variable given as a column name or as a vector +#' +#' Returns its `values`, numeric with a logical turned to 0 and 1, whether +#' it was `logical`, its `name`, `NULL` for a vector, and whether it was a +#' `single` number standing for every row. `several` says +#' whether `arg` may also name several columns, which the caller reads one +#' at a time, and `logical` whether a logical variable is accepted. +#' +#' @noRd +read_variable <- function(sample, y, arg, several = FALSE, logical = TRUE) { + name <- NULL + v <- y + if (is.character(y) && length(y) == 1L && !is.na(y)) { + if (!y %in% names(sample)) { + stop("`sample` has no column `", y, "`.", call. = FALSE) + } + name <- y + v <- sample[[y]] + if (!is.numeric(v) && !(logical && is.logical(v))) { + stop("`", arg, "` names `", y, "`, ", a_class(v), " column of ", + "`sample`. Name a numeric", if (logical) " or logical", + " column.", call. = FALSE) + } + } + # A single number stands for that value in every row, so a total of 1 + # estimates the number of frame rows. + single <- is.null(name) && is.numeric(v) && length(v) == 1L + if (single) v <- rep(v, nrow(sample)) + if (!(is.numeric(v) || (logical && is.logical(v))) || + length(v) != nrow(sample)) { + stop(variable_forms(y, arg, several, sample), call. = FALSE) + } + was_logical <- is.logical(v) + if (was_logical) v <- as.numeric(v) + list(values = v, logical = was_logical, name = name, single = single) +} + +#' What `arg` must be, and what it was +#' @noRd +variable_forms <- function(y, arg, several, sample) { + forms <- if (several) { + "one column name, several column names, or a numeric vector or factor" + } else { + "one column name or a numeric vector" + } + what <- if (is.null(y)) { + "NULL" + } else if (is.character(y) && length(y) == 1L && is.na(y)) { + "NA, a missing column name" + } else if (is.character(y) && length(y) > 1L) { + paste0("a character vector of ", length(y), " values, ", + if (anyNA(y) || !all(nzchar(y))) { + "some of them missing or empty" + } else { + "none of them a column of `sample`" + }) + } else if (is.atomic(y)) { + paste0(a_class(y), " vector of length ", length(y), + if (length(y) != nrow(sample)) { + paste0(", and `sample` has ", nrow(sample), " rows") + }) + } else { + a_class(y) + } + # A character vector as long as the sample is more likely categories than + # column names. + hint <- if (several && is.character(y) && length(y) == nrow(sample)) { + " For the share or count of each of its values, pass it as a factor." + } + paste0("`", arg, "` must be ", forms, " as long as `sample`. It is ", + what, ".", hint) +} + +#' Refuse a variable that is infinite or `NaN` in some sampled row +#' +#' `label` names the variable and `need` is the sentence saying what needs +#' it finite. +#' +#' @noRd +check_finite_values <- function(v, missing, label, need) { + bad <- which(!is.finite(v) & !missing) + if (length(bad)) { + stop(label, " is ", paste(unique(as.character(v[bad])), collapse = " or "), + " in ", length(bad), " row(s) of `sample`: ", format_rows(bad), + ". ", need, call. = FALSE) + } + invisible(NULL) +} + +#' Why a missing `y` is refused, and what to do instead +#' +#' A total over the rows with `y` present counts the others as 0, so it is +#' low by about their share of the weight. ht_total() (`na_rm = NULL`) says +#' so; ht_mean() points to its `na_rm`. +#' +#' @noRd +missing_y_message <- function(sample, missing, na_rm, label = "`y`") { + head <- paste0(label, " is missing in ", sum(missing), " of the ", + length(missing), " sampled rows. ") + see <- "See \"Missing values and nonresponse\" in ?ht_total." + if (!is.null(na_rm)) { + return(paste0(head, "Set `na_rm = TRUE` to estimate the mean over the ", + "rows with `y` present, as a domain of the sample, which ", + "assumes the values are missing completely at random. ", + see)) + } + w <- 1 / sample$.prob + share <- sum(w[missing]) / sum(w) + paste0(head, "A total over the rows with `y` present counts the others ", + "as 0, so it is low by about their share of the weight", + if (is.finite(share)) { + paste0(", ", format(signif(100 * share, 2)), "% here") + }, ". ht_mean(na_rm = TRUE) estimates the mean over the rows with ", + "`y` present, with `by` for domains, as survey's `na.rm = TRUE` ", + "does after as_svydesign(). For a total, adjust the weights for ", + "nonresponse within weighting classes and estimate from them with ", + "as_svydesign(). ", see) +} + +#' Warn when `.weight` is no longer `1 / .prob` +#' +#' ht_total() and ht_mean() estimate from the design probabilities in `.prob`, +#' and as_svydesign() hands `survey` the `.weight` column. After a nonresponse +#' adjustment or trimming written into `.weight`, the two give different +#' answers, and the reason should be said once rather than found by comparing +#' them. +#' +#' @noRd +warn_weight_edited <- function(sample) { + w <- sample[[".weight"]] + if (is.null(w) || !nrow(sample)) return(invisible(NULL)) + design_w <- 1 / sample$.prob + edited <- if (is.numeric(w)) sum(!same_prob(w, design_w)) else nrow(sample) + if (edited == 0L) return(invisible(NULL)) + warn_drawn(paste0( + "`sample` has `.weight` values that differ from 1 / `.prob` in ", edited, + " row(s). ht_total() and ht_mean() use the design probabilities in ", + "`.prob` and ignore `.weight`; estimate from adjusted weights with ", + "as_svydesign()."), "drawn_weight_edited") +} + +#' Warn that dplyr groups play no part in an estimate +#' +#' ht_total() and ht_mean() estimate over the whole sample, and so would a +#' grouped sample without this: the groups are ignored and one overall figure +#' comes back where the caller may expect one per group. +#' +#' @noRd +warn_grouped <- function(sample, fun) { + if (!inherits(sample, "grouped_df")) return(invisible(NULL)) + vars <- setdiff(names(attr(sample, "groups", exact = TRUE)), ".rows") + hint <- if (length(vars)) { + paste0("`by = ", if (length(vars) > 1L) "c(", + paste0("\"", vars, "\"", collapse = ", "), + if (length(vars) > 1L) ")", "`") + } else { + "`by`" + } + warn_drawn(paste0( + "`sample` is grouped with dplyr::group_by(), which ", fun, "() ignores, ", + "so this is one estimate over the whole sample. Use ", hint, " for an ", + "estimate per group."), "drawn_grouped_df") +} + +#' A confidence interval from an estimate, a variance and degrees of freedom +#' +#' `scale` is `"linear"`, `"logit"` or `"beta"`; `logit = TRUE` is short for +#' the second. `alternative` gives a two-sided interval or a one-sided bound, +#' `"less"` an upper bound and `"greater"` a lower one, as in +#' [stats::t.test()]. The open end of a bound is `-Inf` or `Inf`, or 0 or 1 +#' for a proportion. A one-sided bound at `level` is the end of a two-sided +#' interval at `1 - 2 * (1 - level)`. +#' +#' The beta interval (Korn and Graubard 1998) is Clopper-Pearson's at an +#' effective sample size of `p(1 - p) / v`, capped at `n` and scaled by +#' `(qt(a, n - 1) / qt(a, df))^2`, the design's degrees of freedom against +#' those of a simple random sample of `n`. With `a` the tail probability this +#' is `survey::svyciprop(method = "beta")` when the cap does not bind. The +#' scaled size is capped at `n` again, which binds when `df` passes `n - 1`, +#' as a domain's can. Without it the scaling raised a domain's effective size +#' past `n`, giving a narrower interval than Clopper-Pearson's over the +#' domain's own rows: an upper bound of 0.155 for 0 of 20, where +#' Clopper-Pearson gives 0.168. At an estimate of 0 or 1 the variance is 0 +#' and says nothing, and the effective sample size is `n`. That interval +#' needs no variance, so it is given even when the design leaves fewer than +#' 1 degree of freedom, without the scaling, which is undefined there. `n` +#' counts the sampled rows below certainty behind the estimate; with none, +#' the estimate is exact. +#' +#' @noRd +interval <- function(est, v, level, df, logit = FALSE, + alternative = "two.sided", + scale = if (logit) "logit" else "linear", n = NA_real_) { + if (!is.finite(v) || v < 0) return(c(NA_real_, NA_real_)) + proportion <- scale %in% c("logit", "beta") + open <- if (proportion) c(0, 1) else c(-Inf, Inf) + bound <- function(lo, hi) { + switch(alternative, less = c(open[1], hi), greater = c(lo, open[2]), + c(lo, hi)) + } + edge <- est <= 0 || est >= 1 + # A variance of 0 is an exact estimate, whatever the degrees of freedom, + # except for a proportion of 0 or 1, whose variance is 0 because no row of + # the other kind was drawn. + beta_edge <- scale == "beta" && edge && isTRUE(n >= 1) + exact <- v == 0 && !beta_edge + if (exact) return(bound(est, est)) + few_df <- is.finite(df) && df < 1 + if (few_df && !beta_edge) return(c(NA_real_, NA_real_)) + # The tail probability on each side that has one. + a <- if (alternative == "two.sided") (1 - level) / 2 else 1 - level + quantile <- function(p, df) { + if (is.finite(df)) stats::qt(p, df) else stats::qnorm(p) + } + if (scale == "beta" && est >= 0 && est <= 1) { + n_eff <- if (edge) n else min(n, est * (1 - est) / v) + if (n >= 2 && !few_df) { + n_eff <- min(n, n_eff * (stats::qt(a, n - 1) / quantile(a, df))^2) + } + x <- n_eff * est + lo <- if (x <= 0) 0 else stats::qbeta(a, x, n_eff - x + 1) + hi <- if (x >= n_eff) 1 else stats::qbeta(1 - a, x + 1, n_eff - x) + return(bound(lo, hi)) + } + q <- quantile(1 - a, df) + if (proportion && !edge) { + # A proportion's interval on the logit scale, by the delta method, then + # back: it cannot leave [0, 1], and near 0 or 1 it is asymmetric the way + # the sampling distribution is. This is survey::svyciprop()'s "xlogit". + se_logit <- sqrt(v) / (est * (1 - est)) + ends <- stats::plogis(stats::qlogis(est) + c(-1, 1) * q * se_logit) + return(bound(ends[1], ends[2])) + } + if (proportion) open <- c(-Inf, Inf) + bound(est - q * sqrt(v), est + q * sqrt(v)) +} + +#' The interval for a total or mean, and the scale it was formed on +#' +#' A mean that is not a proportion gets the symmetric interval. A proportion +#' gets `ci_method`'s, except that an estimate of exactly 0 or 1 gets the beta +#' interval whatever `ci_method` says: its variance is 0, and a logit interval +#' around it has no width. `pi_i` holds the probabilities of the sampled rows +#' behind the estimate, the domain's for a domain; those below certainty are +#' the beta interval's `n`, and with none of them the estimate is exact. +#' +#' `n` is that count, for a caller that holds it in place of `pi_i`. +#' +#' Returns the interval, its `scale`, `edge` (the beta interval was used for +#' an estimate of 0 or 1) and `exact`. +#' +#' @noRd +ci_for <- function(est, v, level, df, alternative = "two.sided", + proportion = FALSE, ci_method = "logit", pi_i = NULL, + n = sum(!is_certain(pi_i))) { + if (!proportion) { + return(list(ci = interval(est, v, level, df, alternative = alternative), + scale = "linear", edge = FALSE, exact = FALSE)) + } + edge <- is.finite(v) && v >= 0 && (est == 0 || est == 1) && n >= 1 + scale <- if (edge) "beta" else ci_method + # A Horvitz-Thompson mean can pass 1. Its interval is then symmetric. + if (est < 0 || est > 1) scale <- "linear" + list(ci = interval(est, v, level, df, alternative = alternative, + scale = scale, n = n), + scale = scale, edge = edge, exact = n == 0) +} + +#' Why a proportion of 0 or 1 has a beta interval +#' @noRd +edge_note <- function(est = NULL, n = NULL, domains = NULL, + ci_method = "logit", certain = FALSE) { + why <- if (ci_method == "logit") { + ", and a logit interval around it would have no width" + } else { + "" + } + below <- if (certain) " below certainty" else "" + if (is.null(domains)) { + return(paste0( + "The estimate is ", format(est), ", with an estimated variance of 0", + why, ". The interval is Korn and Graubard's beta interval, with the ", + fmt_n(n), " sampled row", if (n > 1) "s", below, " as its effective ", + "sample size.")) + } + several <- length(domains) > 1L + paste0("The domain", if (several) "s", " ", + paste0("`", domains, "`", collapse = ", "), + if (several) " have" else " has", + " a proportion of 0 or 1, with an estimated variance of 0. ", + if (several) "Their intervals are" else "Its interval is", + " Korn and Graubard's beta interval", if (several) "s", + ", with the domain's sampled rows", below, " as the effective ", + "sample size.") +} + +#' Assemble an estimate, its interval, and its design effect +#' +#' `divide_by` is what a mean divides its Horvitz-Thompson total by, for the +#' design effect: see `deff_value()`. `variable` is the name of `y`, `NULL` +#' for a vector, and `n_random` the sampled rows below certainty, which +#' `confint()` needs to form a beta interval at another level. +#' +#' @noRd +finish_estimate <- function(est, var_out, parts, level, df, what, class, + y = NULL, proportion = FALSE, ci_method = "logit", + alternative = "two.sided", + divide_by = parts$reach) { + v <- var_out$variance + se <- if (is.na(v) || v < 0) NA_real_ else sqrt(v) + ci <- ci_for(est, v, level, df, alternative, proportion, ci_method, + parts$pi) + note <- var_out$note + if (!is.na(se) && anyNA(ci$ci)) { + note <- paste(c(note, df_note(df)), collapse = " ") + } + if (proportion && !is.null(parts$proportion_note)) { + note <- paste(c(note, parts$proportion_note), collapse = " ") + } + if (ci$edge) { + certain <- is_certain(parts$pi) + note <- paste(c(note, edge_note(est, sum(!certain), ci_method = ci_method, + certain = any(certain))), + collapse = " ") + } + n <- nrow(parts$sample) + + out <- list(variable = parts$y_name, variance = v, se = se, ci = ci$ci, + level = level, alternative = alternative, df = df, n = n, + n_random = sum(!is_certain(parts$pi)), + ci_scale = ci$scale, design = design_type(parts$design), + deff = if (is.null(y)) NA_real_ else + deff_value(v, y, parts$pi, parts$reach, n, what, divide_by), + method = var_out$method %||% "analytic", note = note, + unreachable = parts$unreachable) + out$unavailable <- parts$unavailable + out[[what]] <- est + structure(out, class = class) +} + +#' Why an estimate with a standard error has no interval +#' +#' `ht_prepare()` refuses a `df` below 1 from the caller, so a missing +#' interval with a finite standard error comes from the design's degrees of +#' freedom. +#' +#' @noRd +df_note <- function(df) { + paste0("The design leaves ", format(df), " degrees of freedom, the number ", + "of primary sampling units below certainty less the number of strata ", + "holding them, so there is no t interval. Pass `df` to set the ", + "degrees of freedom, or `df = Inf` for a normal interval.") +} + +#' Variance under simple random sampling of the same size, for comparison +#' +#' The population variance is estimated from the sample with design weights, so +#' this works from a sample of any design. +#' +#' The denominator is `sum(w) * (n - 1) / n`, not `sum(w) - 1`. Under simple +#' random sampling `sum(w * (y - mu)^2)` has expectation `(N/n)(n-1)S^2`, so +#' dividing by `N - 1` leaves the estimate short by a factor of `n(N-1)/(N(n-1))` +#' -- and the design effect, which divides by it, long by the reciprocal. That +#' put a plain simple random sample of 10 at a design effect of 1.11, printed as +#' "worse than simple random sampling". This form is exactly unbiased there. +#' +#' `N` is the number of rows the design can reach, those with a probability +#' above 0. The simple random sample is drawn from them, since they are the +#' population a total or a Hajek mean estimates over; `survey` uses the sum of +#' the weights, which is the same count for an equal-probability design. +#' `divide_by` is what a mean divides its Horvitz-Thompson total by: `N` for +#' the Hajek mean, and the frame's row count for the Horvitz-Thompson mean, +#' whose design effect is then the total's. +#' +#' A constant `y` gives `NA`. Its spread is 0, and computed it came out as a +#' rounding error, which put a total's design effect at `1e32`. +#' +#' @noRd +deff_value <- function(v, y, pi_i, N, n, what, divide_by = N) { + if (!is.finite(v) || v <= 0 || n < 2L || !is.finite(N) || N < 2L) { + return(NA_real_) + } + if (all(y == y[1])) return(NA_real_) + w <- 1 / pi_i + mu <- sum(w * y) / sum(w) + s2 <- sum(w * (y - mu)^2) * n / (sum(w) * (n - 1)) + if (!is.finite(s2) || s2 <= 0) return(NA_real_) + fpc <- max(0, 1 - n / N) + v_srs <- if (what == "mean") { + (N / divide_by)^2 * s2 / n * fpc + } else { + N^2 * s2 / n * fpc + } + if (!is.finite(v_srs) || v_srs <= 0) return(NA_real_) + v / v_srs +} + +#' @export +print.drawn_mean <- function(x, ...) { + lines <- if (isTRUE(x$n_missing > 0)) { + c(missing = paste0(fmt_n(x$n_missing), " sampled row", + if (x$n_missing > 1) "s", " left out, assumed missing ", + "completely at random")) + } + print_estimate(x, "mean", if (identical(x$estimator, "ht")) + "Horvitz-Thompson mean" else "Hajek mean", lines = lines) +} + +#' @noRd +df_label <- function(df) { + if (is.null(df) || !is.finite(df)) "normal" else + paste0("t, ", format(signif(df, 4)), " df") +} + +#' The variance method as printed: the value `method` holds, which a `by` +#' table shows in its `method` column, and whether it is an approximation +#' @noRd +method_label <- function(m) { + m <- m %||% "analytic" + if (m %in% c("deville", "successive difference", "local mean")) { + paste0(m, ", an approximation") + } else { + m + } +} + +#' Print a single estimate +#' +#' `lines` are printed between the heading and the estimate, each after its +#' name. +#' +#' @noRd +print_estimate <- function(x, field, label, lines = NULL) { + cat(label, " (", x$design, " design, n = ", x$n, ")\n", sep = "") + for (nm in names(lines)) { + cat(" ", formatC(nm, width = -8), " ", lines[[nm]], "\n", sep = "") + } + cat(" estimate ", format(x[[field]], big.mark = ","), "\n", sep = "") + if (is.na(x$se)) { + cat(" se NA\n") + } else { + cat(" se ", format(x$se, big.mark = ","), " (", + method_label(x$method), ")\n", sep = "") + if (!anyNA(x$ci)) { + alt <- x$alternative %||% "two.sided" + cat(" ", ci_label(x$level, alt), " ", + switch(alt, + less = format(x$ci[2], big.mark = ","), + greater = format(x$ci[1], big.mark = ","), + paste0(format(x$ci[1], big.mark = ","), " to ", + format(x$ci[2], big.mark = ",")) + ), " (", scale_label(x$ci_scale), df_label(x$df), ")\n", sep = "") + } + if (is.finite(x$deff)) { + cat(" deff ", signif(x$deff, 3), " (", + if (x$deff > 1.05) "worse than" else if (x$deff < 0.95) "better than" + else "about the same as", " simple random sampling)\n", sep = "") + } + } + print_unreachable(x$unreachable, "this estimate", x$unavailable) + # A standard error of 0 always has a reason worth stating: rows taken with + # certainty, a constant `y`, or a proportion of 0 or 1. So does a + # proportion's interval, whose shape can rest on the sampled values. + if (!is.null(x$note) && (is.na(x$se) || x$se == 0 || + !identical(x$method, "analytic") || + anyNA(x$ci) || + !identical(x$ci_scale %||% "linear", "linear"))) { + cat_note(x$note) + } + invisible(x) +} + +#' Print a note, wrapped and indented, after one blank line +#' @noRd +cat_note <- function(text) { + cat("\n", paste0(strwrap(text, prefix = " "), collapse = "\n"), "\n", + sep = "") +} + +#' A `by` table without its classes and attributes +#' @noRd +plain_frame <- function(x) { + attributes(x) <- attributes(x)[c("names", "row.names")] + class(x) <- "data.frame" + x +} + +# ---- the estimate as numbers ---------------------------------------------- +# +# coef(), vcov(), confint(), as.data.frame() and tidy() for the four kinds of +# estimate. survey::SE() and survey::cv() call vcov() and coef(), so they work +# through these. + +#' The field that holds a single estimate +#' @noRd +estimate_field <- function(x) { + if (inherits(x, "drawn_ht")) "total" else + if (inherits(x, "drawn_mean")) "mean" else + if (inherits(x, "drawn_ratio")) "ratio" else + if (inherits(x, "drawn_quantile")) "quantile" else "contrast" +} + +#' What coef() names each estimate +#' +#' A total or mean is named after `y`, or "total" or "mean" when `y` was a +#' vector; a ratio as "y/x", as `survey::svyratio()` names it; a contrast by +#' its weights, as in "a - b"; and each domain of a `by` table as `contrast` +#' names it, after its variable when the table holds several. +#' +#' @noRd +estimate_names <- function(x) { + if (inherits(x, "drawn_by")) return(domain_names(x)) + if (inherits(x, "drawn_contrast")) { + return(contrast_label(x$weights, quote = FALSE)) + } + if (inherits(x, "drawn_ratio")) { + return(paste0(x$variable %||% "y", "/", x$x %||% "x")) + } + x$variable %||% estimate_field(x) +} + +#' Each row's domain, named as `contrast` names it, such as "a . east" +#' @noRd +domain_names <- function(x) { + key <- group_key(x, attr(x, "by")) + group_label(levels(key))[as.integer(key)] +} + +#' Refuse a `by` table that lost the attributes the methods read +#' +#' Selecting columns with `[` or subset() keeps the class and drops them; +#' selecting rows keeps them. +#' +#' @noRd +check_by_table <- function(x) { + what <- attr(x, "what") + by <- attr(x, "by") + if (is.null(what) || is.null(by) || !all(c(by, what) %in% names(x))) { + stop("`object` does not carry the attributes of a `by` table, which ", + "selecting columns with `[` or subset() drops. Use the table ", + "ht_total() or ht_mean() returned, or select rows only.", + call. = FALSE) + } + invisible(x) +} + +#' @noRd +check_ci_level <- function(level, arg = "level") { + if (!is.numeric(level) || length(level) != 1L || is.na(level) || + level <= 0 || level >= 1) { + stop("`", arg, "` must be a single number strictly between 0 and 1, not ", + format_bad(level, value = TRUE), ".", call. = FALSE) + } + level +} + +#' Whether `level` is the level an interval was formed at +#' @noRd +same_level <- function(level, stored) { + !is.null(stored) && abs(level - stored) < 1e-12 +} + +#' Intervals as confint() returns them: a row per estimate, and columns named +#' by the probability at each end +#' @noRd +ci_matrix <- function(lo, hi, names, level, alternative, parm = NULL) { + p <- switch(alternative %||% "two.sided", + less = c(0, level), + greater = c(1 - level, 1), + c((1 - level) / 2, 1 - (1 - level) / 2) + ) + out <- matrix(c(lo, hi), ncol = 2L, dimnames = list(names, paste( + format(100 * p, trim = TRUE, scientific = FALSE, digits = 3), "%"))) + if (is.null(parm)) return(out) + if (is.numeric(parm)) parm <- names[parm] + out[parm, , drop = FALSE] +} + +#' The interval of a total, mean or contrast at `level` +#' +#' The stored one at its own level. At another, it is formed again by +#' `interval()` on the estimate's scale, with the design's degrees of freedom +#' and, for a beta interval, the sampled rows below certainty. +#' +#' @noRd +single_ci <- function(x, level) { + if (same_level(level, x$level)) return(x$ci) + if (inherits(x, "drawn_quantile")) { + if (is.null(x$steps)) { + stop("`object` does not hold the distribution function its interval ", + "needs at another level. Estimate again with `level = ", + format(level), "`.", call. = FALSE) + } + return(woodruff(x$steps, x$quantile, x$cdf, x$cdf_se^2, level, + x$df)$ci) + } + scale <- x$ci_scale %||% "linear" + if (scale == "beta" && is.null(x$n_random)) { + stop("`object` does not hold the sample size its beta interval needs at ", + "another level. Estimate again with `level = ", format(level), "`.", + call. = FALSE) + } + interval(x[[estimate_field(x)]], x$variance, level, x$df, + alternative = x$alternative %||% "two.sided", scale = scale, + n = x$n_random %||% NA_real_) +} + +#' The intervals of a `by` table at `level`, a row per domain +#' @noRd +by_ci <- function(x, level) { + if (same_level(level, attr(x, "level"))) { + return(cbind(x$ci_lower, x$ci_upper)) + } + if (identical(attr(x, "what"), "quantile")) return(quantile_by_ci(x, level)) + est <- x[[attr(x, "what")]] + v <- if ("variance" %in% names(x)) x$variance else x$se^2 + scale <- row_scales(x) + proportion <- scale %in% c("logit", "beta") + n <- if (any(proportion)) unname(attr(x, "n_random")[domain_names(x)]) + if (any(proportion) && (is.null(n) || anyNA(n[proportion]))) { + stop("`object` does not hold the sample sizes its intervals for a ", + "proportion need at another level. Estimate again with `level = ", + format(level), "`.", call. = FALSE) + } + out <- vapply(seq_along(est), function(i) { + ci_for(est[i], v[i], level, attr(x, "df"), + attr(x, "alternative") %||% "two.sided", proportion[i], scale[i], + n = n[i])$ci + }, numeric(2)) + t(out) +} + +#' The interval scale of each row of a `by` table +#' +#' One value for the whole table, or, for a table of several variables of +#' which some are proportions, one per row, named by domain_names(). +#' +#' @noRd +row_scales <- function(x) { + scale <- attr(x, "ci_scale") %||% "linear" + if (length(scale) == 1L) return(rep(scale, nrow(x))) + unname(scale[domain_names(x)]) +} + +#' @export +coef.drawn_ht <- function(object, ...) { + stats::setNames(object[[estimate_field(object)]], estimate_names(object)) +} + +#' @export +coef.drawn_mean <- function(object, ...) coef.drawn_ht(object) + +#' @export +coef.drawn_contrast <- function(object, ...) coef.drawn_ht(object) + +#' @export +coef.drawn_ratio <- function(object, ...) coef.drawn_ht(object) + +#' @export +coef.drawn_by <- function(object, ...) { + check_by_table(object) + stats::setNames(object[[attr(object, "what")]], domain_names(object)) +} + +#' @export +vcov.drawn_ht <- function(object, ...) { + nm <- estimate_names(object) + matrix(object$variance %||% NA_real_, 1L, 1L, dimnames = list(nm, nm)) +} + +#' @export +vcov.drawn_mean <- function(object, ...) vcov.drawn_ht(object) + +#' @export +vcov.drawn_contrast <- function(object, ...) vcov.drawn_ht(object) + +#' @export +vcov.drawn_ratio <- function(object, ...) vcov.drawn_ht(object) + +# The covariances between domains are not estimated, so the off-diagonal +# entries are NA, except 0 between domains of a stratified design that share +# no stratum. A difference of domains needs `contrast`. The table holds its +# matrix in its `vcov` attribute, with the covariances between several +# variables within each domain, matched to the rows by name, so that it +# follows a selection of rows. A table without one, such as one of +# quantiles, has its variances alone. + +#' @export +vcov.drawn_by <- function(object, ...) { + check_by_table(object) + nm <- domain_names(object) + full <- attr(object, "vcov") + if (!is.null(full) && all(nm %in% rownames(full))) { + return(full[nm, nm, drop = FALSE]) + } + v <- if ("variance" %in% names(object)) object$variance else object$se^2 + between_domains(v, seq_along(v), NULL, nm) +} + +#' @export +confint.drawn_ht <- function(object, parm, level = object$level, ...) { + check_ci_level(level) + ci <- single_ci(object, level) + ci_matrix(ci[1], ci[2], estimate_names(object), level, object$alternative, + if (!missing(parm)) parm) +} + +#' @export +confint.drawn_mean <- function(object, parm, level = object$level, ...) { + confint.drawn_ht(object, parm, level) +} + +#' @export +confint.drawn_contrast <- function(object, parm, level = object$level, ...) { + confint.drawn_ht(object, parm, level) +} + +#' @export +confint.drawn_ratio <- function(object, parm, level = object$level, ...) { + confint.drawn_ht(object, parm, level) +} + +#' @export +confint.drawn_by <- function(object, parm, level = attr(object, "level"), + ...) { + check_by_table(object) + check_ci_level(level) + ci <- by_ci(object, level) + ci_matrix(ci[, 1], ci[, 2], domain_names(object), level, + attr(object, "alternative"), if (!missing(parm)) parm) +} + +#' One row for a total, mean or contrast +#' @noRd +single_frame <- function(x, row.names = NULL) { + out <- data.frame(variable = x$variable %||% NA_character_, + stringsAsFactors = FALSE) + if (inherits(x, "drawn_contrast")) { + out$domains <- contrast_label(x$weights, quote = FALSE) + } + if (inherits(x, "drawn_ratio")) out$x <- x$x %||% NA_character_ + if (inherits(x, "drawn_quantile")) out$prob <- x$prob + out$n <- x$n + out[[estimate_field(x)]] <- x[[estimate_field(x)]] + out$variance <- x$variance + out$se <- x$se + out$ci_lower <- x$ci[1] + out$ci_upper <- x$ci[2] + out$level <- x$level + out$df <- x$df + out$deff <- x$deff + out$method <- x$method + if (!is.null(row.names)) row.names(out) <- row.names + out +} + +#' @export +as.data.frame.drawn_ht <- function(x, row.names = NULL, optional = FALSE, + ...) { + single_frame(x, row.names) +} + +#' @export +as.data.frame.drawn_mean <- function(x, row.names = NULL, optional = FALSE, + ...) { + single_frame(x, row.names) +} + +#' @export +as.data.frame.drawn_contrast <- function(x, row.names = NULL, + optional = FALSE, ...) { + single_frame(x, row.names) +} + +#' @export +as.data.frame.drawn_ratio <- function(x, row.names = NULL, optional = FALSE, + ...) { + single_frame(x, row.names) +} + +#' @export +as.data.frame.drawn_by <- function(x, row.names = NULL, optional = FALSE, + ...) { + out <- plain_frame(x) + if (!is.null(row.names)) row.names(out) <- row.names + out +} + +#' The columns of tidy(): `term`, `estimate`, `std.error`, and the interval +#' with `conf.int = TRUE` +#' @noRd +tidy_frame <- function(term, estimate, se, ci = NULL) { + out <- data.frame(term = term, estimate = estimate, std.error = se, + stringsAsFactors = FALSE) + if (!is.null(ci)) { + out$conf.low <- ci[, 1] + out$conf.high <- ci[, 2] + } + out +} + +#' @exportS3Method generics::tidy +tidy.drawn_ht <- function(x, conf.int = FALSE, conf.level = x$level, ...) { + ci <- if (isTRUE(conf.int)) { + check_ci_level(conf.level, "conf.level") + matrix(single_ci(x, conf.level), 1L) + } + tidy_frame(estimate_names(x), x[[estimate_field(x)]], x$se, ci) +} + +#' @exportS3Method generics::tidy +tidy.drawn_mean <- function(x, conf.int = FALSE, conf.level = x$level, ...) { + tidy.drawn_ht(x, conf.int, conf.level) +} + +#' @exportS3Method generics::tidy +tidy.drawn_contrast <- function(x, conf.int = FALSE, conf.level = x$level, + ...) { + tidy.drawn_ht(x, conf.int, conf.level) +} + +#' @exportS3Method generics::tidy +tidy.drawn_ratio <- function(x, conf.int = FALSE, conf.level = x$level, ...) { + tidy.drawn_ht(x, conf.int, conf.level) +} + +#' @exportS3Method generics::tidy +tidy.drawn_by <- function(x, conf.int = FALSE, + conf.level = attr(x, "level"), ...) { + check_by_table(x) + what <- attr(x, "what") + ci <- if (isTRUE(conf.int)) { + check_ci_level(conf.level, "conf.level") + by_ci(x, conf.level) + } + by <- attr(x, "by") + term <- if (several_y(x)) { + by <- setdiff(by, "variable") + x$variable + } else if (what == "ratio") { + rep(paste0(attr(x, "variable") %||% "y", "/", attr(x, "x") %||% "x"), + nrow(x)) + } else { + rep(attr(x, "variable") %||% what, nrow(x)) + } + out <- tidy_frame(term, x[[what]], x$se, ci) + if (!length(by)) return(out) + cbind(plain_frame(x)[by], out) } diff --git a/R/inclusion.R b/R/inclusion.R index 1ccba2e..2b2373a 100644 --- a/R/inclusion.R +++ b/R/inclusion.R @@ -16,62 +16,104 @@ #' \tabular{ll}{ #' [design_simple()] \tab `n / N` \cr #' [design_stratified()] \tab `n_h / N_h` within each stratum \cr -#' [design_systematic()] \tab `1 / interval`, for every row, exactly \cr -#' [design_cluster()] \tab `n_clusters / N_clusters` \cr -#' [design_multistage()] \tab `(n_clusters / N_clusters) * (n_h / N_h)`, when the per-cluster take is constant \cr -#' [design_weighted()] \tab `n * p_i` for the `"systematic"` and `"poisson"` methods \cr +#' [design_systematic()] \tab `1 / interval` with a random `start`, or `n / N` with `n`, for every row walked, exactly \cr +#' [design_cluster()] \tab `n_clusters / N_clusters`; with `balanced = TRUE`, that times the cluster's average take over its size, worked out exactly (see [design_cluster()]) \cr +#' [design_multistage()] \tab `(n_clusters / N_clusters) * (n_h / N_h)`, when the per-cluster take `n_h` is constant; with replacement, `(n_clusters / N_clusters) * (1 - (1 - 1 / N_h)^n_h)`; with `size`, the cluster's `pi_h = n_clusters * M_h / sum(M)` in place of `n_clusters / N_clusters` \cr +#' [design_weighted()] \tab `n * p_i` for the `"systematic"` and `"poisson"` methods, with rows past 1 taken with certainty and the rest rescaled to sum to `n`; with `strata`, `n_h * p_i` within each stratum \cr #' [design_certainty()] \tab `1` above the threshold, `rest`'s own below it \cr #' [design_reservoir()] \tab `n / min(N, max_items)`, and `0` past `max_items` \cr #' [design_temporal()] \tab `per_interval / N_bucket` within each interval \cr #' [design_spatial()] \tab `n / N_in_region` \cr -#' [design_spread()] \tab `n / N`, or `n * p_i` with a `size` column \cr +#' [design_spread()] \tab `n / N`, or `n * p_i` with a `size` column; with `strata`, the same within each stratum \cr #' } #' -#' Five cases have no closed form, and the package refuses to invent one: +#' A design with `reserve` gives the probabilities of its main sample, which +#' the reserves do not change. The design of a sample from [use_reserves()] +#' gives `n / (N - u)`, and `0` for the `u` rows found unavailable. +#' +#' Four cases have no closed form, and the package refuses to invent one: #' -#' * `design_cluster(balanced = TRUE)` — the per-cluster take is the smallest -#' *selected* cluster's size, which is itself random. Simulation on clusters of -#' 2/4/6/8 gives 0.50, 0.41, 0.34, 0.25, against the 0.50 a naive -#' `n_clusters / N_clusters` would claim for every row. #' * `design_multistage(allocation = "proportional")` — the stage-two allocation #' depends on which clusters were selected. Simulation on clusters of 3/5/7/9 #' gives 0.17, 0.20, 0.17, 0.15, against a naive 0.33, 0.20, 0.14, 0.11. #' * `design_multistage()` where the per-cluster take is not constant — `n` not -#' divisible by `n_clusters`, or a cluster smaller than `n / n_clusters`. The -#' allocation runs over the *selected* clusters, so the remainder goes to the -#' largest of them and an undersized cluster is capped with its shortfall -#' dealt to whichever clusters came with it. A row's probability then depends -#' on the company it keeps. On clusters of 20/10/8/6 with `n = 7` over 2 -#' clusters, the average take is out by up to 17%, and a cluster smaller than -#' the take can push the figure above 1. +#' divisible by `n_clusters`, or, without replacement, a cluster smaller than +#' `n / n_clusters`. The allocation runs over the *selected* clusters, so the +#' remainder goes to the largest of them and an undersized cluster is capped +#' with its shortfall dealt to whichever clusters came with it. A row's +#' probability then depends on the company it keeps. On clusters of +#' 20/10/8/6 with `n = 7` over 2 clusters, the average take is out by up to +#' 17%, and a cluster smaller than the take can push the figure above 1. +#' +#' For these two, the exact probability is the probability given the +#' clusters selected, averaged over every possible selection, and that +#' average has no formula. `draw(weights = TRUE)` weights the sample +#' conditional on the clusters it selected instead, which gives an +#' unbiased total without the average; see "Design weights" in [draw()]. #' * `design_weighted(method = "successive")` — the default. Successive sampling #' has no closed-form inclusion probability; this is the whole reason the other #' two methods exist. Note that its realised probabilities are not merely #' unknown but genuinely different from proportional-to-size: for weights -#' `1:10` at `n = 5`, simulation puts them up to 35% away. +#' `1:10` at `n = 5`, enumerating every ordered draw puts them up to about +#' 36% away. #' * [design_bootstrap()] — resampling with replacement from the sample is not a #' probability sample of a finite population, so there is no `pi` to report. #' +#' A [design_systematic()] with a fixed `start` is refused too, for another +#' reason. It is deterministic: each row has probability 0 or 1, and +#' `simulate = TRUE` reports exactly that. Without `simulate` those values +#' are refused, because `draw(weights = TRUE)` would give every sampled row a +#' weight of 1 and [ht_total()] would report the sum over the sample as the +#' total of the frame. So are [sampling_weight()], [joint_prob()], +#' `draw(weights = TRUE)` and the estimators. Leave `start` as `NULL` for a +#' probability sample. +#' #' For all but the bootstrap, pass `simulate = TRUE` to estimate them by Monte #' Carlo instead. The estimate carries `R`-sized error, which is fine for #' checking a design and not fine for publishing a variance. Simulating a #' bootstrap is refused rather than answered: every row turns up in some #' replicate, so the count converges to 1 for all of them. #' +#' @section What a simulation costs: +#' `simulate = TRUE` makes `R` draws, 5,000 by default, so it takes `R` +#' times as long as one [draw()]. Most designs draw from a frame of 10,000 +#' rows in well under a second. The local pivotal method of [design_spread()] +#' does work in proportion to `N^2` on every draw, so at 10,000 rows each +#' draw takes seconds and the default `R` takes hours. When the draws after +#' the first two, which carry one-off costs, project a run of more than 30 +#' seconds, a message says how long it will take, and an interactive session +#' shows a progress bar. Lower `R` for a +#' quicker answer with more Monte Carlo error: its standard error is +#' `sqrt(p * (1 - p) / R)`, at most 0.007 for `R = 5000`. +#' +#' A warning that every draw raises, such as a stratum allocated no rows or +#' `max_items` cutting a frame short, is given once at the end, with the +#' number of draws that raised it. +#' #' @param data A data frame. #' @param design A design object. #' @param simulate Estimate the probabilities by repeated draws rather than in #' closed form. Required for the designs listed above; allowed for any #' probability design, which is a convenient way to check the exact formulas. -#' @param R Number of simulated draws when `simulate = TRUE`. -#' @param seed Optional seed for the simulation. +#' @param R Number of simulated draws when `simulate = TRUE`. See "What a +#' simulation costs". +#' @param seed Optional seed for the simulation, applied as in [draw()] (see +#' "Seeding" there). Checked whether or not `simulate` is `TRUE`. #' #' @return A numeric vector with one element per row of `data`. #' -#' Rows the design can never select — outside the region, outside the time -#' window, at zero weight — get `0` from `inclusion_prob()` and `NA` from -#' `sampling_weight()`, since no finite number of population rows is -#' represented by a row that cannot be drawn. [sample_summary()] counts them. +#' A row the design can never select gets `0` from `inclusion_prob()` and +#' `NA` from `sampling_weight()`, since no finite number of population rows +#' is represented by a row that cannot be drawn. Such a row lies outside +#' the region or the time window, comes past `max_items`, or was dropped +#' under `na_rm = TRUE`. +#' [sample_summary()] counts them. A weight of 0 is not one of these. The +#' designs that select in proportion to size refuse it, so drop such rows +#' from `data` first. +#' +#' A design that [draw()] refuses, such as an `n` larger than the frame or +#' than the rows inside a region, is refused here too, with the same +#' message, rather than given probabilities above 1 or a census. #' #' @examples #' df <- data.frame(id = 1:20, site = rep(c("a", "b"), times = c(15, 5))) @@ -93,12 +135,11 @@ #' @export inclusion_prob <- function(data, design, simulate = FALSE, R = 5000, seed = NULL) { - if (!is_design(design)) { - stop("`design` must come from one of the design_*() constructors, not a ", - class(design)[1], ". See ?designs.", call. = FALSE) - } + design <- check_design(design, data, "inclusion_prob") validate_data(data) check_flag(simulate, "simulate") + check_seed(seed) + warn_region(design, data) if (isTRUE(simulate)) { return(simulate_inclusion(data, design, R = check_count(R, "R", @@ -118,14 +159,82 @@ sampling_weight <- function(data, design, simulate = FALSE, R = 5000, out } +#' Rows a size-proportional design takes with certainty +#' +#' A design whose inclusion probabilities are proportional to size gives a +#' row whose share of `n` reaches 1 a probability of exactly 1, and spreads +#' what is left of `n` over the other rows, repeating until no share passes +#' 1. `certainty_set()` says which rows of `data` those are, and where the +#' cut-off falls, before any sample is drawn. +#' +#' @param data A data frame. +#' @param design [design_weighted()] with `method = "systematic"` or +#' `"poisson"`, or [design_spread()] with a `size` column. Other designs are +#' refused, since none of them has inclusion probabilities proportional to +#' size. +#' +#' @return An integer vector of the rows of `data` whose inclusion probability +#' is 1, in frame order, the same rows as +#' `which(inclusion_prob(data, design) == 1)`. Its attribute `threshold` is +#' the smallest size among them, or `NA` when there are none. Of the rows +#' the design can select, those whose size is at least `threshold` are the +#' set. With `strata`, [design_weighted()] and [design_spread()] put the +#' cut-off in each stratum at its own size, so there `threshold` is `NA`. +#' For [design_weighted()] without `strata`, [design_certainty()] with +#' that `threshold` on the weights column therefore takes the same rows +#' with certainty, and a `rest` of the same +#' method with `n` reduced by the number of rows in the set gives the other +#' rows the same probabilities too. +#' +#' @examples +#' df <- data.frame(id = 1:10, w = c(1, 2, 3, 4, 5, 6, 7, 8, 60, 90)) +#' d <- design_weighted("w", n = 4, method = "systematic") +#' cs <- certainty_set(df, d) +#' df[cs, ] +#' attr(cs, "threshold") +#' +#' # The same probabilities, with the cut-off made explicit +#' same <- design_certainty("w", attr(cs, "threshold"), +#' rest = design_weighted("w", n = 4 - length(cs), +#' method = "systematic")) +#' all.equal(inclusion_prob(df, same), inclusion_prob(df, d)) +#' +#' @seealso [inclusion_prob()], [design_certainty()] +#' @export +certainty_set <- function(data, design) { + design <- check_design(design, data, "certainty_set") + size <- if (inherits(design, "drawn_design_weighted") && + design$method %in% c("systematic", "poisson")) { + design$weights + } else if (inherits(design, "drawn_design_spread")) { + design$size + } + if (is.null(size)) { + stop("`design` is ", design_label(design), ", whose inclusion ", + "probabilities are not proportional to size. certainty_set() takes ", + "design_weighted() with method = \"systematic\" or \"poisson\", or ", + "design_spread() with `size`.", call. = FALSE) + } + validate_data(data) + rows <- which(is_certain(exact_inclusion(design, data))) + # With strata, each stratum has a cut-off of its own. + structure(rows, threshold = if (length(rows) && is.null(design$strata)) { + min(data[[size]][rows]) + } else { + NA_real_ + }) +} + #' Monte Carlo inclusion probabilities #' #' Draws `R` samples and counts how often each row appears. Works for every -#' design, including the four with no closed form. +#' design, including those with no closed form. #' #' @noRd simulate_inclusion <- function(data, design, R, seed) { refuse_simulation(design) + # The probabilities of a design with `reserve` are its main sample's. + design <- main_design(design) n_rows <- nrow(data) key <- ".drawn_row_id" if (key %in% names(data)) { @@ -136,22 +245,168 @@ simulate_inclusion <- function(data, design, R, seed) { tagged[[key]] <- seq_len(n_rows) hits <- integer(n_rows) - with_seed(seed, quietly_empty({ + simulate_draws(R, seed, function() { + # A row drawn twice in one replicate is still one inclusion. + ids <- unique(drawn_ids(draw_design(design, tagged), key, design)) + hits[ids] <<- hits[ids] + 1L + }) + hits / R +} + +#' The frame rows of one simulated draw +#' +#' Read from the column the simulators add to `data`. A draw method that +#' drops it, as one written outside the package might, is refused rather +#' than counted as drawing nothing. +#' +#' @noRd +drawn_ids <- function(s, key, design) { + ids <- if (is.data.frame(s)) s[[key]] else unlist(s) + if (is.null(ids)) { + stop("The draw_design() method for design type \"", design_type(design), + "\" returned rows without the `", key, "` column the simulation ", + "adds to `data`. A method must return rows of `data` with all its ", + "columns; see ?draw_design.", call. = FALSE) + } + ids +} + +#' Run `R` simulated draws +#' +#' `one()` makes one draw and records it, and the draws run under `seed`. +#' A warning of drawn's own class is muffled and counted, and each kind is +#' given once at the end with the number of draws that raised it, rather than +#' once per draw. The first message of a kind is the one shown. When the +#' draws worded it differently, as when it names the cluster or the start of +#' the draw, the count is given for warnings like it, since the details shown +#' are the first draw's alone. A draw that gave several messages of one kind, +#' the same in every draw, is reported with how many each draw gave. +#' +#' A run is timed over the draws that follow its first two. Those two carry +#' one-off costs, such as loading a package on the first call or compiling a +#' function that was not byte-compiled on its second. Under +#' devtools::load_all() a second draw took a hundred times as long as the +#' third. The timing lasts until five draws have taken 0.05 seconds or more, +#' which keeps the clock's millisecond steps small against the time +#' measured, or until any number of draws have taken two seconds. A run +#' projected to take more than 30 seconds says so with a message and, in an +#' interactive session, shows a progress bar. +#' +#' @noRd +simulate_draws <- function(R, seed, one) { + i <- 0L + kinds <- character(0) + first <- character(0) + draws <- integer(0) + last <- integer(0) + # The distinct messages of each kind in the first draw that gave it + # (`first_set`) and in the latest one (`this_set`). `across` marks a kind + # whose messages differ between draws, `within` one that gave several + # different messages in one draw. + first_set <- list() + this_set <- list() + across <- logical(0) + within <- logical(0) + close_draw <- function(k) { + if (draws[k] == 1L) { + first_set[[k]] <<- this_set[[k]] + } else if (!setequal(this_set[[k]], first_set[[k]])) { + across[k] <<- TRUE + } + if (length(this_set[[k]]) > 1L) within[k] <<- TRUE + } + record <- function(w) { + msg <- conditionMessage(w) + k <- match(class(w)[1L], kinds) + if (is.na(k)) { + kinds <<- c(kinds, class(w)[1L]) + first <<- c(first, msg) + draws <<- c(draws, 0L) + last <<- c(last, 0L) + across <<- c(across, FALSE) + within <<- c(within, FALSE) + k <- length(kinds) + } + if (last[k] != i) { + if (draws[k] > 0L) close_draw(k) + draws[k] <<- draws[k] + 1L + last[k] <<- i + this_set[[k]] <<- msg + } else if (!msg %in% this_set[[k]]) { + this_set[[k]] <<- c(this_set[[k]], msg) + } + invokeRestart("muffleWarning") + } + + bar <- NULL + on.exit(if (!is.null(bar)) close(bar), add = TRUE) + warm <- 2L + start <- NA_real_ + timed <- FALSE + with_seed(seed, withCallingHandlers({ for (i in seq_len(R)) { - s <- draw_design(design, tagged) - ids <- s[[key]] - # A row drawn twice in one replicate is still one inclusion. - hits[unique(ids)] <- hits[unique(ids)] + 1L + one() + if (!timed && i >= warm) { + now <- elapsed_time() + if (i == warm) { + start <- now + } else { + spent <- now - start + if ((i - warm >= 5L && spent >= 0.05) || spent >= 2) { + timed <- TRUE + bar <- announce_run(R, i, spent / (i - warm)) + } + } + } + if (!is.null(bar)) utils::setTxtProgressBar(bar, i) } - })) - hits / R + }, drawn_warning = record)) + + for (k in seq_along(kinds)) { + close_draw(k) + count <- if (across[k]) { + paste0(" This is the first of these warnings. ", fmt_n(draws[k]), + " of the ", fmt_n(R), " simulated draws gave one like it, ", + "with details that differ from draw to draw.") + } else if (within[k]) { + paste0(" This happened in ", fmt_n(draws[k]), " of the ", fmt_n(R), + " simulated draws. ", + if (draws[k] == 1L) "That draw gave " else + "Each of them gave the same ", + length(first_set[[k]]), + " warnings like it, and this is the first.") + } else { + paste0(" This happened in ", fmt_n(draws[k]), " of the ", fmt_n(R), + " simulated draws.") + } + warn_drawn(paste0(first[k], count), kinds[k]) + } + invisible(NULL) +} + +#' Say how long a simulation will take, when that is more than 30 seconds +#' +#' `done` draws have been made, and one takes `per_draw` seconds. Returns a +#' progress bar, already at `done`, in an interactive session, else `NULL`. +#' +#' @noRd +announce_run <- function(R, done, per_draw) { + total <- per_draw * R + if (done >= R || total <= 30) return(NULL) + message("Simulating ", fmt_n(R), " draws will take about ", + format_duration(total), ", at ", format_duration(per_draw), + " a draw. A smaller `R` takes less time, with more Monte Carlo ", + "error.") + if (!is_interactive()) return(NULL) + utils::txtProgressBar(min = 0, max = R, initial = done, style = 3) } #' @noRd no_closed_form <- function(what, alternative) { - stop(what, " has no closed-form inclusion probability.\n", - alternative, "\n", - "Or pass simulate = TRUE to estimate it by Monte Carlo.", call. = FALSE) + stop_declined(paste0( + what, " has no closed-form inclusion probability.\n", alternative, "\n", + "Or estimate it by Monte Carlo with ", + "inclusion_prob(data, design, simulate = TRUE).")) } #' @noRd @@ -161,7 +416,11 @@ exact_inclusion <- function(design, data) { #' @noRd exact_inclusion.default <- function(design, data) { - stop("No inclusion probability method for design type \"", - design_type(design), "\".", call. = FALSE) + stop_declined(paste0( + "Design type \"", design_type(design), "\" is not one of drawn's own, ", + "so drawn has no inclusion probabilities for it, and `weights = TRUE`, ", + "the exact inclusion_prob() and joint_prob() and the estimators are not ", + "available. inclusion_prob(data, design, simulate = TRUE) estimates the ", + "probabilities by Monte Carlo; see ?draw_design.")) } diff --git a/R/joint.R b/R/joint.R index 1887474..43a963c 100644 --- a/R/joint.R +++ b/R/joint.R @@ -12,40 +12,70 @@ #' [design_simple()] \tab `n(n-1) / (N(N-1))` for a pair, without replacement \cr #' [design_stratified()] \tab within a stratum as above; across strata, independent \cr #' [design_cluster()] \tab same cluster: `a/A`; different clusters: `a(a-1)/(A(A-1))` \cr -#' [design_multistage()] \tab the two stages multiplied, where the per-cluster take is constant \cr +#' [design_multistage()] \tab the two stages multiplied, where the per-cluster take is constant and `size` is not given \cr #' [design_certainty()] \tab `1` between certainty rows; otherwise the other row's own `pi` \cr #' [design_reservoir()] \tab simple random sampling over the first `max_items` rows \cr #' [design_temporal()] \tab within an interval as above; across intervals, independent \cr #' [design_spatial()] \tab simple random sampling inside the region \cr #' [design_weighted()] \tab `"poisson"` only, where rows are independent: `pi_i * pi_j` \cr -#' [design_systematic()] \tab `1/interval` for rows sharing a residue class, otherwise **zero** \cr +#' [design_systematic()] \tab `1/interval` for rows sharing a residue class, otherwise **zero**; with `n`, the overlap of the two rows' stretches, from 0 to `n / N`; with `n_starts = m`, `1/interval` for rows sharing a residue class modulo `m * interval`, otherwise `m(m-1) / (mk(mk-1))` with `k` the interval \cr #' } #' -#' Systematic sampling is the awkward one. Most pairs can never co-occur, so -#' their joint probability is genuinely 0 and no design-unbiased variance -#' estimator exists; [ht_total()] uses the successive-difference approximation -#' instead, and says so. Its residue classes follow the order the design walks, -#' so `order_by` changes which pairs can co-occur. +#' Systematic sampling is the awkward one. At a step of 2 rows or more, which +#' is every `interval` above 1 and every `n` up to half the rows walked, +#' neighbouring rows and many other pairs can never co-occur, so their joint +#' probability is genuinely 0 and no design-unbiased variance estimator +#' exists; [ht_total()] uses the successive-difference approximation instead, +#' and says so. Its residue classes follow the order the design walks, so +#' `order_by` changes which pairs can co-occur. Given `n`, the design walks at +#' a step of `N / n` rows from a start `u` uniform on (0, 1), each row +#' covering a stretch of length `n / N`, and a pair is drawn together when `u` +#' falls where both stretches, moved into (0, 1), overlap. With `n` above +#' `N / 2` the stretches are longer than 1/2, any two of them overlap, and +#' every pair has a positive joint probability; [ht_total()] uses the +#' successive-difference approximation there too. With a fixed `start` the +#' design is deterministic, and it is refused as in [inclusion_prob()]. With +#' several starts (`n_starts`), rows in different residue classes can be drawn +#' together too, which is what gives a replicated sample its unbiased +#' variance. Within the strata of +#' `design_stratified(within = design_systematic())`, pairs in one stratum +#' get the overlap of their stretches, as with `n`, and pairs in two strata +#' the product of their probabilities. #' -#' Two designs have joint probabilities that are positive but have no closed -#' form: `design_weighted(method = "systematic")`, which shuffles the rows -#' before walking them so every pair can co-occur, and [design_spread()]. For -#' both, [ht_total()] uses a variance approximation that needs only -#' first-order probabilities, and `simulate = TRUE` here estimates the joint -#' probabilities themselves. +#' Three designs have joint probabilities that are positive but have no +#' closed form: `design_weighted(method = "systematic")`, which shuffles the +#' rows before walking them so every pair can co-occur, with or without +#' `strata`; [design_multistage()] with `size`, which does the same with the +#' clusters; and [design_spread()]. For all three, [ht_total()] uses a +#' variance approximation that needs only first-order probabilities, and +#' `simulate = TRUE` here estimates the joint probabilities themselves. +#' +#' @section Size: +#' The matrix has a row and a column for each of `rows`, by default every row +#' of `data`, and holds 8 bytes for each pair: 800 MB for 10,000 rows. Past +#' about 1 GB, from about 11,200 rows, `joint_prob()` refuses and gives the +#' size, rather than risk exhausting memory, which can end the R session. +#' [ht_total()] and [ht_mean()] do not build this matrix for any design in +#' the package. #' #' @param data A data frame. #' @param design A design object. -#' @param rows Optional row indices. Supply these — usually the rows you drew — -#' to get the submatrix for them instead of the full `nrow(data)` square, -#' which is what makes this usable on a large population. +#' @param rows Optional row indices, usually the rows you drew, which are +#' `s$.row` for a sample `s` from `draw(weights = TRUE)`. The result is then +#' the submatrix for these rows instead of the full `nrow(data)` square, +#' which is what makes this usable on a large population. See "Size". +#' Indices must be whole numbers. A row given more than once is one unit, +#' so its entry with itself, off the diagonal too, is its own inclusion +#' probability. #' @param simulate Estimate the probabilities by repeated draws rather than in #' closed form. Works for every probability design, including the ones with no #' closed form, at the cost of Monte Carlo error. Refused for #' [design_bootstrap()], where every row appears in some replicate and the #' count converges to 1 for all of them. -#' @param R Number of simulated draws when `simulate = TRUE`. -#' @param seed Optional seed for the simulation. +#' @param R Number of simulated draws when `simulate = TRUE`. A simulation +#' costs `R` draws; see "What a simulation costs" in [inclusion_prob()]. +#' @param seed Optional seed for the simulation, applied as in [draw()] (see +#' "Seeding" there). Checked whether or not `simulate` is `TRUE`. #' #' @return A square matrix with one row and column per element of `rows` #' (or per row of `data`). The diagonal holds first-order probabilities. @@ -61,23 +91,76 @@ #' @export joint_prob <- function(data, design, rows = NULL, simulate = FALSE, R = 5000, seed = NULL) { - if (!is_design(design)) { - stop("`design` must come from one of the design_*() constructors, not a ", - class(design)[1], ". See ?designs.", call. = FALSE) - } + design <- check_design(design, data, "joint_prob") validate_data(data) check_flag(simulate, "simulate") + check_seed(seed) + warn_region(design, data) + given <- !is.null(rows) rows <- rows %||% seq_len(nrow(data)) if (!is.numeric(rows) || anyNA(rows) || any(rows < 1) || any(rows > nrow(data))) { stop("`rows` must be valid row indices into `data`.", call. = FALSE) } + frac <- rows != trunc(rows) + if (any(frac)) { + stop("`rows` must be whole row numbers, not ", format_rows(rows[frac]), + ". Pass the rows of `data` to pair, such as `s$.row` for a sample ", + "`s`.", call. = FALSE) + } rows <- as.integer(rows) - if (isTRUE(simulate)) { - return(simulate_joint(data, design, rows, - check_count(R, "R", allow_zero = FALSE), seed)) + check_pair_size(length(rows), given) + # A row given twice is one unit, so the pair it makes with itself is in a + # sample exactly when the row is, with the row's own `pi`. The methods work + # on distinct rows and the result is spread back out. + u <- unique(rows) + out <- if (isTRUE(simulate)) { + simulate_joint(data, design, u, check_count(R, "R", allow_zero = FALSE), + seed) + } else { + joint_inclusion(design, data, u) + } + if (length(u) < length(rows)) { + i <- match(rows, u) + out <- out[i, i, drop = FALSE] + } + out +} + +#' Refuse a joint matrix too large to hold +#' +#' `k` rows make a `k` x `k` matrix of doubles. Past `pair_limit()` bytes the +#' request is refused before anything is allocated, with the size and the +#' way round it. `given` says whether the caller passed `rows`. +#' +#' @noRd +check_pair_size <- function(k, given) { + bytes <- 8 * as.numeric(k)^2 + if (bytes <= pair_limit()) return(invisible(NULL)) + k_text <- format(k, big.mark = ",") + shape <- paste0(k_text, " x ", k_text) + if (given) { + stop("`joint_prob()` would build a ", shape, " matrix for the ", k_text, + " `rows` given, which needs about ", format_gb(bytes), + " of memory. Pass fewer `rows`.", call. = FALSE) } - joint_inclusion(design, data, rows) + stop("`joint_prob()` would build a ", shape, " matrix for every row of ", + "`data`, which needs about ", format_gb(bytes), " of memory. Pass ", + "`rows`, such as `rows = s$.row` for the rows of a sample `s` drawn ", + "with `weights = TRUE`.", call. = FALSE) +} + +#' The most memory a matrix over pairs of rows may take, in bytes +#' +#' About 1 GB. Shared by `joint_prob()` and the Sen-Yates-Grundy estimator. +#' +#' @noRd +pair_limit <- function() 1e9 + +#' A size in bytes, for a message +#' @noRd +format_gb <- function(bytes) { + paste(format(signif(bytes / 1e9, 2), big.mark = ","), "GB") } #' Monte Carlo joint inclusion probabilities @@ -89,6 +172,7 @@ joint_prob <- function(data, design, rows = NULL, simulate = FALSE, R = 5000, #' @noRd simulate_joint <- function(data, design, rows, R, seed) { refuse_simulation(design) + design <- main_design(design) key <- ".drawn_row_id" if (key %in% names(data)) { stop("`data` already has a column called `", key, @@ -100,22 +184,28 @@ simulate_joint <- function(data, design, rows, R, seed) { pos <- match(seq_len(nrow(data)), rows) # NA for rows we are not tracking counts <- matrix(0L, k, k) - with_seed(seed, quietly_empty({ - for (i in seq_len(R)) { - s <- draw_design(design, tagged) - ids <- unique(if (is.data.frame(s)) s[[key]] else unlist(s)) - hit <- pos[ids] - hit <- hit[!is.na(hit)] - if (length(hit)) counts[hit, hit] <- counts[hit, hit] + 1L - } - })) + simulate_draws(R, seed, function() { + ids <- unique(drawn_ids(draw_design(design, tagged), key, design)) + hit <- pos[ids] + hit <- hit[!is.na(hit)] + if (length(hit)) counts[hit, hit] <<- counts[hit, hit] + 1L + }) counts / R } +#' Refuse joint probabilities the design does not define +#' +#' `simulate` adds the pointer to a simulation, for the designs where one +#' estimates them: every design but the bootstrap. +#' #' @noRd -no_joint_form <- function(what, alternative) { - stop(what, " has no closed-form joint inclusion probability.\n", alternative, - call. = FALSE) +no_joint_form <- function(what, alternative, simulate = TRUE) { + stop_declined(paste0( + what, " has no closed-form joint inclusion probability.\n", alternative, + if (simulate) { + paste0("\nOr estimate them by Monte Carlo with ", + "joint_prob(data, design, simulate = TRUE).") + })) } #' @noRd @@ -129,58 +219,95 @@ joint_inclusion.default <- function(design, data, rows) { ) } -#' Pairwise matrix from a group id and a per-group (n, N) +#' A matrix over pairs of rows, built one group's block at a time #' -#' Rows in the same group are a simple random sample of `n_g` from `N_g`; rows -#' in different groups are selected independently. +#' Pairs of rows in different groups get `between`, times +#' `product[i] * product[j]` when `product` is given. Pairs in the same group +#' get that group's entry of `within`. `group` is each row's position in +#' `within`, or `NA` for a row in no group, which co-occurs with nothing. The +#' diagonal is `on_diag`. +#' +#' The matrix is allocated once and each group's block is assigned in place, +#' so the memory used beyond the result is one block at a time. Comparing +#' every pair of codes with `outer()` held up to twelve matrices of the +#' result's size. `diag<-` is a closure and copies the matrix it is given, so +#' the diagonal is assigned by position instead. #' #' @noRd -joint_from_groups <- function(group, n_g, size_g, pi_i) { +pair_matrix <- function(group, within, on_diag, between = 0, product = NULL) { k <- length(group) - out <- outer(pi_i, pi_i) # independent case - same <- outer(group, group, "==") - if (any(same)) { - n <- n_g[as.character(group)] - N <- size_g[as.character(group)] - within <- outer(seq_len(k), seq_len(k), function(a, b) { - nn <- n[a]; NN <- N[a] - ifelse(NN > 1, nn * (nn - 1) / (NN * (NN - 1)), 0) - }) - out[same] <- within[same] + gone <- which(is.na(group)) + out <- if (is.null(product)) { + matrix(between, k, k) + } else { + product <- as.numeric(product) + product[gone] <- 0 + tcrossprod(product) * between + } + if (length(gone)) { + out[gone, ] <- 0 + out[, gone] <- 0 + } + idx <- split(seq_len(k), structure(as.integer(group), + levels = as.character(seq_along(within)), + class = "factor")) + for (g in which(lengths(idx) > 1L)) { + out[idx[[g]], idx[[g]]] <- within[[g]] } - diag(out) <- pi_i - dimnames(out) <- NULL + out[diag_index(k)] <- on_diag out } +#' Positions of the diagonal of a `k` x `k` matrix +#' @noRd +diag_index <- function(k) seq.int(1, by = k + 1, length.out = k) + +#' Pairwise matrix from a group code and a per-group (n, N) +#' +#' Rows in the same group are a simple random sample of `n_g` from `N_g`; rows +#' in different groups are selected independently. `group` is each row's +#' position in `n_g` and `size_g`, or `NA` for a row in no group, which +#' co-occurs with nothing. +#' +#' @noRd +joint_from_groups <- function(group, n_g, size_g, pi_i) { + n <- as.numeric(n_g) + N <- as.numeric(size_g) + within <- ifelse(N > 1, n * (n - 1) / (N * (N - 1)), 0) + pair_matrix(group, within, pi_i, between = 1, product = pi_i) +} + #' @noRd joint_inclusion.drawn_design_simple <- function(design, data, rows) { if (design$replace) { no_joint_form("`design_simple(replace = TRUE)`", "Use replace = FALSE, or estimate variance by resampling.") } - N <- nrow(data) + keep <- simple_setup(design, data) + N <- length(keep) n <- design$n - pi_i <- rep(n / N, length(rows)) - out <- matrix(if (N > 1) n * (n - 1) / (N * (N - 1)) else 0, - length(rows), length(rows)) - diag(out) <- pi_i + k <- length(rows) + out <- matrix(if (N > 1) n * (n - 1) / (N * (N - 1)) else 0, k, k) + out[diag_index(k)] <- n / N + # Rows use_reserves() found unavailable are never drawn. + gone <- !rows %in% keep + if (any(gone)) { + out[gone, ] <- 0 + out[, gone] <- 0 + } out } #' @noRd joint_inclusion.drawn_design_reservoir <- function(design, data, rows) { - reach <- reservoir_reach(design, nrow(data)) - out <- joint_inclusion.drawn_design_simple( - new_design("simple", list(n = min(design$n, reach), replace = FALSE)), - utils::head(data, reach), rows[rows <= reach] - ) - if (reach == nrow(data)) return(out) - # Rows past `max_items` are never read, so they co-occur with nothing. - full <- matrix(0, length(rows), length(rows)) - seen <- rows <= reach - full[seen, seen] <- out - full + # A simple random sample from the rows before `max_items`. Rows past it are + # never read, so they co-occur with nothing. + N <- reservoir_reach(design, nrow(data)) + n <- min(design$n, N) + seen <- rows <= N + pair_matrix(ifelse(seen, 1L, NA_integer_), + if (N > 1) n * (n - 1) / (N * (N - 1)) else 0, + ifelse(seen, n / N, 0)) } #' @noRd @@ -188,85 +315,84 @@ joint_inclusion.drawn_design_stratified <- function(design, data, rows) { if (design$replace) { no_joint_form("`design_stratified(replace = TRUE)`", "Use replace = FALSE.") } - validate_data(data, required_columns = design$strata) - check_key_columns(data, design$strata, "strata") - - keys <- data[design$strata] - bad <- Reduce(`|`, lapply(keys, is.na)) - group <- group_key(data, design$strata) - idx <- split(seq_len(nrow(data))[!bad], group[!bad]) - sizes <- lengths(idx) - n_alloc <- allocate(design$n, sizes, design$allocation, - design$min_per_stratum, cap = TRUE, - spread = stratum_spread(design, data, idx)) + al <- stratum_allocation(design, data) + if (walks_strata(design)) return(walk_joint(design, data, rows, al)) + # A dropped row has no stratum code, so it co-occurs with nothing. + joint_from_groups(al$code[rows], al$n_alloc, al$sizes, + stratum_pi(design, al)[rows]) +} - pi_all <- exact_inclusion(design, data) - # A dropped row belongs to no stratum. Give it a label of its own so it - # co-occurs with nothing, rather than letting NA reach the subscript. - g <- as.character(group[rows]) - g[bad[rows]] <- paste0("\r__dropped__", seq_len(sum(bad[rows]))) - joint_from_groups(g, n_alloc, sizes, pi_all[rows]) +#' Joint probabilities of a stratified design that walks each stratum +#' +#' Strata are drawn independently, so a pair in two strata gets the product +#' of its probabilities. A pair in one stratum gets the overlap of its +#' stretches on that stratum's walk, from `fractional_joint()` with the +#' stratum's `n_h` and `N_h`. A row in no stratum co-occurs with nothing. +#' +#' @noRd +walk_joint <- function(design, data, rows, al) { + pos <- walk_positions(design, data, al$code, length(al$sizes))[rows] + code <- al$code[rows] + p <- stratum_pi(design, al)[rows] + out <- tcrossprod(p) + for (h in unique(code[!is.na(code)])) { + i <- which(code == h) + out[i, i] <- fractional_joint(pos[i], al$n_alloc[h], al$sizes[h]) + } + out } #' @noRd joint_inclusion.drawn_design_temporal <- function(design, data, rows) { - pi_all <- exact_inclusion(design, data) - bucket <- temporal_bucket(design, data) - sizes <- table(bucket[!is.na(bucket)]) - n_g <- pmin(sizes, design$per_interval) + bucket <- temporal_setup(design, data)$bucket + sizes <- tabulate(bucket[!is.na(bucket)]) - g <- bucket[rows] - g[is.na(g)] <- paste0("__out__", seq_len(sum(is.na(g)))) # never co-occur - joint_from_groups(g, stats::setNames(as.integer(n_g), names(n_g)), - stats::setNames(as.integer(sizes), names(sizes)), - pi_all[rows]) + # A row outside every interval has no code, so it co-occurs with nothing. + joint_from_groups(bucket[rows], pmin(sizes, design$per_interval), sizes, + temporal_pi(design, bucket)[rows]) } #' @noRd joint_inclusion.drawn_design_spatial <- function(design, data, rows) { - require_suggested("sf", "spatial sampling") - inside <- spatial_inside(design, data) + inside <- spatial_setup(design, data) N <- sum(inside) - n <- min(design$n, N) + n <- design$n pi_all <- exact_inclusion(design, data) - out <- matrix(if (N > 1) n * (n - 1) / (N * (N - 1)) else 0, - length(rows), length(rows)) - out[!inside[rows], ] <- 0 - out[, !inside[rows]] <- 0 - diag(out) <- pi_all[rows] - out + # A row outside the region co-occurs with nothing. + pair_matrix(ifelse(inside[rows], 1L, NA_integer_), + if (N > 1) n * (n - 1) / (N * (N - 1)) else 0, pi_all[rows]) } #' @noRd joint_inclusion.drawn_design_cluster <- function(design, data, rows) { + cl <- cluster_setup(design, data) if (design$balanced) { no_joint_form("`design_cluster(balanced = TRUE)`", "Use balanced = FALSE.") } - cl <- count_clusters(design, data) A <- cl$total a <- design$n_clusters - lab <- as.character(cl$labels[rows]) - - same <- outer(lab, lab, "==") - same[is.na(same)] <- FALSE - out <- matrix(if (A > 1) a * (a - 1) / (A * (A - 1)) else 0, - length(rows), length(rows)) - out[same] <- a / A - # A row with no cluster -- a dropped key -- is in no sample at all, so it - # co-occurs with nothing. Without this it inherits the between-cluster rate. - gone <- is.na(lab) - if (any(gone)) { - out[gone, ] <- 0 - out[, gone] <- 0 - } pi_all <- exact_inclusion(design, data) - diag(out) <- pi_all[rows] - out + # Same cluster: that cluster selected. Different clusters: both selected. A + # row with no cluster, dropped under `na_rm = TRUE`, is in no sample, so it + # co-occurs with nothing. + pair_matrix(cl$code[rows], rep(a / A, A), pi_all[rows], + between = if (A > 1) a * (a - 1) / (A * (A - 1)) else 0) } #' @noRd joint_inclusion.drawn_design_multistage <- function(design, data, rows) { + cl <- multistage_setup(design, data) + if (!is.null(design$size)) { + no_joint_form( + "`design_multistage(size = )`", + paste0("Its clusters are shuffled before the systematic PPS walk, so ", + "every pair of clusters\ncan be selected together, but their ", + "joint probabilities average over every ordering\nand have no ", + "closed form. ht_total() uses Deville's approximation for the ", + "clusters.") + ) + } if (design$allocation == "proportional") { no_joint_form("`design_multistage(allocation = \"proportional\")`", "Use allocation = \"equal\".") @@ -284,36 +410,32 @@ joint_inclusion.drawn_design_multistage <- function(design, data, rows) { design$n_clusters, ").") ) } - cl <- count_clusters(design, data) A <- cl$total a <- design$n_clusters m <- design$n %/% design$n_clusters - sizes <- table(cl$labels[cl$present]) - - lab <- as.character(cl$labels[rows]) - Nh <- as.numeric(sizes[lab]) - same <- outer(lab, lab, "==") - same[is.na(same)] <- FALSE + sizes <- as.numeric(tabulate(cl$code, A)) + code <- cl$code[rows] + pi_all <- exact_inclusion(design, data) # Different clusters: both clusters selected, then each row within its own. - out <- outer(m / Nh, m / Nh) * (if (A > 1) a * (a - 1) / (A * (A - 1)) else 0) - # Same cluster: that cluster selected, then both rows drawn from it. - win <- outer(seq_along(rows), seq_along(rows), function(i, j) { - NN <- Nh[i] - ifelse(NN > 1, (a / A) * (m * (m - 1)) / (NN * (NN - 1)), 0) - }) - out[same] <- win[same] - pi_all <- exact_inclusion(design, data) - diag(out) <- pi_all[rows] - out + # Same cluster: that cluster selected, then both rows drawn from it. A row + # with no cluster co-occurs with nothing. + pair_matrix(code, + ifelse(sizes > 1, + (a / A) * (m * (m - 1)) / (sizes * (sizes - 1)), 0), + pi_all[rows], + between = if (A > 1) a * (a - 1) / (A * (A - 1)) else 0, + product = m / sizes[code]) } #' @noRd joint_inclusion.drawn_design_weighted <- function(design, data, rows) { + weighted_setup(design, data) if (design$method == "poisson") { pi_all <- exact_inclusion(design, data) - out <- outer(pi_all[rows], pi_all[rows]) # independent - diag(out) <- pi_all[rows] + p <- pi_all[rows] + out <- tcrossprod(p) # independent + out[diag_index(length(rows))] <- p return(out) } if (design$method == "systematic") { @@ -321,8 +443,8 @@ joint_inclusion.drawn_design_weighted <- function(design, data, rows) { "`design_weighted(method = \"systematic\")`", paste0("The rows are shuffled before the systematic walk, so every pair ", "can co-occur,\nbut the joint probabilities average over every ", - "ordering and have no closed form.\nPass simulate = TRUE to ", - "estimate them; ht_total() uses Deville's approximation.") + "ordering and have no closed form.\nht_total() uses Deville's ", + "approximation.") ) } no_joint_form("`design_weighted(method = \"successive\")`", @@ -331,28 +453,61 @@ joint_inclusion.drawn_design_weighted <- function(design, data, rows) { #' @noRd joint_inclusion.drawn_design_systematic <- function(design, data, rows) { - if (!is.null(design$start)) { - stop("A systematic design with a fixed `start` is not a probability ", - "sample.", call. = FALSE) - } - k <- design$interval + refuse_fixed_start(design) # Residue classes come from the order the design walks, which `order_by` # changes. Taking them from frame order instead reports 0 for pairs that # always co-occur and 1/k for pairs that never can. - pos <- systematic_positions(design, data)[rows] - res <- (pos - 1L) %% k - out <- matrix(0, length(rows), length(rows)) - same <- outer(res, res, "==") - same[is.na(same)] <- FALSE - out[same] <- 1 / k - diag(out) <- ifelse(is.na(pos), 0, 1 / k) + walk <- systematic_positions(design, data) + pos <- walk[rows] + if (!is.null(design$n)) { + return(fractional_joint(pos, design$n, sum(!is.na(walk)))) + } + # With `m` starts drawn from 1:(m * k), a pair in one residue class modulo + # m * k is taken when its start is among them, m times in m * k, and a + # pair in two classes when both starts are. One start is the case m = 1. + # Only the classes of `rows` get a block. + k <- design$interval + m <- systematic_starts(design) + step <- m * k + cls <- as.integer((pos - 1L) %% step) + live <- unique(cls[!is.na(cls)]) + pair_matrix(match(cls, live), rep(1 / k, length(live)), + ifelse(is.na(pos), 0, 1 / k), + between = if (m > 1L) (m - 1) / (k * (step - 1)) else 0) +} + +#' Joint probabilities of a systematic sample of fixed size `n` +#' +#' Walk position `p` is taken when the start `u` lands in its stretch moved +#' into (0, 1): an arc of length `n / N` beginning at `(p - 1) * n / N` +#' modulo 1. Two positions are taken together when `u` lands where their arcs +#' overlap. For positions `d` apart, the arcs begin `gap / N` apart, where +#' `gap` is `(d * n) %% N`, and overlap by +#' `(max(n - gap, 0) + max(gap + n - N, 0)) / N`. The arithmetic is on whole +#' numbers, so when `n` divides `N` the result is `n / N` within a residue +#' class and 0 between them, as for `interval = N / n`. +#' +#' @noRd +fractional_joint <- function(pos, n, N) { + k <- length(pos) + out <- matrix(0, k, k) + ok <- which(!is.na(pos)) + if (length(ok) == 0L) return(out) + # The overlap depends only on the distance along the walk, modulo N. + gap <- (as.double(seq.int(0L, N - 1L)) * n) %% N + overlap <- (pmax(n - gap, 0) + pmax(gap + n - N, 0)) / N + p <- pos[ok] + for (j in seq_along(ok)) { + out[ok, ok[j]] <- overlap[(p - p[j]) %% N + 1L] + } out } #' @noRd joint_inclusion.drawn_design_bootstrap <- function(design, data, rows) { no_joint_form("`design_bootstrap()`", - "A bootstrap is not a probability sample of a finite population.") + "A bootstrap is not a probability sample of a finite population.", + simulate = FALSE) } diff --git a/R/plan.R b/R/plan.R index 843ee61..c983475 100644 --- a/R/plan.R +++ b/R/plan.R @@ -12,45 +12,136 @@ #' range divided by four as a rough stand-in. #' * For a **proportion**, a `p`. Leave it at `0.5`, the most pessimistic value, #' unless you have a better guess; that is the honest default because it -#' maximises the required size. +#' maximises the required size. The margin is a proportion too, `0.03` for +#' 3 percentage points. +#' +#' `sd` given for a proportion, or `p` for a mean or a total, is not used, +#' and `plan_size()` warns that it is ignored. +#' +#' For a stratified sample, give the size and the spread of each stratum in +#' `strata` instead (see "Planning a stratified sample"). #' #' @section The corrections: #' `N` applies a finite population correction: sampling 400 from 500 is very #' different from 400 from 500,000, and past a certain point a bigger frame -#' stops mattering. `deff` inflates for the design — pass the [deff()] from a -#' comparable past sample, since a clustered design of 400 may carry the -#' information of 100. `response` inflates for non-response: at `0.6` you draw +#' stops mattering. `response` inflates for non-response: at `0.6` you draw #' enough to end up with what you need. #' -#' @param margin Half-width of the confidence interval you want. +#' `deff` inflates for the design, since a clustered design of 400 may carry +#' the information of 100. Before any pilot, [deff_cluster()] gives the +#' design effect of taking `m` rows from each cluster from their intraclass +#' correlation. Measure it with [deff()] on a comparable past +#' sample, using the estimator you will report: [ht_mean()] for a mean or a +#' proportion, and [ht_total()] for a total. The two design effects differ for +#' the same sample, and can differ many times over. In one cluster sample +#' with clusters of 2 to 40 rows, the total's design effect was 28 and the +#' mean's 0.66, and a total planned with the mean's figure came out a small +#' fraction of the size it needed. A total reported as `N` times a mean takes +#' the mean's design effect, and is planned as a mean with `margin / N`. You +#' can pass the result of `ht_mean()` or `ht_total()` itself as `deff`, and +#' `plan_size()` refuses one of the wrong kind for `target`. +#' +#' A design effect from one pilot is an estimate, and a noisy one, which +#' comes out below the truth more often than above it. Round it up. [deff()] +#' gives `NA` for a pilot without a variance estimate, such as one taken with +#' `variance = "none"`, a census, or one with a single cluster, and for one in +#' which `y` took a single value. It is `NA` too for a mean from +#' `ht_mean(na_rm = TRUE)` with `y` missing in some sampled rows, since the +#' rows with `y` are a domain, whose design effect is not estimated. Such a +#' pilot cannot supply a design effect, and `plan_size()` refuses an `NA`. +#' It refuses an estimate from `survey` too, such as +#' `survey::svymean(deff = TRUE)`, whose value is the estimate itself; pass +#' `survey::deff()` of it instead. +#' +#' @param margin Half-width of the confidence interval you want, the +#' half-width the plan expects (see "Where the formula comes from"). For a +#' proportion it is a proportion, and a `margin` of 1 or more is refused. +#' Several margins give several plans (see "Several plans at once"). #' @param sd Standard deviation of the measure, for `target = "mean"` or -#' `"total"`. -#' @param p Expected proportion, for `target = "proportion"`. -#' @param N Population size. `Inf` for an effectively unbounded frame. +#' `"total"`, as [stats::sd()] computes it. Not used with `strata`. +#' @param p Expected proportion, for `target = "proportion"`. Not used with +#' `strata`. +#' @param N Population size, at least 1. `Inf` for an effectively unbounded +#' frame. An estimated `N` need not be a whole number; `n` is at most +#' `floor(N)`. Not used with `strata`, whose sizes add up to it. #' @param level Confidence level. -#' @param deff Design effect to inflate by. `1` assumes simple random sampling. +#' @param deff Design effect to inflate by: a positive number, or the result +#' of [ht_mean()] for a mean or a proportion, or of [ht_total()] for a +#' total, on a pilot sample. `1` assumes simple random sampling. A number +#' should come from [deff()] on the estimator you will report, rounded up, +#' or from [deff_cluster()] (see "The corrections"). With `strata` it +#' inflates the variance of the stratified sample, as for clusters sampled +#' within strata. #' @param response Expected response rate, between 0 and 1. #' @param target `"mean"`, `"proportion"` or `"total"`. For `"total"` the #' margin is on the population total and `N` must be finite. +#' @param strata `NULL`, or a data frame with a row per stratum, to plan a +#' stratified sample (see "Planning a stratified sample"). Its columns +#' are those that name the strata; `N`, the rows of the frame in each +#' stratum; `sd`, the standard deviation of the measure within each +#' stratum, or for a proportion `p`, the expected proportion within it; +#' and, with `allocation = "neyman"` only, an optional `cost`, the cost +#' of one row in each stratum. +#' @param allocation How `n` is split over `strata`: `"proportional"`, +#' `"equal"` or `"neyman"`, as in [design_stratified()]. Neyman shares are +#' proportional to `N_h * S_h`, or `N_h * S_h / sqrt(cost_h)` with a +#' `cost` column. +#' @param min_per_stratum The fewest rows a stratum is allocated, as in +#' [design_stratified()], 1 or more. A stratum smaller than this is taken +#' whole. The default of 2 is the fewest that give each stratum a +#' variance, which [ht_total()] and [ht_mean()] need from every stratum +#' not taken whole. 0, the default of [design_stratified()], is refused, +#' since a split without a floor can leave a small stratum without rows, +#' and the estimate then leaves it out. #' -#' @return A list with a `print()` method, holding: +#' @return A plan, a list of class `drawn_plan` with a `print()` method, +#' or for several plans a data frame (see "Several plans at once"). A plan +#' holds: #' \describe{ -#' \item{`n`}{Draw this many. Never more than `N`.} +#' \item{`n`}{Draw this many. Never more than `N`, and without `strata` +#' at least two when the frame has two rows or more.} #' \item{`n_effective`}{What you expect to analyse once `response` has #' taken its share.} -#' \item{`capped`}{`TRUE` when the frame is not large enough to reach the -#' margin at all, however you sample it.} -#' \item{`short`}{`TRUE` when the frame could reach the margin but not at -#' this `response` rate, so `n` is the whole frame and the margin -#' achieved will be wider than the one asked for.} +#' \item{`capped`}{`TRUE` when only a census meets the margin, so `n` is +#' every row of the frame. A census meets any margin when everyone +#' responds.} +#' \item{`short`}{`TRUE` when a sample smaller than the frame would meet +#' the margin if everyone responded, but not at this `response` rate, +#' so `n` is the whole frame and the margin achieved will be wider than +#' the one asked for. It is never `TRUE` with `capped`.} +#' \item{`raised`}{`TRUE` when the margin alone needs one row, and +#' `n_effective` was raised to two, the fewest that give a standard +#' error and an interval.} #' \item{`margin`, `level`, `N`, `deff`, `response`, `target`}{The inputs, -#' returned so the assumptions travel with the number.} +#' returned so the assumptions travel with the number. `deff` is the +#' number used, also when an estimate was passed.} +#' \item{`p`}{The expected proportion for a proportion, and `NA` for a +#' mean or a total.} #' \item{`n_needed`}{Rows that would reach the margin if everyone -#' responded. Equal to `n_effective` unless `short` is `TRUE`.} -#' \item{`spread`}{The standard deviation used — `sd`, or -#' `sqrt(p * (1 - p))` for a proportion.} +#' responded, two at least as for `n_effective`. Equal to `n_effective` +#' unless the whole frame is drawn at a `response` below 1.} +#' \item{`spread`}{The standard deviation used, `sd`, or +#' `sqrt(p * (1 - p))` for a proportion. `NA` with `strata`.} #' } #' +#' With `strata` there are four more, and `raised` is always `FALSE`, +#' since `min_per_stratum` sets the floor: +#' \describe{ +#' \item{`allocation`}{The rows to draw from each stratum, a data frame +#' of the strata columns and `n`, in the order of `strata`. Pass it to +#' [design_stratified()] as `allocation` to draw that split.} +#' \item{`strata`}{The strata as given, checked, with `n` added.} +#' \item{`rule`, `min_per_stratum`}{The `allocation` rule and the floor +#' used.} +#' } +#' +#' A plan can be passed as `n` to any design that takes `n`, such as +#' `design_simple(n = plan)`, which draws `plan$n` rows. `as.data.frame()` +#' turns it into a data frame of one row, with a column for each field +#' above, except that a stratified plan has the number of `strata` in +#' place of the two data frames. Several plans at once give a data frame +#' of those rows, one per plan. +#' #' @examples #' # A proportion, no prior guess, 20,000 in the frame #' plan_size(margin = 0.03, N = 20000, target = "proportion") @@ -64,14 +155,99 @@ #' # A total, to within 100,000 across a 20,000-row frame #' plan_size(margin = 1e5, sd = 40, N = 20000, target = "total") #' +#' # Clusters of ten rows, whose rows correlate at 0.05, before any pilot +#' plan_size(margin = 5, sd = 40, N = 20000, +#' deff = deff_cluster(m = 10, icc = 0.05)) +#' +#' # Three margins at once, one plan per row +#' plan_size(margin = c(3, 5, 10), sd = 40, N = 20000) +#' +#' # A plan is a valid `n` +#' design_simple(n = plan_size(margin = 5, sd = 40, N = 20000)) +#' +#' # Three strata, with the spread of each from an earlier survey +#' bands <- data.frame(band = c("small", "medium", "large"), +#' N = c(1200, 600, 200), sd = c(10, 25, 80)) +#' plan <- plan_size(margin = 2, strata = bands, allocation = "neyman") +#' plan +#' frame <- data.frame(id = 1:2000, +#' band = rep(bands$band, times = bands$N)) +#' s <- draw(frame, design_stratified("band", allocation = plan$allocation), +#' seed = 1) +#' table(s$band) +#' +#' # The design effect of a cluster pilot, passed as the estimate itself +#' pop <- data.frame(cl = rep(paste0("c", 1:50), each = 8)) +#' pop$y <- rep(seq(10, 59), each = 8) + rep(c(-3, 3), 200) +#' pilot <- draw(pop, design_cluster("cl", n_clusters = 6), seed = 1, +#' weights = TRUE) +#' plan_size(margin = 3, sd = sd(pilot$y), N = nrow(pop), +#' deff = ht_mean(pilot, "y")) +#' +#' @section Planning a stratified sample: +#' With `strata`, `plan_size()` plans a stratified simple random sample, as +#' [design_stratified()] draws one. For each total `n` it splits `n` over +#' the strata as that design would, by the same `allocation` rule, the +#' floor `min_per_stratum` and largest-remainder rounding, with no stratum +#' given more rows than it has, and works out the variance of the +#' stratified mean, +#' `deff * sum(W_h^2 * (1 / n_h - 1 / N_h) * S_h^2)` with `W_h = N_h / N` +#' (Cochran 1977, chapter 5). For a proportion `S_h^2` is +#' `N_h * p_h * (1 - p_h) / (N_h - 1)`. The plan is the smallest `n` whose +#' variance is at most `(margin / z)^2`, with `margin / N` for a total. +#' `min_per_stratum` must be 1 or more, since an estimate leaves a stratum +#' without rows out. Without a floor, proportional allocation gives a +#' stratum of one row in a frame of 200,000 its first row at `n` of about +#' 100,000, and the plan would be that large. The rounded split can take a +#' row from one stratum as `n` grows, so the variance does not always fall +#' with `n`, and the search checks each `n` from the first that could meet +#' the margin. +#' +#' `response` divides `n` as without strata, and the rows to draw are split +#' by the same rule. The split is returned as `allocation`, which +#' [design_stratified()] takes as the count for each stratum. Passing the +#' plan as `n` instead lets the design split `n` again by its own rule and +#' `min_per_stratum`, whose default there is 0, which can leave a small +#' stratum without rows. +#' +#' @section Several plans at once: +#' `margin`, `sd`, `p`, `deff` and `response` each take one value, or +#' several for several plans. Those with one value are used for every plan, +#' and those with several must have the same number, one per plan, so +#' `plan_size(margin = c(3, 5, 10), sd = 40)` plans three margins at the +#' same spread. The result is then a data frame with a row per plan, as +#' `as.data.frame()` gives for each, without the split over strata or the +#' printed notes. +#' #' @section Where the formula comes from: -#' `n0 = (z * spread / margin)^2 * deff`, then Cochran's finite population -#' correction `n0 / (1 + (n0 - 1) / N)`, then division by `response` (Cochran -#' 1977, section 4.4; Valliant, Dever and Kreuter 2018, chapter 3). `z` is the -#' normal quantile. The interval [ht_total()] reports uses t on the design's -#' degrees of freedom, which is slightly wider when those are few — with a -#' handful of clusters, plan on more clusters rather than trusting the margin -#' to the last digit. +#' `n0 = (z * spread / margin)^2 * deff` is the size for an unbounded frame, +#' with `z` the normal quantile for `level` and, for a total, `margin / N` as +#' the margin on the mean. For a mean or a total the finite population +#' correction gives `n0 / (1 + n0 / N)`, the smallest `n` with +#' `(1 / n - 1 / N) * deff * sd^2 <= (margin / z)^2`. For a proportion, whose +#' variance `p * (1 - p)` has the divisor `N` rather than `N - 1`, it gives +#' `n0 / (1 + (n0 - 1) / N)`. The result is rounded up, raised to two when it +#' is one, and divided by `response` (Cochran 1977, chapter 4; Valliant, +#' Dever and Kreuter 2018, chapter 3). +#' +#' `margin` is the half-width the plan expects, the usual convention for +#' sizing a sample: the estimate from a sample of size `n` lands within +#' `margin` of the truth with probability about `level`. The interval a +#' sample reports is built from that sample's own estimate of the variance, +#' which comes out above the planned variance about as often as below it, so +#' the reported half-width is wider than `margin` about half the time. +#' +#' That interval also uses t on the design's degrees of freedom rather than +#' `z`, which matters when the primary sampling units are few. With 3, 4 and +#' 6 clusters in one stratum, which give 2, 3 and 5 degrees of freedom, the +#' 95% t quantile is 2.2, 1.6 and 1.3 times `z`. `plan_size()` counts rows +#' and knows nothing of clusters, so when you turn `n` into a few clusters, +#' plan more of them. +#' +#' For a proportion, [ht_mean()] reports an interval on the logit scale, which +#' is asymmetric. When `p` is small its upper arm is longer than its lower one, +#' and exceeds `margin` in most samples even when the estimate is as precise +#' as planned. #' #' @references #' Cochran, W. G. (1977). *Sampling Techniques*, 3rd ed. Wiley. @@ -81,123 +257,688 @@ #' Valliant, R., Dever, J. A. and Kreuter, F. (2018). *Practical Tools for #' Designing and Weighting Survey Samples*, 2nd ed. Springer. #' -#' @seealso [deff()] to measure the design effect of a past sample, [draw()] to +#' @seealso [deff()] to measure the design effect of a past sample, +#' [deff_cluster()] for one from an intraclass correlation, [draw()] to #' take the sample. #' @export plan_size <- function(margin, sd = NULL, p = 0.5, N = Inf, level = 0.95, deff = 1, response = 1, - target = c("mean", "proportion", "total")) { - target <- match.arg(target) - check_pos <- function(x, arg, allow_inf = FALSE) { - if (!is.numeric(x) || length(x) != 1L || is.na(x) || x <= 0 || - (!allow_inf && !is.finite(x))) { - stop("`", arg, "` must be a single positive number", - if (allow_inf) " (or Inf)" else "", ".", call. = FALSE) + target = c("mean", "proportion", "total"), + strata = NULL, + allocation = c("proportional", "equal", "neyman"), + min_per_stratum = 2L) { + target <- check_choice(target, c("mean", "proportion", "total"), "target") + check_pos <- function(x, arg, allow_inf = FALSE, several = TRUE) { + if (!is.numeric(x) || !length(x) || (!several && length(x) != 1L) || + anyNA(x) || any(x <= 0) || (!allow_inf && !all(is.finite(x)))) { + stop("`", arg, "` must be ", + if (several) "a positive number" else "a single positive number", + if (allow_inf) " (or Inf)" else "", + if (several) ", or a vector of them for several plans" else "", + ".", call. = FALSE) } x } margin <- check_pos(margin, "margin") - deff <- check_pos(deff, "deff") - N <- check_pos(N, "N", allow_inf = TRUE) + deff <- check_pos(plan_deff(deff, target), "deff") + if (is.null(strata)) { + given <- c("allocation", "min_per_stratum")[ + c(!missing(allocation) && !is.null(allocation), + !missing(min_per_stratum))] + if (length(given)) { + warn_drawn(paste0( + and_list(given), " ", + if (length(given) == 1L) "is" else "are", " not used without ", + "`strata`, which describes the strata to split `n` over. Give a ", + "row per stratum in `strata`, or leave ", + if (length(given) == 1L) "it" else "them", " out."), + "drawn_irrelevant_argument") + } + if (is.numeric(N) && length(N) > 1L) { + stop("`N` must be a single positive number (or Inf), not ", length(N), + " numbers. For a frame in strata, give each stratum's `N` and ", + "`sd` in `strata`, a data frame with a row per stratum.", + call. = FALSE) + } + N <- check_pos(N, "N", allow_inf = TRUE, several = FALSE) + if (N < 1) { + stop("`N` is ", format_bad(N), ", and a frame holds at least one row. ", + "Give the number of rows in the frame, or Inf.", call. = FALSE) + } + st <- NULL + } else { + given <- c("sd", "p", "N")[c(!is.null(sd), !missing(p), !missing(N))] + if (length(given)) { + warn_drawn(paste0( + and_list(given), " ", + if (length(given) == 1L) "is" else "are", " not used with ", + "`strata`, whose columns give each stratum's `N` and its `", + if (target == "proportion") "p" else "sd", "`. Leave ", + if (length(given) == 1L) "it" else "them", " out."), + "drawn_irrelevant_argument") + } + allocation <- check_choice(allocation, + c("proportional", "equal", "neyman"), + "allocation") + min_per_stratum <- check_count(min_per_stratum, "min_per_stratum") + if (min_per_stratum < 1L) { + stop("`min_per_stratum` is 0, which lets the split give a small ", + "stratum no rows until `n` is large, and an estimate leaves a ", + "stratum without rows out, so no margin holds for the frame. ", + "Use 1 or more, or the default of 2, which also gives each ", + "stratum a variance.", call. = FALSE) + } + st <- plan_strata(strata, target, allocation, min_per_stratum) + N <- st$N + } if (!is.numeric(level) || length(level) != 1L || is.na(level) || level <= 0 || level >= 1) { stop("`level` must be a single number strictly between 0 and 1.", call. = FALSE) } - if (!is.numeric(response) || length(response) != 1L || is.na(response) || - response <= 0 || response > 1) { - stop("`response` must be a single number in (0, 1].", call. = FALSE) + if (!is.numeric(response) || !length(response) || anyNA(response) || + any(response <= 0 | response > 1)) { + stop("`response` must be a number in (0, 1], or a vector of them for ", + "several plans.", call. = FALSE) } if (target == "proportion") { - if (!is.numeric(p) || length(p) != 1L || is.na(p) || p < 0 || p > 1) { - stop("`p` must be a single number in [0, 1].", call. = FALSE) + if (is.null(st) && !is.null(sd)) { + warn_drawn(paste0( + "`sd` is not used for target = \"proportion\", whose spread comes ", + "from `p`. Give the expected proportion as `p`, and leave `sd` out."), + "drawn_irrelevant_argument") } - spread <- sqrt(p * (1 - p)) - if (spread <= 0) { - stop("`p` of exactly 0 or 1 implies no variation and no sample is ", - "needed. Use a value strictly between 0 and 1.", call. = FALSE) + if (any(margin >= 1)) { + m <- margin[margin >= 1][1] + stop("`margin` is ", format_bad(m), ", and a proportion lies ", + "between 0 and 1, so a margin of 1 or more says nothing. Give it ", + "as a proportion, such as ", format(m / 100), " for ", + format(m), " percentage point", if (m != 1) "s", ".", + call. = FALSE) } - unit_margin <- margin - } else { - if (is.null(sd)) { - stop("`sd` is required for target = \"", target, "\". Use a pilot ", - "estimate, or a plausible range divided by four.", call. = FALSE) + if (is.null(st)) { + if (!is.numeric(p) || !length(p) || anyNA(p) || any(p < 0 | p > 1)) { + stop("`p` must be a number in [0, 1], or a vector of them for ", + "several plans.", call. = FALSE) + } + spread <- sqrt(p * (1 - p)) + if (any(spread <= 0)) { + stop("`p` of exactly 0 or 1 implies no variation and no sample is ", + "needed. Use a value strictly between 0 and 1.", call. = FALSE) + } + p_used <- p + } else { + spread <- NA_real_ + p_used <- NA_real_ } - spread <- check_pos(sd, "sd") - if (target == "total") { - if (!is.finite(N)) { - stop("A margin on a total needs a finite `N`.", call. = FALSE) + } else { + if (is.null(st)) { + if (is.null(sd)) { + stop("`sd` is required for target = \"", target, "\". Use a pilot ", + "estimate, or a plausible range divided by four.", + if (!missing(p)) { + " To plan a proportion from `p`, use target = \"proportion\"." + }, call. = FALSE) + } + if (!missing(p)) { + warn_drawn(paste0( + "`p` is not used for target = \"", target, "\", whose spread is ", + "`sd`. To plan a proportion from `p`, use target = \"proportion\"; ", + "otherwise leave `p` out."), "drawn_irrelevant_argument") } - # A margin of M on the total is a margin of M/N on the mean. - unit_margin <- margin / N + spread <- check_pos(sd, "sd") } else { - unit_margin <- margin + spread <- NA_real_ + } + if (target == "total" && !is.finite(N)) { + stop("A margin on a total needs a finite `N`.", call. = FALSE) } + p_used <- NA_real_ + } + + several <- list(margin = margin, deff = deff, response = response) + if (is.null(st)) { + several[[if (target == "proportion") "p" else "sd"]] <- spread + } + k <- plan_count(several) + one <- function(i) { + at <- function(x) x[[if (length(x) == 1L) 1L else i]] + plan_one(at(margin), at(spread), at(p_used), N, level, at(deff), + at(response), target, st) } + if (k == 1L) return(one(1L)) + do.call(rbind, lapply(seq_len(k), function(i) as.data.frame(one(i)))) +} + +#' Argument names in backticks, joined as "`a`, `b` and `c`" +#' @noRd +and_list <- function(names) { + named <- paste0("`", names, "`") + if (length(named) < 2L) return(named) + paste(paste(utils::head(named, -1L), collapse = ", "), + utils::tail(named, 1L), sep = " and ") +} + +#' How many plans the vector arguments of `plan_size()` ask for +#' +#' Each of `args` holds one value, or one per plan; one value is used for +#' every plan, as [base::Map()] recycles it. Lengths that differ otherwise +#' are refused, since recycling them would pair values by accident. +#' +#' @noRd +plan_count <- function(args) { + lens <- lengths(args) + k <- max(lens) + bad <- lens != 1L & lens != k + if (any(bad)) { + long <- names(lens)[lens == k][1] + other <- names(lens)[bad][1] + stop("`", long, "` has ", k, " values and `", other, "` has ", + lens[[other]], ". Give each of ", + paste0("`", utils::head(names(args), -1L), "`", collapse = ", "), + " and `", utils::tail(names(args), 1L), "` one value, or one for ", + "each plan.", call. = FALSE) + } + k +} +#' One plan from single values of each argument +#' +#' `plan_size()` has checked the arguments. `st` is `NULL`, or the strata +#' from `plan_strata()`. +#' +#' @noRd +plan_one <- function(margin, spread, p, N, level, deff, response, target, + st) { + # A margin of M on the total is a margin of M/N on the mean. + unit_margin <- if (target == "total") margin / N else margin z <- stats::qnorm(1 - (1 - level) / 2) - n0 <- (z * spread / unit_margin)^2 * deff - n_eff <- if (is.finite(N)) n0 / (1 + (n0 - 1) / N) else n0 - n_eff <- ceiling(n_eff) - if (is.finite(N)) n_eff <- min(n_eff, N) - n_draw <- ceiling(n_eff / response) + if (is.null(st)) { + n0 <- (z * spread / unit_margin)^2 * deff + # n0 is the size for an unbounded frame. For a mean or a total, whose sd + # has the divisor N - 1, the smallest n with (1/n - 1/N) S^2 deff <= + # (margin/z)^2 is n0 / (1 + n0/N). For a proportion, whose p(1 - p) has + # the divisor N, it is n0 / (1 + (n0 - 1)/N). Both are written with n0 + # in a denominator, so an n0 too large for a double gives N, a census. + n_eff <- if (!is.finite(N)) { + n0 + } else if (target == "proportion") { + N / (1 + (N - 1) / n0) + } else { + N / (1 + N / n0) + } + if (is.na(n_eff) || (!is.finite(N) && !is.finite(n_eff / response))) { + shown <- format(level) + if (shown == "1") shown <- format(level, digits = 17) + stop("`margin` = ", format_bad(margin), " with a spread of ", + format(signif(spread, 4)), " at `level` = ", shown, " needs more ", + "rows than a number can hold. Widen `margin` or lower `level`", + if (!is.finite(N)) ", or give a finite `N`", ".", call. = FALSE) + } - # Two different situations, and only one of them is a census. `capped` means - # the frame cannot reach the margin however hard you sample; `short` means it - # could, but not once non-response has taken its share. - capped <- is.finite(N) && n_eff >= N - short <- is.finite(N) && n_draw > N + # The tolerance keeps a rounding error from adding a row. + n_margin <- max(1, ceiling(n_eff - 1e-9)) + if (is.finite(N)) n_margin <- min(n_margin, floor(N)) + capped <- is.finite(N) && n_margin >= floor(N) + # One row meets a margin of about two standard deviations, but gives no + # variance and no interval. + raised <- n_margin < 2 && floor(N) >= 2 + n_eff <- if (raised) 2 else n_margin + } else { + n_margin <- strata_size(st, (unit_margin / z)^2 / deff) + capped <- n_margin >= N + # The floor `min_per_stratum` takes the place of the two rows. + raised <- FALSE + n_eff <- n_margin + } n_needed <- n_eff - if (short) { - n_draw <- N - n_eff <- min(n_eff, floor(n_draw * response)) + # 21 / 0.7 is 30.000000000000004 in floating point, and the tolerance + # keeps it at 30 rows. + n_draw <- ceiling(n_eff / response - 1e-9) + + # Two different situations, and only one of them is a census. `capped` + # means only a census meets the margin; `short` means a smaller sample + # would, but not once non-response has taken its share. Either way the + # frame is drawn whole, and fewer rows come back when response < 1. + short <- !capped && n_draw > floor(N) + if (n_draw > floor(N)) { + n_draw <- floor(N) + n_eff <- min(n_eff, floor(n_draw * response + 1e-9)) } - structure( - list(n = n_draw, n_effective = n_eff, margin = margin, level = level, - N = N, deff = deff, response = response, target = target, - spread = spread, capped = capped, short = short, - n_needed = n_needed), - class = "drawn_plan" - ) + out <- list(n = n_draw, n_effective = n_eff, margin = margin, + level = level, N = N, deff = deff, response = response, + target = target, spread = spread, p = p, capped = capped, + short = short, raised = raised, n_needed = n_needed) + if (!is.null(st)) { + tab <- st$table + tab$n <- integer(nrow(tab)) + tab$n[st$order] <- strata_split(st, n_draw) + out$rule <- st$rule + out$min_per_stratum <- st$floor + out$strata <- tab + out$allocation <- tab[c(st$keys, "n")] + } + structure(out, class = "drawn_plan") +} + +#' Check the strata given to `plan_size()`, and put them in key order +#' +#' `strata` is a data frame of the columns that name the strata, `N`, `sd` +#' (or `p` for a proportion) and, for Neyman allocation, an optional +#' `cost`. Returns the checked table in the order given, and in key order, +#' the order `design_stratified()` allocates in, the sizes, the variances +#' `S_h^2`, the spreads and costs for Neyman allocation, and `w2`, each +#' stratum's squared share of the frame. +#' +#' @noRd +plan_strata <- function(strata, target, allocation, min_per_stratum) { + spread_col <- if (target == "proportion") "p" else "sd" + if (!is.data.frame(strata)) { + stop("`strata` must be a data frame with a row per stratum, holding the ", + "columns that name the strata, `N` and `", spread_col, "`, not ", + format_bad(strata), ".", call. = FALSE) + } + given <- names(strata) + if ("n" %in% given) { + stop("`strata` has a column `n`, which is what plan_size() works out. ", + "Give the number of rows of the frame in each stratum as `N`.", + call. = FALSE) + } + keys <- setdiff(given, c("N", "sd", "p", "cost")) + if (!length(keys)) { + stop("`strata` has no column naming the strata. Add one, such as the ", + "column `design_stratified()` will take as `strata`, beside `N` ", + "and `", spread_col, "`.", call. = FALSE) + } + need <- setdiff(c("N", spread_col), given) + if (length(need)) { + what <- c(N = "the number of rows of the frame in each stratum", + sd = paste0("the standard deviation of the measure in each ", + "stratum, from a pilot or an earlier survey"), + p = "the expected proportion in each stratum") + stop("`strata` needs a column `", need[1], "`, ", what[[need[1]]], ".", + call. = FALSE) + } + unused <- setdiff(intersect(c("sd", "p"), given), spread_col) + if (length(unused)) { + warn_drawn(paste0( + "`strata` has a `", unused, "` column, which target = \"", target, + "\" does not use, since its spread is the `", spread_col, "` column. ", + "Leave it out", if (unused == "p") { + ", or use target = \"proportion\"" + }, "."), "drawn_irrelevant_argument") + } + has_cost <- "cost" %in% given + if (has_cost && allocation != "neyman") { + stop("`strata` has a `cost` column, which applies only to allocation = ", + "\"neyman\", and `allocation` is \"", allocation, "\". Use ", + "allocation = \"neyman\", or drop the column.", call. = FALSE) + } + value <- c("N", spread_col, if (has_cost) "cost") + spec <- strata_frame(strata, keys, "strata", value) + + sizes <- spec$N + if (!is.numeric(sizes)) { + stop("The stratum sizes in `strata$N` must be numbers, not ", + class(sizes)[1], ".", call. = FALSE) + } + bad <- !is.finite(sizes) | sizes < 1 | sizes != trunc(sizes) | + sizes > .Machine$integer.max + if (any(bad)) { + h <- which(bad)[1] + stop("The stratum sizes in `strata$N` must be whole numbers of 1 or ", + "more, the rows of the frame in each stratum, and stratum ", + spec_label(spec, keys, h), " has ", format(sizes[h]), ".", + call. = FALSE) + } + spec$N <- as.integer(sizes) + sizes <- as.numeric(sizes) + if (spread_col == "sd") { + spread <- check_stratum_values(spec[c(keys, "sd")], keys, "strata", + "sd")$sd + spec$sd <- spread + s2 <- spread^2 + } else { + p <- spec$p + if (!is.numeric(p)) { + stop("The proportions in `strata$p` must be numbers, not ", + class(p)[1], ".", call. = FALSE) + } + bad <- is.na(p) | p < 0 | p > 1 + if (any(bad)) { + h <- which(bad)[1] + stop("The proportions in `strata$p` must lie between 0 and 1, and ", + "stratum ", spec_label(spec, keys, h), " has ", format(p[h]), ".", + call. = FALSE) + } + # p(1 - p) has the divisor N_h; S_h^2 has N_h - 1. A stratum of one row + # is taken whole and adds nothing. + s2 <- ifelse(sizes > 1, sizes * p * (1 - p) / pmax(sizes - 1, 1), 0) + spread <- sqrt(s2) + } + cost <- if (has_cost) { + spec$cost <- check_stratum_values(spec[c(keys, "cost")], keys, "strata", + "cost", positive = TRUE)$cost + spec$cost + } + + o <- order(as.integer(group_key(spec, keys))) + # Neyman shares do not change when every spread is scaled alike, and a + # spread near the largest double would overflow `size * spread`. + if (any(spread > 0)) spread <- spread / max(spread) + N <- sum(sizes) + list(table = spec, keys = keys, order = o, sizes = sizes[o], + s2 = s2[o], w2 = (sizes[o] / N)^2, + spread = if (allocation == "neyman") spread[o], + cost = if (!is.null(cost)) cost[o], + rule = allocation, floor = min_per_stratum, N = N) +} + +#' The split of `n` over the strata of a plan, in key order +#' +#' As `design_stratified()` splits it: the same rule, floor and +#' largest-remainder rounding, with no stratum given more rows than it has. +#' +#' @noRd +strata_split <- function(st, n) { + allocate(n, st$sizes, st$rule, st$floor, cap = TRUE, spread = st$spread, + cost = st$cost) +} + +#' Variance of a stratified mean for a split `n_h` of a plan's strata +#' +#' `sum(W_h^2 * (1 / n_h - 1 / N_h) * S_h^2)`. A stratum taken whole adds +#' nothing, even when its `S_h^2` is too large for a double. A split that +#' leaves a stratum with no rows gives `Inf`, since the estimate then leaves +#' the stratum out and no margin holds for it. +#' +#' @noRd +strata_variance <- function(st, n_h) { + if (any(n_h < 1)) return(Inf) + sum(st$w2 * ifelse(n_h >= st$sizes, 0, (1 / n_h - 1 / st$sizes) * st$s2)) +} + +#' The smallest total whose split meets a variance bound +#' +#' The variance of the rounded split need not fall as `n` grows, since +#' largest-remainder rounding can give a stratum one row fewer at `n + 1` +#' than at `n`. So the search scans upward from the first `n` that a lower +#' bound on the variance allows. Rounding gives each stratum its share +#' before rounding, rounded down or up. A share that is a whole number gets +#' no row more: the rows left over after rounding down add up to the +#' fractional parts, fewer than the strata that have one, and those strata +#' take the rows first. The shares never fall as `n` grows, so the variance +#' at the shares rounded up is a lower bound that falls with `n`, and +#' bisection finds the first `n` it allows. Every smaller `n` has a variance +#' above `bound`, and the scan ends at the census at the latest, whose +#' variance is 0. With a floor of one row or more every split in the scan +#' gives each stratum a row. +#' +#' @noRd +strata_size <- function(st, bound) { + limit <- bound * (1 + 1e-9) + share <- allocation_share(st$rule, st$sizes, st$spread, st$cost) + lower <- group_floor(st$floor, st$sizes, cap = TRUE) + floor_at <- function(n) { + raw <- capped_shares(n, share, st$sizes, cap = TRUE, lower = lower) + strata_variance(st, pmin(ceiling(raw), st$sizes)) + } + lo <- sum(lower) + hi <- st$N + if (floor_at(lo) > limit) { + while (hi - lo > 1) { + mid <- floor((lo + hi) / 2) + if (floor_at(mid) <= limit) hi <- mid else lo <- mid + } + lo <- hi + } + n <- lo + while (n < st$N && strata_variance(st, strata_split(st, n)) > limit) { + n <- n + 1 + } + n +} + +#' The design effect `plan_size()` inflates by +#' +#' `deff` is a number, or a result of `ht_mean()` or `ht_total()` whose own +#' design effect is used. The estimate must be of the kind `target` plans, +#' since a mean's design effect and a total's differ for the same sample. +#' Any other object is refused by class, also one that is a number +#' underneath, such as an estimate from `survey`, whose value is the +#' estimate rather than its design effect. A number marked with [I()] is +#' a plain number and is taken as one. An `NA`, which `deff()` gives for +#' a pilot without a variance, is refused with that reason. Any other number +#' is left to `plan_size()`'s own check. +#' +#' @noRd +plan_deff <- function(deff, target) { + na_fix <- paste0("Use a pilot that has a variance, or a design effect from ", + "a similar survey.") + if (inherits(deff, c("drawn_mean", "drawn_ht"))) { + if (inherits(deff, "drawn_mean") && target == "total") { + stop("`deff` is a mean from ht_mean(), and `target` is \"total\". ", + "Pass ht_total() on the same pilot, since the design effects of a ", + "mean and a total can differ many times over for one sample. A ", + "total reported as N times a mean is planned as target = \"mean\" ", + "with `margin` divided by N.", call. = FALSE) + } + if (inherits(deff, "drawn_ht") && target != "total") { + stop("`deff` is a total from ht_total(), and `target` is \"", target, + "\". Pass ht_mean() on the same pilot, since the design effects ", + "of a total and a mean can differ many times over for one sample.", + call. = FALSE) + } + value <- deff[["deff"]] + if (length(value) != 1L || is.na(value)) { + if (isTRUE(deff[["n_missing"]] > 0)) { + stop("`deff` has a design effect of NA, which ht_mean(na_rm = TRUE) ", + "gives when `y` is missing in some sampled rows, since the rows ", + "with `y` are a domain and a domain's design effect is not ", + "estimated. Use a pilot with `y` in every sampled row, or a ", + "design effect from a similar survey.", call. = FALSE) + } + stop("`deff` has a design effect of NA, which a pilot with no variance ", + "estimate or with one value of `y` gives. ", na_fix, call. = FALSE) + } + return(value) + } + if (identical(oldClass(deff), "AsIs") && is.numeric(unclass(deff))) { + deff <- unclass(deff) + } + if (is.object(deff) || !is.atomic(deff)) { + from_survey <- inherits(deff, c("svystat", "svrepstat")) + cls <- class(deff)[1] + stop("`deff` is ", with_article(cls, paste0("`", cls, "`")), + if (from_survey) { + ", whose value is the survey estimate, not its design effect" + }, ". Give a design effect as a positive number, a vector of them for ", + "several plans, or the result of ht_mean() or ht_total() for one ", + "variable without `by`.", if (from_survey) { + " survey::deff() reads the design effect out of a survey estimate." + }, call. = FALSE) + } + if (length(deff) && anyNA(deff)) { + stop("`deff` ", if (length(deff) == 1L) "is NA" else "holds an NA", + ", which deff() gives for a pilot with no variance estimate or with ", + "one value of `y`, and for a mean from ht_mean(na_rm = TRUE) with ", + "`y` missing in some rows. ", na_fix, call. = FALSE) + } + deff } #' @export print.drawn_plan <- function(x, ...) { - cat("Sample size for a ", x$target, "\n", sep = "") + by_strata <- !is.null(x$allocation) + cat("Sample size for a ", x$target, + if (by_strata) paste0(", over ", nrow(x$allocation), " strata"), "\n", + sep = "") cat(" draw ", fmt_n(x$n), "\n", sep = "") if (x$n != x$n_effective) { cat(" to analyse ", fmt_n(x$n_effective), " (after ", format(100 * x$response), "% response)\n", sep = "") } - cat(" margin +/- ", format(x$margin), " at ", + cat(" margin +/- ", + format(x$margin, big.mark = ",", scientific = 15), " at ", format(100 * x$level), "% confidence\n", sep = "") - cat(" assuming sd ", signif(x$spread, 4), + spread <- if (by_strata) { + paste0(if (x$rule == "neyman") "Neyman" else x$rule, " allocation", + if (x$min_per_stratum > 0L) { + paste0(", at least ", x$min_per_stratum, " row", + if (x$min_per_stratum != 1L) "s", " per stratum") + }) + } else if (identical(x$target, "proportion") && isTRUE(x$p >= 0)) { + paste0("p ", signif(x$p, 4)) + } else { + paste0("sd ", signif(x$spread, 4)) + } + frame <- if (!is.finite(x$N)) { + "unbounded" + } else if (x$N == floor(x$N)) { + fmt_n(x$N) + } else { + format(x$N, big.mark = ",") + } + cat(" assuming ", spread, if (x$deff != 1) paste0(", deff ", signif(x$deff, 3)) else "", - ", N ", if (is.finite(x$N)) fmt_n(x$N) else "unbounded", "\n", sep = "") + ", N ", frame, "\n", sep = "") + if (by_strata) print_strata(x$strata) msg <- if (isTRUE(x$capped)) { - paste0("That is a census: the frame is not large enough to reach this ", - "margin by sampling, so every row is needed. ", + paste0("That is a census. No sample smaller than the frame meets this ", + "margin, so every row is needed. ", if (x$response < 1) paste0( "Even then only about ", fmt_n(x$n_effective), " will come back, ", "which will fall short of the margin asked for. "), "Widen `margin`, or accept the precision a full count gives.") } else if (isTRUE(x$short)) { - paste0("The frame can reach this margin -- ", fmt_n(x$n_needed), - " rows would do it -- but not at ", format(100 * x$response), - "% response, which would need more rows than the frame holds. ", - "Every row is drawn, and the margin achieved will be wider than ", - "the one asked for.") + paste0("The frame can reach this margin, with ", fmt_n(x$n_needed), + " rows, but not at ", format(100 * x$response), "% response, ", + "which would need more rows than the frame holds. Every row is ", + "drawn, and the margin achieved will be wider than the one asked ", + "for.") } else { NULL } if (!is.null(msg)) { cat_note(msg) } + if (isTRUE(x$raised)) { + cat_note(paste0("One row meets this margin, but a standard error and an ", + "interval need two, so the plan is for two.")) + } invisible(x) } +#' The strata of a plan, ten at most, with the rows to draw from each +#' @noRd +print_strata <- function(tab, max = 10L) { + shown <- utils::capture.output( + print(utils::head(tab, max), row.names = FALSE)) + cat("\n", paste0(" ", shown, "\n"), sep = "") + if (nrow(tab) > max) { + cat(" ... and ", nrow(tab) - max, " more strata, all in ", + "`$allocation`\n", sep = "") + } +} + +#' @export +as.data.frame.drawn_plan <- function(x, row.names = NULL, optional = FALSE, + ...) { + fields <- c("n", "n_effective", "margin", "level", "N", "deff", "response", + "target", "spread", "p", "capped", "short", "raised", + "n_needed") + out <- data.frame(unclass(x)[fields], stringsAsFactors = FALSE) + if (!is.null(x$allocation)) { + out$strata <- nrow(x$allocation) + out$rule <- x$rule + out$min_per_stratum <- x$min_per_stratum + } + if (!is.null(row.names)) row.names(out) <- row.names + out +} + +#' Design effect of a cluster sample, from the intraclass correlation +#' +#' The design effect of taking `m` rows from each cluster, for +#' [plan_size()] before a pilot has measured one with [deff()]: +#' `1 + (m - 1) * icc`, with `icc` the intraclass correlation of the +#' measure, the correlation between two rows of one cluster (Kish 1965). +#' Rows of one cluster tend to be alike, so each row taken from a cluster +#' already sampled adds less than a row from a new cluster would, and the +#' more alike they are and the more taken from each, the larger the design +#' effect. +#' +#' The formula assumes every cluster gives the same number of rows, drawn +#' by simple random sampling of clusters. `plan_size()` counts rows, so a +#' plan of `n` rows in clusters of `m` takes `ceiling(n / m)` clusters, and +#' the "Where the formula comes from" section of [plan_size()] explains why +#' a few clusters call for more than the plan. +#' +#' @param m Rows taken from each cluster, 1 or more. With one row a +#' cluster, the design effect is 1 whatever `icc` is. +#' @param icc Intraclass correlation, from a pilot or a published study of +#' the same measure, between `-1 / (m - 1)` and 1. A negative one, rows +#' of a cluster less alike than rows taken at random, gives a design +#' effect below 1. +#' +#' @return The design effect, a number. `m` and `icc` may be vectors, +#' recycled to a common length, and give one design effect per pair. +#' +#' @references +#' Kish, L. (1965). *Survey Sampling*. Wiley. +#' +#' @examples +#' deff_cluster(m = 10, icc = 0.05) +#' +#' # Rows to draw, and the clusters of ten rows that hold them +#' p <- plan_size(margin = 5, sd = 40, N = 20000, +#' deff = deff_cluster(m = 10, icc = 0.05)) +#' p$n +#' ceiling(p$n / 10) +#' +#' # Takes of 5, 10 and 20 rows a cluster, side by side +#' plan_size(margin = 5, sd = 40, N = 20000, +#' deff = deff_cluster(m = c(5, 10, 20), icc = 0.05)) +#' +#' @seealso [plan_size()], [deff()] to measure the design effect of a past +#' sample. +#' @export +deff_cluster <- function(m, icc) { + if (!is.numeric(m) || !length(m) || anyNA(m) || !all(is.finite(m)) || + any(m < 1)) { + stop("`m` must be the rows taken from each cluster, a finite number of ", + "1 or more, not ", format_bad(m, value = TRUE), ".", + call. = FALSE) + } + if (!is.numeric(icc) || !length(icc) || anyNA(icc) || + !all(is.finite(icc))) { + stop("`icc` must be a finite number, the intraclass correlation, not ", + format_bad(icc, value = TRUE), ".", call. = FALSE) + } + k <- max(length(m), length(icc)) + if (!all(c(length(m), length(icc)) %in% c(1L, k))) { + stop("`m` has ", length(m), " values and `icc` has ", length(icc), + ". Give each one value, or the same number of values.", + call. = FALSE) + } + m <- rep_len(m, k) + icc <- rep_len(icc, k) + low <- ifelse(m > 1, -1 / (m - 1), -Inf) + # A rounding error below the bound still means the bound. + bad <- icc > 1 | icc < low - 1e-12 + if (any(bad)) { + i <- which(bad)[1] + stop("`icc` must lie between -1 / (m - 1) and 1, and is ", + format(icc[i]), " with `m` = ", format(m[i]), + if (icc[i] < 1) paste0(", below ", format(signif(low[i], 3))), + ". A correlation above 1 is impossible, and one below the bound ", + "would make the design effect negative.", call. = FALSE) + } + pmax(1 + (m - 1) * icc, 0) +} + #' Describe a drawn sample #' #' What you actually got, against what the design asked for. Worth a look before @@ -210,16 +951,70 @@ print.drawn_plan <- function(x, ...) { #' \describe{ #' \item{`design`}{The design's type, as a string.} #' \item{`n`, `N`}{Rows drawn, and rows in the frame.} +#' \item{`N_reachable`}{Rows of the frame the design gives a probability +#' above 0, the population it samples. For weights conditional on the +#' clusters selected, the rows of the clusters not selected count, since +#' another selection could have drawn them. The printed sampling +#' fraction is `n / N_reachable`. `NA` only when the frame's +#' probabilities cannot be worked out, for an empty sample saved by +#' drawn 0.2.0, which records none, from a design with no closed-form +#' inclusion probability. The fraction is then `n / N`.} +#' \item{`expected_n`}{The sample size the design expects, the sum of +#' the inclusion probabilities over the frame. It is `n` for a design +#' of fixed size, and printed beside `n` when the two differ, as they +#' can under Poisson sampling, a [design_systematic()] `interval` that +#' does not divide the frame, or clusters of unequal size. `NA` where +#' `N_reachable` is, and for weights conditional on the clusters +#' selected.} #' \item{`weight_range`}{The smallest and largest design weight.} #' \item{`weight_cv`}{Their coefficient of variation. Large values mean a #' few rows carry most of the estimate.} -#' \item{`unreachable`}{Frame rows with inclusion probability 0 — the -#' design could never have selected them. `NA` if the design has no -#' closed-form inclusion probability.} +#' \item{`n_kish`}{Kish's effective sample size, `sum(w)^2 / sum(w^2)` +#' over the weights `w`, which is `n / (1 + cv^2)` with the +#' coefficient of variation computed with divisor `n`: the size of a +#' simple random sample that would estimate a mean as precisely if +#' unequal weights were the only cost. Clustering and stratification +#' are not in it; [deff()] measures those.} +#' \item{`n_certain`}{Sampled rows taken with certainty, at a probability +#' of 1.} +#' \item{`certain_by`}{Those rows by why they are certain, a named count: +#' `threshold`, above the threshold of [design_certainty()]; `size`, +#' put at probability 1 by a size measure, in [design_weighted()] or +#' in [design_spread()] or [design_multistage()] with `size`, which +#' includes the rows of a cluster put at 1 by its size and then taken +#' whole; and `whole`, in a stratum, interval or cluster taken whole, +#' or a census, with a size measure or without. Under a size measure a +#' group counts as taken whole when the design gives every row of it +#' probability 1, or every cluster of a multistage design a +#' first-stage probability of 1, so a Poisson sample that holds every +#' row of a stratum by chance files its certain rows under `size`.} +#' \item{`conditional`}{The number of clusters selected, when the +#' weights are conditional on them, as for [design_cluster()] with +#' `balanced = TRUE` (see "Design weights" in [draw()]); otherwise +#' `NA`.} +#' \item{`unreachable`}{Frame rows with inclusion probability 0, which +#' the design could never have selected, such as rows `na_rm` drops. +#' `NA` where `N_reachable` is.} #' \item{`by_group`}{A data frame of `group`, `drawn`, `in_frame` and -#' `rate` per stratum or cluster, or `NULL` for a design with no -#' grouping.} +#' `rate` per stratum, interval or cluster, or `NULL` for a design with +#' no grouping. The strata are those of [design_stratified()], and of +#' [design_spread()] and [design_weighted()] when they have `strata`, +#' and every stratum of the frame is listed, one allocated no rows +#' included. A stratum's `in_frame` counts the rows the design can +#' draw from it, as `N` of [allocation_table()] does, so rows `na_rm` +#' drops are left out, and a stratum it empties is not listed. The +#' intervals of [design_temporal()] are listed in time +#' order and named by their start, such as `"2024-01-03 00:00"`. For +#' [design_cluster()] and [design_multistage()], only the clusters +#' drawn are listed. For [design_certainty()], the groups are those of +#' its `rest` over the rows below the threshold, after a `"(certain)"` +#' row for the rows above it.} #' \item{`group_col`}{The column(s) `by_group` is keyed on.} +#' \item{`drawn`}{How the sample was drawn, from its `drawn_meta` +#' attribute: `seed`, `rng_kind`, `version`, `time`, `frame_rows` and +#' `made_by` (see "Seeding" in [draw()]). `NULL` for a sample from an +#' earlier version of drawn, which recorded none. The print shows the +#' seed, the version and the date.} #' } #' #' @examples @@ -234,54 +1029,243 @@ print.drawn_plan <- function(x, ...) { #' @seealso [draw()], [deff()] #' @export sample_summary <- function(sample) { - if (!is.data.frame(sample) || is.null(attr(sample, "drawn_design"))) { - stop("`sample` must be a data frame from draw(..., weights = TRUE).", - call. = FALSE) - } - design <- attr(sample, "drawn_design") - pop <- attr(sample, "drawn_population") + state <- drawn_state(sample) + design <- state$design + pop <- state$pop w <- sample$.weight + groups <- summary_groups(design, pop, state$rows) + certain <- is_certain(sample$.prob) - grp_col <- switch(design_type(design), - stratified = design$strata, - cluster = , - multistage = design$clusters, - NULL - ) - by_group <- NULL - if (!is.null(grp_col) && all(grp_col %in% names(sample))) { - got <- table(group_key(sample, grp_col)) - have <- table(group_key(pop, grp_col)) - by_group <- data.frame( - group = group_label(names(got)), - drawn = as.integer(got), - in_frame = as.integer(have[names(got)]), - rate = round(as.integer(got) / as.integer(have[names(got)]), 4), - row.names = NULL - ) - } - - pi_all <- tryCatch(exact_inclusion(design, pop), error = function(e) NULL) + pi_all <- state$pi_all %||% + tryCatch(exact_inclusion(design, pop), error = function(e) NULL) structure(list( design = design_type(design), n = nrow(sample), N = nrow(pop), + N_reachable = if (is.null(pi_all)) { + NA_integer_ + } else { + sum(reachable(pi_all)) + }, + # Weights conditional on the clusters selected leave the probabilities + # of the rest of the frame unknown (NA), and their sum with them. + expected_n = if (is.null(pi_all)) NA_real_ else sum(pi_all), weight_range = if (length(w)) range(w, na.rm = TRUE) else c(NA, NA), weight_cv = if (length(w) > 1L && mean(w, na.rm = TRUE) > 0) { stats::sd(w, na.rm = TRUE) / mean(w, na.rm = TRUE) } else NA_real_, - unreachable = if (is.null(pi_all)) NA_integer_ else sum(pi_all == 0), - by_group = by_group, - group_col = grp_col + n_kish = if (length(w) && sum(w^2, na.rm = TRUE) > 0) { + sum(w, na.rm = TRUE)^2 / sum(w^2, na.rm = TRUE) + } else NA_real_, + n_certain = sum(certain), + certain_by = certain_counts(design, pop, state$rows, certain, pi_all), + conditional = if (is.null(state$selection)) { + NA_integer_ + } else { + length(state$selection) + }, + unreachable = if (is.null(pi_all)) { + NA_integer_ + } else { + sum(!reachable(pi_all)) + }, + by_group = groups$table, + group_col = groups$col, + drawn = state$meta ), class = "drawn_summary") } +#' The line of a summary that says how the sample was drawn +#' +#' The seed, or that there was none, with the generator when it is not R's +#' default; then the version of drawn and the date. A sample rebuilt by +#' as_drawn() says so, since its seed is not known. +#' +#' @noRd +meta_line <- function(meta) { + stamp <- paste0("drawn ", meta$version, " on ", + format(meta$time, "%Y-%m-%d")) + if (!identical(meta$made_by, "draw()")) { + return(paste0(" rebuilt by ", meta$made_by, " of ", stamp, + "; the seed is not recorded")) + } + kind <- if (!identical(meta$rng_kind, seed_kind())) { + paste0(" (", paste(meta$rng_kind, collapse = ", "), ")") + } + paste0(" drawn ", + if (is.null(meta$seed)) { + "without a seed" + } else { + paste0("with seed ", format(meta$seed, scientific = FALSE)) + }, kind, ", by ", stamp) +} + +#' Rows drawn against rows in the frame, per stratum, interval or cluster +#' +#' Keyed on the frame and counted at the sampled frame rows `rows`, so a +#' stratum or cluster column renamed or recoded in the sample after the draw +#' still counts the groups that were drawn. Strata and intervals are listed +#' whether drawn or not, so one allocated no rows shows as 0; clusters only +#' when drawn, since most clusters of a frame are not. A certainty design's +#' groups are its `rest`'s over the rows below the threshold, after a row for +#' those above it. Returns `NULL` for a design with no grouping, otherwise +#' `table` and `col`, the column(s) keyed on. +#' +#' @noRd +summary_groups <- function(design, pop, rows) { + if (inherits(design, "drawn_design_certainty")) { + sp <- certainty_parts(design, pop) + top <- sp$keep[sp$take] + pos <- match(rows, sp$keep[sp$rest]) + inner <- summary_groups(design$rest, sp$rest_data, pos[!is.na(pos)]) + if (is.null(inner)) return(NULL) + got <- sum(rows %in% top) + inner$table <- rbind( + data.frame(group = "(certain)", drawn = got, in_frame = length(top), + rate = if (length(top)) round(got / length(top), 4) else NA, + row.names = NULL), + inner$table) + return(inner) + } + type <- design_type(design) + col <- switch(type, + stratified = , + spread = , + weighted = design$strata, + cluster = , + multistage = design$clusters, + temporal = design$time, + NULL + ) + if (is.null(col)) return(NULL) + key <- if (type == "temporal") { + temporal_bucket(design, pop) + } else { + group_key(pop, col) + } + if (walks_strata(design)) { + # Rows the walk leaves out for a missing `order_by` are in no stratum. + key[is.na(stratum_allocation(design, pop)$code)] <- NA + } + if (type %in% c("spread", "weighted")) { + # A spread or weighted design allocates over the rows it keeps, so rows + # its `na_rm` drops are in no stratum, as in allocation_table(). + keep <- if (type == "spread") { + spread_frame(design, pop)$keep + } else { + weighted_setup(design, pop)$keep + } + key[!seq_along(key) %in% keep] <- NA + } + code <- as.integer(key) + got <- tabulate(code[rows], nlevels(key)) + have <- tabulate(code, nlevels(key)) + shown <- if (type %in% c("cluster", "multistage")) { + which(got > 0L) + } else { + which(have > 0L) + } + list(table = data.frame( + group = group_label(levels(key)[shown]), + drawn = got[shown], + in_frame = have[shown], + rate = round(got[shown] / have[shown], 4), + row.names = NULL + ), col = col) +} + +#' Sampled rows taken with certainty, by why they are certain +#' +#' `certain` marks the sampled rows at probability 1 and `rows` gives their +#' frame rows. Rows above a certainty design's threshold count as +#' `threshold`; the others are put there by the design below it, a size +#' measure (`size`) or a group taken whole (`whole`). Under a design with a +#' size measure, a certain row counts as `whole` when the design takes its +#' group whole (see `groups_taken_whole()`), since the size measure then +#' made no difference. `pi_all`, the frame's probabilities, says which rows +#' the design could reach and which it takes with certainty; `NULL` counts +#' every row as reachable. +#' +#' @noRd +certain_counts <- function(design, pop, rows, certain, pi_all = NULL) { + out <- c(threshold = 0L, size = 0L, whole = 0L) + while (inherits(design, "drawn_design_certainty")) { + sp <- certainty_parts(design, pop) + out[["threshold"]] <- out[["threshold"]] + + sum(certain & rows %in% sp$keep[sp$take]) + pos <- match(rows, sp$keep[sp$rest]) + certain <- certain[!is.na(pos)] + rows <- pos[!is.na(pos)] + if (!is.null(pi_all)) pi_all <- pi_all[sp$keep[sp$rest]] + pop <- sp$rest_data + design <- design$rest + } + by_size <- inherits(design, "drawn_design_weighted") || + (inherits(design, c("drawn_design_spread", "drawn_design_multistage")) && + !is.null(design$size)) + whole <- if (by_size) { + groups_taken_whole(design, pop, rows, certain, pi_all) + } else { + TRUE + } + out[["whole"]] <- out[["whole"]] + sum(certain & whole) + out[["size"]] <- out[["size"]] + sum(certain & !whole) + out +} + +#' Whether the design takes each sampled row's group whole, under a size measure +#' +#' The answer comes from the design's probabilities, so every sample of a +#' design files its certain rows alike. A multistage design takes its +#' clusters whole when every cluster it could reach has a stage-one +#' probability of 1. A weighted or spread design takes a stratum whole, or +#' the frame when it has no strata, when every row of it the design could +#' reach has probability 1. A Poisson draw can hold every row of a stratum +#' by chance; its rows below 1 keep the stratum from counting as whole. +#' Without `pi_all` the certain rows of the frame are the sampled rows +#' marked `certain`, since a row at probability 1 is always drawn. +#' +#' @noRd +groups_taken_whole <- function(design, pop, rows, certain, pi_all) { + if (inherits(design, "drawn_design_multistage")) { + pi1 <- cluster_stage(design, pop)$pi1 + return(rep(all(is_certain(pi1)), length(rows))) + } + code <- if (is.null(design$strata)) { + rep(1L, nrow(pop)) + } else { + as.integer(group_key(pop, design$strata)) + } + k <- max(c(0L, code), na.rm = TRUE) + if (is.null(pi_all)) { + sure <- tabulate(code[rows[certain]], k) + have <- tabulate(code, k) + } else { + reach <- reachable(pi_all) + sure <- tabulate(code[which(reach & is_certain(pi_all))], k) + have <- tabulate(code[reach], k) + } + (sure == have)[code[rows]] +} + #' @export print.drawn_summary <- function(x, ...) { cat("Sample of ", fmt_n(x$n), " from ", fmt_n(x$N), " (", x$design, " design)\n", sep = "") - cat(" sampling fraction ", signif(x$n / x$N, 3), "\n", sep = "") + # The fraction of the rows the design could draw: rows at probability 0 + # are listed below as unreachable, and counting them in would understate + # it. + reach <- x$N_reachable + partial <- isTRUE(reach < x$N) + cat(" sampling fraction ", + signif(x$n / if (partial) reach else x$N, 3), + if (partial) paste0(" (of the ", fmt_n(reach), " reachable rows)"), + "\n", sep = "") + if (isTRUE(abs(x$expected_n - x$n) > 1e-6 * max(1, x$n))) { + cat(" expected n ", signif(x$expected_n, 4), + " (the sample size is random under this design)\n", sep = "") + } if (all(is.finite(x$weight_range))) { cat(" design weights ", signif(x$weight_range[1], 4), " to ", signif(x$weight_range[2], 4), sep = "") @@ -290,21 +1274,42 @@ print.drawn_summary <- function(x, ...) { } cat("\n") } + if (isTRUE(is.finite(x$n_kish))) { + cat(" effective n ", signif(x$n_kish, 4), + " (Kish, from the weights alone)\n", sep = "") + } + if (isTRUE(x$n_certain > 0)) { + why <- c(threshold = "above the threshold", size = "by size", + whole = "taken whole") + k <- x$certain_by[x$certain_by > 0] + cat(" certain rows ", fmt_n(x$n_certain), sep = "") + if (length(k)) { + cat(" (", paste(fmt_n(k), why[names(k)], collapse = ", "), ")", + sep = "") + } + cat("\n") + } + if (isTRUE(x$conditional > 0)) { + cat(" conditional on the ", x$conditional, + " clusters selected\n", sep = "") + } if (isTRUE(x$unreachable > 0)) { cat(" unreachable rows ", fmt_n(x$unreachable), " (probability 0 under this design)\n", sep = "") } + if (!is.null(x$drawn)) cat(meta_line(x$drawn), "\n", sep = "") if (!is.null(x$by_group)) { cat("\n by ", paste(x$group_col, collapse = " x "), ":\n", sep = "") b <- x$by_group - w1 <- max(nchar(c(b$group, "group"))) + w1 <- max(text_width(c(b$group, "group"))) cat(" ", formatC("group", width = -w1), " drawn in frame rate\n", sep = "") for (i in seq_len(nrow(b))) { cat(" ", formatC(b$group[i], width = -w1), formatC(b$drawn[i], width = 7), formatC(b$in_frame[i], width = 9), - formatC(format(b$rate[i], nsmall = 3), width = 7), "\n", sep = "") + formatC(formatC(b$rate[i], format = "f", digits = 3), width = 7), + "\n", sep = "") } } invisible(x) diff --git a/R/plot.R b/R/plot.R index 4a523c9..9b44179 100644 --- a/R/plot.R +++ b/R/plot.R @@ -29,19 +29,37 @@ drawn_pal <- function() { #' sampling scatters, systematic makes a lattice, cluster sampling takes #' solid contiguous runs, and probability-proportional-to-size thickens #' wherever the weight is large. If your frame is sorted by something -#' meaningful, an unintended pattern shows up immediately.} +#' meaningful, an unintended pattern shows up immediately. A design that +#' samples with replacement rings each row it drew more than once, and the +#' count under the title gives the draws and the distinct rows. A +#' bootstrap is shown by its first replicate.} #' \item{`"probability"`}{Each row's inclusion probability across the frame, -#' as a step. Flat means every row had the same chance; plateaus mean -#' strata; a rise means size-proportional selection. Rows the design can -#' never reach sit at zero and are marked, which is usually the thing worth -#' finding out.} +#' as a step, with frame rows along the axis. Flat means every row had the +#' same chance; plateaus mean strata; a rise means size-proportional +#' selection. Rows the design can never reach sit at zero and are marked, +#' which is usually the thing worth finding out. The count of those rows, +#' the count taken with certainty, the range and the mean cover every row +#' of the frame.} #' \item{`"map"`}{Every row placed by two columns — coordinates, or any #' two numeric variables — with the selected ones filled in. This is the #' view for [design_spread()] and [design_spatial()], where what matters is #' how evenly the sample covers the space: compare a simple random sample's -#' clumps and gaps against a spread one.} +#' clumps and gaps against a spread one. For [design_spatial()] the +#' outline of `region` is drawn as well, with each edge of a +#' longitude/latitude region following its great circle under spherical +#' geometry, which is how the design decides which rows are inside. +#' The coordinates of [design_spatial()], and those of [design_spread()] +#' with `scale = FALSE`, get the same scale on both axes (`asp = 1`, or +#' `1 / cos()` of the middle latitude for longitude and latitude), so the +#' map shows the distances the design works with; other columns fill the +#' panel. When `across` names more than two columns, the first two place +#' the rows. The line under the title names the columns left out, counts +#' the selected rows that have no position and so are not drawn, and says +#' when the background is thinned.} #' } #' +#' A design with `reserve` is shown by its main sample, without the reserves. +#' #' Base graphics, so there is no plotting dependency to install. #' #' @param x A design object. @@ -51,15 +69,37 @@ drawn_pal <- function() { #' reproducible. #' @param ncol Dots per row in the `"selection"` grid. Defaults to whatever #' fills the panel at its current aspect ratio. -#' @param max_dots Frames larger than this are shown as an evenly spaced -#' subset, noted under the title. Keeps individual dots visible. -#' @param main Title. Defaults to a description of the design. -#' @param palette Named list overriding any of `surface`, `ink`, `secondary`, -#' `muted`, `recessive`, `accent`, `fill`, `rule`. +#' @param max_dots The most dots or steps to draw, which keeps them visible. +#' A larger frame is shown in runs of consecutive rows: in `"selection"` a +#' dot stands for a run and is filled when any row in it is selected, and in +#' `"probability"` a step spans the lowest and highest probability in its +#' run. `"map"` draws every selected row and at most `max_dots` of the +#' others, evenly spaced through the frame. The counts under the title +#' cover the whole frame. +#' @param main Title, a single string, or one expression, a call or a name +#' such as `quote(alpha)` drawn as plotmath. Defaults to a description of +#' the design: its constructor and the arguments that differ from their +#' defaults. +#' @param palette Named list, or named character vector, of colours +#' overriding any of `surface`, `ink`, `secondary`, `muted`, `recessive`, +#' `accent`, `fill`, `rule`. Each entry is one colour, a name from +#' [grDevices::colors()] or a code such as `"#1B6B52"`. Other names are +#' refused. #' @param coords For `type = "map"`, the two columns to place rows by, `c(x, -#' y)`. Defaults to the design's own `across` ([design_spread()]) or -#' `coords` ([design_spatial()]); required for any other design. -#' @param ... Passed to the underlying plot call. +#' y)`, or one POINT geometry column. Defaults to the design's own `across` +#' ([design_spread()]) or `coords` ([design_spatial()]); required for any +#' other design. Date and date-time columns get date axes. +#' @param sub A single string, added to the end of the line under the title, +#' after the counts the plot puts there. +#' @param ... Graphical parameters for the call that sets up the panel, such +#' as `xlim`, `ylim`, `asp` or `log`. They replace the plot's own: `asp = 1` +#' gives any map the same scale on both axes, and `xlim` and `ylim` zoom in, +#' with the rules and the mean line of `"probability"` following them. +#' Axes and labels drawn by base graphics are off (`axes = FALSE`, `ann = +#' FALSE`) unless turned on here. The dots, steps and titles keep their +#' own look, so `col`, `cex` and `pch` here change nothing visible; their +#' colours come from `palette`. A name that is not a graphical parameter is +#' refused. #' #' @return `x`, invisibly. Called for the plot. #' @@ -85,93 +125,338 @@ drawn_pal <- function() { #' @export plot.drawn_design <- function(x, y, type = c("selection", "probability", "map"), seed = NULL, ncol = NULL, max_dots = 4000, - main = NULL, palette = NULL, coords = NULL, ...) { - type <- match.arg(type) + main = NULL, palette = NULL, coords = NULL, + sub = NULL, ...) { + type <- check_choice(type, c("selection", "probability", "map"), "type") if (missing(y)) { stop("Pass the population data frame as the second argument: ", "plot(design, data).", call. = FALSE) } - validate_data(y) + validate_data(y, arg = "y") + design <- legacy_design(x) max_dots <- check_count(max_dots, "max_dots", allow_zero = FALSE) if (!is.null(ncol)) ncol <- check_count(ncol, "ncol", allow_zero = FALSE) + main <- check_title(main, "main") + sub <- check_title(sub, "sub") + pal <- check_palette(palette) + check_panel_args(...) + dots <- list(...) + main <- main %||% design_label(design) - pal <- utils::modifyList(drawn_pal(), palette %||% list()) - n_pop <- nrow(y) - shown <- if (n_pop > max_dots) { - round(seq(1, n_pop, length.out = max_dots)) + if (type == "probability") { + plot_probability(x = design, y = y, max_dots = max_dots, main = main, + sub = sub, pal = pal, dots = dots) + } else if (type == "map") { + # A design with `reserve` is shown by its main sample. + plot_map(x = main_design(design), y = y, coords = coords, + max_dots = max_dots, seed = seed, main = main, sub = sub, + pal = pal, dots = dots) } else { - seq_len(n_pop) + plot_selection(x = main_design(design), y = y, max_dots = max_dots, + seed = seed, ncol = ncol, main = main, sub = sub, + pal = pal, dots = dots) + } + invisible(x) +} + +#' Set up the panel: the plot's own settings, replaced by any in `...` +#' +#' A limit given as NULL keeps the plot's own. Returns the arguments used, so +#' the caller can read the limits the panel was drawn with. +#' +#' @noRd +panel_frame <- function(defaults, dots) { + args <- utils::modifyList(defaults, dots) + for (lim in c("xlim", "ylim")) { + if (is.null(args[[lim]])) args[[lim]] <- defaults[[lim]] + } + do.call(graphics::plot, args) + args +} + +#' The line under the title: its parts, those present, side by side +#' @noRd +subtitle <- function(...) { + parts <- c(...) + paste(parts[nzchar(parts)], collapse = " | ") +} + +#' Runs of consecutive frame rows, one per dot or step +#' +#' Every run holds `size` rows except the last, which holds what is left, so +#' there are at most `max_dots` runs. Runs are whole rows, so a periodic +#' selection cannot fall between the rows shown. +#' +#' @noRd +row_runs <- function(n_rows, max_dots) { + size <- max(1, ceiling(n_rows / max_dots)) + k <- ceiling(n_rows / size) + from <- (seq_len(k) - 1) * size + 1 + list(size = size, k = k, from = from, to = pmin(from + size - 1, n_rows)) +} + +#' The run each of `rows` falls in +#' @noRd +run_of <- function(rows, runs) (rows - 1) %/% runs$size + 1 + +#' How many times a design draws each frame row, for the selection and map +#' views +#' +#' A bootstrap is drawn as one replicate, as rows. The union of a thousand +#' replicates holds nearly every row, and the matrix outputs hold no row ids. +#' +#' @noRd +plot_counts <- function(x, y, seed) { + key <- ".drawn_plot_id" + if (key %in% names(y)) { + stop("`y` already has a column called `", key, "`. Rename it.", + call. = FALSE) + } + tagged <- y + tagged[[key]] <- seq_len(nrow(y)) + if (inherits(x, "drawn_design_bootstrap")) { + x$output <- "rows" + x$n_replicates <- 1L } - sub <- if (length(shown) < n_pop) { - paste0(fmt_n(length(shown)), " of ", fmt_n(n_pop), " rows shown") + picked <- tryCatch({ + s <- draw(tagged, x, seed = seed) + if (is.data.frame(s)) s[[key]] else unlist(s) + }, error = function(e) { + stop("Could not draw this design against `y`: ", conditionMessage(e), + call. = FALSE) + }) + tabulate(picked[!is.na(picked)], nbins = nrow(y)) +} + +#' The count under the title of the selection and map views +#' +#' Distinct rows for a design without replacement; draws and distinct rows +#' for one with replacement, where a row can be drawn more than once. A +#' bootstrap names the replicate shown. +#' +#' @noRd +selection_label <- function(design, counts) { + boot <- inherits(design, "drawn_design_bootstrap") + distinct <- sum(counts > 0) + of <- fmt_n(length(counts)) + if (boot || samples_with_replacement(design) || any(counts > 1)) { + draws <- sum(counts) + out <- paste0(fmt_n(draws), " draw", if (draws != 1) "s", ", ", + fmt_n(distinct), " distinct row", if (distinct != 1) "s", + " of ", of) } else { - NULL + out <- paste0(fmt_n(distinct), " of ", of, " rows selected") + } + if (boot) { + out <- paste0("replicate 1 of ", fmt_n(design$n_replicates), " | ", + out) } - main <- main %||% design_label(x) + out +} - if (type == "probability") { - return(plot_probability(x, y, shown, main, sub, pal, ...)) +#' One dot per run of rows, for the selection view +#' +#' A dot is filled when any row of its run was drawn, and ringed when any was +#' drawn more than once. `key` explains a dot that stands for more than one +#' row, and the ring, for the line under the panel. +#' +#' @noRd +selection_view <- function(counts, max_dots) { + runs <- row_runs(length(counts), max_dots) + filled <- tabulate(run_of(which(counts > 0), runs), runs$k) > 0 + ringed <- tabulate(run_of(which(counts > 1), runs), runs$k) > 0 + key <- NULL + if (runs$size > 1) { + key <- paste0("each dot is ", fmt_n(runs$size), " rows, filled when any ", + "of them is selected", + if (any(ringed)) { + " and ringed when one was drawn more than once" + }) + } else if (any(ringed)) { + key <- "a ring marks a row drawn more than once" } - if (type == "map") { - return(plot_map(x, y, coords, shown, seed, main, sub, pal, ...)) + list(filled = filled, ringed = ringed, size = runs$size, key = key) +} + +#' What the probability view draws +#' +#' Each row is a plateau one unit wide, centred on its frame row, so the +#' first and last rows show as wide as the others. Above `max_dots` rows, a +#' run of rows is one step that passes through its lowest and highest +#' probability, in the order they come, so no unreachable or take-all row +#' drops out of the line. Zero marks go on every unreachable row, or on the +#' first such row of each run. The counts, range and mean come from every +#' row. +#' +#' @noRd +probability_view <- function(p, max_dots) { + n <- length(p) + runs <- row_runs(n, max_dots) + left <- runs$from - 0.5 + right <- runs$to + 0.5 + if (runs$size == 1) { + sx <- as.vector(rbind(left, right)) + sy <- rep(p, each = 2) + zero <- which(p == 0) + } else { + ends <- vapply(seq_len(runs$k), function(r) { + v <- p[runs$from[r]:runs$to[r]] + lo <- which.min(v) + hi <- which.max(v) + if (!length(lo)) return(c(NA_real_, NA_real_, NA_real_)) + first_zero <- if (v[lo] == 0) runs$from[r] - 1 + lo else NA_real_ + c(if (lo <= hi) c(v[lo], v[hi]) else c(v[hi], v[lo]), first_zero) + }, numeric(3)) + mid <- (left + right) / 2 + sx <- as.vector(rbind(left, mid, mid, right)) + sy <- as.vector(rbind(ends[1, ], ends[1, ], ends[2, ], ends[2, ])) + zero <- ends[3, !is.na(ends[3, ])] } - plot_selection(x, y, shown, seed, ncol, main, sub, pal, ...) + list(x = sx, y = sy, zero = zero, n = n, size = runs$size, + n_zero = sum(p == 0, na.rm = TRUE), + n_certain = sum(is_certain(p), na.rm = TRUE), + low = min(p, na.rm = TRUE), top = max(p, na.rm = TRUE), + mean = mean(p, na.rm = TRUE)) +} + +#' The line under the title of the probability view +#' @noRd +probability_label <- function(view) { + rows <- function(k) paste0(fmt_n(k), " row", if (k != 1) "s") + paste(c( + if (view$n_zero) paste0(rows(view$n_zero), " unreachable"), + if (view$n_certain) paste0(rows(view$n_certain), " taken with certainty"), + paste0("range ", signif(view$low, 3), " to ", signif(view$top, 3)) + ), collapse = " | ") +} + +#' Whole-row tick positions for the frame-row axis +#' @noRd +row_ticks <- function(n) { + xt <- pretty(c(1, n), n = 5) + xt[xt >= 1 & xt <= n & xt == round(xt)] } #' @noRd fmt_n <- function(n) formatC(n, format = "d", big.mark = ",") #' A one-line description of the design, for the default title +#' +#' The arguments that decide what is drawn, in R syntax. A vector of names +#' is wrapped in `c()`, and a nested design is shown by its own label. +#' Arguments at their default are left out, except the `allocation` and +#' `method` rules and a temporal design's `unit`, which say what `n` and +#' `interval` mean. The window of a temporal design, `from`, `to` and `tz`, +#' is left out to keep the title to one line. +#' #' @noRd design_label <- function(x) { p <- unclass(x) + defaults <- list(replace = FALSE, reserve = 0L, n_starts = 1L, + min_per_stratum = 0L, min_per_cluster = 0L, + max_items = Inf, scale = TRUE, batches = FALSE, + output = "rows", balanced = FALSE, na_rm = FALSE, + crs = 4326) + for (k in intersect(names(defaults), names(p))) { + v <- p[[k]] + if (is.atomic(v) && length(v) == 1L && !is.na(v) && + isTRUE(v == defaults[[k]])) { + p[k] <- list(NULL) + } + } + # A coordinate reference system given as an object has no short form. + if (!is.null(p$crs) && !(is.atomic(p$crs) && length(p$crs) == 1L)) { + p$crs <- NULL + } p <- p[!vapply(p, function(v) is.null(v) || inherits(v, c("sf", "sfc")), logical(1))] - keep <- intersect(c("strata", "clusters", "weights", "across", "size", - "time", "n", - "n_clusters", "interval", "per_interval", "n_replicates", - "allocation", "method", "balanced"), names(p)) - bits <- vapply(keep, function(k) paste0(k, " = ", fmt_param(p[[k]])), + keep <- intersect(c("strata", "clusters", "weights", "above", "threshold", + "across", "coords", "size", "time", "n", "replace", + "reserve", "n_clusters", "interval", "unit", "start", + "n_starts", "order_by", "per_interval", "n_replicates", + "max_items", "allocation", "allocation_by", "cost", + "min_per_stratum", "min_per_cluster", "method", + "block_length", "balanced", "scale", + "crs", "within", "rest", "output", "batches", + "na_rm"), names(p)) + bits <- vapply(keep, function(k) paste0(k, " = ", label_param(p[[k]], k)), character(1)) paste0("design_", design_type(x), "(", paste(bits, collapse = ", "), ")") } +#' One argument's value in a design label +#' +#' As printed, with a vector of several values wrapped in `c()`. +#' +#' @noRd +label_param <- function(v, name = NULL) { + shown <- fmt_param(v, name) + several <- is.atomic(v) && length(v) > 1L && length(v) <= 6L && + !is_per_stratum(v, name) && !inherits(v, c("POSIXt", "Date")) + if (several) paste0("c(", shown, ")") else shown +} + #' Title above the panel, subtitle beneath it, both left-aligned +#' +#' Each starts at the left edge of the panel. One too long to end inside the +#' figure is shrunk to fit, down to two thirds of its size, and text still +#' too long at that size is cut and ends in "...", so a long default title +#' is not cut off unseen at the edge of the figure. +#' #' @noRd draw_titles <- function(main, sub, pal) { - graphics::mtext(main, side = 3, line = 1.55, adj = 0, cex = 0.9, - font = 2, col = pal$ink, xpd = NA) + title <- fit_line(main, 0.9, font = 2) + graphics::mtext(title$text, side = 3, line = 1.55, adj = 0, + cex = title$cex, font = 2, col = pal$ink, xpd = NA) if (!is.null(sub) && nzchar(sub)) { - graphics::mtext(sub, side = 3, line = 0.5, adj = 0, cex = 0.72, - col = pal$secondary, xpd = NA) + below <- fit_line(sub, 0.72) + graphics::mtext(below$text, side = 3, line = 0.5, adj = 0, + cex = below$cex, col = pal$secondary, xpd = NA) } } +#' A line above the panel, at the size and length that end inside the figure #' @noRd -plot_selection <- function(x, y, shown, seed, ncol, main, sub, pal, ...) { - key <- ".drawn_plot_id" - if (key %in% names(y)) { - stop("`y` already has a column called `", key, "`. Rename it.", - call. = FALSE) +fit_line <- function(text, cex, font = 1) { + room <- graphics::par("pin")[1] + graphics::par("mai")[4] + # strwidth() scales by par("cex"), and mtext() does not. + width <- function(x, size) { + graphics::strwidth(x, units = "inches", font = font, + cex = size / graphics::par("cex")) } - tagged <- y - tagged[[key]] <- seq_len(nrow(y)) - - picked <- tryCatch({ - s <- draw(tagged, x, seed = seed) - if (is.data.frame(s)) s[[key]] else unlist(s) - }, error = function(e) { - stop("Could not draw this design against `y`: ", conditionMessage(e), - call. = FALSE) - }) + wide <- max(width(text, cex)) + if (!is.finite(wide) || wide <= room) { + return(list(text = text, cex = cex)) + } + smallest <- cex * 2 / 3 + cex <- max(cex * room / wide, smallest) + # Font sizes come in steps, so the width does not shrink in proportion. + while (cex > smallest && max(width(text, cex)) > room) { + cex <- max(cex - 0.02, smallest) + } + if (is.character(text) && width(text, cex) > room) { + cut <- paste0(substring(text, 1, seq_len(nchar(text) - 1L)), "...") + fits <- which(width(cut, cex) <= room) + if (length(fits)) text <- cut[max(fits)] + } + list(text = text, cex = cex) +} - sel <- rep(FALSE, nrow(y)) - sel[picked[!is.na(picked)]] <- TRUE - sel <- sel[shown] +#' @noRd +plot_selection <- function(x, y, max_dots, seed, ncol, main, sub, pal, + dots = list()) { + counts <- plot_counts(x, y, seed) + view <- selection_view(counts, max_dots) + sel <- view$filled - k <- length(shown) - op <- graphics::par(mar = c(2.4, 1.4, 3.6, 1.4), bg = pal$surface) + k <- length(sel) + # A second line under the grid needs room. + bottom <- if (is.null(view$key)) 2.4 else 3.2 + # The old values are taken first, so a value par() refuses partway through + # cannot leave the margins changed for the next plot. + op <- graphics::par(c("mar", "bg")) on.exit(graphics::par(op), add = TRUE) + graphics::par(mar = c(bottom, 1.4, 3.6, 1.4), bg = pal$surface) # Shape the grid to the panel so it fills the space instead of floating in it. if (is.null(ncol)) { @@ -183,147 +468,232 @@ plot_selection <- function(x, y, shown, seed, ncol, main, sub, pal, ...) { gx <- ((seq_len(k) - 1L) %% ncol) + 1L gy <- nr - ((seq_len(k) - 1L) %/% ncol) - graphics::plot(gx, gy, type = "n", axes = FALSE, ann = FALSE, - xlim = c(0.4, ncol + 0.6), ylim = c(0.4, nr + 0.6), ...) + panel_frame(list(x = gx, y = gy, type = "n", axes = FALSE, ann = FALSE, + xlim = c(0.4, ncol + 0.6), ylim = c(0.4, nr + 0.6)), + dots) graphics::points(gx[!sel], gy[!sel], pch = 19, cex = 0.5, col = pal$recessive) # A surface-coloured ring goes on first, so adjacent selected dots stay # visually separate instead of merging into a blob. graphics::points(gx[sel], gy[sel], pch = 21, cex = 0.9, lwd = 1.5, col = pal$surface, bg = pal$accent) + # A second ring, in the accent, marks a row drawn more than once. It + # shrinks with the spacing of the grid, so a dense grid is not covered in + # large overlapping circles. A circle at cex 1 is about 0.45 * ps / 72 + # inches across. + ring <- view$ringed + if (any(ring)) { + gap <- graphics::par("pin")[1] / diff(graphics::par("usr")[1:2]) + across <- 0.45 * graphics::par("ps") / 72 * graphics::par("cex") + ring_cex <- min(1.5, max(1.1, 0.9 * gap / across)) + graphics::points(gx[ring], gy[ring], pch = 1, cex = ring_cex, + lwd = if (ring_cex < 1.5) 0.7 else 1, col = pal$accent) + } - draw_titles(main, paste0(fmt_n(sum(sel)), " of ", fmt_n(k), " rows selected", - if (!is.null(sub)) paste0(" | ", sub) else ""), - pal) + draw_titles(main, subtitle(selection_label(x, counts), sub), pal) graphics::mtext("frame order, left to right, top to bottom", side = 1, line = 0.8, adj = 0, cex = 0.68, col = pal$muted, xpd = NA) + if (!is.null(view$key)) { + graphics::mtext(view$key, side = 1, line = 1.6, adj = 0, cex = 0.68, + col = pal$muted, xpd = NA) + } invisible(x) } #' @noRd -plot_probability <- function(x, y, shown, main, sub, pal, ...) { +plot_probability <- function(x, y, max_dots, main, sub, pal, dots = list()) { # Keep the real reason. Assuming "no closed form" sent anyone with a missing - # column, or a fixed `start`, off in entirely the wrong direction. + # column, or a fixed `start`, off in entirely the wrong direction. A + # bootstrap is not sent to the selection view, which shows one replicate + # of many. p <- tryCatch(inclusion_prob(y, x), error = function(e) { stop("Cannot plot inclusion probabilities for this design: ", conditionMessage(e), - "\nUse type = \"selection\" to see what it draws instead.", + if (!inherits(x, "drawn_design_bootstrap")) { + "\nUse type = \"selection\" to see what it draws instead." + }, call. = FALSE) }) - pv <- p[shown] - k <- length(pv) - top <- max(pv, na.rm = TRUE) - ylim <- c(0, if (!is.finite(top) || top <= 0) 1 else top * 1.14) + view <- probability_view(p, max_dots) + n <- view$n + top <- view$top - op <- graphics::par(mar = c(3.6, 4.4, 3.6, 1.4), bg = pal$surface) + op <- graphics::par(c("mar", "bg")) on.exit(graphics::par(op), add = TRUE) - graphics::plot(NA, xlim = c(1, max(k, 2)), ylim = ylim, axes = FALSE, - ann = FALSE, xaxs = "i", yaxs = "i", ...) + graphics::par(mar = c(3.6, 4.4, 3.6, 1.4), bg = pal$surface) + # The rules, the mean line and the axis follow the limits the panel was + # drawn with, which `xlim` and `ylim` in `...` replace. + frame <- panel_frame(list( + x = NA, xlim = c(0.5, n + 0.5), + ylim = c(0, if (!is.finite(top) || top <= 0) 1 else top * 1.14), + axes = FALSE, ann = FALSE, xaxs = "i", yaxs = "i" + ), dots) + xlim <- frame$xlim + ylim <- frame$ylim # Rules sit behind the data, so the eye reads level before shape. - ticks <- pretty(c(0, ylim[2]), n = 4) - ticks <- ticks[ticks >= 0 & ticks <= ylim[2]] + ticks <- pretty(ylim, n = 4) + ticks <- ticks[ticks >= min(ylim) & ticks <= max(ylim)] graphics::abline(h = ticks, col = pal$rule, lwd = 1) - if (k >= 2L) { - sx <- rep(seq_len(k), each = 2)[-1] - sy <- rep(pv, each = 2)[-(2 * k)] - graphics::polygon(c(sx[1], sx, sx[length(sx)]), c(0, sy, 0), - col = pal$fill, border = NA) - graphics::lines(sx, sy, col = pal$accent, lwd = 1.9) - } + sx <- view$x + sy <- view$y + graphics::polygon(c(sx[1], sx, sx[length(sx)]), c(0, sy, 0), + col = pal$fill, border = NA) + graphics::lines(sx, sy, col = pal$accent, lwd = 1.9) - zero <- which(pv == 0) - if (length(zero)) { - graphics::points(zero, rep(0, length(zero)), pch = 19, cex = 0.32, - col = pal$muted) + if (length(view$zero)) { + graphics::points(view$zero, rep(0, length(view$zero)), pch = 19, + cex = 0.32, col = pal$muted) } - m <- mean(pv, na.rm = TRUE) - graphics::segments(1, m, k, m, col = pal$secondary, lty = 2, lwd = 1.1) - graphics::text(k, m, labels = paste0("mean ", signif(m, 3), " "), pos = 3, - offset = 0.2, adj = 1, cex = 0.68, col = pal$secondary, - xpd = NA) + m <- view$mean + graphics::segments(xlim[1], m, xlim[2], m, col = pal$secondary, lty = 2, + lwd = 1.1) + # Right-aligned above the end of the line, inside the panel. + graphics::text(xlim[2], m, labels = paste0("mean ", signif(m, 3)), + adj = c(1, -0.4), cex = 0.68, col = pal$secondary, xpd = NA) graphics::axis(2, at = ticks, labels = format(ticks), las = 1, cex.axis = 0.7, col = NA, col.ticks = NA, col.axis = pal$secondary, line = -0.7) - xt <- pretty(c(1, k), n = 5) - xt <- xt[xt >= 1 & xt <= k] + xt <- row_ticks(n) graphics::axis(1, at = xt, labels = fmt_n(xt), cex.axis = 0.7, col = pal$rule, col.axis = pal$secondary, lwd = 1, tck = -0.016) - graphics::mtext(if (length(shown) < nrow(y)) "row (frame order, thinned)" - else "row (frame order)", + graphics::mtext(if (view$size > 1) { + paste0("row (frame order; a step per ", fmt_n(view$size), + " rows, through their lowest and highest)") + } else "row (frame order)", side = 1, line = 2.1, cex = 0.72, col = pal$secondary) graphics::mtext("inclusion probability", side = 2, line = 3.0, cex = 0.72, col = pal$secondary) - draw_titles(main, paste0( - if (length(zero)) { - paste0(fmt_n(length(zero)), " row", if (length(zero) > 1) "s" else "", - " unreachable | ") - } else "", - "range ", signif(min(pv, na.rm = TRUE), 3), " to ", signif(top, 3), - if (!is.null(sub)) paste0(" | ", sub) else ""), pal) + draw_titles(main, subtitle(probability_label(view), sub), pal) invisible(x) } #' @noRd -plot_map <- function(x, y, coords, shown, seed, main, sub, pal, ...) { +plot_map <- function(x, y, coords, max_dots, seed, main, sub, pal, + dots = list()) { coords <- coords %||% x$across %||% x$coords - if (is.null(coords) || length(coords) < 2L) { + if (!is.null(coords)) { + validate_data(y, required_columns = coords, arg = "y") + pos <- coordinate_columns(y, coords, "coords") + } + if (is.null(coords) || length(pos) < 2L) { stop("type = \"map\" needs two columns to place rows by. Pass ", - "`coords = c(\"x\", \"y\")`.", call. = FALSE) + "`coords = c(\"x\", \"y\")`, or the name of a POINT geometry ", + "column.", call. = FALSE) } - coords <- coords[1:2] - validate_data(y, required_columns = coords) - if (!is.numeric(y[[coords[1]]]) || !is.numeric(y[[coords[2]]])) { - stop("`", coords[1], "` and `", coords[2], "` must both be numeric.", - call. = FALSE) + # A spread design's `across` may hold more than two coordinates. The first + # two place the rows, and the line under the title names the others. + left_out <- names(pos)[-(1:2)] + pos <- pos[1:2] + axis_ok <- function(v) is.numeric(v) || inherits(v, c("Date", "POSIXt")) + if (!axis_ok(pos[[1]]) || !axis_ok(pos[[2]])) { + stop("`", names(pos)[1], "` and `", names(pos)[2], "` must both be ", + "numeric, dates or date-times.", call. = FALSE) } - - key <- ".drawn_plot_id" - if (key %in% names(y)) { - stop("`y` already has a column called `", key, "`. Rename it.", + px <- pos[[1]] + py <- pos[[2]] + placed <- is.finite(as.numeric(px)) & is.finite(as.numeric(py)) + if (!any(placed)) { + stop("`", names(pos)[1], "` and `", names(pos)[2], "` are not both ", + "finite in any row of `y`, so the map has no row to place. Pass ", + "`coords` naming the columns that hold each row's position.", call. = FALSE) } - tagged <- y - tagged[[key]] <- seq_len(nrow(y)) - picked <- tryCatch({ - s <- draw(tagged, x, seed = seed) - if (is.data.frame(s)) s[[key]] else unlist(s) - }, error = function(e) { - stop("Could not draw this design against `y`: ", conditionMessage(e), - call. = FALSE) - }) - sel <- rep(FALSE, nrow(y)) - sel[picked[!is.na(picked)]] <- TRUE + + counts <- plot_counts(x, y, seed) + sel <- counts > 0 + ring <- counts > 1 + lost <- sum(sel & !placed) # Thinning a map would hide exactly the gaps it exists to show, so every - # selected row is drawn and only the unselected background is thinned. - bg <- setdiff(shown, which(sel)) - px <- y[[coords[1]]] - py <- y[[coords[2]]] + # selected row is drawn and only the unselected background is thinned, + # evenly through the frame. + others <- which(!sel & placed) + bg <- if (length(others) > max_dots) { + others[round(seq(1, length(others), length.out = max_dots))] + } else { + others + } - op <- graphics::par(mar = c(3.6, 3.8, 3.6, 1.4), bg = pal$surface) + op <- graphics::par(c("mar", "bg")) on.exit(graphics::par(op), add = TRUE) - graphics::plot(px, py, type = "n", axes = FALSE, ann = FALSE, asp = NA, ...) + graphics::par(mar = c(3.6, 3.8, 3.6, 1.4), bg = pal$surface) + panel_frame(list(x = px, y = py, type = "n", axes = FALSE, ann = FALSE, + asp = map_asp(x, y, coords, pos)), dots) graphics::box(col = pal$rule) - graphics::axis(1, cex.axis = 0.7, col = NA, col.ticks = pal$rule, - col.axis = pal$secondary, tck = -0.016) - graphics::axis(2, cex.axis = 0.7, col = NA, col.ticks = pal$rule, - col.axis = pal$secondary, las = 1, tck = -0.016) + # A spatial design's region, drawn under the rows so the rows inside it + # and outside it can be told apart. + if (inherits(x, "drawn_design_spatial") && identical(coords, x$coords)) { + outline <- region_outline(x, y) + graphics::polygon(outline$x, outline$y, border = pal$secondary, + col = NA, lwd = 1.2) + } + # Axis() labels a Date or date-time axis with dates. + graphics::Axis(px, side = 1, cex.axis = 0.7, col = NA, + col.ticks = pal$rule, col.axis = pal$secondary, tck = -0.016) + graphics::Axis(py, side = 2, cex.axis = 0.7, col = NA, + col.ticks = pal$rule, col.axis = pal$secondary, las = 1, + tck = -0.016) graphics::points(px[bg], py[bg], pch = 19, cex = 0.45, col = pal$recessive) graphics::points(px[sel], py[sel], pch = 21, cex = 1.05, lwd = 1.5, col = pal$surface, bg = pal$accent) - graphics::mtext(coords[1], side = 1, line = 2.1, cex = 0.72, + graphics::points(px[ring], py[ring], pch = 1, cex = 1.7, lwd = 1, + col = pal$accent) + graphics::mtext(names(pos)[1], side = 1, line = 2.1, cex = 0.72, col = pal$secondary) - graphics::mtext(coords[2], side = 2, line = 2.6, cex = 0.72, + graphics::mtext(names(pos)[2], side = 2, line = 2.6, cex = 0.72, col = pal$secondary) - draw_titles(main, paste0(fmt_n(sum(sel)), " of ", fmt_n(nrow(y)), - " rows selected", - if (!is.null(sub)) paste0(" | ", sub) else ""), - pal) + draw_titles(main, subtitle( + selection_label(x, counts), + if (any(ring)) "ringed rows were drawn more than once", + if (length(left_out)) { + paste0("placed by ", names(pos)[1], " and ", names(pos)[2], ", not ", + paste(left_out, collapse = ", ")) + }, + if (lost) { + paste0(fmt_n(lost), " selected row", if (lost != 1) "s", + " not shown, missing ", names(pos)[1], " or ", names(pos)[2]) + }, + if (length(bg) < length(others)) { + paste0("background thinned to ", fmt_n(length(bg)), " of ", + fmt_n(length(others))) + }, + sub + ), pal) invisible(x) } + +#' The aspect ratio of a map +#' +#' The coordinates a design measures distance in, those of +#' [design_spatial()] and of [design_spread()] with `scale = FALSE`, get the +#' same scale on both axes, so the map shows the distances the design works +#' with. A degree of longitude spans `cos(latitude)` degrees of latitude, so +#' longitude and latitude get `1 / cos()` of the middle latitude. Other +#' columns, scaled ones and dates fill the panel, as `asp = NA` does. +#' +#' @noRd +map_asp <- function(design, data, coords, pos) { + measured <- inherits(design, "drawn_design_spatial") || + (inherits(design, "drawn_design_spread") && isFALSE(design$scale)) + timed <- any(vapply(pos, inherits, logical(1), what = c("Date", "POSIXt"))) + if (!measured || timed || !identical(coords, design$across %||% + design$coords)) { + return(NA) + } + crs <- if (inherits(design, "drawn_design_spatial")) { + spatial_crs(design, data) + } else if (length(coords) == 1L && inherits(data[[coords]], "sfc")) { + sf::st_crs(data[[coords]]) + } + if (!is.null(crs) && isTRUE(sf::st_is_longlat(crs))) { + lat <- mean(range(pos[[2]], finite = TRUE)) + return(1 / cos(lat * pi / 180)) + } + 1 +} diff --git a/R/quantile.R b/R/quantile.R new file mode 100644 index 0000000..b671a69 --- /dev/null +++ b/R/quantile.R @@ -0,0 +1,530 @@ +#' Estimate population quantiles from a sample +#' +#' `ht_quantile()` estimates quantiles of `y`, such as the median or the +#' quartiles, from the Hajek estimate of its distribution function, +#' `F(t) = sum(w * (y <= t)) / sum(w)` with `w = 1 / pi`, and gives each a +#' Woodruff confidence interval and a standard error from the design's own +#' variance estimator. +#' +#' @section The quantile rule: +#' The estimate at `p` is the smallest sampled value of `y` whose estimated +#' distribution function is `p` or more, which inverts the step function +#' `F` without interpolating between sampled values. It is always a value +#' some sampled row has. This is the rule of +#' `survey::svyquantile(qrule = "math")`, survey's default, and with equal +#' weights it is `stats::quantile(type = 1)`, apart from the tolerance +#' below. `p = 0` gives the smallest sampled value and `p = 1` the largest. +#' +#' A share of the weight equal to `p` can come out of the sums a rounding +#' error below `p`, so a share within `1e-9` below `p` counts as reaching it. +#' A `p` that is a rounding error above a share therefore gives the value +#' at that share. `seq(0, 1, 0.01)[71]`, which is 0.7 plus a rounding error, +#' gives the 21st of 30 equally weighted values, where +#' `stats::quantile(type = 1)` and `survey::svyquantile()` give the 22nd. +#' +#' @section Interval and standard error: +#' The interval is Woodruff's (1952). At the estimate `q`, `F(q)` is a Hajek +#' mean of the indicator `y <= q`, and its variance is the variance of the +#' total of the linearised residuals `((y <= q) - F(q)) / N_hat`, with +#' `N_hat = sum(w)`, from the design's own estimator, as for [ht_mean()]. +#' "Variance" and "Confidence intervals" in [ht_total()] describe the +#' estimators, the fallback to the jackknife, the degrees of freedom and the +#' notes. The interval `F(q)` plus or minus `t` standard errors, with `t` on +#' the design's degrees of freedom, is carried back through the quantile +#' rule, so its ends are the estimated quantiles at its two ends. The standard +#' error is the interval's width divided by `2 t`, and `variance` is its +#' square. `cdf` and `cdf_se` in the result hold `F(q)` and its standard +#' error. +#' +#' Where the interval for `F(q)` runs below 0 or above 1, the sample bounds +#' the quantile on one side only. That end of `ci` is then `NA`, and so are +#' `se` and `variance`, with a note. +#' +#' At the largest sampled value `F(q)` is 1 and its residuals are 0, so its +#' estimated variance is 0 whatever the spread of `y`, and the interval +#' would have no width. A quantile there, which a `p` close to 1 or a `y` +#' with one value gives, gets no standard error, with a note, unless every +#' frame row the design can reach was taken with certainty, when it is +#' exact. A quantile whose sampled rows lie in one primary sampling unit +#' gets none either, as a Hajek mean does, because its residuals sum to +#' zero over that unit. +#' +#' A quantile has no design effect, and `deff` is `NA`. +#' +#' @section Domains: +#' `by` gives the quantiles of each domain, each from the distribution +#' function of the domain's sampled rows. The variance of `F(q)` is that of +#' the domain's Hajek mean of `y <= q`, from the whole sample, as described +#' under "Domains" in [ht_total()], and the degrees of freedom are the +#' design's. The result is a `drawn_by` table with a row for each domain +#' and probability. +#' +#' @section Comparison with survey: +#' For the designs [as_svydesign()] maps with identical standard errors, +#' the estimate, the interval and the standard error equal those of +#' `survey::svyquantile(ci = TRUE, interval.type = "mean")` on its result, +#' whose interval is also centred on `F(q)` rather than on `p`. They differ +#' in these places: +#' +#' * At the largest sampled value survey gives an interval of no width and a +#' standard error of 0, where `ht_quantile()` gives none. +#' * Where the interval for `F(q)` passes 0 or 1, survey gives `NaN` for +#' that end and the standard error, where `ht_quantile()` gives `NA`. +#' * For a `p`, or an end of the interval for `F(q)`, below the share of the +#' weight held by the smallest sampled value, survey's rule gives the +#' second smallest value and `ht_quantile()` the smallest. +#' * For a `p` within `1e-9` above a share of the weight, `ht_quantile()` +#' gives the value at that share and survey the next one, as "The quantile +#' rule" describes. +#' * With `by`, `survey::svyby()` with `survey::svyquantile()` forms each +#' interval on the degrees of freedom of the domain's own units, and +#' `ht_quantile()` on the design's, as for every domain estimate here. +#' With `df = Inf` in both, the standard errors agree. +#' +#' For systematic, spread and systematic PPS samples the variance of `F(q)` +#' comes from the estimator this package uses for their totals, which +#' `survey` does not have. +#' +#' A missing `y` is refused. `survey::svyquantile(na.rm = TRUE)` on +#' [as_svydesign()] estimates the quantiles over the rows that have one. +#' +#' @inheritParams ht_total +#' @param y The variable: a numeric column name of `sample`, or a numeric +#' vector as long as `sample`. A logical `y` is refused, since its +#' quantiles are 0 or 1; [ht_mean()] estimates the share that is `TRUE`. +#' @param probs The probabilities, each from 0 to 1, such as `0.5` for the +#' median or `c(0.25, 0.5, 0.75)` for the quartiles. +#' +#' @return For one probability without `by`, a list of class +#' `drawn_quantile` with a `print()` method, holding `quantile`, the +#' estimate; `prob`; `variable`, the name of `y` when it is a column name, +#' else `NULL`; `cdf` and `cdf_se`, the estimated distribution function +#' at the estimate and its standard error; `steps`, the estimated +#' distribution function as the sorted sampled values `x` and the share +#' of the weight `F` at or below each, which `confint()` reads to form the +#' interval at another level; and `variance`, `se`, `ci`, `level`, +#' `alternative` (always `"two.sided"`), `df`, `n`, `n_random`, `design`, +#' `deff`, `method`, `note` and `unreachable` as for [ht_total()], with +#' `ci_scale` `"woodruff"`. +#' +#' For several probabilities, or with `by`, a `drawn_by` table with a row +#' for each domain and probability: the `by` columns, `prob`, `n`, +#' `quantile`, `variance`, `se`, `ci_lower`, `ci_upper` and `method`. +#' +#' Both have `coef()`, `vcov()`, `confint()`, `as.data.frame()` and +#' `tidy()` methods, as described under "Working with the result" in +#' [ht_total()]. `confint()` at another level carries the interval for +#' `F(q)` at that level back through the quantile rule. `vcov()` holds +#' the variances, and `NA` for the covariances between quantiles, which +#' are not estimated. +#' +#' @references +#' Woodruff, R. S. (1952). Confidence intervals for medians and other +#' position measures. *Journal of the American Statistical Association*, +#' 47, 635–646. +#' +#' Särndal, C.-E., Swensson, B. and Wretman, J. (1992). *Model Assisted Survey +#' Sampling*. Springer. +#' +#' @examples +#' set.seed(1) +#' pop <- data.frame( +#' id = 1:300, +#' site = rep(c("a", "b", "c"), each = 100), +#' spend = round(stats::rlnorm(300, 4, 0.8)) +#' ) +#' s <- draw(pop, design_stratified("site", n = 60), seed = 1, weights = TRUE) +#' +#' # The median, and its Woodruff interval +#' ht_quantile(s, "spend") +#' stats::median(pop$spend) # the truth +#' +#' # The quartiles of each site, from the whole sample +#' ht_quantile(s, "spend", probs = c(0.25, 0.5, 0.75), by = "site") +#' +#' @seealso [ht_mean()], [ht_total()], [as_svydesign()] +#' @export +ht_quantile <- function(sample, y, probs = 0.5, by = NULL, + variance = c("auto", "analytic", "jackknife", "none"), + level = 0.95, df = NULL) { + variance <- check_choice(variance, + c("auto", "analytic", "jackknife", "none"), + "variance") + check_probs(probs) + parts <- prepare_sample(sample, level, df) + parts <- add_quantile_variable(parts, y) + parts <- finish_prepare(parts) + if (!nrow(sample)) { + stop("`sample` has no rows, so there is no quantile to estimate.", + call. = FALSE) + } + ctx <- variance_context() + if (is.null(by)) warn_grouped(sample, "ht_quantile") + if (is.null(by) && length(probs) == 1L) { + return(quantile_result(parts, quantile_cells(parts, NULL, probs, variance, + level, df, ctx)[[1]], + level)) + } + quantile_table(parts, probs, by, variance, level, df, ctx) +} + +#' Check the probabilities of ht_quantile() +#' @noRd +check_probs <- function(probs) { + if (!is.numeric(probs) || !length(probs) || anyNA(probs) || + any(probs < 0 | probs > 1)) { + stop("`probs` must be one or more numbers from 0 to 1, such as 0.5 for ", + "the median, not ", format_bad(probs, value = TRUE), ".", + call. = FALSE) + } + twice <- unique(probs[duplicated(probs)]) + if (length(twice)) { + stop("`probs` holds ", paste(format(twice), collapse = ", "), " more ", + "than once. Give each probability once.", call. = FALSE) + } + invisible(probs) +} + +#' Read the `y` of a quantile into the parts of a sample +#' +#' It must be present and finite in every sampled row. +#' +#' @noRd +add_quantile_variable <- function(parts, y) { + sample <- parts$sample + col <- if (is.character(y) && length(y) == 1L && !is.na(y) && + y %in% names(sample)) { + sample[[y]] + } else { + y + } + refuse_gap <- function(n_gap, n) { + stop("`y` is missing in ", n_gap, " of the ", n, " sampled ", + "rows. A quantile needs `y` in every sampled row. ", + "survey::svyquantile(na.rm = TRUE) on as_svydesign() estimates it ", + "over the rows that have one.", call. = FALSE) + } + if (is.logical(col) && length(col) == nrow(sample)) { + # A `y` of NA alone is logical by R's default type only. + if (length(col) && all(is.na(col))) refuse_gap(length(col), length(col)) + what <- if (is.character(y)) { + paste0("names `", y, "`, a logical column") + } else { + "is logical" + } + stop("`y` ", what, ", and the quantiles of TRUE and FALSE are 0 or 1. ", + "Use ht_mean() for the share that is TRUE, or give a numeric `y`.", + call. = FALSE) + } + v <- read_variable(sample, y, "y", logical = FALSE) + gap <- is.na(v$values) & !is.nan(v$values) + if (any(gap)) refuse_gap(sum(gap), length(gap)) + check_finite_values(v$values, gap, "`y`", + "A quantile needs a finite `y` for every sampled row.") + parts$y <- v$values + parts$respond <- rep(TRUE, length(v$values)) + parts$y_name <- v$name + parts$y_logical <- v$logical + parts +} + +#' The estimated distribution function of `y` with weights `w` +#' +#' Returns the sorted distinct values `x` and `F`, the share of the weight +#' at or below each. The last share is exactly 1. +#' +#' @noRd +cdf_steps <- function(y, w) { + o <- order(y, method = "radix") + y <- y[o] + cw <- cumsum(w[o]) + last <- c(y[-1L] != y[-length(y)], TRUE) + list(x = y[last], F = cw[last] / cw[length(cw)]) +} + +#' The position in `steps` of the quantile at `p` +#' +#' The first value whose share is `p` or more. A share equal to `p` can come +#' out of the cumulative sum a rounding error below it, and the tolerance +#' keeps the quantile at that value rather than the next. +#' +#' @noRd +step_index <- function(steps, p) { + match(TRUE, steps$F >= p - 1e-9) +} + +#' The quantile at `p` of an estimated distribution function +#' @noRd +step_quantile <- function(steps, p) steps$x[step_index(steps, p)] + +#' The Woodruff interval of a quantile +#' +#' `q` is the estimate, `cdf` the distribution function there and `v` its +#' variance. The interval for `F(q)` at `level` on `df` degrees of freedom +#' is carried back through the quantile rule. An end past 0 or 1 is `NA`. +#' Returns `ci`, `se`, the interval's width over `2 t`, and `open`, whether +#' an end is missing for that reason. +#' +#' @noRd +woodruff <- function(steps, q, cdf, v, level, df) { + none <- list(ci = c(NA_real_, NA_real_), se = NA_real_, open = FALSE) + if (!is.finite(v) || v < 0) return(none) + if (v == 0) return(list(ci = c(q, q), se = 0, open = FALSE)) + if (is.finite(df) && df < 1) return(none) + a <- (1 - level) / 2 + t <- if (is.finite(df)) stats::qt(1 - a, df) else stats::qnorm(1 - a) + ends <- cdf + c(-1, 1) * t * sqrt(v) + ci <- c(if (ends[1] < 0) NA_real_ else step_quantile(steps, ends[1]), + if (ends[2] > 1) NA_real_ else step_quantile(steps, ends[2])) + list(ci = ci, se = if (anyNA(ci)) NA_real_ else (ci[2] - ci[1]) / (2 * t), + open = anyNA(ci)) +} + +#' The quantiles of each domain at each probability, with their intervals +#' +#' `dom` is the domains of `by` from domain_keys(), or `NULL` for the whole +#' sample. For each probability the residuals of every domain go into one +#' variable, each 0 outside its domain, and the variance of each domain's +#' `F(q)` comes from domain_variances(), as for a domain's Hajek mean, or +#' for the whole sample from the design's own estimator. Returns a list with +#' an element for each domain and probability, domain by domain, holding +#' the domain's position `j`, `prob`, `n`, `n_random`, `steps`, the +#' estimate `quantile`, `cdf`, `cdf_se`, `ci`, `se`, `method`, `note` and +#' the flags `top` (a quantile at the largest value, whose variance is +#' declined), `open` and `no_df` that the notes are built from. +#' +#' @noRd +quantile_cells <- function(parts, dom, probs, variance, level, df, ctx) { + n <- nrow(parts$sample) + pi_i <- parts$pi + yv <- parts$y + groups <- if (is.null(dom)) list(seq_len(n)) else dom$idx + k <- length(groups) + steps <- lapply(groups, function(i) cdf_steps(yv[i], 1 / pi_i[i])) + n_hat <- vapply(groups, function(i) sum(1 / pi_i[i]), numeric(1)) + df_use <- df %||% design_df(parts$design, parts$units, parts$pop, + parts$rows, pi_i) + psu <- if (is.null(dom) && variance != "none") { + sample_units(parts$design, parts$units, parts$pop, parts$rows, + parts$pi) + } + jk_psu <- if (!is.null(psu)) jackknife_units(parts, psu, variance) + cells <- vector("list", k * length(probs)) + for (h in seq_along(probs)) { + fits <- lapply(steps, function(st) { + at <- step_index(st, probs[h]) + list(q = st$x[at], cdf = st$F[at]) + }) + z <- numeric(n) + for (j in seq_len(k)) { + i <- groups[[j]] + z[i] <- (as.numeric(yv[i] <= fits[[j]]$q) - fits[[j]]$cdf) / n_hat[j] + } + vars <- if (is.null(dom)) { + declined <- linear_declines(parts, rep(TRUE, n), variance, + estimate = "quantile", psu = psu, + jk_psu = jk_psu) + list(declined$any %||% + ht_variance_dispatch(parts$design, parts$units, parts$pop, + parts$rows, z, pi_i, variance, ctx = ctx, + jk_decline = declined$jackknife)) + } else { + domain_variances(parts, dom, list(z = z), variance, "quantile", ctx) + } + for (j in seq_len(k)) { + fit <- fits[[j]] + v <- vars[[j]] + frame <- if (is.null(dom)) TRUE else domain_frame(dom, j) + # At the largest value the residuals are 0 and so is the variance, + # however `y` is spread, unless the domain is a census. + top <- variance != "none" && fit$cdf >= 1 && + is.finite(v$variance) && !certain_domain(parts, frame) + if (top) v <- list(variance = NA_real_, method = "none", note = NULL) + w <- woodruff(steps[[j]], fit$q, fit$cdf, v$variance, level, df_use) + i <- groups[[j]] + cells[[(j - 1L) * length(probs) + h]] <- list( + j = j, prob = probs[h], n = length(i), + n_random = sum(!is_certain(pi_i[i])), steps = steps[[j]], + quantile = fit$q, cdf = fit$cdf, + cdf_se = if (is.finite(v$variance) && v$variance >= 0) { + sqrt(v$variance) + } else { + NA_real_ + }, + ci = w$ci, se = w$se, method = v$method %||% "analytic", + note = v$note, top = top, open = w$open, + no_df = is.finite(v$variance) && v$variance > 0 && + is.finite(df_use) && df_use < 1, + df = df_use) + } + } + cells +} + +#' One quantile without `by`, as a `drawn_quantile` +#' @noRd +quantile_result <- function(parts, cell, level) { + notes <- c(cell$note, + if (cell$top) top_note(), + if (cell$open) open_note(), + if (cell$no_df) df_note(cell$df)) + out <- list( + quantile = cell$quantile, prob = cell$prob, variable = parts$y_name, + cdf = cell$cdf, cdf_se = cell$cdf_se, variance = cell$se^2, + se = cell$se, ci = cell$ci, level = level, alternative = "two.sided", + df = cell$df, n = cell$n, n_random = cell$n_random, + ci_scale = "woodruff", design = design_type(parts$design), + deff = NA_real_, method = cell$method, + note = if (length(notes)) paste(notes, collapse = " "), + unreachable = parts$unreachable, steps = cell$steps + ) + out$unavailable <- parts$unavailable + structure(out, class = "drawn_quantile") +} + +#' Quantiles at several probabilities, or by domain, as a `drawn_by` table +#' +#' A row for each domain and probability, domain by domain. What `confint()` +#' needs to form an interval at another level, each row's distribution +#' function and the standard error of `F(q)`, is kept in the `woodruff` +#' attribute by the row's name, so that it still matches after rows are +#' selected. +#' +#' @noRd +quantile_table <- function(parts, probs, by, variance, level, df, ctx) { + dom <- NULL + if (!is.null(by)) { + dom <- domain_keys(parts, by) + check_table_names(by, c("prob", "n", "quantile", "variance", "se", + "ci_lower", "ci_upper", "method")) + } + cells <- quantile_cells(parts, dom, probs, variance, level, df, ctx) + field <- function(name, type) vapply(cells, `[[`, type, name) + j <- field("j", integer(1)) + out <- if (is.null(dom)) { + data.frame(prob = field("prob", numeric(1))) + } else { + first <- match(dom$levels_in, dom$key)[j] + cols <- data.frame(stats::setNames(lapply(by, function(b) { + parts$sample[[b]][first] + }), by), check.names = FALSE) + cols$prob <- field("prob", numeric(1)) + cols + } + out$n <- field("n", integer(1)) + out$quantile <- field("quantile", numeric(1)) + se <- field("se", numeric(1)) + out$variance <- se^2 + out$se <- se + ci <- vapply(cells, `[[`, numeric(2), "ci") + out$ci_lower <- ci[1, ] + out$ci_upper <- ci[2, ] + out$method <- field("method", character(1)) + out <- structure(out, class = c("drawn_by", "data.frame"), + what = "quantile", level = level, + alternative = "two.sided", df = cells[[1]]$df, + design = design_type(parts$design), ci_scale = "woodruff", + unreachable = parts$unreachable, variable = parts$y_name, + by = c(by, "prob")) + attr(out, "unavailable") <- parts$unavailable + nm <- domain_names(out) + flag <- function(name) nm[field(name, logical(1))] + notes <- unique(unlist(lapply(cells, `[[`, "note"))) + if (length(flag("top"))) notes <- c(notes, top_note(flag("top"))) + if (length(flag("open"))) notes <- c(notes, open_note(flag("open"))) + if (length(flag("no_df"))) notes <- c(notes, df_note(cells[[1]]$df)) + attr(out, "notes") <- notes + attr(out, "n_random") <- stats::setNames(field("n_random", integer(1)), nm) + attr(out, "woodruff") <- stats::setNames(lapply(cells, function(cell) { + cell[c("steps", "quantile", "cdf", "cdf_se")] + }), nm) + out +} + +#' Why a quantile at the largest sampled value has no standard error +#' +#' `labels` names the rows of a table, as domain_names() names them. +#' +#' @noRd +top_note <- function(labels = NULL) { + core <- paste0("where the estimated distribution function reaches 1 and ", + "has an estimated variance of 0 whatever the spread of ", + "`y`, so the Woodruff interval would have no width. A ", + "standard error needs a quantile below the largest sampled ", + "value: a smaller `probs`, or a larger sample.") + if (is.null(labels)) { + return(paste0("The estimate is the largest sampled value of `y`, ", core)) + } + several <- length(labels) > 1L + paste0("The estimate", if (several) "s", " for ", quote_labels(labels), + if (several) " are" else " is", " the largest sampled value of `y` ", + "in ", if (several) "their domains" else "its domain", ", ", core) +} + +#' Why an end of a quantile's interval is missing +#' @noRd +open_note <- function(labels = NULL) { + what <- if (is.null(labels)) { + "the estimate" + } else { + paste0("the estimate", if (length(labels) > 1L) "s", " for ", + quote_labels(labels)) + } + paste0("The interval for the distribution function at ", what, ", `F(q)` ", + "plus or minus `t` standard errors, runs below 0 or above 1, so the ", + "sample bounds the quantile on one side only. That end of the ", + "interval is NA, and so is the standard error, which is the ", + "interval's width over `2 t`. A larger sample, or a probability ", + "further from 0 and 1, narrows it.") +} + +#' The Woodruff intervals of a quantile table at `level`, a row per row +#' @noRd +quantile_by_ci <- function(x, level) { + w <- attr(x, "woodruff") + nm <- domain_names(x) + if (is.null(w) || !all(nm %in% names(w))) { + stop("`object` does not hold the distribution functions its intervals ", + "need at another level. Estimate again with `level = ", + format(level), "`.", call. = FALSE) + } + out <- vapply(w[nm], function(r) { + woodruff(r$steps, r$quantile, r$cdf, r$cdf_se^2, level, + attr(x, "df"))$ci + }, numeric(2)) + t(out) +} + +#' @export +print.drawn_quantile <- function(x, ...) { + print_estimate(x, "quantile", + paste("Quantile of", ratio_name(x$variable, "y")), + lines = c(prob = format(x$prob))) +} + +#' @export +#' @exportS3Method survey::deff +deff.drawn_quantile <- function(object, quietly = FALSE, ...) object$deff + +#' @export +coef.drawn_quantile <- function(object, ...) coef.drawn_ht(object) + +#' @export +vcov.drawn_quantile <- function(object, ...) vcov.drawn_ht(object) + +#' @export +confint.drawn_quantile <- function(object, parm, level = object$level, ...) { + confint.drawn_ht(object, parm, level) +} + +#' @export +as.data.frame.drawn_quantile <- function(x, row.names = NULL, + optional = FALSE, ...) { + single_frame(x, row.names) +} + +#' @exportS3Method generics::tidy +tidy.drawn_quantile <- function(x, conf.int = FALSE, conf.level = x$level, + ...) { + tidy.drawn_ht(x, conf.int, conf.level) +} diff --git a/R/state.R b/R/state.R new file mode 100644 index 0000000..113bfba --- /dev/null +++ b/R/state.R @@ -0,0 +1,1652 @@ +# The state a weighted sample carries, and the one place it is read. +# +# draw(weights = TRUE) attaches five attributes: the design (`drawn_design`), +# the frame rows in draw order (`drawn_rows`), a copy of the frame +# (`drawn_population`), every frame row's inclusion probability at draw time +# (`drawn_pi`) and a record of how it was drawn (`drawn_meta`). It also adds +# a `.row` column holding each sampled row's frame row. Everything that +# estimates from a sample reads that state through +# drawn_state(), which matches rows through `.row` rather than by position, +# checks `.prob` against the probabilities recorded at draw time, and checks +# that the design still gives the frame those probabilities. Design keys +# (strata, clusters, time) are read from the frame's copy of each sampled row, +# never from the sample's own columns, which the caller can rename or edit. +# +# A sample weighted conditional on its clusters (see conditional_design()) +# also carries the codes of the clusters selected (`drawn_selection`), and +# its `drawn_pi` holds the probabilities given that selection: `NA` for the +# rows of the clusters not selected, whose probability the selection does +# not fix. Such a row could have been drawn, so reachable() counts it. +# +# as_drawn() sets the same columns and attributes on rows read back from a +# file, through rebuild_sample(), which every function that makes a weighted +# sample other than draw() uses. compact_sample() replaces the stored frame +# with its design columns and records what it dropped (`drawn_compact`). +# +# A design with `reserve` gives a list rather than a sample: the main sample +# and then the reserves, with `drawn_rows` in that order, which is the order +# the reserves are used in. drawn_state() refuses it unless the caller reads +# lists, and use_reserves() turns it into a sample. + +#' Copy a data frame column by column +#' +#' A data frame holds references to its column vectors, and data.table edits +#' those vectors in place (`:=`, `set()`, `setorder()`, `setkey()`). A frame +#' stored by reference therefore changes when the caller's does. Every column +#' here is a new vector with the original's attributes, so the copy keeps the +#' frame's class and attributes (tibble, data.table, sf) and later edits to +#' the original do not reach it. The frame's own attributes are copied too, +#' because `setnames()`, `setcolorder()` and deleting a column with `:=` +#' rewrite the names vector in place, and a shared one renamed or dropped +#' columns of the copy. +#' +#' @noRd +snapshot_frame <- function(data) { + out <- lapply(unclass(data), copy_column) + attributes(out) <- lapply(attributes(data), function(a) { + if (is.atomic(a)) copy_column(a) else a + }) + out +} + +#' @noRd +copy_column <- function(x) { + if (is.data.frame(x)) return(snapshot_frame(x)) + if (!is.atomic(x) && !is.list(x)) return(x) + # Without its class, a column has no `[` or length() method that could + # change what is copied, so every element is copied. The attributes are + # then put back as they were. Setting attributes does not set the S4 bit, + # so an S4 vector column (a lubridate Period, Duration or Interval) gets it + # back from asS4(); without it, the copy no longer dispatches its methods. + base <- unclass(x) + out <- .subset(base, seq_along(base)) + attributes(out) <- attributes(x) + if (isS4(x)) out <- asS4(out) + out +} + +#' Refuse a sample whose design cannot be recovered +#' +#' With no `reason`, the sample has lost the attributes that hold its design. +#' Otherwise `reason` completes a sentence that starts with the argument name. +#' +#' @noRd +stop_not_drawn <- function(reason = NULL, arg = "sample") { + if (is.null(reason)) { + reason <- paste0( + "does not carry its design. It was drawn without `weights = TRUE`, or ", + "a later step dropped the attributes that hold the design; merge(), ", + "column selection (`s[, cols]`), subset(), transform() and cbind() all ", + "do. Estimate from the result of draw(..., weights = TRUE), use `by` ", + "for groups, and add fieldwork columns to that result with ", + "add_fieldwork() or `s$col <- value`. A sample read back from a file ", + "or a database is rebuilt with as_drawn().") + } + stop("`", arg, "` ", reason, call. = FALSE) +} + +#' Up to five values for a message, and how many more +#' @noRd +format_rows <- function(x) { + x <- sort(unique(x), na.last = TRUE) + paste0(paste(utils::head(x, 5L), collapse = ", "), more_text(x)) +} + +#' " and k more" for the values of `x` past the first `shown`, or "" +#' +#' Counting the rest, rather than ending on "...", leaves the full stop that +#' follows in a message on its own. +#' +#' @noRd +more_text <- function(x, shown = 5L) { + if (length(x) > shown) paste0(" and ", length(x) - shown, " more") else "" +} + +#' The design, frame and frame rows behind a weighted sample +#' +#' Returns `design`, `pop` (the frame as it was at draw time), `rows` (the +#' frame row of each sample row, in the sample's current order), `pi_all` +#' (every frame row's inclusion probability at draw time, `NULL` for a sample +#' saved by drawn 0.2.0), `units` (`pop[rows, ]`, the frame's copy of each +#' sample row), `selection` (the codes of the clusters selected, for a +#' sample weighted conditional on them, else `NULL`), `compact` (what +#' compact_sample() dropped from the stored frame, else `NULL`) and `reserve` +#' (for a list from a design with `reserve`, each row's place among the +#' reserves, 0 for the main sample, else `NULL`) and `meta` (how the sample +#' was drawn, from draw_meta(), or `NULL` for a sample from an earlier +#' version of drawn). In a conditional sample, +#' `pi_all` is `NA` for the rows of clusters not selected; count the rows a +#' design can reach with reachable(). +#' +#' A list from a design with `reserve` is refused unless `reserves` is +#' `TRUE`, since it is not a sample to estimate from until use_reserves() +#' has replaced the units found unavailable. Its `.reserve` column, when it +#' has one, must agree with the order the reserves were drawn in. +#' +#' `rows` comes from the `.row` column, so reordering a sample, by `[`, +#' dplyr::arrange() or data.table::setorder(), changes nothing. A subset, a +#' sample bound to itself or another sample, or a join that repeats rows does +#' not match the rows that were drawn and is refused. A zero-row sample passes; +#' callers decide what to do with it. +#' +#' Strata, clusters, time stamps and every other design key are read from +#' `units`, so renaming, recoding or dropping one of those columns in the +#' sample changes nothing. `y` and `by` come from the sample. +#' +#' A sample with `drawn_pi` is also refused when its `.prob` column no longer +#' holds the probabilities recorded at draw time, and when the design, applied +#' to the stored frame in this session, gives the frame other probabilities +#' than it did then. The joint probabilities and variance are recomputed in +#' this session, so they would otherwise describe another design. A design +#' that no longer applies to the stored frame at all is refused the same way. +#' +#' A sample saved by drawn 0.2.0 has no `.row` column and records no +#' probabilities for the frame. Its rows are matched to the frame rows by +#' position, so the frame columns it keeps must hold the values of those +#' rows in the order drawn, as check_legacy_order() checks. Its `.prob` +#' column must hold probabilities, and the design must give each sampled row +#' the probability in its `.prob`. Its design gets the fields added since +#' 0.2.0 from legacy_design(). +#' A conditional sample's probabilities are worked out again from its stored +#' selection. +#' +#' A sample whose design samples with replacement is refused, as draw() +#' refuses to weight one; drawn 0.2.0 weighted a certainty design over a +#' with-replacement `rest`. A sample that carries a bootstrap design, which +#' only a sample built by hand can, is refused too. +#' +#' @noRd +drawn_state <- function(sample, arg = "sample", reserves = FALSE) { + if (!is.data.frame(sample)) { + stop_not_drawn(paste0("must be a data frame returned by ", + "draw(..., weights = TRUE), not ", + a_class(sample), "."), arg) + } + design <- attr(sample, "drawn_design", exact = TRUE) + drawn <- attr(sample, "drawn_rows", exact = TRUE) + pop <- attr(sample, "drawn_population", exact = TRUE) + pi_all <- attr(sample, "drawn_pi", exact = TRUE) + compact <- attr(sample, "drawn_compact", exact = TRUE) + meta <- attr(sample, "drawn_meta", exact = TRUE) + if (is.null(design) || is.null(drawn) || is.null(pop)) { + stop_not_drawn(arg = arg) + } + if (inherits(design, "drawn_design_bootstrap")) { + # draw() never weights a bootstrap, so only a sample built by hand + # carries one. + stop_not_drawn(paste0( + "comes from a bootstrap design, which resamples the sample rather than ", + "drawing a probability sample of a finite population. It has no ", + "inclusion probabilities, so it has no design-based estimate and no ", + "survey equivalent. Draw a probability sample with `weights = TRUE` to ", + "estimate from."), arg) + } + if (samples_with_replacement(design)) { + # draw() refuses to weight such a design, but drawn 0.2.0 checked only + # the outer design and weighted a certainty design over one. + stop_not_drawn(paste0("comes from ", replacement_design(design), + ", for which `weights = TRUE` is not available.\n", + replacement_problem(design)), arg) + } + r <- reserve_size(design) + if (r > 0L && !reserves) { + stop_not_drawn(paste0( + "lists the ", design$n, " units of a main sample and ", r, " reserve", + if (r > 1L) "s", " (`reserve = ", r, "`), so it is not yet a sample to ", + "estimate from. Pass the list to use_reserves() with the units found ", + "unavailable marked, and estimate from the sample it returns."), arg) + } + + if (is.null(pi_all)) { + # Saved by drawn 0.2.0, which had no `.row` column. Rows can only be + # matched by position. A change in the row count shows, and so do frame + # columns whose values were moved to other rows and a `.prob` that the + # design no longer gives the row in that position. + if (length(drawn) != nrow(sample)) { + stop_not_drawn(paste0( + "has ", nrow(sample), " rows but was drawn with ", length(drawn), + ", so its rows no longer match the frame rows it records. Estimate ", + "from the sample as draw() returned it, and use `by` for groups."), + arg) + } + design <- legacy_design(design) + check_prob(sample, arg = arg) + check_legacy_order(sample, pop, drawn, arg) + check_legacy_prob(sample, design, pop, drawn, arg) + return(list(design = design, pop = pop, rows = drawn, pi_all = NULL, + units = pop[drawn, , drop = FALSE], selection = NULL, + compact = compact, meta = meta)) + } + + rows <- sample_rows(sample, drawn, nrow(pop), arg) + check_prob(sample, pi_all[rows], arg) + selection <- check_selection(sample, design, pop, arg) + check_drift(design, pop, pi_all, arg, selection) + list(design = design, pop = pop, rows = rows, pi_all = pi_all, + units = pop[rows, , drop = FALSE], selection = selection, + compact = compact, + reserve = if (r > 0L) list_places(sample, rows, drawn, design$n, arg), + meta = meta) +} + +#' Each row's place among a list's reserves, checked against `.reserve` +#' +#' `drawn` holds the frame rows of the main sample and then of the reserves +#' in the order they are used, so a row's place in it, less `n`, is its +#' reserve number, and 0 for a row of the main sample. +#' +#' @noRd +list_places <- function(sample, rows, drawn, n, arg = "sample") { + place <- pmax(match(rows, drawn) - n, 0L) + col <- sample[[".reserve"]] + if (!is.null(col)) { + ok <- is.numeric(col) && is.null(dim(col)) && !anyNA(col) && + all(col == place) + if (!ok) { + stop_not_drawn(paste0( + "has `.reserve` values that differ from the order its reserves were ", + "drawn in, so `.reserve` was changed after draw(). use_reserves() ", + "uses the reserves in the order drawn; keep `.reserve` as draw() set ", + "it."), arg) + } + } + as.integer(place) +} + +#' Frame rows a sample's design could have drawn +#' +#' Rows with a draw-time probability above 0, and the rows of the clusters a +#' conditional sample did not select, whose probability is `NA` but which +#' another selection could have drawn. +#' +#' @noRd +reachable <- function(pi_all) { + is.na(pi_all) | pi_all > 0 +} + +#' The clusters a conditional sample selected, checked against its frame +#' +#' `NULL` for a design that is not weighted conditional on its clusters, +#' whose probabilities do not depend on them. Otherwise the stored codes +#' must be `n_clusters` distinct clusters of the frame; a sample that lost +#' them cannot have its probabilities checked or its variance worked out. +#' +#' @noRd +check_selection <- function(sample, design, pop, arg = "sample") { + if (!conditional_design(design, pop)) return(NULL) + selection <- attr(sample, "drawn_selection", exact = TRUE) + fix <- paste0(" `.prob` is conditional on the clusters draw() selected, ", + "which it records with the sample. Estimate from the sample ", + "as draw() returned it.") + if (is.null(selection)) { + stop_not_drawn(paste0("does not record which clusters were selected, ", + "so its probabilities cannot be checked.", fix), + arg) + } + total <- count_clusters(design, pop)$total + ok <- is.numeric(selection) && !anyNA(selection) && + length(selection) == design$n_clusters && + all(selection == trunc(selection) & selection >= 1 & + selection <= total) && + !anyDuplicated(selection) + if (!ok) { + stop_not_drawn(paste0("records clusters that are not ", + design$n_clusters, " distinct clusters of the ", + total, " in its frame.", fix), arg) + } + as.integer(selection) +} + +#' Do two vectors of probabilities agree, element by element? +#' +#' To a relative tolerance of `sqrt(.Machine$double.eps)`, the one +#' `all.equal()` uses. Zeros must match exactly, and so must `NA`s. An +#' infinite value agrees with the same infinity only, since `Inf - Inf` is +#' `NaN` and every finite number is within any tolerance of `Inf`. +#' +#' @noRd +same_prob <- function(a, b) { + both_na <- is.na(a) & is.na(b) + close <- a == b | (is.finite(a) & is.finite(b) & + abs(a - b) <= sqrt(.Machine$double.eps) * pmax(abs(a), abs(b))) + both_na | (!is.na(close) & close) +} + +#' Refuse a `.prob` column that is not the one draw() set +#' +#' ht_total() and ht_mean() divide by `.prob`, and as_svydesign() gives it to +#' `survey` as the probabilities of a PPS design. A value changed after the +#' draw changes those estimates while the joint probabilities and the variance +#' still follow the design. `expected` is the draw-time probability of each +#' sample row, or `NULL` for a sample saved by drawn 0.2.0, which records none; +#' then only the column's type and range are checked. +#' +#' @noRd +check_prob <- function(sample, expected = NULL, arg = "sample") { + fix <- paste0(" `.prob` holds the design's inclusion probabilities and ", + "must stay as draw() set it. Put adjusted weights in ", + "`.weight` and estimate from them with as_svydesign().") + p <- sample[[".prob"]] + if (is.null(p)) { + stop_not_drawn(paste0("has no `.prob` column, so it was removed after ", + "draw().", fix), arg) + } + if (!is.numeric(p)) { + stop_not_drawn(paste0("has ", a_class(p), " `.prob` column, so it ", + "was changed after draw().", fix), arg) + } + # A probability of 1 can carry rounding error from a sum, so the upper + # bound allows for it. + bad <- is.na(p) | p <= 0 | p > 1 + 1e-9 + if (any(bad)) { + vals <- unique(signif(p[bad], 4)) + stop_not_drawn(paste0( + "has `.prob` values that are not probabilities in (0, 1] in ", + sum(bad), " row(s): ", paste(utils::head(vals, 5L), collapse = ", "), + more_text(vals), ". `.prob` was changed after draw().", + fix), arg) + } + if (!is.null(expected)) { + off <- !same_prob(p, expected) + if (any(off)) { + stop_not_drawn(paste0( + "has `.prob` values in ", sum(off), " row(s) that differ from the ", + "inclusion probabilities recorded when it was drawn, so `.prob` was ", + "changed after draw().", fix), arg) + } + } + invisible(p) +} + +#' Refuse a sample whose design gives its frame other probabilities now +#' +#' The variance, the design's degrees of freedom and the `survey` mapping are +#' all recomputed from the design and the stored frame in the current session. +#' If the design no longer gives the frame the probabilities it gave at draw +#' time, those figures describe another design. A spatial design decides which +#' rows lie inside its region under the current [sf::sf_use_s2()], so turning +#' spherical geometry on or off between drawing and estimating is enough. +#' Reading a sample saved with saveRDS() into a new session, where s2 is on +#' again, does the same. A sample weighted conditional on its clusters is +#' checked against the probabilities given the stored `selection`. +#' +#' @noRd +check_drift <- function(design, pop, pi_all, arg = "sample", + selection = NULL) { + now <- inclusion_now(design, pop, selection, arg) + differ <- if (length(now) != length(pi_all)) { + rep(TRUE, max(length(now), length(pi_all))) + } else { + !same_prob(now, pi_all) + } + if (!any(differ)) return(invisible(NULL)) + stop_not_drawn(paste0( + "has a design that gives ", sum(differ), " of its ", length(differ), + " frame rows a different inclusion probability in this session or this ", + "version of drawn than when the sample was drawn, so its standard errors ", + "would describe another design. ", drift_fix(design)), arg) +} + +#' The inclusion probabilities the design gives the stored frame now +#' +#' The draw worked them out from the same design and frame, so an error here +#' means the session or the version of drawn has changed what the design does +#' with the frame. A spatial design drawn with `n = 100` under +#' `sf::sf_use_s2(FALSE)` may find fewer than 100 rows inside `region` under +#' `TRUE`, and stop there. The sample is then refused as one whose +#' probabilities have changed, with the design's error quoted. A spatial +#' design in a session without sf keeps the error that asks for sf. +#' +#' @noRd +inclusion_now <- function(design, pop, selection = NULL, arg = "sample") { + tryCatch( + if (is.null(selection)) { + exact_inclusion(design, pop) + } else { + conditional_inclusion(design, pop, selection) + }, + error = function(e) { + if (uses_s2(design) && !requireNamespace("sf", quietly = TRUE)) stop(e) + stop_not_drawn(paste0( + "has a design that gives its frame different inclusion ", + "probabilities in this session or this version of drawn than when ", + "the sample was drawn. Applied to the stored frame now, the design ", + "stops with the error \"", gsub("\n", " ", conditionMessage(e)), + "\", so the probabilities and standard errors of the draw cannot be ", + "worked out again. ", drift_fix(design)), arg) + }) +} + +#' What to do about a design whose probabilities have changed since the draw +#' @noRd +drift_fix <- function(design) { + if (uses_s2(design)) { + paste0("sf::sf_use_s2() decides which rows of a spatial design fall ", + "inside `region`, and it is ", isTRUE(sf::sf_use_s2()), " now. ", + "Set it to the value it had when the sample was drawn, in a ", + "session with the same version of sf, then estimate.") + } else { + paste0("Estimate in a session set up as the one the sample was drawn in, ", + "with the same version of drawn, or draw the sample again.") + } +} + +#' Refuse a sample saved by drawn 0.2.0 whose `.prob` the design no longer gives +#' +#' Such a sample records no probabilities for the frame, but its `.prob` +#' column holds the draw-time probability of each sampled row, and its rows +#' are in the order of `drawn`. The design, applied to the stored frame in +#' this session, must give each of those rows the same probability. A +#' spatial design under another sf::sf_use_s2() setting does not, and +#' neither does a `.prob` edited after the draw. Rows put in another order +#' change `.prob` only in a design that gives rows unequal probabilities; +#' check_legacy_order() refuses them before this, through the frame columns +#' the sample keeps. +#' +#' @noRd +check_legacy_prob <- function(sample, design, pop, drawn, arg = "sample") { + if (!length(drawn)) return(invisible(NULL)) + now <- inclusion_now(design, pop, arg = arg)[drawn] + differ <- !same_prob(now, sample[[".prob"]]) + if (!any(differ)) return(invisible(NULL)) + stop_not_drawn(paste0( + "has a design that gives ", sum(differ), " of its ", length(differ), + " rows a different inclusion probability in this session or this ", + "version of drawn than its `.prob` column records, so its standard ", + "errors would describe another design. ", drift_fix(design), " A `.prob` ", + "changed after draw(), or rows put in another order, gives the same ", + "difference, because a sample saved by drawn 0.2.0 is matched to its ", + "frame rows by position. Keep such a sample as draw() returned it."), arg) +} + +#' Refuse a sample saved by drawn 0.2.0 whose rows were put in another order +#' +#' Such a sample has no `.row` column, so its rows are matched to the frame +#' rows in `drawn` by position. Sorting it pairs `y` with the strata, +#' clusters, time stamps and frame positions of other rows, and in a design +#' that gives every row the same probability `.prob` does not change. The +#' frame columns the sample keeps show it: a column that holds the values of +#' the drawn rows, in another order, was moved with its rows. A column whose +#' values were changed after the draw holds other values and is passed over, +#' as are columns that `row_values_agree()` does not compare. A sample that +#' keeps no frame column cannot be checked. +#' +#' A column that holds a different value in every frame row, such as an id, +#' and agrees with the drawn rows position by position shows that the rows +#' are in the order drawn. The check then stops there, so two values swapped +#' between rows of another column by a later correction are not taken for a +#' reorder. +#' +#' @noRd +check_legacy_order <- function(sample, pop, drawn, arg = "sample") { + shared <- setdiff(intersect(names(sample), names(pop)), + c(".prob", ".weight", ".row", ".reserve", ".replicate")) + for (col in shared) { + if (!identifies_rows(pop[[col]])) next + v <- comparable_values(sample[[col]], pop[[col]][drawn]) + if (!is.null(v) && same_values(v$a, v$b)) return(invisible(NULL)) + } + sorted <- function(x) sort(x, method = "radix", na.last = TRUE) + for (col in shared) { + v <- comparable_values(sample[[col]], pop[[col]][drawn]) + if (is.null(v) || same_values(v$a, v$b)) next + if (!same_values(sorted(v$a), sorted(v$b))) next + id <- c(col, setdiff(shared, col)) + id <- id[vapply(id, function(k) identifies_rows(pop[[k]]), logical(1))] + by <- if (length(id)) encodeString(id[1L], quote = "\"") else + "" + stop_not_drawn(paste0( + "has its rows in another order than draw() returned them: its `", col, + "` column holds the values of the drawn rows, in another order. A ", + "sample saved by drawn 0.2.0 has no `.row` column and is matched to ", + "its frame rows by position, so its standard errors would pair rows ", + "with the strata, clusters or frame positions of other rows. Rebuild ", + "it with as_drawn(sample, attr(sample, \"drawn_design\"), ", + "attr(sample, \"drawn_population\"), by = ", by, "), which adds a ", + "`.row` column, or put its rows back in the order draw() returned ", + "them."), arg) + } + invisible(NULL) +} + +#' Does a frame column hold a different value in every row? +#' @noRd +identifies_rows <- function(x) { + is.atomic(x) && is.null(dim(x)) && !anyNA(x) && !anyDuplicated(x) +} + +#' Do two vectors from comparable_values() agree in every position? +#' +#' Missing values agree with missing values only. +#' +#' @noRd +same_values <- function(a, b) { + agree <- if (is.numeric(a)) same_prob(a, b) else a == b + all((!is.na(agree) & agree) | (is.na(a) & is.na(b))) +} + +#' Fill in the fields that a design saved by drawn 0.2.0 does not have +#' +#' Each field added since then gets the value that keeps the design as it +#' was. A missing field is not the same as a `NULL` one, because `$` matches +#' a partial name: a systematic design without `n` read its `na_rm` as `n`, +#' and drew no rows. check_design(), as_drawn(), the plot method and +#' drawn_state() apply it, so a design read back with readRDS() works +#' wherever a design is passed or a sample carries one. +#' +#' @noRd +legacy_design <- function(design) { + added <- switch( + class(design)[1L], + drawn_design_simple = list(reserve = 0L), + drawn_design_stratified = list(cost = NULL, within = NULL), + drawn_design_systematic = list(n = NULL, n_starts = 1L), + drawn_design_multistage = list(size = NULL), + drawn_design_weighted = list(strata = NULL, allocation = NULL), + drawn_design_reservoir = list(batches = FALSE), + drawn_design_bootstrap = list(output = "rows"), + drawn_design_spread = list(strata = NULL, allocation = NULL, + reserve = 0L), + list()) + missing <- setdiff(names(added), names(design)) + if (length(missing)) design[missing] <- added[missing] + if (inherits(design, "drawn_design_certainty")) { + design$rest <- legacy_design(design$rest) + } + design +} + +#' Does a design decide membership with `sf`, directly or through `rest`? +#' @noRd +uses_s2 <- function(design) { + inherits(design, "drawn_design_spatial") || + (inherits(design, "drawn_design_certainty") && uses_s2(design$rest)) +} + +#' Frame rows from the `.row` column, checked against the rows drawn +#' @noRd +sample_rows <- function(sample, drawn, N, arg) { + ids <- sample[[".row"]] + if (is.null(ids)) { + stop_not_drawn(paste0( + "has no `.row` column, so its rows cannot be matched to the frame rows ", + "they were drawn from. Keep the `.prob`, `.weight` and `.row` columns ", + "that draw(..., weights = TRUE) adds."), arg) + } + if (!is.numeric(ids)) { + stop_not_drawn(paste0( + "has ", a_class(ids), " `.row` column, where draw() puts the frame ", + "row of each sampled row. Estimate from the sample as draw() returned ", + "it."), arg) + } + bad <- is.na(ids) | ids != trunc(ids) | ids < 1 | ids > N + if (any(bad)) { + stop_not_drawn(paste0( + "has `.row` values that are not rows of the ", N, "-row frame it was ", + "drawn from: ", format_rows(ids[bad]), ". Estimate from the sample as ", + "draw() returned it."), arg) + } + ids <- as.integer(ids) + dup <- ids[duplicated(ids)] + if (length(dup)) { + stop_not_drawn(paste0( + "holds frame row(s) ", format_rows(dup), " more than once, as rbind() ", + "of samples or a join that matches a row twice produces. Estimate from ", + "the sample as draw() returned it, and add fieldwork columns with one ", + "value per sampled row."), arg) + } + extra <- setdiff(ids, drawn) + if (length(extra)) { + stop_not_drawn(paste0( + "holds frame row(s) ", format_rows(extra), " that were not in the ", + "sample drawn, as rbind() of two samples produces. Estimate from each ", + "sample on its own."), arg) + } + if (length(ids) < length(drawn)) { + stop_not_drawn(paste0( + "has ", length(ids), " of the ", length(drawn), " rows that were ", + "drawn. A subset of a sample is not a sample from the design, and its ", + "standard errors would be wrong. Estimate from the full result of ", + "draw() and use `by` for groups."), arg) + } + ids +} + +# ---- rebuilding, joining and compacting a sample ------------------------------ + +#' Rebuild a weighted sample from its rows +#' +#' A weighted sample carries its design, a copy of its frame and its +#' inclusion probabilities as attributes. A CSV or spreadsheet file, a +#' database table and [merge()] keep none of them, so [ht_total()], +#' [ht_mean()], [as_svydesign()] and [sample_summary()] refuse the rows that +#' come back. `as_drawn()` puts the attributes back. It matches each row of +#' `data` to its row of `frame`, works out the inclusion probabilities again +#' from `design`, and sets `.prob`, `.weight` and `.row` as [draw()] sets +#' them. +#' +#' @section Matching rows to the frame: +#' With `by = NULL`, each row is matched through its `.row` column, the frame +#' row [draw()] recorded for it. `frame` must then be the frame the sample was +#' drawn from, with its rows in the same order. A frame in another order, such +#' as a database table read without `ORDER BY`, holds other rows at those +#' positions, and its strata and clusters would be wrong for the sample. Each +#' column `data` shares with `frame` is therefore compared with the frame rows +#' `.row` names, and a column whose values differ is refused. Numbers need to +#' agree to about eight significant digits, fewer than a CSV file keeps, and a +#' number read back from text, such as `"007"`, is compared as the number 7. +#' Text such as `"T"`, `"F"`, `"t"` or `"f"` that a file gave back as a logical +#' column is compared as `TRUE` or `FALSE`, as `readr::read_csv()` reads it. A +#' date-time read back in another time zone agrees when it is the same instant +#' or shows the same clock time, since `readr::read_csv()` and +#' `data.table::fread()` read the clock time a CSV file holds as UTC. A missing +#' value on either side is not compared, so a frame column that fieldwork fills +#' in is accepted. Nor is a date that a file gave back as text, whose format a +#' spreadsheet may have changed. A column changed after the draw, such as a +#' corrected address, is refused too; rename it in `data`, or match on an id. A +#' `data` that shares no column with `frame` besides those [draw()] adds cannot +#' be checked, so keep an id column in the file. +#' +#' With `by`, rows are matched on the values of one or more id columns that +#' `data` and `frame` share. Values are compared as [match()] compares them, +#' and as text when the two columns have different classes, so an id stored +#' as `"007"` does not match the number 7 that a CSV file gives back. +#' +#' When `data` has both `.row` and the `by` columns, they must agree. A frame +#' row found through `by` that is not the one `.row` names means `frame` is +#' not in the order it had when the sample was drawn, which changes the +#' probabilities of designs that depend on that order, such as +#' [design_systematic()]; the rebuild is refused. +#' +#' A row with a missing id, an id that appears twice in `data`, an id that +#' `frame` does not have or holds more than once, and a row the design gives a +#' probability of 0 are refused, with the ids named. +#' +#' @section Every row drawn: +#' `data` must hold every row that was drawn, with or without a fieldwork +#' result. A subset, such as the rows that responded, is not a sample from +#' the design, and its standard errors would be wrong. For a design that +#' draws a fixed number of rows (simple, stratified, spread, temporal, +#' spatial and reservoir designs, systematic designs given `n`, and +#' [design_weighted()] with `method = "systematic"`, alone or as the `rest` +#' of [design_certainty()]), a `data` with another number of rows is refused. +#' A [design_cluster()] or [design_multistage()] sample, also as the `rest` +#' of [design_certainty()], is refused when its rows are not of `n_clusters` +#' clusters or a cluster does not hold the rows the design takes from it, +#' which are all of its rows for whole clusters, and the same number from +#' each cluster when that number does not depend on which clusters were +#' selected. A design weighted conditional on its clusters (see "Design +#' weights" in [draw()]) is rebuilt from the clusters its rows belong to, +#' which must hold the rows the design takes from each given that selection. +#' A frame row the design takes with certainty, with probability 1, is in +#' every sample, and a `data` without it is refused whatever the design. Keep +#' the rows with no response, with `y` missing, and estimate a mean with +#' `ht_mean(na_rm = TRUE)`; see "Missing values and nonresponse" in +#' [ht_total()]. +#' +#' A list from a design with `reserve` is rebuilt whole, the main sample and +#' every reserve, with the `.reserve` column [draw()] added, which records +#' the order the reserves are used in. Pass the result to [use_reserves()]. +#' +#' @section What comes back: +#' The rows of `data` in their own order, with `.prob`, `.weight` and `.row` +#' first and the other columns of `data` after them. `.prob` and `.weight` +#' come from `design`. A numeric `.prob` in `data` must agree with them, or +#' the design or the frame is not the one the sample was drawn with. A +#' `.weight` adjusted after the draw is replaced by `1 / .prob`, so the +#' adjustment has to be made again. +#' +#' Strata, clusters and the other design columns are read from the copy of +#' `frame` stored with the result, as for a sample from [draw()], so `data` +#' needs only the columns to estimate from: `y` and the `by` columns of the +#' estimates. [add_fieldwork()] joins results that come back keyed by an id. +#' +#' @param data The sampled rows as read back: a data frame with the `.row` +#' column [draw()] added, or with the id column or columns named in `by`. +#' @param design The design the sample was drawn with. +#' @param frame The data frame the sample was drawn from, as it was then. +#' @param by `NULL` to match rows through `.row`, or the names of one or more +#' columns of `data` and `frame` that identify a frame row. +#' +#' @return A data frame of the class of `data`, ready for [ht_total()], +#' [ht_mean()], [as_svydesign()] and [sample_summary()]. +#' +#' @examples +#' pop <- data.frame(id = 1:200, site = rep(c("a", "b"), times = c(150, 50))) +#' by_site <- design_stratified("site", n = 40) +#' s <- draw(pop, by_site, seed = 1, weights = TRUE) +#' +#' # A file keeps the rows and loses the design +#' path <- tempfile(fileext = ".csv") +#' write.csv(s, path, row.names = FALSE) +#' back <- as_drawn(read.csv(path), by_site, pop) +#' sample_summary(back) +#' +#' # Without `.row`, match on an id column +#' ids <- read.csv(path)[, c("id", "site")] +#' back <- as_drawn(ids, by_site, pop, by = "id") +#' unlink(path) +#' +#' @seealso [add_fieldwork()] to join fieldwork results, [compact_sample()] +#' to drop frame columns before saving or sharing a sample, and [draw()]. +#' @export +as_drawn <- function(data, design, frame, by = NULL) { + if (!is_design(design)) { + stop("`design` must come from one of the design_*() constructors, not ", + a_class(design), ". See ?designs.", call. = FALSE) + } + design <- legacy_design(design) + if (!is.data.frame(data)) { + stop("`data` must be a data frame of the sampled rows, not ", + a_class(data), ".", call. = FALSE) + } + if (!is.data.frame(frame)) { + stop("`frame` must be the data frame the sample was drawn from, not ", + a_class(frame), ".", call. = FALSE) + } + if (samples_with_replacement(design)) { + stop("`design` samples with replacement, and draw() gives such a sample ", + "no weights to rebuild; see \"Design weights\" in ?draw.", + call. = FALSE) + } + clash <- intersect(c(".prob", ".weight", ".row"), names(frame)) + if (length(clash)) { + stop("`frame` has ", quote_names(clash), ", which a weighted sample has ", + "and a frame does not. Pass the data frame the sample was drawn ", + "from as `frame`, and the sample as `data`.", call. = FALSE) + } + if (anyDuplicated(names(data))) { + dup <- unique(names(data)[duplicated(names(data))]) + stop("`data` has duplicated column name(s): ", format_bad(dup), + ". Rename them before rebuilding the sample.", call. = FALSE) + } + warn_region(design, frame) + + rows <- frame_rows(data, frame, by) + if (is.null(by)) check_row_values(data, frame, rows, design) + selection <- NULL + if (conditional_design(design, frame)) { + selection <- rebuilt_selection(design, frame, rows) + pi_all <- conditional_inclusion(design, frame, selection) + } else { + pi_all <- exact_inclusion(design, frame) + if (inherits(design, "drawn_design_certainty")) { + check_rest_reach(design, frame, pi_all) + } + check_cluster_rows(design, frame, rows) + } + p <- pi_all[rows] + zero <- is.na(p) | p <= 0 + if (any(zero)) { + stop("`data` holds ", sum(zero), " row(s) that `design` gives a ", + "probability of 0 in `frame`, so it cannot have drawn them: frame ", + "row(s) ", format_rows(rows[zero]), ". Pass the design and the ", + "frame the sample was drawn with.", call. = FALSE) + } + r <- reserve_size(design) + if (r > 0L) { + # A list: the main sample and its reserves, whose order comes from + # `.reserve`. + listed <- as.numeric(design$n) + r + if (nrow(data) != listed) { + stop("`data` has ", nrow(data), " rows, and `design` lists ", + listed, ": ", design$n, " in the main sample and ", r, + " reserve", if (r > 1L) "s", ". Rebuild the whole list as draw() ", + "returned it, then pass it to use_reserves().", call. = FALSE) + } + reserve <- rebuilt_reserve(data, design$n, r) + } else if (fixed_size(design)) { + expected <- sum(pi_all) + if (abs(nrow(data) - expected) > 1e-6 * max(1, expected)) { + stop("`data` has ", nrow(data), " rows, and `design` draws ", + format(signif(expected, 6)), " from `frame`. A sample rebuilt ", + "from some of the rows drawn, such as those that responded, is ", + "not a sample from the design, and its standard errors would be ", + "wrong. Keep every row drawn, with `y` missing where there is no ", + "result, and estimate a mean with ht_mean(na_rm = TRUE).", + call. = FALSE) + } + } + certain <- which(!is.na(pi_all) & is_certain(pi_all)) + left_out <- certain[!certain %in% rows] + if (length(left_out)) { + stop("`data` does not hold frame row(s) ", format_rows(left_out), + ", which `design` takes with certainty, so every sample from it ", + "holds them. A sample rebuilt from some of the rows drawn is not a ", + "sample from the design; keep every row drawn, with `y` missing ", + "where there is no result.", call. = FALSE) + } + old <- data[[".prob"]] + if (is.numeric(old)) { + off <- !same_prob(old, p) + if (any(off)) { + stop("`data` has `.prob` values in ", sum(off), " row(s) that differ ", + "from the probabilities `design` gives `frame`, such as ", + format(signif(old[off][1], 4)), " where the design gives ", + format(signif(p[off][1], 4)), ". Pass the design and the frame ", + "the sample was drawn with.", call. = FALSE) + } + } + # The seed and generator of the draw are not in the file. + meta <- draw_meta(NULL, nrow(frame), made_by = "as_drawn()") + if (r > 0L) { + return(rebuild_sample(data, design, frame, rows, pi_all, selection, + reserve = reserve, drawn = rows[order(reserve)], + meta = meta)) + } + rebuild_sample(data, design, frame, rows, pi_all, selection, meta = meta) +} + +#' Each row's reserve number, from the `.reserve` column of a list +#' +#' A list drawn with `reserve = r` numbers its `n` main rows 0 and its +#' reserves 1 to `r`, the order they are used in, which nothing else in a +#' file records. +#' +#' @noRd +rebuilt_reserve <- function(data, n, r) { + col <- data[[".reserve"]] + if (is.null(col)) { + stop("`data` has no `.reserve` column, which records the order of the ", + "reserves `design` lists. Keep the `.reserve` column draw() added.", + call. = FALSE) + } + ok <- is.numeric(col) && is.null(dim(col)) && !anyNA(col) && + all(col == trunc(col)) && + identical(sort(as.integer(col)), c(integer(n), seq_len(r))) + if (!ok) { + stop("`data` has a `.reserve` column that does not hold 0 for ", n, + " rows and each of 1 to ", r, " once, as draw() set it. Restore it ", + "from the list draw() returned.", call. = FALSE) + } + as.integer(col) +} + +#' Set the columns and attributes of a weighted sample on rows of a frame +#' +#' `rows` are the frame rows of `data`'s rows, in `data`'s order, and +#' `pi_all` every frame row's inclusion probability, as draw() records them. +#' `selection` holds the codes of the clusters selected, for a design +#' weighted conditional on them. Any `.prob`, `.weight` and `.row` columns and +#' `drawn_*` attributes `data` already has are replaced, so drawn_state() +#' accepts the result on the same terms as a sample from draw(). +#' +#' `reserve`, when given, is each row's reserve number, set as a `.reserve` +#' column after `.row`. `drawn` is the frame rows in the order recorded as +#' `drawn_rows`, which for a list is the main sample and then the reserves +#' in the order they are used. `compact` is what compact_sample() dropped +#' from `frame`, kept as `drawn_compact`. `meta` is the record of how the +#' sample was drawn, from draw_meta(), kept as `drawn_meta`. +#' +#' @noRd +rebuild_sample <- function(data, design, frame, rows, pi_all, + selection = NULL, reserve = NULL, drawn = rows, + compact = NULL, meta = NULL) { + added <- c(".prob", ".weight", ".row", if (!is.null(reserve)) ".reserve") + out <- data + for (col in intersect(added, names(out))) out[[col]] <- NULL + p <- pi_all[rows] + out[[".prob"]] <- p + out[[".weight"]] <- 1 / p + out[[".row"]] <- rows + if (!is.null(reserve)) out[[".reserve"]] <- as.integer(reserve) + out <- out[, c(added, setdiff(names(out), added)), drop = FALSE] + for (a in grep("^drawn_", names(attributes(out)), value = TRUE)) { + attr(out, a) <- NULL + } + attr(out, "drawn_design") <- design + # `.row` holds `rows` itself, so the attribute gets its own copy, as in + # draw(). + attr(out, "drawn_rows") <- copy_column(drawn) + attr(out, "drawn_population") <- snapshot_frame(frame) + attr(out, "drawn_pi") <- pi_all + if (!is.null(selection)) attr(out, "drawn_selection") <- selection + if (!is.null(compact)) attr(out, "drawn_compact") <- compact + if (!is.null(meta)) attr(out, "drawn_meta") <- meta + table_ready(out) +} + +#' The frame row of each row of `data`, through `.row` or the `by` columns +#' @noRd +frame_rows <- function(data, frame, by) { + N <- nrow(frame) + stored <- data[[".row"]] + if (is.null(by)) { + if (is.null(stored)) { + stop("`data` has no `.row` column, which matches each row to the ", + "frame row it was drawn from. Name an id column of `data` and ", + "`frame` in `by`.", call. = FALSE) + } + if (!is.numeric(stored)) { + stop("`data` has ", a_class(stored), " `.row` column, where draw() ", + "puts the frame row of each sampled row. Name an id column of ", + "`data` and `frame` in `by` instead.", call. = FALSE) + } + bad <- is.na(stored) | stored != trunc(stored) | stored < 1 | stored > N + if (any(bad)) { + stop("`data` has `.row` values that are not rows of the ", N, + "-row `frame`: ", format_rows(stored[bad]), ". Pass the frame the ", + "sample was drawn from, or name an id column in `by`.", + call. = FALSE) + } + rows <- as.integer(stored) + dup <- rows[duplicated(rows)] + if (length(dup)) { + stop("`data` holds frame row(s) ", format_rows(dup), " more than ", + "once. A sample holds each row it drew once; remove the repeats.", + call. = FALSE) + } + return(rows) + } + + by <- check_columns(by, "by") + for (where in c("data", "frame")) { + absent <- setdiff(by, names(if (where == "data") data else frame)) + if (length(absent)) { + stop("`by` names ", quote_names(absent), ", which `", where, "` does ", + "not have.", call. = FALSE) + } + } + check_key_columns(data, by, "by") + check_key_columns(frame, by, "by") + keys <- group_key2(data, frame, by) + kd <- as.integer(keys$x) + kf <- as.integer(keys$table) + labels <- group_label(levels(keys$x)) + id <- quote_names(by) + if (anyNA(kd)) { + stop("`data` has no value of ", id, " in ", sum(is.na(kd)), " row(s), ", + "so they cannot be matched to `frame`. Every sampled row needs one.", + call. = FALSE) + } + dup <- kd[duplicated(kd)] + if (length(dup)) { + stop("`data` has ", id, " ", format_rows(labels[dup]), " in more than ", + "one row. A sample holds each row it drew once; remove the repeats.", + call. = FALSE) + } + rows <- match(kd, kf) + if (anyNA(rows)) { + stop("`data` has ", id, " ", format_rows(labels[kd[is.na(rows)]]), + ", which `frame` does not have. Pass the frame the sample was ", + "drawn from.", call. = FALSE) + } + twice <- intersect(kd, kf[duplicated(kf)]) + if (length(twice)) { + stop("`frame` has ", id, " ", format_rows(labels[twice]), " in more ", + "than one row, so ", id, " does not identify a frame row. Name ", + "columns in `by` that do, or match through `.row` with by = NULL.", + call. = FALSE) + } + if (is.numeric(stored)) { + off <- is.na(stored) | stored != rows + if (any(off)) { + stop("`data` has a `.row` column that disagrees with ", id, " in ", + sum(off), " row(s), so `frame` does not have its rows in the ", + "order they had when the sample was drawn, and some designs ", + "depend on that order. Pass `frame` in that order.", call. = FALSE) + } + } + rows +} + +#' Refuse `.row` values that name frame rows holding other values +#' +#' With `by = NULL`, rows are matched through `.row`, a position in the +#' frame. A frame in another order, such as a database table read without +#' ORDER BY, holds other rows at those positions, and the strata, clusters +#' and probabilities read from it would belong to other rows. Each column +#' `data` shares with `frame` is compared on the rows `.row` names, the +#' design's own columns first, and the first that disagrees is refused. +#' +#' A missing value on either side is not compared, since a frame column may +#' be a placeholder that fieldwork fills in and a CSV file reads an empty or +#' `"NA"` text back as missing. Columns are compared as `row_values_agree()` +#' compares them. +#' +#' @noRd +check_row_values <- function(data, frame, rows, design) { + shared <- setdiff(intersect(names(data), names(frame)), + c(".prob", ".weight", ".row", ".reserve", ".replicate")) + shared <- c(intersect(design_columns(design), shared), + setdiff(shared, design_columns(design))) + for (col in shared) { + a <- data[[col]] + b <- frame[[col]][rows] + agree <- row_values_agree(a, b) + if (is.null(agree)) next + compared <- !is.na(a) & !is.na(b) + off <- which(compared & !agree) + if (!length(off)) next + i <- off[1L] + stop("`data` has `", col, "` values that differ from those of the ", + "`frame` rows its `.row` column names in ", length(off), " of the ", + sum(compared), " rows compared, such as ", shown_value(a[i]), + " where `frame` row ", rows[i], " has ", shown_value(b[i]), ". ", + "Pass `frame` with its rows in the order they had when the sample ", + "was drawn; if it is in that order and `", col, "` was changed ", + "after the draw, rename it in `data` or match rows on an id column ", + "with `by`.", call. = FALSE) + } + invisible(NULL) +} + +#' Do two columns hold the same values, row by row? +#' +#' `a` is a column of `data` as read back and `b` the frame's column on the same +#' rows. Numbers and logical values are compared as numbers, with the tolerance +#' of `same_prob()`, since a CSV file keeps 15 significant digits. A number that +#' came back as text, such as an id written `"007"`, is compared as a number +#' too, and other text and factors as text. Text such as `"T"`, `"F"`, `"t"` or +#' `"f"` that came back as a logical column is compared as `TRUE` or `FALSE`, +#' read by `as.logical()` in capitals, since `readr::read_csv()` reads `"t"` and +#' `"f"` as logical. Two columns of one class, such as two `Date` columns, are +#' compared as numbers. Two date-times in different time zones agree when they +#' are the same instant or show the same clock time, since `readr::read_csv()` +#' and `data.table::fread()` read the clock time a CSV file holds as UTC. +#' Returns `NULL` for a pair it does not compare: a list or matrix column, or a +#' classed column, such as a `Date`, on one side only, since a spreadsheet the +#' file went through may have changed its format. +#' +#' @noRd +row_values_agree <- function(a, b) { + v <- comparable_values(a, b) + if (is.null(v)) return(NULL) + agree <- if (is.numeric(v$a)) same_prob(v$a, v$b) else v$a == v$b + if (other_time_zones(a, b)) { + agree <- agree | same_prob(as.numeric(a), as.numeric(b)) + } + agree +} + +#' Two columns as plain numbers or text, the way row_values_agree() compares +#' +#' A list with `a` and `b`, both numeric or both character, or `NULL` for a +#' pair that is not compared. Date-times in different time zones are given +#' as their clock times. +#' +#' @noRd +comparable_values <- function(a, b) { + if (!is.atomic(a) || !is.atomic(b) || !is.null(dim(a)) || + !is.null(dim(b))) { + return(NULL) + } + classed <- function(x) is.object(x) && !is.factor(x) + if (classed(a) || classed(b)) { + if (!identical(class(a), class(b)) || !is.numeric(unclass(a))) { + return(NULL) + } + if (other_time_zones(a, b)) { + return(list(a = clock_time(a), b = clock_time(b))) + } + a <- unclass(a) + b <- unclass(b) + } + number <- function(x) is.numeric(x) || is.logical(x) + text <- function(x) is.character(x) || is.factor(x) + as_number <- function(x) suppressWarnings(as.numeric(as.character(x))) + as_flag <- function(x) as.numeric(as.logical(toupper(as.character(x)))) + if (number(a) && number(b)) { + return(list(a = as.numeric(a), b = as.numeric(b))) + } + if (is.numeric(a)) return(list(a = as.numeric(a), b = as_number(b))) + if (is.numeric(b)) return(list(a = as_number(a), b = as.numeric(b))) + if (is.logical(a) && text(b)) { + return(list(a = as.numeric(a), b = as_flag(b))) + } + if (text(a) && is.logical(b)) { + return(list(a = as_flag(a), b = as.numeric(b))) + } + list(a = as.character(a), b = as.character(b)) +} + +#' Are `a` and `b` date-times with different time zones? +#' +#' A date-time with no `tzone` attribute, or an empty one, is in the +#' session's zone. +#' +#' @noRd +other_time_zones <- function(a, b) { + zone <- function(x) { + z <- attr(x, "tzone") + if (length(z)) z[[1L]] else "" + } + inherits(a, "POSIXct") && inherits(b, "POSIXct") && zone(a) != zone(b) +} + +#' The clock time a date-time shows in its own zone, as seconds +#' +#' Read as if it were UTC, so two zones' clock times compare as numbers. +#' +#' @noRd +clock_time <- function(x) { + lt <- as.POSIXlt(x) + as.numeric(ISOdatetime(lt$year + 1900, lt$mon + 1, lt$mday, lt$hour, + lt$min, lt$sec, tz = "UTC")) +} + +#' One value of a column, for a message +#' +#' A date-time shows its zone, since two columns can hold the same clock +#' time in different zones. +#' +#' @noRd +shown_value <- function(x) { + if (is.factor(x)) x <- as.character(x) + if (is.character(x)) return(encodeString(x, quote = "\"")) + if (inherits(x, "POSIXct")) return(format(x, usetz = TRUE)) + if (is.numeric(x)) return(as.character(unclass(x))) + format(x) +} + +#' Refuse rows that leave out part of what a cluster design takes together +#' +#' A design that takes whole clusters, or the same number of rows from each +#' cluster it selects, gives every sample `n_clusters` clusters holding those +#' rows, so a sample with a cluster missing or short of its take is a subset +#' of one. `rebuilt_selection()` checks it. A certainty design passes the +#' rows below its threshold to `rest`. +#' +#' @noRd +check_cluster_rows <- function(design, frame, rows) { + if (inherits(design, "drawn_design_certainty")) { + sp <- certainty_split(design, frame) + below <- sp$keep[sp$rest] + at <- match(rows, below) + return(check_cluster_rows(design$rest, frame[below, , drop = FALSE], + at[!is.na(at)])) + } + if (inherits(design, c("drawn_design_cluster", "drawn_design_multistage"))) { + rebuilt_selection(design, frame, rows, conditional = FALSE) + } + invisible(NULL) +} + +#' The clusters a conditionally weighted sample selected, from its rows +#' +#' A file keeps the rows and not the selection. The clusters are those the +#' rows belong to, and the probabilities given them need each cluster to +#' hold the rows the design takes from it. Which clusters a largest-remainder +#' split gives one row more depends on the order they were selected in, which +#' is lost too. Listing first the clusters holding more rows than the split +#' in code order gives them reproduces the split the draw made. +#' +#' `conditional` is `FALSE` for a design whose take from each cluster is the +#' same whichever clusters are selected, which `check_cluster_rows()` checks +#' the same way. +#' +#' @noRd +rebuilt_selection <- function(design, frame, rows, conditional = TRUE) { + cl <- conditional_setup(design, frame) + code <- cl$code[rows] + chosen <- sort(unique(code[!is.na(code)])) + if (length(chosen) != design$n_clusters) { + stop("`data` holds rows of ", length(chosen), " cluster(s), and ", + "`design` selects ", design$n_clusters, ". A sample rebuilt from ", + "some of the rows drawn is not a sample from the design; keep every ", + "row drawn.", call. = FALSE) + } + sizes <- tabulate(cl$code, cl$total) + got <- tabulate(match(code, chosen), length(chosen)) + take <- cluster_takes(design, sizes[chosen]) + if (any(take != got)) { + chosen <- chosen[order(take - got)] + got <- tabulate(match(code, chosen), length(chosen)) + take <- cluster_takes(design, sizes[chosen]) + } + off <- which(take != got) + if (length(off)) { + label <- cl$labels[match(chosen[off[1]], cl$code)] + stop("`data` holds ", got[off[1]], " row(s) of cluster `", format(label), + "`, where `design` takes ", take[off[1]], " from it", + if (conditional) " given the clusters selected", ". A sample ", + "rebuilt from some of the rows drawn is not a sample from the ", + "design; keep every row drawn.", call. = FALSE) + } + chosen +} + +#' Does a design draw the same number of rows from a frame every time? +#' +#' Only designs certain to are listed, since as_drawn() refuses a sample of +#' another size from them. Random-size designs, such as Poisson sampling, +#' whole clusters of unequal size or an interval that does not divide the +#' frame, are not. +#' +#' @noRd +fixed_size <- function(design) { + if (inherits(design, "drawn_design_certainty")) { + return(fixed_size(design$rest)) + } + if (inherits(design, "drawn_design_systematic")) { + return(!is.null(design$n)) + } + if (inherits(design, "drawn_design_weighted")) { + return(identical(design$method, "systematic")) + } + inherits(design, c("drawn_design_simple", "drawn_design_stratified", + "drawn_design_spread", "drawn_design_temporal", + "drawn_design_spatial", "drawn_design_reservoir")) +} + +#' Join fieldwork results to a weighted sample +#' +#' Fieldwork results usually come back as a table of their own, keyed by an +#' id and in another order. `add_fieldwork()` adds its columns to `sample`, +#' row by row through the id, and keeps the sample's rows, their order and +#' the attributes that hold its design. [merge()] reorders the rows and drops +#' those attributes, and a join that matches a row twice would repeat it. +#' +#' A sampled row with no row in `field` gets missing values, as a +#' nonrespondent should: [ht_total()] refuses them, and `ht_mean(na_rm = TRUE)` +#' estimates the mean over the rows with a result (see "Missing values and +#' nonresponse" in [ht_total()]). An id that appears twice in `field`, an id +#' that is not in `sample`, a missing id, and a column of `field` that +#' `sample` already has are refused. Ids are compared as in [as_drawn()]. +#' +#' A list from a design with `reserve` takes fieldwork columns too, such as +#' which units were found unavailable, before [use_reserves()] turns it into +#' the sample to estimate from. +#' +#' @param sample A data frame returned by [draw()] with `weights = TRUE`, or +#' by [as_drawn()]. +#' @param field A data frame of results: the `by` columns and the columns to +#' add. +#' @param by The names of one or more columns of `sample` and `field` that +#' identify a sampled row. +#' +#' @return `sample` with the other columns of `field` added after its own. +#' +#' @examples +#' pop <- data.frame(id = 1:200, site = rep(c("a", "b"), times = c(150, 50))) +#' s <- draw(pop, design_stratified("site", n = 40), seed = 1, weights = TRUE) +#' +#' # Results for 36 of the 40 rows, in the order they came in +#' field <- data.frame(id = rev(s$id)[1:36], spend = seq(20, 370, by = 10)) +#' s <- add_fieldwork(s, field, by = "id") +#' ht_mean(s, "spend", na_rm = TRUE) +#' +#' @seealso [as_drawn()], [ht_mean()], [use_reserves()] +#' @export +add_fieldwork <- function(sample, field, by) { + drawn_state(sample, reserves = TRUE) + if (!is.data.frame(field)) { + stop("`field` must be a data frame of fieldwork results, not ", + a_class(field), ".", call. = FALSE) + } + by <- check_columns(by, "by") + for (where in c("sample", "field")) { + absent <- setdiff(by, names(if (where == "sample") sample else field)) + if (length(absent)) { + stop("`by` names ", quote_names(absent), ", which `", where, "` does ", + "not have.", call. = FALSE) + } + } + check_key_columns(sample, by, "by") + check_key_columns(field, by, "by") + new <- setdiff(names(field), by) + if (!length(new)) { + stop("`field` has no column besides ", quote_names(by), ", so there is ", + "nothing to add.", call. = FALSE) + } + reserved <- intersect(new, c(".prob", ".weight", ".row", ".reserve", + ".replicate")) + if (length(reserved)) { + stop("`field` has ", quote_names(reserved), ", which draw() sets in a ", + "weighted sample to hold its design. Rename ", + if (length(reserved) > 1L) "them" else "it", " in `field`.", + call. = FALSE) + } + clash <- intersect(new, names(sample)) + if (length(clash)) { + them <- if (length(clash) > 1L) "them" else "it" + stop("`field` has ", quote_names(clash), ", which `sample` already has. ", + "Rename ", them, " in `field`, or remove ", them, " from `sample` ", + "with `s$col <- NULL` first.", call. = FALSE) + } + + keys <- group_key2(sample, field, by) + ks <- as.integer(keys$x) + kf <- as.integer(keys$table) + labels <- group_label(levels(keys$x)) + id <- quote_names(by) + if (anyNA(ks)) { + stop("`sample` has no value of ", id, " in ", sum(is.na(ks)), " row(s), ", + "so `field` cannot be matched to them.", call. = FALSE) + } + dup <- ks[duplicated(ks)] + if (length(dup)) { + stop("`sample` has ", id, " ", format_rows(labels[dup]), " in more ", + "than one row, so ", id, " does not identify its rows. Join on ", + "columns that do.", call. = FALSE) + } + if (anyNA(kf)) { + stop("`field` has no value of ", id, " in ", sum(is.na(kf)), " row(s), ", + "so they cannot be matched to the sample.", call. = FALSE) + } + dup <- kf[duplicated(kf)] + if (length(dup)) { + stop("`field` has ", id, " ", format_rows(labels[dup]), " in more than ", + "one row. Give each sampled row one result.", call. = FALSE) + } + unknown <- setdiff(kf, ks) + if (length(unknown)) { + stop("`field` has ", id, " ", format_rows(labels[unknown]), ", which ", + if (length(unknown) > 1L) "are" else "is", " not in `sample`. ", + "Remove results for rows the sample did not draw.", call. = FALSE) + } + + at <- match(ks, kf) + out <- sample + for (col in new) { + x <- field[[col]] + out[[col]] <- if (is.null(dim(x))) x[at] else x[at, , drop = FALSE] + } + table_ready(out) +} + +#' Replace unavailable units from a reserve list +#' +#' [design_simple()] and [design_spread()] with `reserve` give a list: the +#' `n` units of the main sample, then the reserves, with a `.reserve` column +#' that numbers them 1, 2, ... in the order they are used. Visit every unit +#' of the main sample, and for each one found unavailable, visit the next +#' reserve, until the units found available make up `n`. +#' `use_reserves()` takes the list and what the visits found, and returns the +#' sample to estimate from: the units of the main sample found available, +#' and as many reserves, taken in order, as replace the others. +#' +#' @section What the estimates describe: +#' Replacing units changes the population being estimated. The sample that +#' comes back stands for the units of the frame that can be reached, and its +#' totals and means are theirs, not the whole frame's. It is weighted as a +#' sample of `n` drawn at equal probability from the frame without the `u` +#' listed units found unavailable: each unit used has probability +#' `n / (N - u)`, and the units found unavailable have probability 0, so +#' [ht_total()] and [ht_mean()] count them among the frame rows the estimate +#' does not cover. +#' +#' The probabilities assume that every unit of the frame nobody visited is +#' available. A frame that holds more unavailable units than were found has +#' fewer than `N - u` units that can be reached, and the totals are too high +#' by about the share of the frame those units make up. The Hajek mean of +#' [ht_mean()] does not depend on `N - u` and is not affected. An estimate +#' from the sample keeps `u` in `unavailable`, and its printed `unreachable` +#' line adds that the units nobody visited are taken as available. +#' +#' For [design_simple()] the weighting is exact under that assumption, when +#' the reserves suffice. The list is one random draw in random order, so its +#' first `n` available units are a simple random sample of `n` from the +#' available units of the frame, and the variance is that of a simple random +#' sample from `N - u`. For +#' [design_spread()] the reserves are a second spread sample from the rows +#' the main sample left, in random order. The units used are spread over the +#' space, and under the same assumption their probabilities average +#' `n / (N - u)`, but each unit's own probability is not known exactly, so +#' the weights are an approximation. The variance is the local mean +#' estimator over the units used. +#' +#' Reserves are for units that cannot be reached or measured at all. A unit +#' that is reached but gives no answer is nonresponse: keep it in the sample +#' with `y` missing, as "Missing values and nonresponse" in [ht_total()] +#' describes. +#' +#' @section Marking the visits: +#' `unavailable` holds one value for each row of `sample`: `TRUE` for a unit +#' found unavailable, `FALSE` for one found available, and `NA` for one not +#' visited. Every unit of the main sample needs `TRUE` or `FALSE`, and so +#' does each reserve up to the one that completes the sample; a missing +#' value there is refused, with the frame row named. Reserves visited past +#' that one are not used, and those of them found unavailable count among +#' the `u` units outside the population. When the reserves run out first, +#' the sample holds fewer than `n` units and is weighted as a sample of that +#' many, with a warning. +#' +#' @section What comes back: +#' The units used, in the order of `sample`, with `.prob`, `.weight`, `.row` +#' and `.reserve` first. `.reserve` is 0 for a unit of the main sample and +#' the reserve's number for a unit that replaced one. The design stored with +#' the result is the list's design with `n` the number of units used, no +#' `reserve`, and the frame rows found unavailable recorded as +#' `unavailable`; [inclusion_prob()] of it gives those rows probability 0. +#' +#' @param sample A list from [draw()] with `weights = TRUE` and a design +#' with `reserve`, or from [as_drawn()]. +#' @param unavailable A logical vector with one value for each row of +#' `sample`, in its order, or the name of such a column of `sample`. See +#' "Marking the visits". +#' +#' @return A weighted sample, ready for [ht_total()], [ht_mean()], +#' [as_svydesign()] and [sample_summary()]. +#' +#' @examples +#' pop <- data.frame(id = 1:200, spend = (1:200) %% 37) +#' s <- draw(pop, design_simple(n = 20, reserve = 5), seed = 1, weights = TRUE) +#' table(s$.reserve) +#' +#' # Two units of the main sample could not be reached, nor could the first +#' # reserve; reserves 2 and 3 replaced them, and 4 and 5 were not visited +#' gone <- c(s$id[c(3, 11)], s$id[s$.reserve == 1]) +#' found <- ifelse(s$.reserve <= 3, s$id %in% gone, NA) +#' used <- use_reserves(s, found) +#' table(used$.reserve) +#' ht_total(used, "spend") +#' +#' @seealso [design_simple()], [design_spread()], [add_fieldwork()] to add +#' what the visits found to the list. +#' @export +use_reserves <- function(sample, unavailable) { + state <- drawn_state(sample, reserves = TRUE) + design <- state$design + r <- reserve_size(design) + if (r == 0L || is.null(state$reserve)) { + stop("`sample` was drawn with no `reserve`, so it lists no reserves to ", + "use. Estimate from it as it is.", call. = FALSE) + } + gone <- visit_findings(sample, unavailable) + place <- state$reserve + rows <- state$rows + main <- place == 0L + open <- main & is.na(gone) + if (any(open)) { + stop("`unavailable` is missing for ", sum(open), " unit(s) of the main ", + "sample, at frame row(s) ", format_rows(rows[open]), ". Visit every ", + "unit of the main sample and mark it TRUE or FALSE.", call. = FALSE) + } + + # Each unavailable unit of the main sample is replaced by the next reserve + # found available, in the order of `.reserve`. + used <- main & !gone + need <- sum(gone[main]) + at <- match(seq_len(r), place) + for (k in seq_len(r)) { + if (need == 0L) break + i <- at[k] + if (is.na(gone[i])) { + stop("`unavailable` is missing for reserve ", k, ", at frame row ", + rows[i], ", which is needed to replace ", need, " more ", + "unavailable unit(s). Visit the reserves in order and mark each ", + "one TRUE or FALSE.", call. = FALSE) + } + if (!gone[i]) { + used[i] <- TRUE + need <- need - 1L + } + } + m <- sum(used) + if (m == 0L) { + stop("Every unit `sample` lists was found unavailable, so there is no ", + "sample to estimate from.", call. = FALSE) + } + if (need > 0L) { + warn_drawn(paste0( + "The ", r, " reserve(s) of `sample` ran out with ", need, " unavailable ", + "unit(s) of the main sample not replaced, so the sample holds ", m, + " units rather than ", design$n, ". It is weighted as a sample of ", m, + " from the units not found unavailable."), "drawn_reserves_short") + } + + resolved <- design + resolved$n <- as.integer(m) + resolved$reserve <- 0L + resolved$unavailable <- sort(rows[gone %in% TRUE]) + pi_all <- exact_inclusion(resolved, state$pop) + keep <- which(used) + rebuild_sample(reindex(sample, keep), resolved, state$pop, rows[keep], + pi_all, reserve = place[keep], compact = state$compact, + meta = state$meta) +} + +#' What the visits to a list found, as a logical vector over its rows +#' @noRd +visit_findings <- function(sample, unavailable) { + if (is.character(unavailable) && length(unavailable) == 1L && + !is.na(unavailable)) { + if (!unavailable %in% names(sample)) { + stop("`sample` has no column `", unavailable, "`.", call. = FALSE) + } + unavailable <- sample[[unavailable]] + } + if (!is.logical(unavailable) || !is.null(dim(unavailable)) || + length(unavailable) != nrow(sample)) { + stop("`unavailable` must be a logical vector with one value for each of ", + "the ", nrow(sample), " rows of `sample`, or the name of such a ", + "column, not ", format_bad(unavailable), ". Mark a unit TRUE when it ", + "was found unavailable, FALSE when it was available and NA when it ", + "was not visited; `sample$id %in% ids` turns a list of ids into ", + "such a vector.", call. = FALSE) + } + as.vector(unavailable) +} + +#' Drop the frame columns a sample's design does not need +#' +#' A weighted sample holds its own copy of the whole frame, every column of +#' it, so that [ht_total()], [ht_mean()], [as_svydesign()] and +#' [sample_summary()] can work from the sample alone. That copy is kept in +#' memory and written to every file the sample is saved to, which costs as +#' much as the frame each time, and hands the frame, with any names, +#' addresses or other personal data in it, to whoever receives the file. +#' `compact_sample()` replaces the copy with one that holds only the columns +#' the design reads (strata, clusters, size measures, `order_by`, time +#' stamps, coordinates and the like) and the columns named in `keep`. +#' +#' Estimates, standard errors, [as_svydesign()] and [sample_summary()] are +#' unchanged, with two exceptions that read other frame columns. A `by` +#' domain's size in the frame, which `ht_mean(estimator = "ht")` with `by` +#' divides by, needs the `by` columns in the stored frame; without them that +#' estimator is refused with a message naming `keep`. And a stratum with a +#' single sampled row leaves a domain's variance unmeasured unless the +#' stored frame's `by` columns show the stratum holds none of the domain (see +#' "Domains" in [ht_total()]). Keep the `by` columns of the estimates in +#' `keep`, and the columns [frame_totals()] is asked for. Whether a column of +#' the frame left out holds only 0 and 1, which makes [ht_mean()] treat it as +#' a proportion, is recorded. +#' +#' The sample's own columns are not changed: drop columns of the sample with +#' `s$col <- NULL`. The inclusion probabilities of every frame row are kept, +#' one number per row. +#' +#' @param sample A data frame returned by [draw()] with `weights = TRUE`, or +#' by [as_drawn()]. +#' @param keep Names of other columns of the frame to keep, such as the `by` +#' columns of the estimates. +#' +#' @return `sample`, with a smaller copy of the frame. +#' +#' @examples +#' pop <- data.frame(id = 1:5000, site = rep(c("a", "b"), each = 2500), +#' note = strrep("x", 40), spend = (1:5000) %% 97) +#' s <- draw(pop, design_stratified("site", n = 100), seed = 1, weights = TRUE) +#' small <- compact_sample(s) +#' +#' # The same estimate from a fraction of the bytes +#' c(full = length(serialize(s, NULL)), +#' compact = length(serialize(small, NULL))) +#' all.equal(ht_total(s, "spend")$se, ht_total(small, "spend")$se) +#' +#' @seealso [draw()], [as_drawn()] +#' @export +compact_sample <- function(sample, keep = NULL) { + state <- drawn_state(sample, reserves = TRUE) + pop <- state$pop + if (!is.null(keep)) { + keep <- check_columns(keep, "keep") + unknown <- setdiff(keep, names(pop)) + if (length(unknown)) { + gone <- intersect(unknown, state$compact$dropped) + stop("`keep` names ", quote_names(unknown), ", which ", + if (length(unknown) > 1L) "are not columns" else "is not a column", + " of the frame stored with `sample`. ", + if (length(gone)) { + paste0("An earlier compact_sample() dropped ", + quote_names(gone), "; compact the sample draw() returned ", + "instead.") + } else { + "Name columns of the frame the sample was drawn from." + }, call. = FALSE) + } + } + cols <- names(pop)[names(pop) %in% c(design_columns(state$design), keep)] + small <- frame_columns(pop, cols) + dropped <- setdiff(names(pop), names(small)) + binary <- dropped[vapply(dropped, function(nm) binary_column(pop[[nm]]), + logical(1))] + out <- sample + attr(out, "drawn_population") <- small + attr(out, "drawn_compact") <- list( + dropped = union(state$compact$dropped, dropped), + binary = union(state$compact$binary, binary) + ) + table_ready(out) +} + +#' The frame columns a design reads +#' +#' Strata, the column of standard deviations a Neyman allocation reads, +#' clusters, weights and size measures, the columns a spread design spreads +#' across, time stamps, `order_by` (of a systematic design, or of the walk +#' within each stratum) and coordinates. A certainty design adds `above` to +#' those of its `rest`. +#' +#' @noRd +design_columns <- function(design) { + if (inherits(design, "drawn_design_certainty")) { + return(unique(c(design[["above"]], design_columns(design[["rest"]])))) + } + allocation_by <- design[["allocation_by"]] + within <- design[["within"]] + unique(c(design[["strata"]], + if (is.character(allocation_by)) allocation_by, + design[["clusters"]], design[["weights"]], design[["across"]], + design[["size"]], design[["time"]], design[["order_by"]], + design[["coords"]], + if (is_design(within)) design_columns(within))) +} + +#' Columns `cols` of a frame, as a plain data frame +#' +#' An `sf` frame whose geometry is one of `cols` keeps its class, since a +#' design reads coordinates and their CRS from it. Any other frame becomes a +#' plain data frame, which estimates read the same way, and an `sf` frame +#' whose geometry the design does not read loses it. +#' +#' @noRd +frame_columns <- function(pop, cols) { + geometry <- attr(pop, "sf_column", exact = TRUE) + if (!is.null(geometry) && geometry %in% cols) { + return(pop[, cols, drop = FALSE]) + } + out <- unclass(pop)[cols] + structure(out, names = cols, row.names = .set_row_names(nrow(pop)), + class = "data.frame") +} + +#' Does a column hold a proportion: logical, or numbers that are all 0 or 1? +#' @noRd +binary_column <- function(x) { + if (is.logical(x)) return(TRUE) + if (!is.numeric(x)) return(FALSE) + x <- x[!is.na(x)] + length(x) > 0L && all(x == 0 | x == 1) +} diff --git a/R/survey.R b/R/survey.R index bf056bc..cf05dda 100644 --- a/R/survey.R +++ b/R/survey.R @@ -1,8 +1,8 @@ #' Hand a sample to the survey package #' -#' Builds a [survey::svydesign()] object from a drawn sample, so the analysis -#' this package does not do — regression, calibration, quantiles with proper -#' standard errors, replicate weights — can be done by the package that does. +#' Builds a [survey::svydesign()] object from a drawn sample, so that the +#' survey package can do the analysis this package does not, such as +#' regression, calibration and analysis with replicate weights. #' #' The two packages compute variance from different starting points. This one #' uses the design's inclusion probabilities; `survey` reconstructs the @@ -16,49 +16,182 @@ #' [design_reservoir()] \tab `ids = ~1` with `fpc` the rows the stream reached \tab identical \cr #' [design_stratified()] \tab `strata` from the strata columns, `fpc` each stratum's size \tab identical \cr #' [design_temporal()] \tab `strata` from the sampling intervals, `fpc` each interval's size \tab identical \cr -#' [design_cluster()] \tab `ids` the cluster column, `fpc` the number of clusters \tab identical \cr -#' [design_multistage()] \tab two stages, `ids = ~cluster + row`, `fpc` the number of clusters and each cluster's size \tab identical \cr -#' [design_weighted()], `"poisson"` \tab `survey::poisson_sampling()`, which models the random size \tab identical \cr -#' [design_certainty()] \tab the certainty rows as their own stratum, taken whole \tab as `rest` \cr -#' [design_weighted()], `"systematic"` \tab `pps = "brewer"` with the inclusion probabilities \tab within about 0.2 percent \cr -#' [design_spread()] \tab as its first-order design: `ids = ~1`, or `pps = "brewer"` with `size` \tab **`survey`'s is larger** \cr -#' [design_systematic()] \tab `ids = ~1` with `fpc` the frame size \tab **differ** \cr +#' [design_cluster()] \tab `ids` a `.cluster` column numbering the clusters, `fpc` the number of clusters \tab identical \cr +#' [design_multistage()], and [design_cluster()] with `balanced = TRUE` \tab two stages, `ids` the `.cluster` numbers then the rows, `fpc` the number of clusters and each cluster's size; with one sampled row from a selected cluster of several, one stage, `ids` the `.cluster` numbers and no `fpc` \tab identical \cr +#' [design_weighted()], `"poisson"` \tab `survey::poisson_sampling()`, which models the random size; with `strata`, the strata too, which change only the degrees of freedom \tab identical \cr +#' [design_certainty()] \tab the certainty rows as one unit in a stratum of their own, taken whole, beside `rest` as it maps alone; over a Poisson `rest`, `survey::poisson_sampling()` from the whole sample's `.prob` \tab as `rest` \cr +#' [design_weighted()], `"systematic"` \tab `pps = "brewer"` with the inclusion probabilities; with `strata`, `strata` from the strata columns and Brewer's within them \tab close for totals, less so for means \cr +#' [design_multistage()] with `size` \tab two stages, `ids` the `.cluster` numbers then the rows, `pps = "brewer"` with each cluster's stage-one probability and `m / N_i` at the second stage; each cluster taken with certainty a stratum of its own, whose rows are its units; with one sampled row from a selected cluster of several, one stage, `ids` the `.cluster` numbers and no `fpc` \tab close; identical in one stage \cr +#' [design_spread()] \tab as its first-order design: `ids = ~1`, or `pps = "brewer"` with `size`; with `strata`, `strata` from the strata columns and `fpc` each stratum's size, or Brewer's within them \tab **differ** \cr +#' [design_systematic()] with `n_starts` of 2 or more \tab `ids` a `.cluster` column numbering the replicates, `fpc` the `n_starts * interval` possible starts \tab identical \cr +#' [design_systematic()] \tab `ids = ~1` with `fpc` the rows the walk can reach \tab **differ** \cr +#' [design_stratified()] with `within` \tab `strata` from the strata columns, `fpc` each stratum's rows walked \tab **differ** \cr #' } #' -#' "Identical" means to floating point, and is checked by this package's tests -#' against `survey::svytotal()`, as are domain estimates against -#' `survey::svyby()` and degrees of freedom against `survey::degf()`. The -#' exceptions are real and worth knowing: +#' "Identical" means to floating point under `survey`'s default options, and +#' is checked by this package's tests against `survey::svytotal()`, as are +#' domain estimates against `survey::svyby()` and degrees of freedom against +#' `survey::degf()`. The exceptions are real and worth knowing: #' #' * **Systematic PPS.** Neither package has its joint probabilities. This one -#' uses Deville's approximation and `survey` uses Brewer's; the two are close -#' relatives and agree to a fraction of a percent. +#' uses Deville's approximation and `survey` uses Brewer's. In simulations +#' on frames of 100 to 300 rows with gamma and lognormal sizes, the +#' standard errors of totals usually agreed within 0.5 percent, and within +#' 3 percent in every sample. Those of means differed more, and more as the +#' sampling fraction grew: typically by under 2 percent at a fraction of a +#' tenth or a fifth, 2 to 4 percent at a third and 3 to 7 percent at a +#' half, where single samples differed by up to 12 percent. On a frame +#' whose units below certainty had probabilities from 0.05 to 0.95, with +#' about 17 of them in each sample, totals differed by about 1 percent +#' typically and by up to 9 percent, and means by 7 to 9 percent typically +#' and by up to 17 percent. The degrees of freedom agree. With `strata`, +#' each stratum is handed over the same way. +#' [design_multistage()] with `size` meets the same two approximations at +#' the first stage, while the variance within the selected clusters is the +#' same in both packages. Where the clusters below certainty had +#' stage-one probabilities of 0.12 to 0.41, the standard errors of totals +#' agreed within 0.3 percent over 200 samples. With a cluster at 0.93 among +#' them, `survey`'s came out 0.97 to 1.48 times this package's: Brewer's +#' approximation centres on the plain mean of the clusters' totals over +#' their probabilities, which that cluster pulls, where Deville's weights +#' each by `1 - pi`. #' * **Spread.** `survey` has no estimator for a spatially balanced sample, so #' it is told only the first-order design and computes a variance that -#' ignores the spreading. That errs conservative, often substantially. +#' ignores the spreading. Relative to the true variance that errs +#' conservative, often substantially. Relative to [ht_total()]'s local mean +#' approximation it goes either way. In simulations drawing 30 of 300 +#' points spread over a square, `survey`'s standard error was the larger in +#' every sample when `y` varied smoothly over the square, three times as +#' large at the median. When `y` had no spatial pattern it was the smaller +#' in 67 to 79 percent of samples, by 4 to 6 percent at the median, and +#' drawing 150 of the 300 it was the smaller in every sample, by 30 percent +#' at the median, because the local mean has no finite population +#' correction. #' * **Systematic.** `survey`, told only `ids = ~1`, computes the simple-random #' variance; [ht_total()] uses the successive-difference approximation, which -#' can see a trend along the sort order. Neither is design-unbiased, because -#' no such estimator exists for one systematic sample. +#' can see a trend along the sort order. Neither is design-unbiased, and at +#' a step of 2 rows or more no such estimator exists for one systematic +#' sample. Within strata, `survey` computes the stratified simple-random +#' variance and [ht_total()] adds up the strata's successive-difference +#' approximations. With `n_starts` of 2 or more the replicates are clusters +#' and the two agree. A replicated sample with a start that drew no rows, +#' which happens only when `n_starts * interval` exceeds the rows walked, is +#' refused, because `survey` would count one replicate fewer. #' -#' Certainty rows arrive in a stratum where `n == N`, so `survey`'s own finite -#' population correction zeroes them out, matching this package's treatment. +#' Units taken with certainty are in every sample and add nothing to the +#' variance: the rows above a [design_certainty()] threshold, strata and +#' intervals taken whole, the units [design_weighted()] and +#' [design_spread()] with `size` put at probability 1, and the clusters +#' [design_multistage()] and [design_cluster()] with `balanced = TRUE` take +#' whole when they select every cluster. Each group of them goes to `survey` +#' as one primary sampling unit in a stratum of its own, with an `fpc` of 1, +#' so `survey` gives them no variance and `survey::degf()` leaves them out +#' of the degrees of freedom, as [ht_total()] does. For the PPS designs this +#' also keeps them out of Brewer's approximation, which left among the other +#' units inflated `survey`'s standard error, by a factor of 23 on a frame +#' with four dominant units. Beside a `rest` of clusters, or of the +#' replicates of several systematic starts, the certainty rows form one more +#' primary sampling unit. In two stages, such a unit is taken whole at the +#' second stage too. #' -#' Two compositions have no single `survey` design and are refused rather than -#' approximated: [design_certainty()] over a cluster, multistage or Poisson -#' `rest`, where the certainty rows and the rest are different kinds of sampling -#' unit. [design_bootstrap()] is refused outright — it resamples the sample, so +#' A sample in which every row was taken with certainty, a census, goes to +#' `survey` as `ids = ~1` with `fpc` the number of rows. Both packages then +#' report a variance of 0, and `survey::degf()` gives `n - 1` where +#' [ht_total()] gives `Inf`. A sample with no rows is refused, and so is a +#' certainty sample whose `rest` drew none of the rows below the threshold, +#' whose total `survey` would report as exact where [ht_total()] reports no +#' variance. +#' +#' [design_certainty()] over a Poisson `rest` goes to `survey` as +#' `survey::poisson_sampling()` built from the whole sample's `.prob`, so the +#' certainty rows enter at probability 1 and add no variance. +#' [design_bootstrap()] is refused outright — it resamples the sample, so #' there is no finite population for `svydesign()` to represent. #' #' A stratum or interval with a single sampled row makes `survey` stop with #' "Stratum has only one PSU" unless `options(survey.lonely.psu)` says #' otherwise; [ht_total()] declines in the same situation. Draw at least two -#' per stratum. +#' per stratum. Under [design_multistage()] with `size`, a cluster taken with +#' certainty is a stratum of its sampled rows, so one that gives a single row +#' of several is such a stratum. +#' `options(survey.ultimate.cluster = TRUE)` makes `survey` leave out the +#' second stage of every two-stage design, so its standard errors then +#' differ from [ht_total()]'s. The agreement the table states holds under +#' the default, `FALSE`. #' -#' @param sample A data frame returned by [draw()] with `weights = TRUE`. -#' @param ... Passed to [survey::svydesign()]. Anything named here overrides -#' what the mapping above would have supplied, so `nest = TRUE` or a -#' replacement `fpc` is yours to set. +#' A sample weighted conditional on the clusters selected (see "Design +#' weights" in [draw()]) goes over in two stages too. `survey` works out +#' each cluster's second-stage sampling fraction from the rows sampled in +#' it, which is the take given that selection, so its estimate and standard +#' error are those of [ht_total()]. +#' +#' One sampled row from a selected cluster of several leaves the variation +#' within clusters unmeasured. [ht_total()] then falls back to the +#' delete-a-cluster jackknife, which is the ultimate-cluster variance with no +#' finite population correction, and `survey` gets that design: one stage, +#' `ids` the `.cluster` numbers and no `fpc`. So does a certainty design's +#' `rest` of balanced clusters, which [draw()] weights without regard to the +#' clusters selected, leaving no two-stage estimator. Under +#' [design_multistage()] with `size` the jackknife runs over the clusters +#' below certainty, and a cluster taken whole is held fixed in a stratum of +#' its own in both packages. +#' +#' @section Weights and design columns: +#' `survey` gets the sample's `.weight` column as its weights. Weights adjusted +#' after the draw, for nonresponse or by trimming, and written into `.weight` +#' are therefore estimated here, while [ht_total()] and [ht_mean()] keep to the +#' design probabilities in `.prob` and warn that `.weight` differs. `.prob` +#' itself must stay as [draw()] set it: it supplies the probabilities of the +#' PPS mappings above, and a sample whose `.prob` was changed is refused. +#' +#' Strata, intervals, cluster labels and population counts come from the copy +#' of the frame stored with the sample, not from the sample's own columns, and +#' are passed in the columns `.stratum`, `.cluster`, `.psu`, `.fpc`, `.fpc2` +#' and `.unit`. Renaming or recoding a design column in the sample after the draw +#' does not change the survey design. Those six names are reserved: a sample +#' with a column of one of them is refused rather than overwritten. Rename +#' the column in the sample, which leaves the design as drawn. +#' +#' @section Replicate weights and calibration: +#' `survey::as.svrepdesign()` turns the design returned here into one with +#' replicate weights. For samples from [design_simple()], +#' [design_stratified()] without `within`, [design_cluster()] without +#' `balanced`, [design_temporal()], [design_spatial()] and [design_spread()] +#' without `size`, its jackknife gives the standard errors of +#' `ht_total(variance = "jackknife")`. It stops with an error on the +#' designs handed over with Brewer's approximation or as Poisson sampling, +#' those of [design_weighted()], [design_spread()] and [design_multistage()] +#' with `size`, and [design_certainty()] over them, because `survey` builds +#' no replicates for its own probability-proportional-to-size and Poisson +#' designs. That is a +#' limitation of `survey`. For a systematic sample, alone or within strata, +#' it builds a jackknife that ignores the order of the walk. For +#' [design_cluster()] with `balanced = TRUE` and [design_multistage()] +#' without `size` it keeps the finite population correction of the first +#' stage, which `ht_total(variance = "jackknife")` leaves out, and warns +#' that it dropped the corrections after the first stage. Its variance is +#' then the jackknife's times `1 - n / N`, for `n` of the `N` clusters +#' selected. +#' +#' [replicate_weights()] builds replicate weights from the sample itself, +#' for [survey::svrepdesign()]: the jackknife of +#' `ht_total(variance = "jackknife")`, for balanced clusters and the designs +#' handed over with Brewer's approximation too, and successive differences +#' along the walk for systematic samples. Poisson sampling, which the +#' jackknife understates, has none, and `survey` estimates it from the +#' design returned here. +#' +#' [frame_totals()] gives the population totals that `survey::calibrate()` +#' and `survey::postStratify()` take, from the frame stored with the +#' sample, over the rows the design could reach. Calibration is left to +#' `survey`, on the design returned here. +#' +#' @param sample A data frame returned by [draw()] with `weights = TRUE`. See +#' "Weights and design columns". +#' @param ... Passed to [survey::svydesign()] by name, and an unnamed +#' argument is refused. Anything named here overrides what the mapping +#' above would have supplied, so `nest = TRUE` or a replacement `fpc` is +#' yours to set. #' #' @return A `survey.design` object. #' @@ -78,28 +211,42 @@ #' ht_total(s, "spend") #' #' # Now the analysis this package does not do -#' survey::svyquantile(~spend, des, quantiles = 0.5) +#' coef(summary(survey::svyglm(spend ~ site, des))) #' -#' @seealso [ht_total()], [ht_mean()] +#' @seealso [ht_total()], [ht_mean()], [replicate_weights()], +#' [frame_totals()] #' @export as_svydesign <- function(sample, ...) { require_suggested("survey", "handing a sample to the survey package") - if (!is.data.frame(sample) || is.null(attr(sample, "drawn_design"))) { - stop("`sample` must be a data frame from draw(..., weights = TRUE).", - call. = FALSE) - } - design <- attr(sample, "drawn_design") - pop <- attr(sample, "drawn_population") - if (design_type(design) == "bootstrap") { - stop("A bootstrap design has no survey equivalent: it resamples the ", - "sample rather than drawing a probability sample of a finite ", - "population.", call. = FALSE) - } - - dat <- as.data.frame(sample) - parts <- survey_parts(design, dat, pop, rows = attr(sample, "drawn_rows")) - dat$.fpc <- parts$fpc - fpc <- stats::as.formula("~.fpc") + overrides <- list(...) + check_named_dots(overrides) + # drawn_state() refuses a bootstrap design, which has no survey equivalent. + state <- drawn_state(sample) + design <- state$design + pop <- state$pop + + if (!nrow(sample)) { + stop_not_drawn(paste0( + "has no rows, so there is no design to hand to `survey`. For an empty ", + "draw from a design of random size, ht_total() gives the total, 0, ", + "without a variance.")) + } + check_survey_columns(sample) + + # `survey` keeps the data it is given by reference, so it gets its own copy. + # An in-place reorder of the sample afterwards would otherwise reach it. + dat <- snapshot_frame(as.data.frame(sample)) + parts <- survey_parts(design, dat, state$units, pop, rows = state$rows) + if (all(is_certain(dat$.prob))) parts <- census_parts(dat) + # Clusters come from the frame, so a cluster column renamed or recoded in + # the sample after the draw still gives `survey` the clusters that were + # drawn. + if (!is.null(parts$cluster)) dat$.cluster <- parts$cluster + fpc <- NULL + if (!is.null(parts$fpc)) { + dat$.fpc <- parts$fpc + fpc <- stats::as.formula("~.fpc") + } if (!is.null(parts$fpc2)) { # Two stages: clusters, then rows within them, each with its own # population count, so `survey` computes the full two-stage variance. @@ -108,83 +255,552 @@ as_svydesign <- function(sample, ...) { fpc <- stats::as.formula("~.fpc + .fpc2") } if (!is.null(parts$stratum)) dat$.stratum <- parts$stratum + ids <- parts$ids + if (any(parts$whole)) { + # Units taken with certainty share one primary sampling unit per stratum, + # with an `fpc` of one unit, so `survey` treats each group as taken whole. + # The other units keep their own ids, which are rows, or the clusters or + # replicates numbered in `.cluster`. + dat$.psu <- shared_psu(parts$stratum, parts$whole, parts$cluster) + ids <- if (is.null(parts$fpc2)) { + stats::as.formula("~.psu") + } else { + stats::as.formula("~.psu + .unit") + } + } + if (identical(parts$extra$pps, "poisson")) { + # Built from the whole sample, so rows a certainty design took above its + # threshold enter at probability 1 beside its Poisson `rest`. + parts$extra$pps <- survey::poisson_sampling(dat$.prob) + } args <- c(list(data = dat, weights = stats::as.formula("~.weight"), - ids = parts$ids, fpc = fpc), + ids = ids, fpc = fpc), parts$extra) if (!is.null(parts$stratum)) { args$strata <- stats::as.formula("~.stratum") } - do.call(survey::svydesign, utils::modifyList(args, list(...))) + do.call(survey::svydesign, utils::modifyList(args, overrides)) } -#' Strata, population counts and cluster ids for one design +#' Replicate weights for a sample #' -#' `survey` reconstructs a variance from the design's shape, not from the -#' inclusion probabilities, so each design has to be expressed in its own terms: -#' a stratified design as strata, a cluster design as ids, a temporal design as -#' strata over its intervals, and a certainty design as a stratum that was taken -#' whole -- where `n == N` makes `survey`'s own correction zero out, matching -#' this package's treatment of certainty rows. +#' Builds replicate weights from a drawn sample for [survey::svrepdesign()], +#' from the design the sample was drawn with. Each replicate is the +#' sample's `.weight` column times a factor, and the variance of a total +#' over the replicates is that of one of [ht_total()]'s estimators: +#' +#' * For most designs, the delete-a-unit jackknife of +#' `ht_total(variance = "jackknife")`. Each replicate deletes one primary +#' sampling unit, a cluster where the design has them and a row +#' otherwise, and reweights the other units of its stratum; strata are +#' the design's strata, the intervals of [design_temporal()] and the +#' strata of [design_weighted()] and [design_spread()]. `rscales` holds +#' `(m - 1) / m` for a stratum of `m` sampled units, times its finite +#' population correction. +#' Units taken with certainty keep their weight in every replicate, as +#' the jackknife holds them fixed. Where the default of [ht_total()] is +#' another estimator, such as Deville's approximation for +#' [design_weighted()] with `method = "systematic"`, the local mean +#' approximation for [design_spread()] or the two-stage variance for +#' [design_multistage()] and balanced [design_cluster()], the replicates +#' give the jackknife's variance, not that default. +#' * For [design_systematic()] with one start, and [design_stratified()] +#' with `within`, successive-difference replicates in the order the +#' design walked, whose variance is the successive-difference +#' approximation [ht_total()] gives by default, with its term for a +#' random sample size. Each pair of neighbours in the walk shares a row of +#' a Hadamard matrix, which raises one of the two and lowers the other. +#' The first and last rows of a walk are not paired with each other: the +#' circular form of successive-difference replication pairs them, which +#' adds the squared difference between the two ends of the sort order. On +#' a frame of 240 rows sorted on a size measure related to `y`, at an +#' interval of 8, that more than doubled the variance in each of the 8 +#' possible samples. +#' * For [design_systematic()] with `n_starts` of 2 or more, one replicate +#' per start, each deleting the rows its start drew. The variance is the +#' random group variance [ht_total()] gives by default. +#' +#' Rows above the threshold of [design_certainty()] keep their weight in +#' every replicate, and the replicates for the rows below it are those of +#' `rest`. A sample whose every row was taken with certainty gets one +#' replicate equal to its weights, and a variance of 0. +#' +#' Poisson sampling, alone or as the `rest` of [design_certainty()], is +#' refused: its sample size is random, and deleting rows from it +#' understates the variance. [as_svydesign()] hands it to `survey`, which +#' models it. A sample the jackknife declines, such as one with a single +#' unit in a stratum, is refused with the jackknife's reason. +#' +#' Every replicate is a multiple of `.weight`, so an adjustment written into +#' `.weight` after the draw, such as trimming, is carried into each one +#' unchanged. One that depends on which rows responded is more accurately +#' made again within each replicate. +#' +#' The matrix of weights takes `8 * n * R` bytes for `n` sampled rows and +#' `R` replicates, and building it about twice that. The jackknife has a +#' replicate for each sampled unit, and successive differences have the +#' first power of 2 above the number of pairs of neighbours in the walks, +#' counting one more for each walk of random size, so the size grows with +#' the square of the sample. Past about 1 GB, `replicate_weights()` +#' refuses: from about 11,200 rows for a jackknife over rows, and about +#' 8,200 for successive differences. Such a sample can still be estimated with +#' [ht_total()], or handed to `survey` with [as_svydesign()]. +#' +#' @param sample A data frame returned by [draw()] with `weights = TRUE`. +#' @param type The form of the jackknife. `"JKn"`, the default, deletes +#' units within strata and keeps each stratum's correction in `rscales`. +#' `"JK1"` deletes across the whole sample, with the correction in +#' `scale`, and is given only where the jackknife has one stratum; with +#' more, it would count the differences between strata as sampling +#' variance, and is refused. A systematic sample with one start, and +#' strata walked in order, get successive-difference replicates of type +#' `"other"` whichever is given. +#' +#' @return A numeric matrix with a row for each row of `sample`, in its +#' order, and a column for each replicate, holding replicate weights. +#' Its attributes `type`, `scale` and `rscales` are the arguments of the +#' same names of [survey::svrepdesign()], which with +#' `combined.weights = TRUE` computes the variance as +#' `scale * sum(rscales * (t_r - t)^2)` over the replicate estimates +#' `t_r`, with `t` their mean. For a total that mean is the sample's +#' estimate. +#' +#' @examplesIf requireNamespace("survey", quietly = TRUE) +#' pop <- data.frame( +#' id = 1:400, +#' site = rep(c("a", "b", "c", "d"), times = c(200, 100, 60, 40)), +#' spend = 10 + (1:400 * 37) %% 490 +#' ) +#' s <- draw(pop, design_stratified("site", n = 60), seed = 1, weights = TRUE) +#' +#' rw <- replicate_weights(s) +#' des <- survey::svrepdesign( +#' data = s, repweights = rw, weights = ~.weight, +#' type = attr(rw, "type"), scale = attr(rw, "scale"), +#' rscales = attr(rw, "rscales"), combined.weights = TRUE +#' ) +#' survey::svytotal(~spend, des) +#' +#' # The same standard error as the jackknife here +#' ht_total(s, "spend", variance = "jackknife") +#' +#' # A systematic sample on a sorted frame: the replicates follow the walk +#' sys <- draw(pop, design_systematic(interval = 8, order_by = "spend"), +#' seed = 1, weights = TRUE) +#' rw <- replicate_weights(sys) +#' des <- survey::svrepdesign( +#' data = sys, repweights = rw, weights = ~.weight, +#' type = attr(rw, "type"), scale = attr(rw, "scale"), +#' rscales = attr(rw, "rscales"), combined.weights = TRUE +#' ) +#' survey::SE(survey::svytotal(~spend, des)) +#' ht_total(sys, "spend")$se +#' +#' @seealso [as_svydesign()], [ht_total()] +#' @export +replicate_weights <- function(sample, type = c("JKn", "JK1")) { + type <- check_choice(type, c("JKn", "JK1"), "type") + # drawn_state() refuses a bootstrap design, which has no replicate weights. + state <- drawn_state(sample) + design <- state$design + if (!nrow(sample)) { + stop_not_drawn(paste0( + "has no rows, so there are no weights to replicate. For an empty draw ", + "from a design of random size, ht_total() gives the total, 0, without ", + "a variance.")) + } + if (is.null(state$pi_all)) check_prob(sample) + w <- check_replicate_base(sample) + reps <- tryCatch( + replicate_factors(design, state$units, state$pop, state$rows, + sample$.prob, type), + drawn_declined = function(e) list(note = conditionMessage(e))) + if (is.null(reps$factors)) { + stop("`sample` has no replicate weights. ", reps$note, call. = FALSE) + } + out <- w * reps$factors + attr(out, "type") <- reps$type + attr(out, "scale") <- reps$scale + attr(out, "rscales") <- reps$rscales + out +} + +#' The `.weight` column replicate weights are built on +#' +#' A replicate multiplies each row's weight, so every row needs a finite one. #' #' @noRd -refuse_nested <- function(prefix, what, why) { - if (nzchar(prefix)) { - stop("A certainty design over ", what, " has no single survey equivalent: ", - why, ". Estimate it with ht_total() or ht_mean() instead.", - call. = FALSE) +check_replicate_base <- function(sample) { + fix <- paste0(" Replicate weights multiply `.weight`; set it to ", + "1 / `.prob` for the design weights.") + w <- sample[[".weight"]] + if (is.null(w)) { + stop_not_drawn(paste0("has no `.weight` column, so there are no ", + "weights to replicate.", fix)) + } + if (!is.numeric(w)) { + stop_not_drawn(paste0("has ", a_class(w), " `.weight` column, where ", + "draw() puts a number.", fix)) + } + bad <- !is.finite(w) + if (any(bad)) { + stop_not_drawn(paste0("has `.weight` values that are missing or not ", + "finite in ", sum(bad), " row(s): ", + format_rows(which(bad)), ".", fix)) + } + w +} + +#' Population totals from the frame behind a sample +#' +#' Totals the columns of the frame a sample was drawn from, as stored with +#' the sample, in the form [survey::calibrate()] takes as `population`. A +#' design handed over by [as_svydesign()] can then be calibrated, or +#' post-stratified, to the frame without building the totals by hand. +#' +#' The totals run over the rows the design could have drawn, those with an +#' inclusion probability above 0 when the sample was drawn: the rows inside +#' the region of [design_spatial()] or the window of [design_temporal()], +#' those [design_reservoir()] read before `max_items`, and not the rows +#' `na_rm` dropped. Those are the rows the sample's weights stand for. For +#' a sample weighted conditional on the clusters selected (see "Design +#' weights" in [draw()]), the rows of the clusters left out count too, +#' since another selection could have drawn them. A missing value of a +#' variable in `formula` in any of those rows is refused, since its total +#' is unknown. +#' +#' A value of a column in `formula` that no sampled row has cannot be +#' calibrated to. `survey::calibrate()` stops on such a factor level, and +#' leaves out the total of such a character value with a warning that it +#' reordered the totals. Calibration itself is left to `survey`, which gives +#' the calibrated estimates their standard errors. +#' +#' @param sample A data frame returned by [draw()] with `weights = TRUE`. +#' @param formula A one-sided formula of frame columns, such as +#' `~ w + site`, as [survey::calibrate()] takes it. A name in it that is +#' not a column of the frame, such as `cutoff` in `~ I(w > cutoff)`, is +#' read from the environment of `formula`, as [stats::model.frame()] +#' reads it. A term with no frame column in it, as in `~ cutoff`, has no +#' value for each row and is refused, and so is one that gives a single +#' value for the frame, such as `I(sum(w))`. +#' @param table `FALSE`, the default, for the column totals of the model +#' matrix of `formula`, which [survey::calibrate()] takes. `TRUE` for the +#' count of rows in each cell of the variables in `formula`, as a table, +#' which [survey::postStratify()] and [survey::rake()] take. +#' +#' @return With `table = FALSE`, a named numeric vector: the totals of the +#' columns of `model.matrix(formula)` over the rows the design could +#' reach, `(Intercept)` being the number of those rows. With +#' `table = TRUE`, a table of counts of those rows from [stats::xtabs()]. +#' +#' @examplesIf requireNamespace("survey", quietly = TRUE) +#' pop <- data.frame( +#' id = 1:400, +#' site = rep(c("a", "b", "c", "d"), times = c(200, 100, 60, 40)), +#' size = 20 + (1:400 * 53) %% 300 +#' ) +#' pop$spend <- 3 * pop$size + (1:400 * 37) %% 90 +#' s <- draw(pop, design_simple(n = 60), seed = 1, weights = TRUE) +#' des <- as_svydesign(s) +#' +#' # Calibrate to the frame's row count and total size +#' totals <- frame_totals(s, ~size) +#' totals +#' cal <- survey::calibrate(des, ~size, population = totals) +#' survey::svytotal(~spend, cal) +#' ht_total(s, "spend") +#' +#' # Post-stratify on site +#' counts <- frame_totals(s, ~site, table = TRUE) +#' post <- survey::postStratify(des, ~site, counts) +#' survey::svytotal(~spend, post) +#' +#' @seealso [as_svydesign()] +#' @export +frame_totals <- function(sample, formula, table = FALSE) { + check_flag(table, "table") + if (!inherits(formula, "formula") || length(formula) != 2L) { + stop("`formula` must be a one-sided formula of frame columns, such as ", + "`~ w + site`, not ", + if (inherits(formula, "formula")) { + paste0("`", deparse1(formula), "`, which has a left-hand side") + } else { + a_class(formula) + }, ".", call. = FALSE) + } + vars <- setdiff(all.vars(formula), ".") + if (table && !length(vars)) { + stop("`formula` (`", deparse1(formula), "`) names no column, and ", + "`table = TRUE` counts rows by the columns it names. Name one, as ", + "in `~ site`.", call. = FALSE) + } + state <- drawn_state(sample) + pop <- state$pop + unknown <- setdiff(vars, names(pop)) + gone <- intersect(unknown, state$compact$dropped) + if (length(gone)) { + stop("`formula` uses ", quote_names(gone), ", which compact_sample() ", + "dropped from the frame stored with `sample`. Name ", + if (length(gone) > 1L) "them" else "it", " in `keep` when ", + "compacting, or rebuild the sample from the full frame with ", + "as_drawn().", call. = FALSE) + } + # A name that is not a column, such as `cutoff` in `I(w > cutoff)`, is + # read from where the formula was written, as model.frame() reads it. A + # function of that name is a misspelt column, not a value. + env <- environment(formula) + defined <- vapply(unknown, function(v) { + !is.null(env) && exists(v, envir = env) && + !is.function(get(v, envir = env)) + }, logical(1)) + unknown <- unknown[!defined] + if (length(unknown)) { + many <- length(unknown) > 1L + stop("`formula` uses ", quote_names(unknown), ", which ", + if (many) "are not columns" else "is not a column", + " of the frame `sample` was drawn from, or ", + if (many) "values" else "a value", " defined where `formula` was ", + "written. Use columns of that frame; the totals come from the copy ", + "stored with the sample.", call. = FALSE) + } + # A sample saved by drawn 0.2.0 records no probabilities, so they are + # worked out again from the design. + pi_all <- state$pi_all %||% exact_inclusion(state$design, pop) + reach <- which(reachable(pi_all)) + rows <- as.data.frame(pop)[reach, , drop = FALSE] + check_total_terms(formula, rows) + mf <- stats::model.frame(formula, rows, na.action = stats::na.pass) + gaps <- vapply(mf, function(x) anyNA(x), logical(1)) + if (any(gaps)) { + n_bad <- sum(!stats::complete.cases(mf)) + stop(quote_names(names(mf)[gaps]), if (sum(gaps) > 1L) " are" else " is", + " missing in ", n_bad, " of the ", length(reach), " frame rows the ", + "design could reach, so ", if (sum(gaps) > 1L) "their" else "its", + " population total is unknown. Leave ", + if (sum(gaps) > 1L) "them" else "it", " out of `formula`, or ", + "supply the population totals yourself.", call. = FALSE) + } + if (table) return(stats::xtabs(formula, data = rows)) + colSums(stats::model.matrix(formula, mf)) +} + +#' Refuse a `frame_totals()` formula without one value per frame row +#' +#' Each variable of `formula` has to be an expression of frame columns that +#' gives one value for each of the `rows` the design could reach. A value +#' from where the formula was written, alone, is not tied to the frame's +#' rows: model.frame() builds a frame of one row from a single value, so +#' `~ n` would total one row, and stops with its own message when such a +#' value sits next to a column. An expression such as `I(sum(w))` gives one +#' value for the frame and is refused the same way. +#' +#' @noRd +check_total_terms <- function(formula, rows) { + tt <- stats::terms(formula, data = rows) + vars <- as.list(attr(tt, "variables"))[-1L] + if (!length(vars)) return(invisible(NULL)) + shown <- vapply(vars, deparse1, character(1)) + lone <- !vapply(vars, function(v) any(all.vars(v) %in% names(rows)), + logical(1)) + if (any(lone)) { + many <- sum(lone) > 1L + stop("`formula` has ", quote_names(shown[lone]), ", which ", + if (many) "name" else "names", " no column of the frame `sample` ", + "was drawn from, so ", if (many) "they have" else "it has", + " no value for each frame row to total. Use a value from where ", + "`formula` was written inside an expression of frame columns, as ", + "in `I(w > cutoff)`.", call. = FALSE) + } + env <- environment(formula) %||% baseenv() + len <- vapply(vars, function(v) NROW(eval(v, rows, env)), numeric(1)) + off <- len != nrow(rows) + if (any(off)) { + many <- sum(off) > 1L + stop("`formula` has ", quote_names(shown[off]), ", which ", + if (many) "give" else "gives", " ", + paste(unique(len[off]), collapse = " or "), " value", + if (all(len[off] == 1)) "" else "s", " where the ", nrow(rows), + " frame rows the design could reach need one each. Write each ", + "term as an expression that gives one value per row, as ", + "`I(w > cutoff)` does.", call. = FALSE) } invisible(NULL) } +#' Backticked names for a message: "`a`", "`a` and `b`", "`a`, `b` and `c`" #' @noRd -survey_parts <- function(design, dat, pop, rows, prefix = "") { +quote_names <- function(x) { + shown <- paste0("`", x, "`") + if (length(shown) < 2L) return(shown) + paste(paste(shown[-length(shown)], collapse = ", "), "and", + shown[length(shown)]) +} + +#' Columns `as_svydesign()` writes the design into +#' +#' Each holds what the mapping needs: strata, cluster numbers, primary +#' sampling units, the two stages' population counts and the row ids of the +#' second stage. They are reserved in the sample handed over. +#' +#' @noRd +survey_columns <- function() { + c(".stratum", ".cluster", ".psu", ".fpc", ".fpc2", ".unit") +} + +#' Refuse a sample with a column `as_svydesign()` would overwrite +#' +#' Writing over a user column of one of these names would hand `survey` the +#' design's values in its place. A design column of such a name is in the +#' sample too, unless dropped, and is read from the frame stored with the +#' sample, so renaming it in the sample leaves the design unchanged. +#' +#' @noRd +check_survey_columns <- function(sample) { + clash <- intersect(survey_columns(), names(sample)) + if (!length(clash)) return(invisible(NULL)) + shown <- quote_names(clash) + it <- if (length(clash) == 1L) "it" else "them" + stop_not_drawn(paste0( + "already has ", shown, "; as_svydesign() would overwrite ", it, + ". Rename ", it, " in the sample; the design keeps its strata and ", + "clusters, which come from the copy of the frame stored with the ", + "sample.")) +} + +#' Refuse unnamed arguments to `as_svydesign()` +#' +#' `utils::modifyList()` drops unnamed elements, so `as_svydesign(s, ~cl)` +#' would hand `survey` the mapped design and ignore `~cl`. +#' +#' @noRd +check_named_dots <- function(dots) { + nm <- names(dots) %||% character(length(dots)) + bad <- which(is.na(nm) | !nzchar(nm)) + if (!length(bad)) return(invisible(NULL)) + where <- if (length(bad) > 1L) { + paste("Arguments", paste(bad[-length(bad)], collapse = ", "), "and", + bad[length(bad)], "of `...` have no name") + } else { + paste("Argument", bad, "of `...` has no name") + } + stop(where, ", and as_svydesign() passes `...` to survey::svydesign() by ", + "name. Name ", if (length(bad) > 1L) "them" else "it", ", as in ", + "`nest = TRUE` or `ids = ~cl`.", call. = FALSE) +} + +#' Strata, population counts and cluster ids for one design +#' +#' `survey` reconstructs a variance from the design's shape, not from the +#' inclusion probabilities, so each design has to be expressed in its own terms: +#' a stratified design as strata, a cluster design as ids, a temporal design as +#' strata over its intervals, and a certainty design as a stratum that was taken +#' whole. +#' +#' Units taken with certainty -- a certainty design's rows above the threshold, +#' strata, intervals and clusters taken whole, and the units a size-based +#' design puts at probability 1 -- are flagged in `whole`. Each stratum of +#' them becomes one primary sampling unit with an `fpc` of 1, which reads the +#' same as a count of units and as a probability. `survey` gives such a +#' stratum no variance, and `survey::degf()` no degree of freedom, as +#' `design_df()` does. +#' +#' `dat` is the sample handed to `survey`; `units` is the frame's copy of the +#' same rows, in the same order, and is where strata and intervals are read. +#' Clusters are read from the frame at `rows` and returned as integer codes in +#' `cluster`, for a column of their own in `dat`. +#' +#' @noRd +survey_parts <- function(design, dat, units, pop, rows, prefix = "") { one <- stats::as.formula("~1") - by_group <- function(cols) { - sizes <- table(group_key(pop, cols)) - lab <- as.character(group_key(dat, cols)) - list(stratum = paste0(prefix, lab), - fpc = as.integer(sizes[lab]), ids = one) + # `code` holds each frame row's group as a position in `labels`; the + # sampled units are frame rows `rows`. + by_group <- function(code, labels) { + sizes <- tabulate(code, length(labels)) + unit <- code[rows] + whole <- taken_whole(unit, dat$.prob) + fpc <- sizes[unit] + fpc[whole] <- 1L + list(stratum = paste0(prefix, labels[unit]), fpc = fpc, ids = one, + whole = whole) } switch(design_type(design), - stratified = by_group(design$strata), + stratified = { + if (walks_strata(design)) { + # Rows the walk drops for a missing `order_by` are in no stratum. + al <- stratum_allocation(design, pop) + return(by_group(al$code, unique_labels( + structure(integer(0), levels = al$labels, class = "factor")))) + } + key <- group_key(pop, design$strata) + by_group(as.integer(key), unique_labels(key)) + }, temporal = { - sizes <- table(temporal_bucket(design, pop)) - lab <- temporal_bucket(design, dat) - list(stratum = paste0(prefix, lab), fpc = as.integer(sizes[lab]), - ids = one) + bucket <- temporal_bucket(design, pop) + by_group(as.integer(bucket), levels(bucket)) }, weighted = { + if (!is.null(design$strata)) { + return(weighted_strata_parts(design, dat, pop, prefix, by_group)) + } if (design$method != "poisson") { # Neither package has the joint probabilities of systematic PPS. - # `survey`'s Brewer approximation and this package's Deville - # approximation are close relatives, and agree to a fraction of a - # percent. - return(list(stratum = NULL, fpc = dat$.prob, ids = one, - extra = list(pps = "brewer"))) + # `survey` uses Brewer's approximation and this package Deville's. + return(pps_parts(dat, prefix, "brewer")) } # Poisson sampling has a random size, so no finite population correction - # over a fixed n describes it. `survey` models it directly. - refuse_nested(prefix, "a Poisson `rest`", - "its sample size is random, which no stratum can express") - list(stratum = NULL, fpc = dat$.prob, ids = one, - extra = list(pps = survey::poisson_sampling(dat$.prob))) + # over a fixed n describes it. `survey` models it directly, with + # `survey::poisson_sampling()` over the whole sample's probabilities, + # which as_svydesign() builds. + pps_parts(dat, prefix, "poisson") }, cluster = , multistage = { - refuse_nested(prefix, "a cluster or multistage `rest`", - paste0("the certainty rows and the clusters are different ", - "kinds of sampling unit")) - labels <- pop[[design$clusters]] - n_clusters <- length(unique(labels[!is.na(labels)])) - if (design_type(design) == "cluster") { + # The ids are integer codes. `survey` makes a factor of the ids, which + # compares them as text and would merge two numbers that print alike. + if (!is.null(design$size)) { + return(pps_stage_parts(design, units, pop, dat$.prob, prefix)) + } + cl <- count_clusters(design, pop) + n_clusters <- cl$total + cluster <- cl$code[rows] + ids <- stats::as.formula("~.cluster") + if (design_type(design) == "cluster" && !design$balanced) { return(list(stratum = NULL, fpc = rep(n_clusters, nrow(dat)), - ids = stats::as.formula(paste0("~", design$clusters)))) + ids = ids, cluster = cluster)) + } + sizes <- tabulate(cl$code, n_clusters) + fixed <- design_type(design) == "multistage" && + multistage_fixed(design, sizes) + two_stage <- fixed || + weighted_on_selection(design, cluster, sizes, dat$.prob) + if (!two_stage || one_row_clusters(design, cluster, sizes, fixed)) { + # The two-stage estimator does not apply. One row of a cluster + # leaves the variation within it unmeasured, or a take that depends + # on the clusters selected is weighted without regard to them, as in + # a certainty design's `rest`. ht_total() falls back to the + # delete-a-cluster jackknife, which is the ultimate-cluster variance + # with no finite population correction, and `survey` computes it + # from the clusters alone. + return(whole_cluster_parts( + list(stratum = NULL, fpc = NULL, ids = ids, cluster = cluster), + dat$.prob, prefix)) } - sizes <- table(labels[!is.na(labels)]) - list(stratum = NULL, fpc = rep(n_clusters, nrow(dat)), - fpc2 = as.integer(sizes[as.character(dat[[design$clusters]])]), - ids = stats::as.formula(paste0("~", design$clusters, " + .unit"))) + # Two stages, also for balanced clusters, which subsample. `survey` + # takes each cluster's sampling fraction from the rows sampled in it, + # which is the take given the clusters selected, so its estimate is the + # one weighted conditional on them. + whole_cluster_parts( + list(stratum = NULL, fpc = rep(n_clusters, nrow(dat)), + fpc2 = sizes[cluster], + ids = stats::as.formula("~.cluster + .unit"), cluster = cluster), + dat$.prob, prefix) + }, + simple = { + # Rows use_reserves() found unavailable are outside the population. + list(stratum = NULL, + fpc = rep(length(available_rows(design, nrow(pop))), nrow(dat)), + ids = one) }, reservoir = { # Rows past `max_items` are never read, so the population is the rows @@ -192,16 +808,28 @@ survey_parts <- function(design, dat, pop, rows, prefix = "") { list(stratum = NULL, fpc = rep(reservoir_reach(design, nrow(pop)), nrow(dat)), ids = one) }, + systematic = { + if (replicated(design)) { + return(replicate_parts(design, dat, pop, rows)) + } + # Rows `na_rm` drops from the walk can never be drawn, so the + # population is the rows with a sort key, not the whole frame. + list(stratum = NULL, fpc = rep(reachable_rows(design, pop), nrow(dat)), + ids = one) + }, spread = { # Neither package has the pivotal method's joint probabilities. Handed # to `survey` as the unequal- or equal-probability draw it is at first # order, which does not credit the spreading and so errs conservative. fr <- spread_frame(design, pop) + if (!is.null(design$strata)) { + return(spread_strata_parts(design, dat, nrow(pop), fr, prefix, + by_group)) + } if (is.null(design$size)) { list(stratum = NULL, fpc = rep(length(fr$keep), nrow(dat)), ids = one) } else { - list(stratum = NULL, fpc = dat$.prob, ids = one, - extra = list(pps = "brewer")) + pps_parts(dat, prefix, "brewer") } }, spatial = { @@ -212,32 +840,52 @@ survey_parts <- function(design, dat, pop, rows, prefix = "") { }, certainty = { sp <- certainty_split(design, pop) - certain_pop <- sp$keep[sp$take] below <- sp$data[sp$rest, , drop = FALSE] # Membership of the certainty part, not `.prob == 1`: `rest` can put a # row at probability 1 of its own accord -- a dominant PPS unit, or an - # `n` equal to the rows below the threshold -- and filing those into the - # certainty stratum made `svydesign()` reject the whole design with - # "FPC implies >100% sampling in some strata". - is_certain <- rows %in% sp$keep[sp$take] + # `n` equal to the rows below the threshold -- and such rows belong to + # `rest`'s strata, which flag them in `whole` themselves. + above <- rows %in% sp$keep[sp$take] + if (!any(!above) && length(sp$rest)) { + stop_not_drawn(paste0( + "holds none of the ", rows_below(design, length(sp$rest)), + ", because `rest` drew none of them, and `survey` would report the ", + "total as exact. ht_total() and ht_mean() report no variance for ", + "such a sample; use a `rest` with a fixed sample size to estimate ", + "one.")) + } out <- list(stratum = character(nrow(dat)), fpc = numeric(nrow(dat)), - ids = one) - out$stratum[is_certain] <- paste0(prefix, "(certain)") - out$fpc[is_certain] <- length(certain_pop) - if (any(!is_certain)) { - rest <- survey_parts(design$rest, dat[!is_certain, , drop = FALSE], - below, rows = match(rows[!is_certain], - sp$keep[sp$rest]), + ids = one, whole = above) + out$stratum[above] <- paste0(prefix, "(certain)") + out$fpc[above] <- 1 + if (any(!above)) { + rest <- survey_parts(design$rest, dat[!above, , drop = FALSE], + units[!above, , drop = FALSE], below, + rows = match(rows[!above], sp$keep[sp$rest]), prefix = paste0(prefix, "(rest) ")) - out$stratum[!is_certain] <- rest$stratum %||% - paste0(prefix, "(rest)") - out$fpc[!is_certain] <- rest$fpc - if (!is.null(rest$extra$pps)) { - # A PPS `rest` states its fpc as probabilities, and `survey` needs - # the whole design in the same terms: certainty rows are probability 1. - out$fpc[is_certain] <- 1 - out$extra <- rest$extra + out$stratum[!above] <- rest$stratum %||% paste0(prefix, "(rest)") + # A `rest` of clusters with no finite population correction gets an + # infinite population, which `survey` reads as none. + out$fpc[!above] <- rest$fpc %||% Inf + out$whole[!above] <- rest$whole %||% FALSE + out$ids <- rest$ids + out$extra <- rest$extra + if (!is.null(rest$cluster)) { + # The clusters, or the replicates of several starts, are `rest`'s + # primary sampling units, and the certainty rows one more beside + # them. + out$cluster <- rep(NA_integer_, nrow(dat)) + out$cluster[!above] <- rest$cluster + } + if (!is.null(rest$fpc2)) { + # The certainty rows are one unit taken whole at both stages: all + # its rows, whether `survey` reads the second stage as counts or + # as probabilities. + counts <- any(c(rest$fpc, rest$fpc2) > 1) + out$fpc2 <- numeric(nrow(dat)) + out$fpc2[above] <- if (counts) sum(above) else 1 + out$fpc2[!above] <- rest$fpc2 } } out @@ -245,3 +893,230 @@ survey_parts <- function(design, dat, pop, rows, prefix = "") { list(stratum = NULL, fpc = rep(nrow(pop), nrow(dat)), ids = one) ) } + +#' A multistage sample with clusters selected in proportion to size +#' +#' Two stages, with Brewer's approximation at the first. Clusters below +#' certainty share the stratum `(pps)`, with their stage-one probabilities +#' as `fpc` and `m / N_i` at the second stage, so `survey` adds the +#' variance within each cluster divided by its probability, as +#' `pps_stage_variance()` does. A cluster taken with certainty is a stratum +#' of its own whose units are its sampled rows, with `m / N_i` at the first +#' stage and nothing left to sample at the second; one taken whole as well +#' is a single unit with an `fpc` of 1. `survey::degf()` then counts what +#' `design_df()` counts. +#' +#' One row from a selected cluster of several leaves the variation within +#' clusters unmeasured, and `ht_total()` falls back to the delete-a-cluster +#' jackknife over the clusters below certainty, with no finite population +#' correction. That is `survey`'s one-stage design of the clusters with no +#' `fpc`, which such a sample gets, with any cluster taken whole in a stratum +#' of its own. A cluster taken with certainty but not whole then has a single +#' unit, and both packages decline; it keeps the two stages, where `survey` +#' stops on it. `prob` holds the sampled rows' inclusion probabilities. +#' +#' @noRd +pps_stage_parts <- function(design, units, pop, prob, prefix = "") { + cu <- cluster_units(design, units, pop) + st <- cluster_stage(design, pop) + p1 <- st$pi1[cu$code] + N <- st$sizes[cu$code] + share <- st$m / N + certain <- is_certain(p1) + taken <- tabulate(cu$code, length(st$pi1))[cu$code] + if (any(taken < 2L & taken < N) && !any(certain & taken < N)) { + return(whole_cluster_parts( + list(stratum = NULL, fpc = NULL, ids = stats::as.formula("~.cluster"), + cluster = cu$psu), + prob, prefix)) + } + list(stratum = paste0(prefix, ifelse(certain, paste0("(certain) ", cu$code), + "(pps)")), + fpc = ifelse(certain, pmin(share, 1), p1), + fpc2 = ifelse(certain, 1, share), + ids = stats::as.formula("~.cluster + .unit"), cluster = cu$psu, + extra = list(pps = "brewer")) +} + +#' A systematic sample with several starts, as a sample of clusters +#' +#' The `m` starts are a simple random sample of the `m * interval` possible +#' ones, and each replicate is the cluster of rows its start takes. Handed +#' to `survey` as clusters numbered in `.cluster`, with that count of +#' possible starts as `fpc`, `survey`'s one-stage variance is the random +#' group variance of `replicate_variance()`. A replicate whose start fell +#' past the last row walked has no rows to pass, and `survey` would count +#' one replicate fewer, so such a sample is refused. +#' +#' @noRd +replicate_parts <- function(design, dat, pop, rows) { + m <- systematic_starts(design) + walk <- systematic_positions(design, pop) + cluster <- systematic_replicates(design, walk, rows) + got <- length(unique(cluster)) + # An interval of 1 takes every row, and a census needs no replicates. + if (got < m && !all(is_certain(dat$.prob))) { + stop("A systematic sample with an empty replicate has no `survey` ", + "equivalent: ", m - got, " of its ", m, " starts fell past the last ", + "of the ", sum(!is.na(walk)), " rows walked and drew none, and ", + "`survey` would count only the ", got, " with rows. Estimate it ", + "with ht_total() or ht_mean(), which count an empty replicate as a ", + "total of 0, or draw with `n_starts * interval` of at most the rows ", + "walked.", call. = FALSE) + } + list(stratum = NULL, fpc = rep(m * design$interval, nrow(dat)), + ids = stats::as.formula("~.cluster"), cluster = cluster) +} + +#' A spread design with strata, as stratified sampling or stratified PPS +#' +#' Each stratum is handed over as the draw it is at first order: without +#' `size`, a simple random sample of its rows, and with it, Brewer's +#' approximation over their probabilities, as `strata_pps_parts()` gives +#' it. `by_group` is the helper of `survey_parts()`, which reads the sampled +#' frame rows, and `n_pop` the number of rows in the frame. +#' +#' @noRd +spread_strata_parts <- function(design, dat, n_pop, fr, prefix, by_group) { + # Each frame row's stratum; rows the design drops count in none. + code <- rep(NA_integer_, n_pop) + code[fr$keep] <- fr$code + labels <- unique_labels(structure(integer(0), levels = fr$labels, + class = "factor")) + if (is.null(design$size)) return(by_group(code, labels)) + strata_pps_parts(code, labels, dat, prefix, by_group, "brewer") +} + +#' A weighted design with strata, as stratified PPS +#' +#' Systematic PPS goes to `survey` as Brewer's approximation within each +#' stratum, and Poisson sampling as `survey::poisson_sampling()` with the +#' strata, whose variance does not depend on them but whose degrees of +#' freedom count them, as `design_df()` does. +#' +#' @noRd +weighted_strata_parts <- function(design, dat, pop, prefix, by_group) { + pps <- if (design$method == "poisson") "poisson" else "brewer" + st <- weighted_setup(design, pop) + # Each frame row's stratum; rows the design drops count in none. + code <- rep(NA_integer_, nrow(pop)) + code[st$keep] <- st$code + labels <- unique_labels(structure(integer(0), levels = st$labels, + class = "factor")) + strata_pps_parts(code, labels, dat, prefix, by_group, pps) +} + +#' Strata sampled in proportion to size, with a stratum for certain units +#' +#' `code` gives each frame row's stratum as a position in `labels`. Rows +#' taken with certainty go in a stratum of their own, `(certain)`, as +#' `pps_parts()` puts them, so that `survey`'s approximation runs over the +#' other rows of each stratum. Every other row has its inclusion probability +#' as `fpc`, for `pps`. +#' +#' @noRd +strata_pps_parts <- function(code, labels, dat, prefix, by_group, pps) { + out <- by_group(code, labels) + certain <- is_certain(dat$.prob) + # A stratum of the frame could be called `(certain)` too. + cert <- paste0(prefix, "(certain)") + while (cert %in% paste0(prefix, labels)) cert <- paste0(cert, " ") + out$stratum[certain] <- cert + out$fpc <- ifelse(certain, 1, dat$.prob) + out$whole <- certain + out$extra <- list(pps = pps) + out +} + +#' Clusters taken whole, in a stratum of their own +#' +#' A cluster is taken whole when every one of its sampled rows is certain, +#' which needs every cluster selected and all of the cluster's rows drawn. +#' Such a cluster is in every sample and adds no variance, and `design_df()` +#' leaves it out of the degrees of freedom, as the jackknife holds it fixed. +#' `survey` would count it as one more primary sampling unit at the first +#' stage, and, in the one-stage form with no `fpc`, give it a share of the +#' variance between clusters. +#' +#' The clusters taken whole go in the stratum `(certain)` with an `fpc` of 1, +#' where `as_svydesign()` makes them one primary sampling unit, and the others +#' in the stratum `(clusters)`. In two stages that stratum's `fpc` is the +#' number of clusters left, all of them selected, and the shared unit is +#' taken whole at the second stage too: its `fpc2` is its number of rows. In +#' one stage, with no finite population correction, the other clusters get an +#' infinite population, which `survey` reads as none. `parts` is the mapping +#' without them, and `prob` the sampled rows' inclusion probabilities. +#' +#' @noRd +whole_cluster_parts <- function(parts, prob, prefix = "") { + whole <- taken_whole(parts$cluster, prob) + if (!any(whole) || all(whole)) return(parts) + parts$stratum <- paste0(prefix, ifelse(whole, "(certain)", "(clusters)")) + parts$whole <- whole + if (is.null(parts$fpc)) { + parts$fpc <- ifelse(whole, 1, Inf) + return(parts) + } + parts$fpc <- ifelse(whole, 1, length(unique(parts$cluster[!whole]))) + parts$fpc2[whole] <- sum(whole) + parts +} + +#' Which rows lie in a stratum taken whole +#' +#' Rows of a stratum or interval are drawn with one probability, so a stratum +#' is taken whole when every sampled row in it is certain. +#' +#' @noRd +taken_whole <- function(stratum, prob) { + certain <- is_certain(prob) + stratum %in% stratum[certain] & !(stratum %in% stratum[!certain]) +} + +#' A size-based design, with its certain units in a stratum of their own +#' +#' `survey`'s Brewer approximation and its Poisson variance read `fpc` as +#' probabilities. A unit at probability 1 left among the others still enters +#' Brewer's centring on the mean of `y / pi` and its `n / (n - 1)` scaling, +#' which put `survey`'s standard error at 23 times this package's on one frame +#' with four dominant units. In a stratum of their own, taken whole, they add +#' nothing and Brewer runs over the units below certainty. +#' +#' @noRd +pps_parts <- function(dat, prefix, pps) { + certain <- is_certain(dat$.prob) + list(stratum = if (any(certain)) { + paste0(prefix, ifelse(certain, "(certain)", "(pps)")) + }, + fpc = ifelse(certain, 1, dat$.prob), ids = stats::as.formula("~1"), + whole = certain, extra = list(pps = pps)) +} + +#' One primary sampling unit for each stratum of units taken with certainty +#' +#' Every other row keeps its unit in `unit`: its cluster's number, or the row +#' itself when `unit` is `NULL`. The shared units are numbered past the +#' others, so the ids are unique across strata and the units nest in their +#' strata without `nest = TRUE`. +#' +#' @noRd +shared_psu <- function(stratum, whole, unit = NULL) { + psu <- unit %||% seq_along(whole) + last <- max(0L, psu[!whole]) + psu[whole] <- last + match(stratum[whole], unique(stratum[whole])) + psu +} + +#' A sample whose every row was taken with certainty +#' +#' One stratum, every row its own unit, and `fpc` the number of rows, so that +#' `survey`'s finite population correction is 0. `svydesign()` reads an `fpc` +#' made only of 1s as neither counts nor probabilities, and stopped with +#' "subscript out of bounds" on the probabilities of 1 the PPS mappings gave +#' a census. +#' +#' @noRd +census_parts <- function(dat) { + n <- nrow(dat) + list(stratum = NULL, fpc = rep(n, n), ids = stats::as.formula("~1")) +} diff --git a/R/utils.R b/R/utils.R index 48e526c..9d1ff68 100644 --- a/R/utils.R +++ b/R/utils.R @@ -4,42 +4,198 @@ `%||%` <- function(x, y) if (is.null(x)) y else x +#' Is an inclusion probability 1? +#' +#' The one test for certainty. `n * w / sum(w)` for a unit that is certain in +#' exact arithmetic can come out a rounding error below 1, so a probability +#' within `1e-9` of 1 counts as 1. +#' +#' @noRd +is_certain <- function(p) { + p >= 1 - 1e-9 +} + +#' Signal a warning with a class of its own +#' +#' The class is `c(class, "drawn_warning", "warning", "condition")`, so a +#' caller can muffle or catch one kind of warning with +#' `withCallingHandlers()` or `tryCatch()` without matching on its text. +#' `class` is named `drawn_`. The warning carries no call, as the +#' package's errors do not. +#' +#' @noRd +warn_drawn <- function(message, class) { + cond <- structure(list(message = message, call = NULL), + class = c(class, "drawn_warning", "warning", "condition")) + warning(cond) +} + +#' Refuse a probability or variance that the design does not define +#' +#' The condition has class `c("drawn_declined", "error", "condition")` and no +#' call. Called directly, as from [joint_prob()], it is an ordinary error. +#' `ht_variance_dispatch()` catches this class and no other, so the estimator +#' declining falls back to the jackknife or reports no variance, while any +#' other error, from running out of memory to a bug, reaches the caller. +#' +#' @noRd +stop_declined <- function(message) { + cond <- structure(list(message = message, call = NULL), + class = c("drawn_declined", "error", "condition")) + stop(cond) +} + #' Evaluate an expression under a seed without disturbing the caller's RNG #' #' Saves `.Random.seed`, seeds, evaluates, then restores the previous state on #' exit. Calling [set.seed()] directly would permanently move the caller's #' random number stream. #' +#' The seed is applied with R's default generator, whatever the session has +#' selected, so a seed draws the same rows after `RNGkind("L'Ecuyer-CMRG")` +#' or under `sample.kind = "Rounding"`. The first element of `.Random.seed` +#' records the generator, so restoring it restores the caller's generator +#' too. With no `.Random.seed` to restore, the generator is set back with +#' RNGkind(), which seeds it afresh, and the `.Random.seed` that leaves is +#' removed, as the caller had none. RNGkind() warns when it sets the +#' "Rounding" sampler, and that warning is muffled, since the caller chose +#' that sampler and was warned then. +#' #' @noRd with_seed <- function(seed, code) { if (is.null(seed)) { return(force(code)) } - if (!is.numeric(seed) || length(seed) != 1L || is.na(seed) || - !is.finite(seed) || seed != trunc(seed)) { - stop("`seed` must be a single whole number, not ", format_bad(seed), ".", - call. = FALSE) - } + check_seed(seed) if (exists(".Random.seed", envir = globalenv(), inherits = FALSE)) { old <- get(".Random.seed", envir = globalenv(), inherits = FALSE) on.exit(assign(".Random.seed", old, envir = globalenv()), add = TRUE) } else { - on.exit(suppressWarnings(rm(".Random.seed", envir = globalenv())), - add = TRUE) + old_kind <- RNGkind() + on.exit({ + suppressWarnings(do.call(RNGkind, as.list(old_kind))) + suppressWarnings(rm(".Random.seed", envir = globalenv())) + }, add = TRUE) } - set.seed(seed) + kind <- seed_kind() + set.seed(seed, kind = kind[[1L]], normal.kind = kind[[2L]], + sample.kind = kind[[3L]]) force(code) } -#' Subset rows and reset row names +#' The generator a seed is applied with +#' +#' R's defaults since 3.6.0, so in a session left at the defaults a seed +#' draws what `set.seed(seed)` alone would. +#' +#' @noRd +seed_kind <- function() c("Mersenne-Twister", "Inversion", "Rejection") + +#' A seed set.seed() takes: one whole number in the integer range +#' +#' Past `.Machine$integer.max` set.seed() gives its own error after a +#' coercion warning, so the range is checked here, with the value. +#' +#' @noRd +check_seed <- function(seed) { + if (is.null(seed)) return(invisible(NULL)) + if (!is.numeric(seed) || length(seed) != 1L || is.na(seed) || + !is.finite(seed) || seed != trunc(seed)) { + stop("`seed` must be a single whole number, not ", + format_bad(seed, value = TRUE), ".", call. = FALSE) + } + if (abs(seed) > .Machine$integer.max) { + stop("`seed` must lie between -", .Machine$integer.max, " and ", + .Machine$integer.max, ", not ", format(seed, scientific = FALSE), + ". Use a smaller whole number.", call. = FALSE) + } + invisible(seed) +} + +#' Seconds since an arbitrary origin, for timing simulated draws +#' @noRd +elapsed_time <- function() proc.time()[["elapsed"]] + +#' Is R running interactively? +#' +#' A function of the package's own, so a test can stand in for it. +#' +#' @noRd +is_interactive <- function() interactive() + +#' A duration in seconds, in words +#' @noRd +format_duration <- function(seconds) { + unit <- if (seconds < 90) { + c(1, "second") + } else if (seconds < 90 * 60) { + c(60, "minute") + } else { + c(3600, "hour") + } + x <- signif(seconds / as.numeric(unit[[1L]]), 2) + paste0(format(x, big.mark = ",", scientific = FALSE), " ", unit[[2L]], + if (x != 1) "s") +} + +#' The number of characters in each string, for padding printed columns +#' +#' Text that is not valid in the session's encoding, such as Latin-1 read in +#' a UTF-8 session, has no character count, so its bytes are counted. +#' +#' @noRd +text_width <- function(x) { + w <- nchar(x, allowNA = TRUE) + bad <- is.na(w) + w[bad] <- nchar(x[bad], type = "bytes") + w +} + +#' Subset rows of a frame #' #' `drop = FALSE` matters: without it a one-column frame collapses to a vector. #' +#' Row names of the frame's own, such as the car names of `mtcars`, stay with +#' their rows. A row taken more than once gets names made unique by +#' make.unique(), "Mazda RX4" then "Mazda RX4.1", as `[` gives them. The +#' automatic row names 1, 2, ... are numbered afresh, since they name +#' positions rather than rows. `.row_names_info()` is negative for automatic +#' row names and positive for names of the frame's own. A tibble's `[` drops +#' row names, and that is kept. +#' +#' A plain data.frame is subset column by column. `[.data.frame` gives the +#' same result but also builds unique row names for the repeated rows, which +#' are then dropped. For the 5 million rows of a default bootstrap of a +#' 5,000-row frame with four columns, that took 8 seconds, and this takes 0.1. +#' Giving those rows unique names made from row names of the frame's own +#' takes about 8 seconds too, which only such a frame pays. +#' #' @noRd reindex <- function(data, idx, sort = FALSE) { if (sort) idx <- sort(idx) + own <- .row_names_info(data) > 0L + if (identical(class(data), "data.frame")) { + out <- lapply(unclass(data), function(col) { + if (length(dim(col)) == 2L) col[idx, , drop = FALSE] else col[idx] + }) + attributes(out) <- attributes(data) + attr(out, "row.names") <- if (own) { + kept_names(attr(data, "row.names"), idx) + } else { + .set_row_names(length(idx)) + } + return(out) + } out <- data[idx, , drop = FALSE] - rownames(out) <- NULL + if (!own) rownames(out) <- NULL + out +} + +#' Row names of the frame's own at `idx`, made unique when a row repeats +#' @noRd +kept_names <- function(names, idx) { + out <- names[idx] + if (anyDuplicated(idx)) out <- make.unique(as.character(out)) out } @@ -55,17 +211,6 @@ take_within <- function(idx_by_group, n, replace) { ) } -#' Sample `size` values from the elements of `x` -#' -#' `sample(x, size)` reinterprets a length-1 numeric `x` as `seq_len(x)`, so a -#' frame with a single numeric cluster id would sample integers that were never -#' in the data. -#' -#' @noRd -sample_values <- function(x, size, replace = FALSE) { - x[sample.int(length(x), size = size, replace = replace)] -} - #' An empty result that still has the input's schema #' #' `do.call(rbind, list())` is `NULL`, which would turn an empty window into a @@ -100,8 +245,7 @@ refuse_simulation <- function(design) { stop("A bootstrap is not a probability sample of a finite population, so ", "simulating it does not estimate an inclusion probability: every row ", "appears in some replicate, and the count converges to 1 for all of ", - "them.\nIf you want the expected number of times each row appears, ", - "that is n_replicates * n / nrow(data).", call. = FALSE) + "them.\n", bootstrap_counts(design), call. = FALSE) } invisible(design) } diff --git a/R/validate.R b/R/validate.R index 00b64eb..407c3b1 100644 --- a/R/validate.R +++ b/R/validate.R @@ -11,8 +11,8 @@ check_count <- function(x, arg, allow_zero = TRUE) { if (!is.numeric(x) || length(x) != 1L || is.na(x) || !is.finite(x) || x != trunc(x)) { - stop("`", arg, "` must be a single whole number, not ", format_bad(x), ".", - call. = FALSE) + stop("`", arg, "` must be a single whole number, not ", + format_bad(x, value = TRUE), ".", call. = FALSE) } if (x < 0 || (!allow_zero && x < 1)) { stop("`", arg, "` must be ", @@ -28,6 +28,17 @@ check_count <- function(x, arg, allow_zero = TRUE) { as.integer(x) } +#' `n` given as a plan from `plan_size()` +#' +#' A design's `n` can be the plan itself, whose `n` is the number of rows to +#' draw. Only `n` arguments take a plan, since `check_count()` also checks +#' counts such as `n_clusters` and `reserve`, where a plan means nothing. +#' +#' @noRd +plan_n <- function(n) { + if (inherits(n, "drawn_plan")) n[["n"]] else n +} + #' Validate a character vector of column names given at design time #' @noRd check_columns <- function(x, arg, max_len = Inf) { @@ -51,24 +62,244 @@ check_flag <- function(x, arg) { x } +#' Match an argument against its allowed values +#' +#' The user-facing stand-in for [base::match.arg()], whose message reads +#' "'arg' should be one of" without naming the argument. `x` left at its +#' default, the whole of `choices`, or `NULL` gives the first choice, and a +#' unique abbreviation is completed, as with `match.arg()`. Code that passes +#' `NULL` on for an argument it was not given gets the default. +#' +#' @noRd +check_choice <- function(x, choices, arg) { + if (is.null(x) || identical(x, choices)) return(choices[[1L]]) + i <- if (is.character(x) && length(x) == 1L && !is.na(x)) { + pmatch(x, choices) + } else { + NA_integer_ + } + if (is.na(i)) { + shown <- paste0("\"", choices, "\"") + stop("`", arg, "` must be one of ", + paste(utils::head(shown, -1L), collapse = ", "), " or ", + utils::tail(shown, 1L), ", not ", + if (is.character(x) && length(x) == 1L && !is.na(x)) { + paste0("\"", x, "\"") + } else { + format_bad(x) + }, ".", call. = FALSE) + } + choices[[i]] +} + +#' A plot title: one string, or NULL for the default +#' +#' `main` also takes an expression, a call such as `quote(alpha^2)` or a +#' name such as `quote(alpha)`, which `mtext()` draws as plotmath. `sub` is +#' added to the line under the title as text, so it takes a string only. An +#' expression vector must hold one title. `mtext()` stops partway through the +#' plot on an empty one, and draws the parts of a longer one over each other. +#' +#' @noRd +check_title <- function(x, arg) { + string <- is.character(x) && length(x) == 1L && !is.na(x) + math <- arg == "main" && is.language(x) && + (!is.expression(x) || length(x) == 1L) + if (is.null(x) || string || math) return(x) + if (arg == "main" && is.expression(x)) { + stop("`main` is a length-", length(x), " expression, ", + if (length(x) == 0L) { + "which has nothing to draw" + } else { + "whose parts would be drawn over each other" + }, + ". Pass one expression, such as `expression(alpha^2)`, or NULL ", + "for the default title.", call. = FALSE) + } + stop("`", arg, "` must be a single string", + if (arg == "main") ", an expression", " or NULL, not ", + format_bad(x), ".", call. = FALSE) +} + +#' The plot palette, with the user's entries in place of the defaults +#' +#' Checked before anything is drawn: an unknown name, a NULL or a value that +#' is not one colour would otherwise stop the plot halfway through, or be +#' ignored. A named character vector is read as a list. +#' #' @noRd -format_bad <- function(x) { - if (is.character(x)) { +check_palette <- function(palette) { + base <- drawn_pal() + if (is.null(palette)) return(base) + if (is.character(palette) && !is.null(names(palette))) { + palette <- as.list(palette) + } + if (!is.list(palette) || is.data.frame(palette)) { + stop("`palette` must be a named list of colours, such as ", + "list(accent = \"darkred\"), not ", + if (is.character(palette)) "an unnamed character vector" + else a_class(palette), ".", call. = FALSE) + } + nm <- names(palette) + unnamed <- if (is.null(nm)) { + seq_along(palette) + } else { + which(is.na(nm) | !nzchar(nm)) + } + if (length(unnamed)) { + stop("`palette` ", if (length(unnamed) == 1L) "entry " else "entries ", + paste(unnamed, collapse = ", "), " ", + if (length(unnamed) == 1L) "has" else "have", " no name. Name ", + "each entry after the colour it replaces, such as ", + "list(accent = \"darkred\").", call. = FALSE) + } + unknown <- setdiff(nm, names(base)) + if (length(unknown)) { + stop("`palette` has ", if (length(unknown) == 1L) "an entry" else + "entries", " ", quote_names(unknown), ", which the plot does not ", + "use. Name entries from ", quote_names(names(base)), ".", + call. = FALSE) + } + for (k in nm) { + v <- palette[[k]] + ok <- (is.character(v) || is.numeric(v)) && length(v) == 1L && + !is.na(v) && + !inherits(tryCatch(grDevices::col2rgb(v), error = identity), "error") + if (!ok) { + shown <- if (is.null(v)) { + "NULL" + } else if (is.character(v) && length(v) == 1L && !is.na(v)) { + paste0("\"", v, "\"") + } else { + format_bad(v) + } + stop("`palette$", k, "` must be one colour, a name from colors() or ", + "a code such as \"#1B6B52\", not ", shown, ".", call. = FALSE) + } + } + utils::modifyList(base, palette) +} + +#' Refuse `...` arguments to plot() that are not graphical parameters +#' +#' `...` reaches the call that sets up the panel. A name it does not take, +#' such as `simulate`, was dropped with a warning from deep inside base +#' graphics. Read by name only, so nothing in `...` is evaluated before the +#' refusal. +#' +#' @noRd +check_panel_args <- function(...) { + if (...length() == 0L) return(invisible(TRUE)) + nm <- ...names() + if (is.null(nm)) nm <- rep("", ...length()) + nm[is.na(nm)] <- "" + if (!all(nzchar(nm))) { + stop("Arguments in `...` must be named graphical parameters, such as ", + "`xlim = c(0, 10)`; ", sum(!nzchar(nm)), " ", + if (sum(!nzchar(nm)) == 1L) "has" else "have", " no name.", + call. = FALSE) + } + bad <- setdiff(nm, panel_parameters()) + if (length(bad)) { + bad <- paste0("`", bad, "`") + if (length(bad) > 1L) { + bad <- paste(paste(bad[-length(bad)], collapse = ", "), "or", + bad[length(bad)]) + } + stop("plot() for a design does not take ", bad, ". Its ", + "`...` takes graphical parameters for the panel, such as `xlim`, ", + "`ylim`, `asp` or `log`.", call. = FALSE) + } + invisible(TRUE) +} + +#' The names plot() of a design passes on to the panel +#' +#' The arguments of `plot.default()` that set up a panel, and the graphical +#' parameters of `par()` that can be set. `panel.first` and `panel.last` are +#' left out, since `...` is evaluated before the panel exists. +#' +#' @noRd +panel_parameters <- function() { + c("xlim", "ylim", "log", "xlab", "ylab", "ann", "axes", "frame.plot", + "asp", "xgap.axis", "ygap.axis", + "adj", "ask", "bg", "bty", "cex", "cex.axis", "cex.lab", "cex.main", + "cex.sub", "col", "col.axis", "col.lab", "col.main", "col.sub", "crt", + "err", "family", "fg", "fig", "fin", "font", "font.axis", "font.lab", + "font.main", "font.sub", "lab", "las", "lend", "lheight", "ljoin", + "lmitre", "lty", "lwd", "mai", "mar", "mex", "mfcol", "mfg", "mfrow", + "mgp", "mkh", "new", "oma", "omd", "omi", "pch", "pin", "plt", "ps", + "pty", "smo", "srt", "tck", "tcl", "usr", "xaxp", "xaxs", "xaxt", + "xlog", "xpd", "yaxp", "yaxs", "yaxt", "ylbias", "ylog") +} + +#' A value that failed a check, for the message +#' +#' Text is shown in backticks, as a name, by default. Where a number or a +#' flag was wanted, `value = TRUE` shows a single string as one, so a seed +#' given as "1" reads `the string "1"` rather than the `1` of a number. +#' +#' @noRd +format_bad <- function(x, value = FALSE) { + if (value && is.character(x) && length(x) == 1L && !is.na(x)) { + return(paste0("the string \"", x, "\"")) + } + if (is.character(x) && length(x)) { return(paste0("`", x, "`", collapse = ", ")) } + # A function, a name or an environment has no value to show, and is.na() + # warns on it. is.na() of a data frame gives one answer per cell. + if (is.data.frame(x) || !(is.null(x) || is.atomic(x) || is.list(x))) { + return(a_class(x)) + } if (length(x) != 1L) { return(paste0("a length-", length(x), " ", class(x)[1])) } if (is.na(x)) return("NA") - if (!is.numeric(x)) return(paste0("a ", class(x)[1])) + if (!is.numeric(x)) return(a_class(x)) paste0(x) } +#' A word with its indefinite article +#' +#' "an" before a vowel, so a class reads "an integer" and "a list". `shown` +#' is the word as the message shows it, such as in backticks. +#' +#' @noRd +with_article <- function(word, shown = word) { + paste(if (grepl("^[aeiouAEIOU]", word)) "an" else "a", shown) +} + +#' The class of `x`, with its article, for messages +#' @noRd +a_class <- function(x) with_article(class(x)[1]) + +#' Require a design, and say so when it and the data are swapped +#' +#' `data |> draw(design)` written the other way round, `design |> draw(data)`, +#' puts the design where the data go. Returns the design with the fields +#' added since drawn 0.2.0 filled in by legacy_design(), so a design saved +#' with saveRDS() then draws as it did; callers use the value returned. +#' +#' @noRd +check_design <- function(design, data, fun) { + if (is_design(data) && !is_design(design)) { + stop("`data` is a sampling design and `design` is ", a_class(design), + ", so the two look swapped. Call ", fun, "(data, design), with the ", + "data first.", call. = FALSE) + } + if (!is_design(design)) { + stop("`design` must come from one of the design_*() constructors, not ", + a_class(design), ". See ?designs.", call. = FALSE) + } + invisible(legacy_design(design)) +} + #' Validate a data frame and, optionally, that it holds the given columns #' @noRd validate_data <- function(data, required_columns = NULL, arg = "data") { if (!is.data.frame(data)) { - stop("`", arg, "` must be a data frame, not a ", class(data)[1], ".", + stop("`", arg, "` must be a data frame, not ", a_class(data), ".", call. = FALSE) } if (nrow(data) == 0L) { @@ -113,7 +344,7 @@ drop_na_rows <- function(data, bad, na_rm, what) { stop(sum(bad), " row(s) have ", what, ". Set na_rm = TRUE to drop them.", call. = FALSE) } - out <- data[!bad, , drop = FALSE] + out <- reindex(data, which(!bad)) if (nrow(out) == 0L) { stop("Every row has ", what, ".", call. = FALSE) } @@ -164,18 +395,185 @@ check_na_policy <- function(bad, na_rm, what) { invisible(bad) } -#' A grouping key that cannot collide +#' A grouping key built from integer codes #' -#' `interaction()` joins levels with `.`, so `("a.b", "c")` and `("a", "b.c")` -#' land in the same level and two distinct strata are silently merged -- -#' allocation, inclusion probabilities and the `min_per_stratum` guarantee all -#' computed over the wrong groups. A separator that cannot appear in a printed -#' value avoids it; `group_label()` puts a readable one back for display. +#' Each column is coded on its own: a factor by its levels, anything else by +#' its distinct values in byte order (`method = "radix"`), which is the same +#' in every locale. The tuples of codes that occur are numbered in +#' lexicographic order, first column slowest. The work grows with the number +#' of rows, however many combinations the columns' levels could form, and no +#' value can make two tuples share a key. A row with a missing value in any +#' column gets `NA`. +#' +#' The levels are the values joined by a carriage return, which +#' `group_label()` shows as ` . `. When that would give two tuples the same +#' level, as a value holding a carriage return can, the levels are the code +#' tuples instead. The codes depend on the data keyed, so keys that are +#' compared across two frames come from `group_key2()`. #' #' @noRd group_key <- function(data, cols) { - interaction(data[cols], drop = TRUE, lex.order = TRUE, sep = "\r") + key_from_columns(lapply(cols, function(col) data[[col]])) +} + +#' Keys for two frames on one set of codes +#' +#' A group has the same code in `x` and in `table`, whatever else either +#' holds, so the two can be compared by position. +#' +#' @noRd +group_key2 <- function(x, table, cols) { + n_x <- nrow(x) + key <- key_from_columns(lapply(cols, function(col) { + stack_values(x[[col]], table[[col]]) + })) + list(x = key[seq_len(n_x)], table = key[n_x + seq_len(nrow(table))]) +} + +#' @noRd +key_from_columns <- function(columns) { + coded <- lapply(columns, column_codes) + codes <- lapply(coded, `[[`, "code") + n <- length(codes[[1L]]) + ok <- which(!Reduce(`|`, lapply(codes, is.na))) + id <- rep(NA_integer_, n) + sub <- lapply(codes, `[`, ok) + o <- do.call(order, c(unname(sub), list(method = "radix"))) + sorted <- lapply(sub, `[`, o) + m <- length(o) + starts <- if (m) { + c(TRUE, Reduce(`|`, lapply(sorted, function(s) s[-1L] != s[-m]))) + } else { + logical(0) + } + id[ok[o]] <- cumsum(starts) + tuples <- lapply(sorted, `[`, which(starts)) + lev <- do.call(paste, c(Map(function(cc, tt) cc$labels[tt], coded, tuples), + sep = "\r")) + if (anyDuplicated(lev)) { + lev <- do.call(paste, c(unname(tuples), sep = "\r")) + } + structure(id, levels = as.character(lev), class = "factor") +} + +#' Integer codes and labels for one key column +#' +#' Classed vectors such as dates are coded on their underlying values, since +#' `match()` would compare them as text. A double whose text repeats another's +#' (`0.3` and `0.1 + 0.2`) is labelled with all its digits. +#' +#' @noRd +column_codes <- function(x) { + if (is.factor(x)) { + return(list(code = as.integer(x), labels = levels(x))) + } + v <- key_text(if (is.object(x) && is.atomic(x)) unclass(x) else x) + u <- sort(unique(v), method = sort_method(v)) + code <- match(v, u) + labels <- as.character(x[match(u, v)]) + if (is.double(v) && anyDuplicated(labels)) labels <- sprintf("%.17g", u) + list(code = code, labels = labels) +} + +#' Order a key column the same way in every locale +#' +#' `method = "radix"` sorts text by byte, as the C locale does, where the +#' default method follows the session's collation. It does not take complex or +#' raw vectors, which have no collation to follow. +#' +#' @noRd +key_order <- function(x) order(key_text(x), method = sort_method(x)) + +#' The distinct values of a key column in key order +#' +#' The values themselves, with their encodings, so they can be matched back +#' to the column. +#' +#' @noRd +key_values <- function(x) { + u <- unique(x[!is.na(x)]) + u[key_order(u)] } +#' Text that a radix sort takes, with the same bytes +#' +#' `method = "radix"` refuses a non-ASCII string of unknown encoding, which +#' is what `read.csv()`, `readLines()` and `data.table::fread()` give unless +#' told the file's encoding. In the copy returned, such a string is marked +#' UTF-8 when its bytes are valid UTF-8 and "bytes" otherwise. Its bytes are +#' unchanged, so text sorts byte by byte, in the same order in a UTF-8 +#' session as in the C locale. `enc2utf8()` is not used because in the C +#' locale it turns each non-ASCII byte into a `` escape, which sorts +#' differently. In the copy, an unmarked string and a UTF-8 string with the +#' same bytes are one value in any session. Callers take labels from the +#' original values. +#' #' @noRd -group_label <- function(x) gsub("\r", " . ", as.character(x), fixed = TRUE) +key_text <- function(x) { + if (!is.character(x)) return(x) + odd <- which(Encoding(x) == "unknown" & + grepl("[^\001-\177]", x, useBytes = TRUE)) + if (length(odd)) { + v <- x[odd] + Encoding(v) <- ifelse(validUTF8(v), "UTF-8", "bytes") + x[odd] <- v + } + x +} + +#' @noRd +sort_method <- function(x) { + if (is.factor(x) || + typeof(x) %in% c("logical", "integer", "double", "character")) { + "radix" + } else { + "auto" + } +} + +#' One vector holding the values of two key columns +#' +#' Factors keep their level order. Plain vectors combine as `c()` combines +#' them, so an integer column matches a double one. Other columns of different +#' kinds are compared as text. +#' +#' @noRd +stack_values <- function(a, b) { + if (is.factor(a) && is.factor(b)) { + return(factor(c(as.character(a), as.character(b)), + levels = union(levels(a), levels(b)))) + } + plain <- !is.object(a) && !is.object(b) + if (!is.factor(a) && !is.factor(b) && + (plain || identical(class(a), class(b)))) { + return(c(a, b)) + } + c(as.character(a), as.character(b)) +} + +#' A key's levels for display +#' +#' Columns are separated by ` . ` and an empty value is shown as `(blank)`. +#' Two groups can share a display label; `unique_labels()` gives labels that +#' cannot. Both patterns are ASCII, so they are matched by byte. Text that is +#' not valid in the session's encoding, such as Latin-1 read in a UTF-8 +#' session, keeps its bytes and its encoding mark. +#' +#' @noRd +group_label <- function(x) { + x <- gsub("(? 0) { + jk$note <- paste0(jk$note, jackknife_inflation(design, pop, ctx)) } - }, error = function(e) { - reason <<- conditionMessage(e) - NULL - }) - if (!is.null(got)) return(got) + return(jk) + } + + # A negative Sen-Yates-Grundy estimate, a declining estimator and an + # overflow are failures rather than variances. Each gets a reason instead + # of a number that sqrt() and deff() would then have to guess about. + a <- tryCatch(ht_variance(design, pop, rows, z, pi_i, domain, ctx), + drawn_declined = function(e) { + list(variance = NA_real_, note = conditionMessage(e)) + }) + a$method <- a$method %||% "analytic" + reason <- if (is.na(a$variance) && !is.nan(a$variance)) { + a$note %||% "The design's own estimator returned no figure." + } else if (!is.finite(a$variance)) { + overflow_note() + } else if (a$variance < 0) { + paste0("The Sen-Yates-Grundy estimator returned a negative variance (", + signif(a$variance, 3), "), which it can do on an unlucky sample. ", + "There is no analytic figure to report.") + } + if (is.null(reason)) return(a) if (variance == "analytic") { return(list(variance = NA_real_, method = "none", note = reason)) } - jk <- jackknife_variance(design, sample, pop, z, pi_i) - first <- sub("\n.*", "", reason) + jk <- jk_decline %||% + jackknife_variance(design, units, pop, z, pi_i, domain, ctx) + first <- sub("\n.*", "", reason, useBytes = TRUE) if (is.na(jk$variance)) { # The jackknife declined too. Say so, and keep its reason rather than # claiming a fallback that did not happen. return(list(variance = NA_real_, method = "none", note = paste0("No variance is available for this sample. ", - first, " ", jk$note))) + first, + if (!identical(jk$note, first)) { + paste0(" ", jk$note) + }))) } jk$note <- paste0("The design's own estimator declined, so the jackknife ", "was used instead. ", first, " ", jk$note) jk } -#' Degrees of freedom for a design's confidence interval +# ---- variance context ------------------------------------------------------- + +#' A store for what the variance estimators read from the frame #' -#' Primary sampling units minus strata, the usual rule (Korn and Graubard -#' 1999) and the one `survey::degf()` applies, so intervals agree across the two -#' packages. +#' The stratum allocation, interval and cluster codes, group sizes, the +#' systematic walk, the certainty split, the spread neighbours, the +#' jackknife's strata and the joint probabilities depend on the design, the +#' frame and the sampled rows, and not on the variable being totalled. +#' `estimate_by()` runs an estimator once per domain, and each run worked all +#' of it out again from the whole frame: 200 domains of a stratified sample +#' from 100,000 rows took 3 seconds, nearly all of it rebuilding the strata. +#' One context is made per call and handed to every run, and each estimator +#' stores a piece there the first time it needs it, with `from_context()`. +#' +#' A context holds the pieces for one design, frame and set of sampled rows, +#' with the same inclusion probabilities. A certainty design keeps the context +#' of its `rest`, over the rows below the threshold, inside its own. #' #' @noRd -design_df <- function(design, sample, pop, rows) { - n <- nrow(sample) - out <- switch(design_type(design), - stratified = n - length(unique(group_key(sample, design$strata))), - temporal = n - length(unique(temporal_bucket(design, sample))), - cluster = , - multistage = length(unique(sample[[design$clusters]])) - 1, - certainty = { - sp <- certainty_split(design, pop) - free <- !(rows %in% sp$keep[sp$take]) - if (!any(free)) { - Inf - } else { - design_df(design$rest, sample[free, , drop = FALSE], - sp$data[sp$rest, , drop = FALSE], - match(rows[free], sp$keep[sp$rest])) - } - }, - n - 1 - ) - max(out, 0) +variance_context <- function() new.env(parent = emptyenv()) + +#' A piece of a variance context, worked out on first use +#' +#' `value` is evaluated only when `ctx` does not hold `name` yet. With no +#' context it is evaluated every time, so an estimator called without one +#' works out the piece itself. +#' +#' @noRd +from_context <- function(ctx, name, value) { + if (is.null(ctx)) return(value) + if (!exists(name, envir = ctx, inherits = FALSE)) { + assign(name, value, envir = ctx) + } + get(name, envir = ctx, inherits = FALSE) } +#' The context of a design nested in another, such as a certainty `rest` #' @noRd -ht_variance <- function(design, data, rows, y, pi_i) UseMethod("ht_variance") +sub_context <- function(ctx, name) { + if (is.null(ctx)) return(NULL) + from_context(ctx, name, variance_context()) +} -#' Sen-Yates-Grundy, for fixed-size designs with closed-form joint -#' probabilities +#' Decline the variance of a Hajek mean or a ratio that rests on one +#' sampling unit +#' +#' The linearised residual of a ratio, `(y - mean) / N_hat` over the domain +#' for a Hajek mean and `(y - R x) / X_hat` for a ratio of `y` to `x`, sums +#' to zero over the domain, weighted by `1 / pi`, and so inside any primary +#' sampling unit that holds the whole domain. +#' Every variance estimator then returns 0, or a rounding error away from it, +#' however much `y` varies. A domain of one sampled row, a domain inside one +#' sampled cluster and a Poisson sample of one row all reported a zero-width +#' interval. `survey` gives the same 0. +#' +#' Units are counted over the sampled rows in `member` as `sample_units()` +#' gives them: clusters or rows, with the units taken with certainty counted +#' together as one. The rows of a cluster that stage one was certain to take +#' are units of their own, since that cluster's rows were drawn at random. +#' The jackknife holds certain units fixed and every other estimator gives +#' them no variance, so a domain whose sampled rows are all certain gets a +#' variance of 0 however many there are. +#' The mean is exact, and a variance of 0 right, only when every unit of the +#' domain that the design can reach was taken with certainty. That is read +#' from the draw-time probabilities over `frame`, which marks the domain's +#' frame rows as `domain_frame()` does: `TRUE` for the whole sample, and `NA` +#' for a row, or for the whole frame, that the frame cannot place. `label` +#' names the domain in the note, `subject` replaces the opening "The domain +#' `label`" for a domain with no label, and `psu` takes `sample_units()` +#' worked out once for many domains. `estimate` names what is estimated, as +#' in "A Hajek mean's linearised residuals". Returns the decline, or `NULL` +#' when the variance can go ahead. +#' +#' With `jackknife = TRUE`, `psu` holds the units of `jackknife_units()`, +#' and the note speaks of the jackknife alone, since the analytic estimator +#' counts other units. +#' #' @noRd -ht_variance.default <- function(design, data, rows, y, pi_i) { - pij <- joint_inclusion(design, data, rows) - if (length(rows) < 2L) { - return(list(variance = NA_real_, - note = "A variance needs at least two sampled rows.")) +ratio_decline <- function(parts, member, frame = TRUE, label = NULL, + psu = sample_units(parts$design, parts$units, + parts$pop, parts$rows, + parts$pi), + subject = if (!is.null(label)) { + paste0("The domain `", label, "`") + }, estimate = "Hajek mean", jackknife = FALSE) { + u <- psu[member] + if (length(unique(u)) >= 2L) return(NULL) + pi_all <- frame_pi(parts) + if (certain_domain(parts, frame, pi_all)) return(NULL) + if (length(u) && all(u == 0L)) { + return(list(variance = NA_real_, method = "none", + note = certain_only_note(subject, parts, frame, pi_all))) } - syg_variance(y, pi_i, pij) + # The jackknife deletes whole clusters even where the analytic estimator + # takes the rows of a census of clusters as its units. + unit <- unit_noun(parts$design, if (!jackknife) parts$pop) + core <- paste0("A ", estimate, "'s linearised residuals sum to zero over ", + "it, so ", + if (jackknife) { + paste0("the jackknife, which deletes whole ", unit, "s,") + } else { + "every variance estimator" + }, + " would give a standard error of about 0, whatever the ", + "spread of `y`.") + note <- if (is.null(subject)) { + paste0("The sample has one ", unit, ". ", core, " A standard error needs ", + "at least two.") + } else { + paste0(subject, " has ", + if (unit == "row") "one sampled row" else + paste0("sampled rows in one ", unit, " only"), ". ", core, + if (unit == "row") { + " A standard error needs at least two sampled rows in the domain." + } else { + paste0(" A standard error needs the domain's sampled rows to ", + "span at least two ", unit, "s.") + }) + } + list(variance = NA_real_, method = "none", note = note) } +#' The declines of a linearised estimate, for any estimator and for the +#' jackknife alone +#' +#' `ratio_decline()` over `psu`, the units of `sample_units()`, and over +#' `jk_psu`, those of `jackknife_units()`, which differ only where stage one +#' of a cluster design takes every cluster. `member`, `frame`, `label`, +#' `subject` and `estimate` are as `ratio_decline()` takes them. Returns a +#' list with `any`, the decline given in place of every variance, and +#' `jackknife`, the decline given in place of a jackknife variance only, as +#' `ht_variance_dispatch()` takes it. Each is `NULL` when the variance can +#' go ahead. With `variance = "jackknife"` only the jackknife's units count. +#' #' @noRd -syg_variance <- function(y, pi_i, pij) { - yk <- y / pi_i - d <- outer(yk, yk, "-")^2 - num <- outer(pi_i, pi_i) - pij - w <- num / pij - w[!is.finite(w)] <- 0 # a zero joint probability contributes nothing - diag(w) <- 0 - list(variance = 0.5 * sum(w * d), note = NULL) +linear_declines <- function(parts, member, variance, frame = TRUE, + label = NULL, + subject = if (!is.null(label)) { + paste0("The domain `", label, "`") + }, estimate = "Hajek mean", + psu = sample_units(parts$design, parts$units, + parts$pop, parts$rows, + parts$pi), + jk_psu = jackknife_units(parts, psu, variance)) { + if (variance == "none") return(list()) + jk <- function() { + if (!is.null(jk_psu)) { + ratio_decline(parts, member, frame, label, jk_psu, subject, estimate, + jackknife = TRUE) + } + } + if (variance == "jackknife" && !is.null(jk_psu)) return(list(any = jk())) + every <- ratio_decline(parts, member, frame, label, psu, subject, estimate) + list(any = every, jackknife = if (is.null(every)) jk()) } -#' Refuse a stratified variance with a stratum that holds one sampled row +#' Each sampled row's unit as the jackknife deletes it, where that differs +#' from `psu` #' -#' Sen-Yates-Grundy sums over pairs, and a stratum with one sampled row has no -#' within-stratum pair: its contribution is silently zero. With one row in -#' every stratum the standard error came out as exactly 0 against a true -#' figure in the hundreds. `survey` fails in the same situation unless told -#' otherwise (`options(survey.lonely.psu)`); declining here keeps the two in -#' step and says what to change. +#' A cluster design whose stage one takes every cluster has the sampled rows +#' as the units of its analytic estimator, as `clusters_all_taken()` sets +#' out, but the jackknife still deletes whole clusters. `NULL` when +#' `variance` never runs the jackknife, or when its units are those of +#' `psu`, from `sample_units()`. #' -#' Strata taken whole (`n_h == N_h`) are not lonely: they contribute no -#' variance because they have none. +#' @noRd +jackknife_units <- function(parts, psu, variance) { + if (!variance %in% c("auto", "jackknife")) return(NULL) + jk <- sample_units(parts$design, parts$units, parts$pop, parts$rows, + parts$pi, jackknife = TRUE) + if (identical(jk, psu)) NULL else jk +} + +#' Why a domain whose sampled rows are all certain gets no variance +#' +#' Every estimator holds those rows fixed, so each gives 0, while the mean +#' still changes with how many of the domain's other rows a sample takes. +#' `subject` is as `ratio_decline()` takes it, `NULL` for the whole sample. +#' The note says the design could have drawn other rows of the domain only +#' when the frame's probabilities `pi_all`, from `frame_pi()`, show a row +#' below certainty that `frame` places in the domain. #' #' @noRd -lonely_note <- function(group, rows, noun, fix) { - # `noun` is c(singular, plural) - keep <- !is.na(group) - N_h <- table(group[keep]) - n_h <- table(group[rows][!is.na(group[rows])]) - lonely <- names(n_h)[n_h == 1L & N_h[names(n_h)] > 1L] - if (!length(lonely)) return(NULL) - shown <- group_label(utils::head(lonely, 5L)) - many <- length(lonely) > 1L - paste0(if (many) paste(length(lonely), noun[2]) else paste("The", noun[1]), - " ", paste0("`", shown, "`", collapse = ", "), - if (length(lonely) > 5L) ", ..." else "", - " ", if (many) "each have" else "has", - " a single sampled row, so the variation within ", - if (many) "them" else "it", - " cannot be measured and leaving it out would understate the standard ", - "error. ", fix) +certain_only_note <- function(subject, parts, frame, + pi_all = frame_pi(parts)) { + whole <- is.null(subject) + known <- could_draw_others(pi_all, frame) + paste0( + if (whole) "Every sampled row was taken with certainty" else + paste0(subject, " has sampled rows taken with certainty only"), + if (known) { + paste0(", and the design could have drawn other rows", + if (!whole) " of it", " in a different sample") + } else { + paste0(", and the frame does not show whether the design could have ", + "drawn others") + }, + ". Every variance estimator holds certain rows fixed, so each would ", + "give a standard error of 0, whatever the spread of `y`. A standard ", + "error needs a sampled row", if (!whole) " of the domain", + " below certainty.") } +#' Whether the design could have drawn rows of a domain below certainty +#' +#' `TRUE` when the frame's probabilities `pi_all` show a row the design can +#' reach, below certainty, that `frame` places in the domain. `FALSE` when +#' there is none, or the probabilities or the domain's rows are unknown. +#' #' @noRd -ht_variance.drawn_design_stratified <- function(design, data, rows, y, pi_i) { - group <- as.character(group_key(data, design$strata)) - note <- lonely_note(group, rows, c("stratum", "strata"), - "Draw at least two rows per stratum (min_per_stratum = 2).") - if (!is.null(note)) return(list(variance = NA_real_, note = note)) - NextMethod() +could_draw_others <- function(pi_all, frame) { + !is.null(pi_all) && + any(reachable(pi_all) & !(is_certain(pi_all) %in% TRUE) & frame %in% TRUE) } +#' Domains whose standard error of 0 comes from certain rows only +#' +#' For a domain total or a Horvitz-Thompson domain mean. Every sampled row of +#' such a domain is in a unit taken with certainty, which every variance +#' estimator holds fixed, so its variance is 0, while the design could have +#' drawn other rows of it. The estimator is unbiased over samples, so the +#' estimate keeps its variance, and `certain_total_note()` says why it is 0. +#' `variances` holds each domain's variance. Returns positions in +#' `dom$levels_in`. +#' #' @noRd -ht_variance.drawn_design_temporal <- function(design, data, rows, y, pi_i) { - bucket <- temporal_bucket(design, data) - note <- lonely_note(bucket, rows, c("interval", "intervals"), - "Draw at least two rows per interval (per_interval = 2).") - if (!is.null(note)) return(list(variance = NA_real_, note = note)) - NextMethod() +certain_only_domains <- function(parts, dom, variances) { + pi_all <- frame_pi(parts) + if (is.null(pi_all)) return(integer(0)) + psu <- sample_units(parts$design, parts$units, parts$pop, parts$rows, + parts$pi) + which(vapply(seq_along(dom$levels_in), function(j) { + u <- psu[dom$idx[[j]]] + length(u) > 0L && all(u == 0L) && is.finite(variances[[j]]) && + could_draw_others(pi_all, domain_frame(dom, j)) + }, logical(1))) } -#' Variance of a single-stage cluster total +#' Why the domains of `certain_only_domains()` have a standard error of 0 +#' @noRd +certain_total_note <- function(domains) { + many <- length(domains) > 1L + paste0( + "The domain", if (many) "s", " ", quote_labels(domains), + if (many) " have" else " has", " sampled rows taken with certainty ", + "only, and the design could have drawn other rows of ", + if (many) "them" else "it", " in a different sample. Every variance ", + "estimator holds certain rows fixed, so the standard error is 0 and the ", + "interval has no width, though the estimate varies from sample to ", + "sample. Measuring that variation needs a sampled row of ", + if (many) "each" else "the", " domain below certainty.") +} + +#' Whether every frame row of a domain the design can reach was certain #' -#' Whole clusters are taken, so the number of *rows* is random whenever the -#' clusters differ in size. Sen-Yates-Grundy assumes a fixed size, and applied -#' row by row here it understates the variance badly -- by a factor of five on a -#' frame whose clusters vary from 2 to 10 rows -- and can return a negative -#' number or a zero-width interval. +#' Read from the frame's probabilities `pi_all`, from `frame_pi()`, over +#' `frame`, which marks the domain's frame rows as `domain_frame()` does. +#' Then every such row is in every sample, and an estimate over the domain +#' is exact. A row the frame cannot place, or a whole frame that cannot say +#' (`NA`), may belong to the domain and is counted in it, so a domain the +#' frame cannot place is exact only when every row the design can reach is +#' certain, as in a census. `FALSE` when the probabilities are unknown. #' -#' The cluster is the sampling unit, so the estimator belongs at that level: the -#' clusters are a simple random sample of `a` from `A`, and the quantity summed -#' over them is each cluster's contribution to the total. That is the textbook -#' form, and it is algebraically identical to the delete-a-cluster jackknife. +#' @noRd +certain_domain <- function(parts, frame, pi_all = frame_pi(parts)) { + if (is.null(pi_all)) return(FALSE) + # A conditional sample's unselected clusters have no recorded + # probability, and were not taken with certainty. + reach <- reachable(pi_all) & (frame | is.na(frame)) + !anyNA(pi_all[reach]) && all(is_certain(pi_all[reach])) +} + +#' The inclusion probability of every frame row +#' +#' The draw-time probabilities the sample records. A sample saved by drawn +#' 0.2.0 records none, so they are worked out again from the design, as +#' `ratio_parts()` does. `NULL` for such a sample whose design has no closed +#' form. #' #' @noRd -ht_variance.drawn_design_cluster <- function(design, data, rows, y, pi_i) { - cl <- count_clusters(design, data) - A <- cl$total - lab <- as.character(cl$labels[rows]) - if (anyNA(lab)) { - return(list(variance = NA_real_, - note = "Some sampled rows have no cluster label.")) - } - u <- vapply(split(y / pi_i, lab), sum, numeric(1)) - m <- length(u) - if (m < 2L) { - return(list(variance = NA_real_, note = paste0( - "A variance needs at least two clusters; this sample has ", m, "."))) - } - fpc <- if (is.finite(A) && A > m) 1 - m / A else 0 - list(variance = fpc * m * stats::var(u), note = NULL) +frame_pi <- function(parts) { + parts$pi_all %||% tryCatch(exact_inclusion(parts$design, parts$pop), + drawn_declined = function(e) NULL) } -#' Two-stage variance, declining where the second stage is unmeasurable +#' Each sampled row's primary sampling unit, as the variance sees it #' -#' With one row per selected cluster, pairs inside a cluster can never be drawn -#' together, so Sen-Yates-Grundy has no way to see the within-cluster variation -#' and understates by around a third. The delete-a-cluster jackknife that -#' `variance = "auto"` falls back to is the ultimate-cluster approximation, -#' which is the standard answer. +#' Clusters for a cluster or multistage design, as the jackknife deletes +#' them, the replicates of a systematic design with several starts, and +#' otherwise rows. A cluster design whose stage one takes every cluster has +#' rows as its units, each cluster a stratum of them, as +#' `clusters_all_taken()` sets out. Under a certainty design the rows below +#' the threshold are grouped as `rest` groups them. A unit whose every +#' sampled row is certain, given the sampled rows' inclusion probabilities +#' `pi`, is in every sample and adds nothing to a variance: the jackknife +#' holds such units fixed and `as_svydesign()` hands them to `survey` as one +#' unit. They share the code 0 here, and every other unit has a positive +#' integer code. `pop` is the frame and `rows` the sampled frame rows, which +#' place a systematic sample's rows on its walk. With `jackknife = TRUE` the +#' clusters of a design that takes every cluster stay the units, as the +#' jackknife deletes them. #' #' @noRd -ht_variance.drawn_design_multistage <- function(design, data, rows, y, pi_i) { - if (!design$replace && design$allocation == "equal" && - design$n %/% design$n_clusters == 1L && - design$n %% design$n_clusters == 0L) { - return(list(variance = NA_real_, note = paste0( - "With one row per selected cluster the variation within clusters ", - "cannot be measured, and the exact two-stage estimator would understate ", - "the variance."))) - } - NextMethod() +sample_units <- function(design, units, pop, rows, pi, jackknife = FALSE) { + psu <- design_units(design, units, pop, rows, jackknife) + code <- match(psu, unique(psu)) + code[!(psu %in% psu[!is_certain(pi)])] <- 0L + code } -#' Variance for the weighted designs +#' Each sampled row's primary sampling unit under the design #' -#' Poisson sampling is exact: rows are independent, so no joint matrix is -#' needed. Systematic PPS has no closed-form joint probabilities; Deville's -#' approximation is the standard answer for a high-entropy fixed-size design. +#' `sample_units()` without the units taken with certainty grouped. Under a +#' certainty design each row at or above the threshold is a unit of its own. #' #' @noRd -ht_variance.drawn_design_weighted <- function(design, data, rows, y, pi_i) { - if (design$method == "poisson") { - return(list(variance = sum((1 - pi_i) / pi_i^2 * y^2), note = NULL)) +design_units <- function(design, units, pop, rows, jackknife = FALSE) { + if (replicated(design)) { + return(systematic_replicates(design, systematic_positions(design, pop), + rows)) } - if (design$method == "systematic") { - return(deville_variance(y, pi_i)) + if (!jackknife && clusters_all_taken(design, pop)) { + return(seq_len(nrow(units))) + } + if (!inherits(design, "drawn_design_certainty")) { + return(jackknife_groups(design, units, pop)) + } + v <- units[[design$above]] + below <- !is.na(v) & v < design$threshold + out <- -seq_len(nrow(units)) + if (any(below)) { + sp <- certainty_split(design, pop) + out[below] <- design_units(design$rest, units[below, , drop = FALSE], + sp$data[sp$rest, , drop = FALSE], + match(rows[below], sp$keep[sp$rest]), + jackknife) } - stop("`design_weighted(method = \"successive\")` has no closed-form ", - "inclusion probability.", call. = FALSE) + out } -#' Deville's (1999) variance approximation for fixed-size unequal-probability -#' sampling +#' Does stage one of an equal-probability cluster design take every cluster? #' -#' `sum(c_k * (y_k / pi_k - A)^2) / (1 - sum(a_k^2))` with `c_k = 1 - pi_k`, -#' `a_k = c_k / sum(c)` and `A = sum(a_k * y_k / pi_k)`: the Hajek -#' approximation to the joint probabilities, which Matei and Tillé (2005) found -#' the most reliable of the standard first-order-only estimators. Certainty -#' rows have `c_k = 0` and drop out, as they should. Identical to -#' `sampling::varest()`. +#' Then every cluster is in every sample, and so is a stratum of its own +#' whose units are its sampled rows, as `cluster_units()` lays out a cluster +#' taken with certainty under `size`. Nothing varies between clusters, and +#' only the variation within them is left to measure. `pop` is the frame. #' #' @noRd -deville_variance <- function(y, pi_i) { - c_k <- 1 - pi_i - if (sum(c_k) <= 0) { - return(list(variance = 0, method = "deville", note = paste0( - "Every sampled row was taken with certainty, so the total is exact ", - "rather than estimated."))) - } - a <- c_k / sum(c_k) - denom <- 1 - sum(a^2) - if (denom <= 0) { - return(list(variance = NA_real_, method = "deville", note = paste0( - "Deville's approximation needs at least two sampled rows below ", - "certainty."))) - } - u <- y / pi_i - A <- sum(a * u) - list(variance = sum(c_k * (u - A)^2) / denom, method = "deville", - note = paste0("Deville's approximation for unequal-probability ", - "sampling: systematic PPS has no closed-form joint ", - "inclusion probabilities.")) +clusters_all_taken <- function(design, pop) { + inherits(design, c("drawn_design_cluster", "drawn_design_multistage")) && + is.null(design$size) && + design$n_clusters >= count_clusters(design, pop)$total } -#' Successive-difference variance for a systematic sample +#' What a design's primary sampling unit is called in a message #' -#' Each sampled row is compared with its neighbour in the order the design -#' walked, and the squared differences stand in for the population variance: -#' `(1 - f) * n / (2 * (n - 1)) * sum(diff(y / pi)^2)`. A trend along the walk -#' order therefore counts as structure, not noise -- the reason systematic -#' sampling on a sorted frame is efficient, and the reason the simple random -#' formula overstates its variance there. +#' A row for a cluster design whose stage one takes every cluster of the +#' frame `pop`, when `pop` is given. #' #' @noRd -ht_variance.drawn_design_systematic <- function(design, data, rows, y, pi_i) { - if (!is.null(design$start)) { - stop("A systematic design with a fixed `start` is not a probability ", - "sample: each row is selected with probability 0 or 1.", - call. = FALSE) +unit_noun <- function(design, pop = NULL) { + clustered <- c("drawn_design_cluster", "drawn_design_multistage") + if (inherits(design, clustered)) { + taken <- !is.null(pop) && clusters_all_taken(design, pop) + return(if (taken) "row" else "cluster") } - n <- length(rows) - if (n < 2L) { - return(list(variance = NA_real_, - note = "A variance needs at least two sampled rows.")) + if (replicated(design)) return("replicate") + if (inherits(design, "drawn_design_certainty") && + (inherits(design$rest, clustered) || replicated(design$rest))) { + return("primary sampling unit") } - pos <- systematic_positions(design, data)[rows] - u <- (y / pi_i)[order(pos)] - f <- 1 / design$interval - list(variance = (1 - f) * n / (2 * (n - 1)) * sum(diff(u)^2), - method = "successive difference", - note = paste0("Systematic sampling has no design-unbiased variance ", - "estimator; this is the successive-difference ", - "approximation. It would be understated if the frame ", - "cycled with a period matching `interval`, or if a smooth ", - "trend along the sort order swamped all other variation.")) + "row" } -# ---- jackknife -------------------------------------------------------------- +#' The reason given for a variance too large to represent +#' +#' Squaring `y / pi` passes the largest double, about `1.8e308`, once the +#' values pass about `1e154`, and the sum comes out infinite or `NaN`. The +#' analytic estimators and the jackknife give the same note, so a fallback +#' from one to the other states it once. +#' +#' @noRd +overflow_note <- function() { + paste0("The variance overflowed, because squaring `y / pi`, or totals ", + "built from it, passes the largest number R can hold. Rescale `y`, ", + "to thousands for example, and estimate again.") +} -#' Delete-a-group jackknife variance +#' Degrees of freedom for a design's confidence interval #' -#' Works from the sample alone, which is what makes it available where the -#' analytic form is not. Primary sampling units are whole clusters where the -#' design has them, otherwise individual rows; where the design has strata -- -#' stratified, and temporal, whose intervals are strata -- units are deleted -#' within their own stratum and only that stratum is reweighted (JKn). Deleting -#' across strata instead counts the differences *between* strata as sampling -#' variance, which stratification exists to remove: on a frame with four -#' well-separated strata that overstated the standard error sixty-fold. +#' Primary sampling units minus strata, the usual rule (Korn and Graubard +#' 1999), counting only units that could have been left out. A unit taken with +#' certainty is in every sample, so it carries no variance and no degree of +#' freedom: the units `design_weighted()` and `design_spread(size =)` take with +#' certainty, strata and intervals taken whole, and the rows above a +#' certainty design's threshold. A stratum holding none of the other units +#' drops out of the count of strata. Counting them put eight certain units of +#' ten at 9 degrees of freedom where the same selection built with +#' `design_certainty()` had 1, and the t interval covered 79%. #' -#' Two designs are declined rather than approximated. A systematic sample has a -#' single primary sampling unit -- the random start -- so deleting rows does not -#' reflect its randomness at all. Poisson sampling has an exact variance and a -#' random size; deleting rows from it understates by a factor of three. +#' A cluster counts when any of its sampled rows is below certainty. A +#' two-stage design that takes every cluster, but not every row in them, has +#' the number of clusters less one. With `size`, a cluster taken with +#' certainty is a stratum whose units are its sampled rows, as +#' `cluster_units()` lays it out. +#' +#' With no unit below certainty the variance is exactly 0 and the result is +#' `Inf`. An empty sample, and a certainty design whose `rest` drew none of the +#' rows below the threshold, have no variance to build an interval on and get +#' 0. A systematic design with `n_starts` of 2 or more has the number of +#' starts less one, the degrees of freedom of its random group variance. +#' +#' `as_svydesign()` hands each group of certain units to `survey` as one +#' primary sampling unit in a stratum of its own, so `survey::degf()` gives the +#' same count. Strata, those of a stratified or spread design or a temporal +#' design's intervals, and clusters are read from `units`, the frame's copy +#' of the sampled rows; `pi_i` holds their inclusion probabilities. #' #' @noRd -jackknife_variance <- function(design, sample, pop, y, pi_i) { - refusal <- jackknife_refusal(design) - if (!is.null(refusal)) { - return(list(variance = NA_real_, method = "jackknife", note = refusal)) - } - # Certainty rows are in every possible sample. Deleting one and inflating the - # rest invents variance the design does not have -- four times too much on a - # sample that is a third certainty -- so hand the whole problem to `rest`. +design_df <- function(design, units, pop, rows, pi_i) { if (inherits(design, "drawn_design_certainty")) { - keep <- pi_i < 1 - if (!any(keep)) { - return(list(variance = 0, method = "jackknife", note = paste0( - "Every sampled row was taken with certainty, so the total is exact ", - "rather than estimated."))) - } sp <- certainty_split(design, pop) - return(jackknife_variance(design$rest, sample[keep, , drop = FALSE], - sp$data[sp$rest, , drop = FALSE], - y[keep], pi_i[keep])) + free <- !(rows %in% sp$keep[sp$take]) + if (!any(free)) return(if (length(sp$rest)) 0 else Inf) + return(design_df(design$rest, units[free, , drop = FALSE], + sp$data[sp$rest, , drop = FALSE], + match(rows[free], sp$keep[sp$rest]), pi_i[free])) } + n <- nrow(units) + if (n == 0L) return(0) + if (replicated(design)) { + # The random group variance has one degree of freedom fewer than the + # number of starts, counting a replicate that drew no rows. + return(if (any(!is_certain(pi_i))) systematic_starts(design) - 1 else Inf) + } + if (inherits(design, "drawn_design_multistage") && !is.null(design$size)) { + cu <- cluster_units(design, units, pop) + random <- cu$psu %in% cu$psu[!is_certain(pi_i)] + if (!any(random)) return(Inf) + return(max(length(unique(cu$psu[random])) - + length(unique(cu$stratum[random])), 0)) + } + psu <- switch(design_type(design), + cluster = , + multistage = cluster_codes(units[[design$clusters]]), + seq_len(n) + ) + stratum <- switch(design_type(design), + stratified = , + spread = , + weighted = if (!is.null(design$strata)) { + as.integer(group_key(units, design$strata)) + }, + temporal = temporal_bucket(design, units), + NULL + ) %||% rep("all", n) + random <- psu %in% psu[!is_certain(pi_i)] + if (!any(random)) return(Inf) + max(length(unique(psu[random])) - length(unique(stratum[random])), 0) +} - psu <- jackknife_groups(design, sample) - st <- jackknife_strata(design, sample, pop, psu) - base <- y / pi_i - total <- sum(base) +#' The variance of an empty sample +#' +#' A design of random size, such as Poisson sampling or a systematic one whose +#' start falls past the last row, can draw nothing. The Horvitz-Thompson +#' estimate is then 0, which keeps it unbiased over repeated draws, but one +#' empty draw has no spread to measure. +#' +#' @noRd +empty_sample <- function() { + list(variance = NA_real_, method = "none", note = paste0( + "The sample is empty. The design could have drawn rows, but this draw ", + "took none, so the estimate is 0 and has no variance. A design with a ", + "fixed sample size, or a larger expected one, avoids this.")) +} - v <- 0 - n_psu <- 0L - lonely <- character(0) - for (h in unique(st$stratum)) { - in_h <- st$stratum == h - g <- psu[in_h] - ug <- unique(g) - m <- length(ug) - f <- st$fpc[[h]] - n_psu <- n_psu + m - if (m < 2L) { - if (f > 0) lonely <- c(lonely, h) - next - } - sums <- vapply(ug, function(u) sum(base[in_h][g == u]), numeric(1)) - reps <- (total - sum(sums)) + (sum(sums) - sums) * m / (m - 1) - v <- v + f * (m - 1) / m * sum((reps - mean(reps))^2) - } +#' @noRd +ht_variance <- function(design, data, rows, y, pi_i, domain = NULL, + ctx = NULL) UseMethod("ht_variance") - n_strata <- length(unique(st$stratum)) - if (n_strata == 1L && n_psu < 2L) { - return(list(variance = NA_real_, method = "jackknife", - note = paste0("The jackknife needs at least two primary ", - "sampling units; this sample has ", n_psu, "."))) +#' Sen-Yates-Grundy, for fixed-size designs with closed-form joint +#' probabilities +#' +#' The designs in the package that select by simple random sampling within +#' groups have methods of their own built on `srs_variance()` and +#' `two_stage_variance()`, which give the same figure in linear time and +#' memory. What reaches this method is a design with a joint matrix and no such +#' form, or one with no joint probabilities at all, whose `joint_inclusion()` +#' declines. +#' +#' The joint probabilities and the sums over pairs are n x n matrices of +#' doubles, about eight of them live at once with `syg_variance()`. Past +#' `pair_limit()` bytes projected, about 1 GB or 4,000 sampled rows, the +#' estimator declines with the size it would need, before anything is +#' allocated. Linux can stop R for want of memory before an allocation error +#' is raised, so waiting for one is no guard. A design with no joint +#' probabilities declines for that reason at any size, so the joint +#' probabilities of two rows are asked for first. The joint matrix is kept in +#' `ctx`, so the domains of one sample share it. +#' +#' @noRd +ht_variance.default <- function(design, data, rows, y, pi_i, domain = NULL, + ctx = NULL) { + n <- length(rows) + bytes <- 8 * 8 * as.numeric(n)^2 + if (bytes > pair_limit()) { + joint_inclusion(design, data, rows[1:2]) + n_text <- format(n, big.mark = ",") + stop_declined(paste0( + "The Sen-Yates-Grundy estimator would need about ", format_gb(bytes), + " of memory for its ", n_text, " x ", n_text, + " matrices.\nUse variance = \"auto\" to fall back to the jackknife.")) } - if (length(lonely)) { - return(list(variance = NA_real_, method = "jackknife", note = paste0( - "The stratified jackknife needs two units per stratum as well."))) + pij <- from_context(ctx, "joint", joint_inclusion(design, data, rows)) + if (length(rows) < 2L) { + return(list(variance = NA_real_, + note = "A variance needs at least two sampled rows.")) } - list(variance = v, method = "jackknife", - note = paste0("Jackknife over ", n_psu, " primary sampling unit(s)", - if (n_strata > 1L) paste0(" in ", n_strata, " strata") - else "", - if (any(unlist(st$fpc) < 1)) ", with a finite population correction" - else "", ".")) + syg_variance(y, pi_i, pij) } -#' Designs the jackknife should decline rather than approximate +#' The variance of a sample whose rows were all taken with certainty +#' +#' Every such row is in every possible sample, so the total is known exactly. +#' `method` names the estimator that found this, or is left unset for the +#' design's own exact one. +#' +#' @noRd +all_certain <- function(method = NULL) { + out <- list(variance = 0, note = paste0( + "Every sampled row was taken with certainty, so the total is exact ", + "rather than estimated.")) + out$method <- method + out +} + +#' The Sen-Yates-Grundy sum over pairs of sampled rows +#' +#' Kept as written, over the full joint matrix, as the reference the closed +#' forms below are tested against. +#' +#' @noRd +syg_variance <- function(y, pi_i, pij) { + yk <- y / pi_i + d <- outer(yk, yk, "-")^2 + num <- outer(pi_i, pi_i) - pij + w <- num / pij + w[!is.finite(w)] <- 0 # a zero joint probability contributes nothing + diag(w) <- 0 + list(variance = 0.5 * sum(w * d), note = NULL) +} + +#' Variance of a total under simple random sampling within groups +#' +#' For a design that takes a simple random sample of `n_g` of the `N_g` rows +#' in each group, independently across groups, the Sen-Yates-Grundy sum comes +#' to `sum(N_g^2 * (1 - n_g / N_g) * s_g^2 / n_g)`, with `s_g^2` the variance +#' of `z` over the sampled rows of group `g`. This computes it in that form, +#' in time and memory linear in the rows, where the sum over pairs held +#' several n x n matrices: about 1.4 GB for a stratified sample of 4,000 rows. +#' +#' `group` is each sampled row's position in `n_g` and `N_g`. A group taken +#' whole adds exactly 0, a group of one row included. A group with one sampled +#' row from several has no pair of rows to compare and adds 0, as it does in +#' the sum over pairs; callers refuse it first with `lonely_note()` where it +#' matters. `z` is whatever is being totalled: `y`, `y` times a domain's +#' indicator, or a Hajek mean's linearised residual. The probability is the +#' same for every row of a group, so the formula holds for all three. An +#' integer `z` is summed as double, where `rowsum()` would overflow to `NA`. +#' +#' @noRd +srs_variance <- function(z, group, n_g, N_g) { + z <- as.numeric(z) + live <- sort(unique(group)) + g <- match(group, live) + m <- tabulate(g, length(live)) + n <- as.numeric(n_g)[live] + N <- as.numeric(N_g)[live] + use <- m >= 2L & n < N + if (!any(use)) return(0) + mu <- rowsum(z, g)[, 1L] / m + ss <- rowsum((z - mu[g])^2, g)[, 1L] + sum((N^2 * (1 - n / N) * ss / ((m - 1) * n))[use]) +} + +#' Variance of a total from a two-stage sample +#' +#' `a` of `A` clusters by simple random sampling, then `m_i` of the +#' `sizes[i]` rows of each selected cluster `i`. The unbiased estimator is +#' `A^2 * (1 - a / A) * s_t^2 / a + (A / a) * sum(N_i^2 * (1 - m_i / N_i) * +#' s_i^2 / m_i)`, with `s_t^2` the variance of the estimated cluster totals +#' `N_i * mean(z_i)` and `s_i^2` the variance of `z` within cluster `i`. With +#' an equal take it is the Sen-Yates-Grundy sum for this design, computed +#' without the n x n joint matrix. Selecting every cluster leaves nothing +#' between them to vary, and a cluster taken whole adds nothing within it. +#' +#' `cluster` is each sampled row's cluster code, indexing `sizes`, and each +#' cluster's take `m_i` is the number of its rows in the sample. The take may +#' depend on which clusters were selected, as in a sample weighted +#' conditional on them: given the selection, the estimated cluster totals +#' vary by their within-cluster variance on top of the variance between +#' clusters, which brings the within term to `(A / a)^2` of the variances +#' within, and the estimator stays unbiased over every selection. +#' +#' @noRd +two_stage_variance <- function(z, cluster, a, A, sizes) { + z <- as.numeric(z) + live <- sort(unique(cluster)) + g <- match(cluster, live) + N_i <- as.numeric(sizes)[live] + m_i <- tabulate(g, length(live)) + totals <- N_i * rowsum(z, g)[, 1L] / m_i + between <- if (a < A) A^2 * (1 - a / A) * stats::var(totals) / a else 0 + within <- srs_variance(z, g, m_i, N_i) + between + A / a * within +} + +#' Two-stage variance of a sample weighted conditional on its clusters +#' +#' For a balanced cluster sample, or a multistage one whose take depends on +#' the clusters selected (see `conditional_inclusion()`). +#' `two_stage_variance()` with each cluster's own take is unbiased for it. +#' +#' The sample must carry the conditional probabilities, `(a / A) * m_i / +#' N_i` with `m_i` the rows of cluster `i` in the sample. A balanced design +#' in the `rest` of a certainty design is weighted with its unconditional +#' probabilities, whose joint probabilities have no closed form, so that +#' declines. So does a sample from one cluster of several, and one with a +#' cluster that gave one row of several, whose variation within cannot be +#' measured. +#' +#' @noRd +conditional_variance <- function(design, cl, rows, y, pi_i) { + code <- cl$code[rows] + if (anyNA(code)) { + return(list(variance = NA_real_, + note = "Some sampled rows have no cluster label.")) + } + k <- length(unique(code)) + if (k < 2L && design$n_clusters < cl$total && !all(is_certain(pi_i))) { + return(list(variance = NA_real_, note = paste0( + "A variance needs at least two clusters; this sample has ", k, "."))) + } + a <- design$n_clusters + A <- cl$total + sizes <- tabulate(cl$code, A) + if (!weighted_on_selection(design, code, sizes, pi_i)) { + no_joint_form( + paste0("`", design_label(design), "`"), + paste0("Its sample is weighted with unconditional probabilities, ", + "which the two-stage estimator\ncannot use. draw(weights = ", + "TRUE) weights the design on its own conditional on the\n", + "clusters selected."), simulate = FALSE) + } + if (all(is_certain(pi_i))) return(all_certain()) + if (one_row_clusters(design, code, sizes, fixed = FALSE)) { + return(list(variance = NA_real_, note = paste0( + "With one row from a selected cluster of several, the variation ", + "within clusters cannot be measured, and the two-stage estimator would ", + "understate the variance.", fallback_note(a, A)))) + } + list(variance = two_stage_variance(y, code, a, A, sizes), note = NULL) +} + +#' Whether a sample is weighted conditional on the clusters selected +#' +#' Each sampled row's probability is then `a / A * m_i / N_i`, with `m_i` +#' the rows sampled from its cluster of `N_i`. draw() weights a design whose +#' take depends on the selection this way, but not when the design is a +#' certainty design's `rest`, which has unconditional probabilities. +#' `code` holds the sampled rows' cluster codes and `sizes` the rows of each +#' cluster. +#' +#' @noRd +weighted_on_selection <- function(design, code, sizes, pi_i) { + live <- unique(code) + g <- match(code, live) + m <- tabulate(g, length(live)) + share <- design$n_clusters / length(sizes) * m / sizes[live] + all(same_prob(pi_i, share[g])) +} + +#' Whether a two-stage sample leaves the variation within clusters unmeasured +#' +#' A design with a fixed, equal take (`fixed`) leaves it unmeasured when the +#' take is one row. A take conditional on the clusters selected leaves it +#' unmeasured when any selected cluster of several rows has one sampled row. +#' The two-stage estimators then decline, `variance = "auto"` falls back to +#' the delete-a-cluster jackknife, and `as_svydesign()` hands `survey` the +#' ultimate-cluster design that gives the same variance. `code` holds the +#' sampled rows' cluster codes and `sizes` the rows of each cluster. +#' +#' @noRd +one_row_clusters <- function(design, code, sizes, fixed) { + if (fixed) return(design$n %/% design$n_clusters == 1L) + live <- unique(code) + m <- tabulate(match(code, live), length(live)) + any(m < 2L & m < sizes[live]) +} + +#' The variance of a simple random sample from one group of `N` rows +#' +#' Shared by the simple, reservoir and spatial designs, which differ only in +#' the `N` they draw `n` from. One sampled row has nothing to compare with +#' unless it is the whole group. +#' +#' @noRd +srs_one_group <- function(z, n, N) { + if (length(z) < 2L && n < N) { + return(list(variance = NA_real_, + note = "A variance needs at least two sampled rows.")) + } + list(variance = srs_variance(z, rep(1L, length(z)), n, N), note = NULL) +} + +#' The groups a design takes a simple random sample within +#' +#' For the simple, reservoir and spatial designs, one group: `n_g` rows drawn +#' from the `N_g` the design reaches. For stratified and temporal designs, +#' `code` gives each frame row's stratum or interval as a position in `n_g`, +#' `N_g` and `labels`. `NULL` for any other design. The analytic estimators of +#' these designs and `srs_layout()`, which estimates every domain in one pass, +#' read their groups from here, so the two cannot disagree. A design drawn +#' with replacement gets its groups too; the callers decide what to do with +#' it. +#' +#' @noRd +srs_groups <- function(design, data, ctx = NULL) { + from_context(ctx, "srs_groups", switch(design_type(design), + simple = list(n_g = design$n, + N_g = length(available_rows(design, nrow(data)))), + reservoir = { + # Rows past `max_items` are never read: the sample is a simple random + # one from the rows before it. + reach <- reservoir_reach(design, nrow(data)) + list(n_g = min(design$n, reach), N_g = reach) + }, + spatial = { + require_suggested("sf", "spatial sampling") + N <- sum(spatial_inside(design, data)) + list(n_g = min(design$n, N), N_g = N) + }, + stratified = { + al <- stratum_allocation(design, data) + list(code = al$code, labels = al$labels, n_g = al$n_alloc, + N_g = al$sizes) + }, + temporal = { + bucket <- key_from_columns(list(temporal_bucket(design, data))) + code <- as.integer(bucket) + sizes <- tabulate(code, nlevels(bucket)) + list(code = code, labels = levels(bucket), + n_g = pmin(sizes, design$per_interval), N_g = sizes) + }, + NULL + )) +} + +#' @noRd +ht_variance.drawn_design_simple <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + if (design$replace) return(NextMethod()) + g <- srs_groups(design, data, ctx) + srs_one_group(y, g$n_g, g$N_g) +} + +#' @noRd +ht_variance.drawn_design_reservoir <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + g <- srs_groups(design, data, ctx) + srs_one_group(y, g$n_g, g$N_g) +} + +#' @noRd +ht_variance.drawn_design_spatial <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + g <- srs_groups(design, data, ctx) + srs_one_group(y, g$n_g, g$N_g) +} + +#' Groups with one sampled row out of several +#' +#' `code` is each frame row's group as a position among `k` groups, and +#' `rows` the sampled frame rows. A group taken whole is not lonely. The one +#' rule for `lonely_note()` and `srs_layout()`. +#' +#' @noRd +lonely_groups <- function(code, rows, k) { + tabulate(code[rows], k) == 1L & tabulate(code, k) > 1L +} + +#' Refuse a stratified variance with a stratum that holds one sampled row +#' +#' Sen-Yates-Grundy sums over pairs, and a stratum with one sampled row has no +#' within-stratum pair: its contribution is silently zero. With one row in +#' every stratum the standard error came out as exactly 0 against a true +#' figure in the hundreds. `survey` fails in the same situation unless told +#' otherwise (`options(survey.lonely.psu)`); declining here keeps the two in +#' step and says what to change. +#' +#' Strata taken whole (`n_h == N_h`) are not lonely: they contribute no +#' variance because they have none. +#' +#' For a domain estimate, `domain` marks the frame rows in the domain. A +#' lonely stratum with none of them adds nothing to the domain's variance, +#' because the domain's `y` is 0 on every unit of it, so it is skipped. That +#' is decided from the frame, never from the sampled rows: a stratum whose one +#' sampled row lies outside the domain can still hold domain units that were +#' not drawn. A frame row marked `NA`, whose `by` value the frame does not +#' hold, may belong to the domain, so a lonely stratum holding one is +#' refused. `domain = NA` means the frame cannot say for any row, and every +#' lonely stratum is refused. +#' +#' @noRd +lonely_note <- function(group, rows, noun, fix, domain = NULL) { + # `noun` is c(singular, plural). `group` is each frame row's group, as a + # factor or as values, and is counted by position. + if (!is.factor(group)) { + group <- key_from_columns(list(group)) + } + code <- as.integer(group) + k <- nlevels(group) + lonely <- lonely_groups(code, rows, k) + unsure <- identical(domain, NA) + if (known_domain(domain, length(code))) { + hold <- domain_groups(code, domain, k) + lonely <- lonely & hold$maybe + unsure <- !any(lonely & hold$sure) + } + lonely_text(levels(group)[lonely], noun, fix, unsure) +} + +#' The refusal of lonely groups, naming them +#' +#' `lonely` holds the groups' key levels, in key order. Shared by the analytic +#' estimators and the jackknife, so the two refuse a sample in the same words +#' and `variance = "auto"` says it once. `unsure` says that the frame cannot +#' tell whether any of them holds units of the domain. +#' +#' @noRd +lonely_text <- function(lonely, noun, fix, unsure = FALSE) { + if (!length(lonely)) return(NULL) + shown <- group_label(utils::head(lonely, 5L)) + many <- length(lonely) > 1L + them <- if (many) "them" else "it" + paste0(if (many) paste(length(lonely), noun[2]) else paste("The", noun[1]), + " ", paste0("`", shown, "`", collapse = ", "), + if (length(lonely) > 5L) ", ..." else "", + " ", if (many) "each have" else "has", + " a single sampled row, so the variation within ", them, + if (unsure) { + paste0(" cannot be measured. If ", if (many) "they hold" else + "it holds", " units of this domain, which cannot be told ", + "from the frame, leaving ", them, " out would understate ", + "the standard error. ") + } else { + paste0(" cannot be measured and leaving ", them, " out would ", + "understate the standard error. ") + }, fix) +} + +#' What to change so that no stratum or interval holds one sampled row +#' @noRd +lonely_fix <- function(design) { + if (inherits(design, "drawn_design_multistage")) { + return(paste0("Draw at least two rows per cluster (`n` of at least ", + "twice `n_clusters`).")) + } + if (inherits(design, "drawn_design_temporal")) { + return("Draw at least two rows per interval (per_interval = 2).") + } + if (inherits(design, c("drawn_design_spread", "drawn_design_weighted"))) { + return(paste0("Draw at least two rows below certainty per stratum (", + if (!has_counts(design)) "a larger `n`, or ", + "a count of 2 or more for each in `allocation`).")) + } + if (has_counts(design)) { + return(paste0("Draw at least two rows per stratum (a count of 2 or more ", + "for each in `allocation`).")) + } + "Draw at least two rows per stratum (min_per_stratum = 2)." +} + +#' Does `domain` mark which of `n` frame rows belong to a domain? +#' +#' A row marked `NA` is one the frame cannot place, and may belong to it. +#' +#' @noRd +known_domain <- function(domain, n) { + is.logical(domain) && length(domain) == n && !identical(domain, NA) +} + +#' The groups that hold units of a domain +#' +#' `code` is each frame row's group as a position among `k` groups, `NA` for +#' a row in none, and `domain` marks the frame rows in the domain, as +#' `known_domain()` accepts it. Returns `sure`, the groups with a frame row in +#' the domain, and `maybe`, those with such a row or with a row the frame +#' cannot place. +#' +#' @noRd +domain_groups <- function(code, domain, k) { + sure <- tabulate(code[which(domain)], k) > 0L + maybe <- sure + if (anyNA(domain)) maybe <- maybe | tabulate(code[is.na(domain)], k) > 0L + list(sure = sure, maybe = maybe) +} + +#' Variance within the groups of `srs_groups()`, refusing a lonely group +#' +#' The stratified and temporal estimators: each group is a simple random +#' sample of its `n_g` rows from its `N_g`, so the variance is +#' `srs_variance()` over groups. `noun` and `fix` word the refusal of a +#' lonely group. A design drawn with replacement is refused for a lonely +#' group too, and otherwise gets `NULL`, for its method to pass on. +#' +#' @noRd +srs_within_groups <- function(design, g, rows, y, domain, noun, fix) { + group <- structure(g$code, levels = g$labels, class = "factor") + note <- lonely_note(group, rows, noun, fix, domain) + if (!is.null(note)) return(list(variance = NA_real_, note = note)) + if (isTRUE(design$replace)) return(NULL) + list(variance = srs_variance(y, g$code[rows], g$n_g, g$N_g), note = NULL) +} + +#' Stratified variance, from the allocation the design used +#' +#' Each stratum is a simple random sample of its `n_alloc` rows from its +#' `sizes` rows, both from `stratum_allocation()`, so the variance is +#' `srs_variance()` over strata. A lonely stratum is refused first. +#' +#' @noRd +ht_variance.drawn_design_stratified <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + if (walks_strata(design)) { + return(walk_strata_variance(design, data, rows, y, pi_i, domain, ctx)) + } + out <- srs_within_groups( + design, srs_groups(design, data, ctx), rows, y, domain, + c("stratum", "strata"), lonely_fix(design)) + if (is.null(out)) return(NextMethod()) + out +} + +#' Successive-difference variance of a sample walked within strata +#' +#' Each stratum is a systematic sample of its `n_h` rows from its `N_h` at a +#' step of `N_h / n_h`, from a start of its own, so the variance is the sum +#' over strata of `(1 - n_h / N_h) * n_h / (2 * (n_h - 1)) * sum(diff(u)^2)`, +#' `u` being `y / pi` over the stratum's sampled rows in walk order. That is +#' the systematic estimator with `n` applied to each stratum. A lonely +#' stratum is refused first, as for simple random sampling within strata, +#' and a stratum taken whole adds 0. +#' +#' @noRd +walk_strata_variance <- function(design, data, rows, y, pi_i, domain = NULL, + ctx = NULL) { + g <- srs_groups(design, data, ctx) + group <- structure(g$code, levels = g$labels, class = "factor") + note <- lonely_note(group, rows, c("stratum", "strata"), lonely_fix(design), + domain) + if (!is.null(note)) return(list(variance = NA_real_, note = note)) + k <- length(g$N_g) + pos <- from_context(ctx, "walk", walk_positions(design, data, g$code, k)) + h <- g$code[rows] + o <- order(h, pos[rows]) + h <- h[o] + u <- as.numeric(y / pi_i)[o] + # Successive differences within a stratum, never across two. + same <- h[-1L] == h[-length(h)] + ss <- vapply(split(diff(u)[same]^2, + factor(h[-1L][same], levels = seq_len(k))), + sum, numeric(1), USE.NAMES = FALSE) + m <- tabulate(h, k) + f <- as.numeric(g$n_g) / as.numeric(g$N_g) + use <- m >= 2L + # A stratum walked at a step of 2 rows or more has pairs that are never + # drawn together. + lead <- if (any(g$n_g > 0 & g$N_g >= 2 * g$n_g)) { + paste0("Systematic sampling within strata has no design-unbiased ", + "variance estimator; this is ") + } else { + "This is " + } + list(variance = sum(((1 - f) * m / (2 * (m - 1)) * ss)[use]), + method = "successive difference", + note = paste0(lead, "the sum over strata of the successive-difference ", + "approximation. It would be understated if a stratum ", + "cycled with a period matching its step, or if a ", + "smooth trend along the sort order swamped all other ", + "variation.")) +} + +#' Temporal variance: intervals are strata +#' +#' Each interval is a simple random sample of `per_interval` of its rows, or +#' all of them when it holds fewer. A lonely interval is refused first. +#' +#' @noRd +ht_variance.drawn_design_temporal <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + srs_within_groups( + design, srs_groups(design, data, ctx), rows, y, domain, + c("interval", "intervals"), lonely_fix(design)) +} + +#' Each sampled row's group, for every domain's variance in one pass +#' +#' Returns `NULL` when the design's analytic variance is not `srs_variance()` +#' over the groups of `srs_groups()`, as for a stratified design that walks +#' its strata, or when it declines for the whole +#' sample, as with one sampled row from a group of several. Otherwise +#' `group` gives each sampled row's position in `n_g` and `N_g`, `NA` for a +#' row taken with certainty above a certainty design's threshold, and +#' `lonely_rows` the frame rows in a group with one sampled row, whose domains +#' `srs_variance()` cannot measure. +#' +#' @noRd +srs_layout <- function(design, data, rows, ctx = NULL) { + if (inherits(design, "drawn_design_certainty")) { + sp <- certainty_parts(design, data, ctx) + free <- !(rows %in% sp$keep[sp$take]) + pos <- match(rows[free], sp$keep[sp$rest]) + if (!any(free) || anyNA(pos)) return(NULL) + out <- srs_layout(design$rest, sp$rest_data, pos, sub_context(ctx, "rest")) + if (is.null(out)) return(NULL) + group <- rep(NA_integer_, length(rows)) + group[free] <- out$group + out$group <- group + out$lonely_rows <- sp$keep[sp$rest][out$lonely_rows] + return(out) + } + if (isTRUE(design$replace) || walks_strata(design)) return(NULL) + g <- srs_groups(design, data, ctx) + if (is.null(g)) return(NULL) + if (is.null(g$code)) { + if (length(rows) < 2L && g$n_g < g$N_g) return(NULL) + return(list(group = rep(1L, length(rows)), n_g = g$n_g, N_g = g$N_g, + lonely_rows = integer(0))) + } + lonely <- lonely_groups(g$code, rows, length(g$N_g)) + list(group = g$code[rows], n_g = g$n_g, N_g = g$N_g, + lonely_rows = which(lonely[g$code])) +} + +#' `srs_variance()` for many domains at once +#' +#' `z` holds each sampled row's value in its own domain: `y`, or the Hajek +#' residual or `y / N_d` of that domain. Domain `d`'s variable is `z` on its +#' rows and 0 on every other row, and `domain` gives each row's `d` among +#' `n_dom`. Within group `g` that variable has mean `S_gd / m_g`, with `S_gd` +#' the sum of `z` over the group's rows in `d` and `m_g` the group's sampled +#' rows, and its squared deviations are those of the rows in `d` plus +#' `(m_g - c_gd)` times the squared mean for the `c_gd` rows outside it. So +#' one `rowsum()` over the group and domain cells gives every domain's +#' variance in time linear in the rows, where a pass per domain was linear in +#' rows times domains. The figures equal `srs_variance()` on each domain's +#' variable, up to the order of summation. +#' +#' @noRd +srs_variance_by <- function(z, group, domain, n_dom, n_g, N_g) { + z <- as.numeric(z) + out <- numeric(n_dom) + live <- sort(unique(group)) + g <- match(group, live) + m <- tabulate(g, length(live)) + n <- as.numeric(n_g)[live] + N <- as.numeric(N_g)[live] + use <- m >= 2L & n < N + rows <- use[g] + if (!any(rows)) return(out) + g <- g[rows] + d <- domain[rows] + z <- z[rows] + # One cell per group and domain that share a sampled row. The arithmetic is + # in doubles, which hold the cell numbers exactly. + cell_id <- (g - 1) * as.numeric(n_dom) + d + cells <- unique(cell_id) + cell <- match(cell_id, cells) + first <- match(seq_along(cells), cell) + cg <- g[first] + mu <- rowsum(z, cell, reorder = FALSE)[, 1L] / m[cg] + ss <- rowsum((z - mu[cell])^2, cell, reorder = FALSE)[, 1L] + + (m[cg] - tabulate(cell, length(cells))) * mu^2 + v <- N[cg]^2 * (1 - n[cg] / N[cg]) * ss / ((m[cg] - 1) * n[cg]) + cd <- d[first] + out[unique(cd)] <- rowsum(v, cd, reorder = FALSE)[, 1L] + out +} + +#' Variance of a single-stage cluster total +#' +#' Whole clusters are taken, so the number of *rows* is random whenever the +#' clusters differ in size. Sen-Yates-Grundy assumes a fixed size, and applied +#' row by row here it understates the variance badly -- by a factor of five on a +#' frame whose clusters vary from 2 to 10 rows -- and can return a negative +#' number or a zero-width interval. +#' +#' The cluster is the sampling unit, so the estimator belongs at that level: the +#' clusters are a simple random sample of `a` from `A`, and the quantity summed +#' over them is each cluster's contribution to the total. That is the textbook +#' form, and it is algebraically identical to the delete-a-cluster jackknife. +#' +#' A balanced design subsamples the clusters it selects, and gets the +#' two-stage form of `conditional_variance()`. +#' +#' @noRd +ht_variance.drawn_design_cluster <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + cl <- from_context(ctx, "clusters", count_clusters(design, data)) + if (design$balanced) return(conditional_variance(design, cl, rows, y, pi_i)) + A <- cl$total + code <- cl$code[rows] + if (anyNA(code)) { + return(list(variance = NA_real_, + note = "Some sampled rows have no cluster label.")) + } + u <- rowsum(y / pi_i, code, reorder = FALSE)[, 1L] + m <- length(u) + if (m < 2L) { + return(list(variance = NA_real_, note = paste0( + "A variance needs at least two clusters; this sample has ", m, "."))) + } + fpc <- if (is.finite(A) && A > m) 1 - m / A else 0 + list(variance = fpc * m * stats::var(u), note = NULL) +} + +#' Two-stage variance, declining where a stage is unmeasurable +#' +#' With an equal take that divides `n`, drawn without replacement, the exact +#' estimator is `two_stage_variance()`. A take that depends on the clusters +#' selected is weighted conditional on them, and `conditional_variance()` +#' applies the same formula at each cluster's own take. A design drawn with +#' replacement has no closed-form joint probabilities, and the default +#' method declines. +#' +#' A sample from a single cluster has no variation between clusters to +#' measure. Sen-Yates-Grundy came out negative on every such sample, or 0 for +#' a constant `y`, so this declines first, in the words `design_cluster()` +#' uses. It does not decline when the frame holds that one cluster only, as +#' stage one then takes every cluster. A sample whose every row is certain +#' goes on to the exact estimator, which gives 0. +#' +#' With one row per selected cluster, pairs inside a cluster can never be drawn +#' together, so the exact estimator has no way to see the within-cluster +#' variation. With `f1 = n_clusters / A`, it understates by `f1` times the +#' within-cluster component of the variance. The delete-a-cluster jackknife +#' that `variance = "auto"` falls back to is the ultimate-cluster +#' approximation. It has no first-stage finite population correction, so it +#' overstates by `f1` times the between-cluster component instead, which +#' `fallback_note()` reports once `f1` passes 0.2. +#' +#' @noRd +ht_variance.drawn_design_multistage <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + if (!is.null(design$size)) { + if (design$replace) return(NextMethod()) + return(pps_stage_variance(design, data, rows, y, pi_i, ctx)) + } + cl <- from_context(ctx, "clusters", count_clusters(design, data)) + n_cl <- length(unique(cl$code[rows])) + # A frame of one cluster makes stage one a census, and the sample a simple + # random one within it, which the exact estimator measures. + if (n_cl < 2L && design$n_clusters < cl$total && !all(is_certain(pi_i))) { + return(list(variance = NA_real_, note = paste0( + "A variance needs at least two clusters; this sample has ", n_cl, "."))) + } + if (design$replace) return(NextMethod()) + sizes <- from_context(ctx, "cluster_sizes", tabulate(cl$code, cl$total)) + if (!multistage_fixed(design, sizes)) { + return(conditional_variance(design, cl, rows, y, pi_i)) + } + if (one_row_clusters(design, cl$code[rows], sizes, fixed = TRUE)) { + return(list(variance = NA_real_, note = paste0( + "With one row per selected cluster the variation within clusters ", + "cannot be measured, and the exact two-stage estimator would understate ", + "the variance.", fallback_note(design$n_clusters, cl$total)))) + } + v <- two_stage_variance(y, cl$code[rows], design$n_clusters, cl$total, + sizes) + list(variance = v, note = NULL) +} + +#' Two-stage variance with clusters selected in proportion to size +#' +#' The unbiased two-stage estimator is the first-stage estimator applied to +#' the estimated cluster totals, plus `sum(V_i / pi_i)` over the selected +#' clusters, where `V_i = N_i^2 * (1 - m / N_i) * s_i^2 / m` is the variance +#' of the simple random sample of `m` rows within cluster `i` (Särndal, +#' Swensson and Wretman 1992). Systematic PPS has no joint +#' probabilities for the first stage, so Deville's approximation takes its +#' place, over the clusters below certainty; a cluster taken with certainty +#' adds only its own `V_i`. With every `pi_i` equal this is +#' `two_stage_variance()`. +#' +#' One row per cluster leaves `V_i` unmeasurable, and one cluster below +#' certainty leaves nothing to compare between clusters, so both decline. +#' +#' @noRd +pps_stage_variance <- function(design, data, rows, y, pi_i, ctx = NULL) { + if (all(is_certain(pi_i))) return(all_certain()) + st <- from_context(ctx, "stage_one", cluster_stage(design, data)) + code <- st$code[rows] + live <- unique(code) + g <- match(code, live) + k <- length(live) + p1 <- st$pi1[live] + N <- as.numeric(st$sizes[live]) + m <- tabulate(g, k) + if (any(m < 2L & m < N)) { + return(list(variance = NA_real_, note = paste0( + "With one row per selected cluster the variation within clusters ", + "cannot be measured, and leaving it out would understate the ", + "variance."))) + } + open <- which(!is_certain(p1)) + if (length(open) == 1L) { + return(list(variance = NA_real_, note = paste0( + "A variance needs at least two clusters below certainty; this sample ", + "has one", + if (k > 1L) paste0(", besides the ", k - 1L, " taken with certainty"), + "."))) + } + z <- as.numeric(y) + mu <- rowsum(z, g)[, 1L] / m + ss <- rowsum((z - mu[g])^2, g)[, 1L] + use <- m >= 2L & m < N + within <- sum((N^2 * (1 - m / N) * ss / ((m - 1) * m) / p1)[use]) + if (!length(open)) return(list(variance = within, note = NULL)) + # Each cluster's estimated total over its stage-one probability. + u <- rowsum(z / pi_i, g)[, 1L] + between <- deville_variance(u[open] * p1[open], p1[open])$variance + list(variance = between + within, method = "deville", + note = paste0("Deville's approximation for the clusters selected in ", + "proportion to size, which have no closed-form joint ", + "inclusion probabilities, plus the variance within the ", + "selected clusters.")) +} + +#' What the ultimate-cluster jackknife does to a multistage variance +#' +#' The jackknife has no first-stage finite population correction, so its +#' between-cluster part is `1 / (1 - f1)` times the true one, with +#' `f1 = a / A`. That is under 1.25 while `f1` is at most 0.2 and is not +#' reported. When every cluster is selected the true between-cluster part is +#' 0, and the clusters are strata. Returns a sentence to append to a note, +#' starting with a space, or `""`. +#' +#' @noRd +fallback_note <- function(a, A) { + f1 <- a / A + if (!is.finite(f1) || f1 <= 0.2) return("") + if (a >= A) { + return(paste0( + " Every cluster is selected, so the clusters are strata and the ", + "variance between them is zero by design, but the delete-a-cluster ", + "jackknife counts it in full because it has no first-stage finite ", + "population correction. Draw with design_stratified() using the ", + "cluster column as `strata` and at least two rows in each.")) + } + paste0( + " With ", a, " of the ", A, " clusters selected, the delete-a-cluster ", + "jackknife, which has no first-stage finite population correction, puts ", + "the variance between clusters at ", signif(1 / (1 - f1), 2), + " times its true size.") +} + +#' What a jackknife asked for does to a multistage variance +#' +#' `fallback_note()` for `variance = "jackknife"`, which runs the jackknife +#' without the analytic estimator declining first. For a multistage design +#' without `size`, drawn without replacement, the jackknife has no +#' first-stage finite population correction, so it puts the variance +#' between clusters at `1 / (1 - f1)` times its size, with +#' `f1 = n_clusters / A`, and counts it in full when every cluster is +#' selected, where it is zero by design. The analytic estimator measures +#' only the variation within clusters then. A certainty design is read +#' through its `rest`. Returns a sentence starting with a space, or `""`. +#' +#' @noRd +jackknife_inflation <- function(design, pop, ctx = NULL) { + if (inherits(design, "drawn_design_certainty")) { + sp <- certainty_parts(design, pop, ctx) + return(jackknife_inflation(design$rest, sp$rest_data, + sub_context(ctx, "rest"))) + } + if (!inherits(design, "drawn_design_multistage") || + !is.null(design$size) || isTRUE(design$replace)) { + return("") + } + A <- from_context(ctx, "clusters", count_clusters(design, pop))$total + if (design$n_clusters < A) return(fallback_note(design$n_clusters, A)) + paste0(" Every cluster is selected, so the variance between clusters is ", + "zero by design, but the delete-a-cluster jackknife counts it in ", + "full because it has no first-stage finite population correction. ", + "variance = \"analytic\" measures the variation within clusters ", + "only.") +} + +#' Variance for the weighted designs +#' +#' Poisson sampling is exact: rows are independent, so no joint matrix is +#' needed. Systematic PPS has no closed-form joint probabilities; Deville's +#' approximation is the standard answer for a high-entropy fixed-size design. +#' +#' @noRd +ht_variance.drawn_design_weighted <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + if (design$method == "poisson") { + return(list(variance = sum((1 - pi_i) / pi_i^2 * y^2), note = NULL)) + } + if (design$method == "systematic") { + if (!is.null(design$strata)) { + return(deville_strata(design, data, rows, y, pi_i, domain, ctx)) + } + return(deville_variance(y, pi_i)) + } + stop_declined(paste0("`design_weighted(method = \"successive\")` has no ", + "closed-form inclusion probability.")) +} + +#' Deville's (1999) variance approximation for fixed-size unequal-probability +#' sampling +#' +#' `sum(c_k * (y_k / pi_k - A)^2) / (1 - sum(a_k^2))` with `c_k = 1 - pi_k`, +#' `a_k = c_k / sum(c)` and `A = sum(a_k * y_k / pi_k)`: the Hajek +#' approximation to the joint probabilities, which Matei and Tillé (2005) found +#' the most reliable of the standard first-order-only estimators. Certainty +#' rows have `c_k = 0` and drop out, as they should. Identical to +#' `sampling::varest()`. +#' +#' @noRd +deville_variance <- function(y, pi_i) { + c_k <- ifelse(is_certain(pi_i), 0, 1 - pi_i) + if (sum(c_k) <= 0) return(all_certain("deville")) + a <- c_k / sum(c_k) + denom <- 1 - sum(a^2) + if (denom <= 0) { + return(list(variance = NA_real_, method = "deville", note = paste0( + "Deville's approximation needs at least two sampled rows below ", + "certainty."))) + } + u <- y / pi_i + A <- sum(a * u) + list(variance = sum(c_k * (u - A)^2) / denom, method = "deville", + note = paste0("Deville's approximation for unequal-probability ", + "sampling: systematic PPS has no closed-form joint ", + "inclusion probabilities.")) +} + +#' Deville's approximation for systematic PPS within strata +#' +#' The strata are drawn independently, so the variance is the sum of +#' `deville_variance()` over each stratum's sampled rows, which is +#' `sampling::varest()` applied stratum by stratum and added up. Rows taken +#' with certainty add nothing. A stratum with one sampled row below certainty +#' has nothing to compare it with, so it is refused by `lonely_note()`, +#' unless `domain` shows it holds no unit of the domain, when it adds 0. +#' +#' @noRd +deville_strata <- function(design, data, rows, y, pi_i, domain = NULL, + ctx = NULL) { + free <- !is_certain(pi_i) + if (!any(free)) return(all_certain("deville")) + st <- from_context(ctx, "weighted", weighted_setup(design, data)) + p <- from_context(ctx, "pps_pi", weighted_pi(design, st)) + # Each frame row's stratum, counting only the rows below certainty. + code <- rep(NA_integer_, nrow(data)) + open <- !is_certain(p) + code[st$keep[open]] <- st$code[open] + group <- structure(code, levels = st$labels, class = "factor") + note <- lonely_note(group, rows, c("stratum", "strata"), lonely_fix(design), + domain) + if (!is.null(note)) { + return(list(variance = NA_real_, method = "deville", note = note)) + } + h <- code[rows] + v <- 0 + for (g in unique(h[free])) { + i <- which(free & h == g) + if (length(i) < 2L) next + v <- v + deville_variance(y[i], pi_i[i])$variance + } + list(variance = v, method = "deville", + note = paste0("Deville's approximation for unequal-probability ", + "sampling, summed over strata: systematic PPS has no ", + "closed-form joint inclusion probabilities.")) +} + +#' Successive-difference variance for a systematic sample +#' +#' Each sampled row is compared with its neighbour in the order the design +#' walked, and the squared differences stand in for the population variance: +#' `(1 - f) * n / (2 * (n - 1)) * sum(diff(y / pi)^2)`. A trend along the walk +#' order therefore counts as structure, not noise -- the reason systematic +#' sampling on a sorted frame is efficient, and the reason the simple random +#' formula overstates its variance there. +#' +#' When the interval `k` does not divide the `N` rows the design walks, the +#' sample holds `N %/% k` or `N %/% k + 1` rows, the larger with probability +#' `(N %% k) / k`. The total `sum(y / pi)` moves with that count by about +#' `mean(y / pi)` per row, which successive differences cannot see. A +#' constant `y` got a variance of 0, and a variable with a coefficient of +#' variation of 0.02 an interval that covered none of the time. The term +#' `mean(y / pi)^2 * (r / k) * (1 - r / k)`, with `r` that remainder, is added +#' for it. It is exact for a constant `y`, ignores the covariance between the +#' count and the sample mean, and is 0 for the linearised residuals of a Hajek +#' mean, whose mean is 0. +#' +#' A design given `n` walks at a step of `N / n` rows and always draws `n`, +#' so `f` is `n / N` and no term is added. +#' +#' A design with `n_starts` of 2 or more has the exact random group variance +#' of `replicate_variance()` instead. +#' +#' @noRd +ht_variance.drawn_design_systematic <- function(design, data, rows, y, pi_i, + domain = NULL, ctx = NULL) { + refuse_fixed_start(design) + if (replicated(design)) { + walk <- from_context(ctx, "walk", systematic_positions(design, data)) + return(replicate_variance(design, walk, rows, y, pi_i)) + } + n <- length(rows) + if (n < 2L) { + return(list(variance = NA_real_, + note = "A variance needs at least two sampled rows.")) + } + walk <- from_context(ctx, "walk", systematic_positions(design, data)) + pos <- walk[rows] + u <- (y / pi_i)[order(pos)] + N <- sum(!is.na(walk)) + step <- walk_step(design, N) + k <- step$k + r <- step$r + period <- if (is.null(design$n)) { + "`interval`" + } else { + paste0("the step of ", format(k, digits = 4), " rows") + } + f <- 1 / k + v <- (1 - f) * n / (2 * (n - 1)) * sum(diff(u)^2) + if (r > 0) v <- v + mean(u)^2 * (r / k) * (1 - r / k) + # Below a step of 2 rows any two rows can be drawn together, so a + # design-unbiased estimator exists there. + lead <- if (k >= 2) { + "Systematic sampling has no design-unbiased variance estimator; this is " + } else { + "This is " + } + list(variance = v, + method = "successive difference", + note = paste0(lead, "the successive-difference ", + "approximation. It would be understated if the frame ", + "cycled with a period matching ", period, ", or if a ", + "smooth trend along the sort order swamped all other ", + "variation.", + if (r > 0) { + paste0(" The ", N, " rows walked are not a multiple of ", + "`interval` (", k, "), so the sample size is ", + "random, ", N %/% k, " or ", N %/% k + 1L, + " rows, and the variance includes a term for ", + "that.") + })) +} + +#' The step of a systematic walk, and the rows left over +#' +#' `k` is `interval`, or `N / n` rows for a design given `n`, which need not +#' be whole. `r` is the remainder of the `N` rows walked over `k`, which +#' makes the sample size random; a design given `n` always draws `n`, so its +#' `r` is 0. +#' +#' @noRd +walk_step <- function(design, N) { + if (is.null(design$n)) { + list(k = design$interval, r = N %% design$interval) + } else { + list(k = N / design$n, r = 0) + } +} + +#' Random group variance of a systematic sample with several starts +#' +#' The `m` starts are a simple random sample of the `m * k` residue classes +#' modulo `m * k`, `k` the interval, and each replicate's total `t_r`, `m` +#' times the sum of `y / pi` over its rows, is the Horvitz-Thompson total of +#' a systematic sample at a step of `m * k`. Their mean is the sample's +#' total, and `(1 - 1 / k) * var(t_r) / m` is the textbook unbiased variance +#' of a mean of `m` units drawn from `m * k` without replacement. Over the +#' sampled rows it is the Horvitz-Thompson variance estimator with the exact +#' joint probabilities of `joint_inclusion()`, and, when `m * k` divides the +#' rows walked and the size is fixed, the Sen-Yates-Grundy one too, computed +#' from the `m` replicate totals alone. A replicate whose start fell past the +#' last row walked drew nothing, and its total of 0 counts among the `m`. +#' +#' @noRd +replicate_variance <- function(design, walk, rows, y, pi_i) { + if (all(is_certain(pi_i))) return(all_certain()) + m <- systematic_starts(design) + rep_id <- systematic_replicates(design, walk, rows) + t_r <- m * rowsum(as.numeric(y / pi_i), rep_id, reorder = FALSE)[, 1L] + t_r <- c(t_r, numeric(m - length(t_r))) + list(variance = (1 - 1 / design$interval) * stats::var(t_r) / m, + note = NULL) +} + +# ---- jackknife -------------------------------------------------------------- + +#' Delete-a-group jackknife variance +#' +#' Works from the sampled rows alone, which is what makes it available where +#' the analytic form is not. `units` is the frame's copy of those rows, so the +#' strata and clusters are the ones the sample was drawn with. Primary sampling +#' units are whole clusters where the design has them, otherwise individual +#' rows; where the design has strata (stratified, and temporal, whose +#' intervals are strata), units are deleted within their own stratum and only +#' that stratum is reweighted (JKn). Deleting across strata instead counts the +#' differences *between* strata as sampling variance, which stratification +#' exists to remove: on a frame with four well-separated strata that overstated +#' the standard error sixty-fold. +#' +#' Two designs are declined rather than approximated. A systematic sample has a +#' single primary sampling unit -- the random start -- so deleting rows does not +#' reflect its randomness at all. Poisson sampling has an exact variance and a +#' random size; deleting rows from it understates by a factor of three. +#' +#' Units taken with certainty are held fixed. They are in every possible +#' sample, so deleting one and inflating the rest invents variance the design +#' does not have. On a frame with six dominant units, systematic PPS samples +#' got 181 times the true variance on average that way. The rule covers the +#' units `design_weighted()` and `design_spread(size =)` take with certainty, +#' strata taken whole and a census. A cluster is held fixed when every one of +#' its sampled rows is certain. The finite population correction counts only +#' the units that were not certain, in the sample and in the frame. +#' +#' A stratum with one unit cannot be deleted from and is refused, unless +#' `domain` shows it holds no unit of the domain being estimated, as in +#' `lonely_note()`. +#' +#' `ctx` is a `variance_context()` for `design`, `pop` and `units`, with +#' `pi_i` the same in every call that shares it. +#' +#' @noRd +jackknife_variance <- function(design, units, pop, y, pi_i, domain = NULL, + ctx = NULL) { + lay <- jackknife_layout(design, units, pop, pi_i, domain, ctx) + if (!is.null(lay$note)) { + return(list(variance = NA_real_, method = "jackknife", note = lay$note)) + } + if (lay$certain) return(all_certain("jackknife")) + + base <- y / pi_i + v <- 0 + for (g in lay$groups) { + if (g$m < 2L) next + # Each unit's total in the stratum. The replicates are symmetric in the + # units, so their order does not matter. Deleting a unit moves only its + # stratum's total, so the rest of the sample adds the same amount to + # every replicate and is left out of the deviations. + sums <- rowsum(base[g$rows], g$psu, reorder = FALSE)[, 1L] + reps <- (sum(sums) - sums) * g$m / (g$m - 1) + v <- v + g$fpc * (g$m - 1) / g$m * sum((reps - mean(reps))^2) + } + if (!is.finite(v)) { + return(list(variance = NA_real_, method = "jackknife", + note = overflow_note())) + } + list(variance = v, method = "jackknife", + note = paste0("Jackknife over ", lay$n_psu, + " primary sampling unit(s)", + if (lay$n_strata > 1L) { + paste0(" in ", lay$n_strata, " strata") + } else "", + if (lay$corrected) ", with a finite population correction" + else "", + if (lay$n_fixed + lay$n_above > 0L) { + one <- lay$n_fixed + lay$n_above == 1L + paste0("; ", held_fixed(lay$n_fixed, lay$n_above), + if (one) " adds no variance and was held fixed" + else " add no variance and were held fixed") + }, ".")) +} + +#' The units the jackknife held fixed, in words +#' +#' `n_fixed` counts the units the design took with certainty, and `n_above` +#' the rows above a certainty design's threshold, which are counted apart +#' because the units of `rest` can be clusters. The phrase is the subject of +#' a verb that the caller makes singular when the two add up to 1. +#' +#' @noRd +held_fixed <- function(n_fixed, n_above = 0L) { + if (n_above == 0L) return(paste0("the ", n_fixed, " taken with certainty")) + above <- paste0("the ", n_above, if (n_above == 1L) " row" else " rows", + " at or above the threshold") + if (n_fixed == 0L) return(above) + paste0(above, " and the ", n_fixed, " unit(s) `rest` took with certainty") +} + +#' What the jackknife deletes, and from which strata +#' +#' The units and strata of `jackknife_variance()`, shared with +#' `replicate_weights()`, which turns them into replicate weights. Returns +#' `note`, the reason the jackknife declines, or `certain = TRUE` when every +#' sampled unit was taken with certainty. Otherwise `groups` has one element +#' per stratum holding a unit that is not fixed: the positions in the sample +#' of its free rows (`rows`), the unit of each (`psu`), the number of units +#' (`m`) and the stratum's finite population correction (`fpc`). `n_psu`, +#' `n_strata`, `n_fixed`, `n_above` and `corrected` are what the note on +#' the result reports. +#' +#' For a certainty design the rows at or above the threshold are in every +#' sample, so the layout is `rest`'s, over the rows below the threshold, +#' with `rows` counted in the whole sample. Those rows are found from the +#' frame's copy of the sampled rows, which holds the `above` column. Rows +#' that `rest` itself takes with certainty go along and are held fixed +#' there, so its finite population correction counts them correctly. +#' `n_above` counts the rows at or above the threshold, so the note names +#' every unit held fixed. +#' +#' @noRd +jackknife_layout <- function(design, units, pop, pi_i, domain = NULL, + ctx = NULL, n_above = 0L) { + refusal <- jackknife_refusal(design) + if (!is.null(refusal)) return(list(note = refusal)) + if (inherits(design, "drawn_design_certainty")) { + sp <- certainty_parts(design, pop, ctx) + v <- units[[design$above]] + below <- !is.na(v) & v < design$threshold + if (!any(below)) { + if (length(sp$rest)) { + return(list(note = empty_rest(design, length(sp$rest))$note)) + } + return(list(certain = TRUE)) + } + lay <- jackknife_layout(design$rest, units[below, , drop = FALSE], + sp$rest_data, pi_i[below], rest_domain(domain, sp), + sub_context(ctx, "rest"), + n_above = n_above + sum(!below)) + if (!is.null(lay$groups)) { + at <- which(below) + lay$groups <- lapply(lay$groups, function(g) { + g$rows <- at[g$rows] + g + }) + } + return(lay) + } + + psu <- from_context(ctx, "psu", jackknife_groups(design, units, pop, ctx)) + fixed <- !(psu %in% psu[!is_certain(pi_i)]) + if (all(fixed)) return(list(certain = TRUE)) + n_fixed <- length(unique(psu[fixed])) + + st <- jackknife_strata(design, units, pop, psu, fixed, domain, ctx) + free <- which(!fixed) + by_stratum <- split(free, factor(match(st$stratum[free], st$levels), + levels = seq_along(st$levels))) + groups <- lapply(seq_along(st$levels), function(k) { + in_h <- by_stratum[[k]] + list(rows = in_h, psu = psu[in_h], m = length(unique(psu[in_h])), + fpc = st$fpc[k]) + }) + m <- vapply(groups, function(g) g$m, integer(1)) + out <- list(certain = FALSE, groups = groups, n_psu = sum(m), + n_strata = length(st$levels), n_fixed = n_fixed, + n_above = n_above, corrected = any(st$fpc < 1)) + + if (out$n_strata == 1L && out$n_psu < 2L) { + out$note <- paste0("The jackknife needs at least two primary sampling ", + "units; this sample has ", out$n_psu, + if (n_fixed + n_above > 0L) { + paste0(" besides ", held_fixed(n_fixed, n_above), + ". Draw more units below certainty") + }, ".") + return(out) + } + # A stratum with one unit cannot be deleted from, unless it was sampled + # whole or holds none of the domain. + lonely <- which(m < 2L & st$fpc > 0 & st$in_domain) + if (!length(lonely)) return(out) + if (!is.null(st$between) && st$between %in% st$levels[lonely]) { + out$note <- paste0("The jackknife needs at least two clusters below ", + "certainty; this sample has one.") + return(out) + } + noun <- if (inherits(design, "drawn_design_temporal")) { + c("interval", "intervals") + } else if (!is.null(st$between)) { + c("cluster taken with certainty", "clusters taken with certainty") + } else { + c("stratum", "strata") + } + lonely <- lonely[order(st$levels[lonely])] + out$note <- lonely_text(st$labels[lonely], noun, lonely_fix(design), + identical(domain, NA) || !any(st$sure[lonely])) + out +} + +#' Designs the jackknife should decline rather than approximate #' #' @noRd jackknife_refusal <- function(design) { + if (replicated(design)) { + return(paste0("A systematic sample with several starts has the starts as ", + "its primary sampling units, not the rows, so deleting ", + "rows does not reflect the design's randomness and the ", + "jackknife is not valid here. variance = \"analytic\" ", + "gives the exact variance between the replicates.")) + } if (inherits(design, "drawn_design_systematic")) { return(paste0("A systematic sample has one primary sampling unit -- the ", "random start -- so deleting rows does not reflect the ", "design's randomness and the jackknife is not valid here.")) } + if (walks_strata(design)) { + return(paste0("Each stratum of a systematic sample within strata has one ", + "random start, so deleting rows does not reflect the ", + "design's randomness and the jackknife is not valid here.")) + } if (inherits(design, "drawn_design_weighted") && design$method == "poisson") { return(paste0("Poisson sampling selects rows independently and has an ", "exact variance, sum((1 - pi) / pi^2 * y^2). Deleting rows ", @@ -607,34 +2496,116 @@ jackknife_refusal <- function(design) { #' Strata for the jackknife, and each stratum's finite population correction #' -#' Stratified and temporal designs delete within strata, with each stratum's -#' own `1 - n_h / N_h`. Everything else is a single stratum, corrected by -#' `jackknife_fpc()`. -#' -#' @noRd -jackknife_strata <- function(design, sample, pop, psu) { - grp <- switch(design_type(design), - stratified = list( - sample = as.character(group_key(sample, design$strata)), - pop = as.character(group_key(pop, design$strata)) - ), - temporal = list( - sample = temporal_bucket(design, sample), - pop = temporal_bucket(design, pop) - ), +#' Stratified and temporal designs, and spread and weighted designs with +#' `strata`, delete within strata, with each stratum's own `1 - n_h / N_h`. +#' The strata of a spread or weighted design count only the rows it can +#' draw. Everything else is a single stratum, corrected by +#' `jackknife_fpc()`. Only strata holding a unit that is not `fixed` are +#' listed, and both counts leave the fixed units out. A unit taken with +#' certainty is in every sample, so the fixed units in the frame are the +#' ones in the sample. A stratum taken whole drops out. +#' +#' A multistage design with `size` deletes clusters below certainty in one +#' stratum, `between`, with no correction, and the rows of each cluster +#' taken with certainty within a stratum of its own, as `cluster_units()` +#' lays them out. +#' +#' Returns each row's `stratum`, the `levels` listed, their `labels`, `fpc`, +#' `in_domain` and `sure`, in the same order, and `between`. The levels are +#' integer codes in key order, and the labels the key's levels, as the +#' analytic estimators name the same strata and intervals. `in_domain` is +#' `FALSE` for a stratum that `domain`, a logical vector over the frame, +#' shows to hold no unit of the domain, and `TRUE` otherwise. `sure` is +#' `TRUE` for a stratum with a frame row known to be in the domain, rather +#' than one only the frame cannot place. +#' +#' @noRd +jackknife_strata <- function(design, units, pop, psu, fixed, domain = NULL, + ctx = NULL) { + # Integer codes, shared by the sampled rows and the frame. + grp <- from_context(ctx, "strata", switch(design_type(design), + stratified = , + spread = , + weighted = if (!is.null(design$strata)) { + key <- group_key2(units, pop, design$strata) + pop_code <- as.integer(key$table) + # Rows the design drops have no stratum to count in. + keep <- switch(design_type(design), + spread = from_context(ctx, "spread", spread_frame(design, pop))$keep, + weighted = from_context(ctx, "weighted", + weighted_setup(design, pop))$keep, + NULL + ) + if (!is.null(keep)) { + out <- rep(TRUE, nrow(pop)) + out[keep] <- FALSE + pop_code[out] <- NA_integer_ + } + list(sample = as.integer(key$x), pop = pop_code, + labels = levels(key$x)) + }, + multistage = if (!is.null(design$size)) { + # Clusters below certainty share stratum 1, with no finite population + # correction, as for any multistage design; each cluster taken with + # certainty is a stratum of its own, of rows drawn without replacement. + cu <- cluster_units(design, units, pop, ctx) + st <- from_context(ctx, "stage_one", cluster_stage(design, pop)) + first <- match(seq_along(st$pi1), st$code) + list(sample = cu$stratum, pop = cu$pop_stratum, + labels = c("(below certainty)", + as.character(pop[[design$clusters]][first])), + between = 1L) + }, + temporal = { + # Keyed as srs_groups() keys the intervals, so the two name them alike. + key <- key_from_columns(list(c(temporal_bucket(design, units), + temporal_bucket(design, pop)))) + code <- as.integer(key) + list(sample = code[seq_len(nrow(units))], + pop = code[nrow(units) + seq_len(nrow(pop))], + labels = levels(key)) + }, NULL - ) + )) if (is.null(grp)) { - m <- length(unique(psu)) - return(list(stratum = rep("all", nrow(sample)), - fpc = list(all = jackknife_fpc(design, pop, m)))) - } - N_h <- table(grp$pop[!is.na(grp$pop)]) - n_h <- table(grp$sample) - fpc <- lapply(stats::setNames(names(n_h), names(n_h)), function(h) { - max(0, 1 - n_h[[h]] / N_h[[h]]) - }) - list(stratum = grp$sample, fpc = fpc) + m <- length(unique(psu[!fixed])) + n_fixed <- length(unique(psu[fixed])) + return(list(stratum = rep("all", nrow(units)), levels = "all", + labels = "all", + fpc = jackknife_fpc(design, pop, m, n_fixed, ctx), + in_domain = TRUE, sure = TRUE)) + } + # The same for every domain of a sample, so `ctx` keeps it and a table of + # many domains reads the frame once. + frame <- from_context(ctx, "jackknife_frame", jackknife_frame(grp, fixed)) + lev <- frame$lev + n_h <- tabulate(match(grp$sample[!fixed], lev), length(lev)) + free_h <- frame$N_h - tabulate(match(grp$sample[fixed], lev), length(lev)) + in_domain <- sure <- rep(TRUE, length(lev)) + if (known_domain(domain, length(grp$pop))) { + hold <- domain_groups(frame$code, domain, length(lev)) + in_domain <- hold$maybe + sure <- hold$sure + } + fpc <- ifelse(free_h > n_h, 1 - n_h / free_h, 0) + if (!is.null(grp$between)) fpc[lev == grp$between] <- 1 + list(stratum = grp$sample, levels = lev, labels = grp$labels[lev], + fpc = fpc, in_domain = in_domain, sure = sure, + between = grp$between) +} + +#' The jackknife's strata over the frame +#' +#' `lev` lists the strata of `grp`, as `jackknife_strata()` builds it, that +#' hold a sampled unit not `fixed`. Returns `lev`, each frame row's stratum +#' as a position in it (`code`, `NA` for a row in none of them), and each +#' stratum's rows in the frame (`N_h`). +#' +#' @noRd +jackknife_frame <- function(grp, fixed) { + lev <- unique(grp$sample[!fixed]) + code <- match(grp$pop, lev) + list(lev = lev, code = code, N_h = tabulate(code, length(lev))) } #' The share of primary sampling units NOT taken @@ -647,46 +2618,397 @@ jackknife_strata <- function(design, sample, pop, psu) { #' where the uncorrected one runs from 0.98 to 1.77, overstating badly once the #' sampling fraction gets large. #' -#' Deliberately not applied to multi-stage designs: -#' the delete-a-cluster jackknife sees only between-cluster variation, so the -#' second stage is already missing, and correcting for the first stage on top of -#' that understates the total. Leaving it out is the ultimate-cluster -#' approximation, which errs conservative -- the usual choice in survey practice. -#' -#' @noRd -jackknife_fpc <- function(design, pop, m) { - if (inherits(design, "drawn_design_multistage")) return(1) - total <- tryCatch({ - if (inherits(design, "drawn_design_cluster")) { - count_clusters(design, pop)$total - } else if (inherits(design, "drawn_design_reservoir")) { - reservoir_reach(design, nrow(pop)) - } else if (inherits(design, "drawn_design_spatial")) { - sum(spatial_inside(design, pop)) - } else { - nrow(pop) +#' `m` counts the sampled units that were not certain, and `n_fixed` the +#' certain ones, which come off the frame's count. A census therefore gets 0. +#' Without a finite count of units in the frame there is nothing to correct +#' by, and the correction is 1. +#' +#' Not applied to multi-stage designs, or to balanced cluster sampling, which +#' subsamples its clusters too. Each estimated cluster total carries +#' the second stage's variance as well as the first's, and multiplying by the +#' first-stage correction `1 - f1`, with `f1 = n_clusters / A`, would scale +#' both, understating by `f1` times the within-cluster component. Leaving it +#' out, the ultimate-cluster approximation usual in survey practice, overstates +#' by `f1` times the between-cluster component instead, which errs on the +#' side of a wider interval. +#' +#' @noRd +jackknife_fpc <- function(design, pop, m, n_fixed = 0L, ctx = NULL) { + if (inherits(design, "drawn_design_multistage") || + (inherits(design, "drawn_design_cluster") && design$balanced)) { + return(1) + } + total <- if (inherits(design, "drawn_design_cluster")) { + from_context(ctx, "clusters", count_clusters(design, pop))$total + } else { + from_context(ctx, "reachable", reachable_rows(design, pop)) + } + if (!is.finite(total)) return(1) + free <- total - n_fixed + if (free <= m) return(0) + 1 - m / free +} + +#' Rows of the frame a design can select +#' +#' The population a finite population correction counts. Rows a design drops, +#' through `na_rm`, past `max_items`, outside its region or window, or because +#' use_reserves() found them unavailable, have probability 0 and are not part +#' of it; counting them put the correction +#' for a systematic or PPS design with `na_rm` too close to 1. The count is +#' read from the design's own columns, so it needs no inclusion probabilities +#' and is defined for a design without a closed form, such as +#' `design_weighted(method = "successive")`. A stratum allocated no rows is +#' not seen here; `sum(pi > 0)` over the draw-time probabilities counts those +#' out too, where a sample stores them. +#' +#' @noRd +reachable_rows <- function(design, pop) { + n <- nrow(pop) + keyed <- function(cols) { + sum(!Reduce(`|`, lapply(cols, function(col) is.na(pop[[col]])))) + } + switch(design_type(design), + simple = length(available_rows(design, n)), + reservoir = reservoir_reach(design, n), + spatial = sum(spatial_inside(design, pop)), + temporal = sum(!is.na(temporal_bucket(design, pop))), + systematic = sum(!is.na(systematic_positions(design, pop))), + weighted = keyed(c(design$weights, design$strata)), + spread = { + bad <- spread_missing( + coordinate_columns(pop, design$across, "across", time = TRUE), + if (!is.null(design$size)) pop[[design$size]]) + if (!is.null(design$strata)) { + bad <- bad | is.na(group_key(pop, design$strata)) + } + sum(!bad[available_rows(design, n)]) + }, + stratified = keyed(c(design$strata, design$within$order_by)), + cluster = , + multistage = keyed(c(design$clusters, design$size)), + certainty = { + sp <- certainty_split(design, pop) + length(sp$take) + + reachable_rows(design$rest, sp$data[sp$rest, , drop = FALSE]) + }, + n + ) +} + +#' Primary sampling units for the jackknife +#' +#' Whole clusters for a cluster or multistage design, read from the frame's +#' copy of the sampled rows, which always has the cluster column, as integer +#' codes; otherwise each row is its own unit. A multistage design with +#' `size` reads which clusters were taken with certainty from the frame +#' `pop`, and makes each of their sampled rows a unit, as `cluster_units()` +#' does. +#' +#' @noRd +jackknife_groups <- function(design, units, pop = NULL, ctx = NULL) { + if (inherits(design, "drawn_design_multistage") && !is.null(design$size)) { + return(cluster_units(design, units, pop, ctx)$psu) + } + if (inherits(design, c("drawn_design_cluster", "drawn_design_multistage"))) { + return(cluster_codes(units[[design$clusters]])) + } + seq_len(nrow(units)) +} + +# ---- replicate weights ------------------------------------------------------ + +#' Replicate factors for the rows of a sample +#' +#' Each column holds one replicate's factor for every sampled row, which +#' `replicate_weights()` multiplies into the row's weight. The replicate +#' totals `t_r` average the sample's total `t`, and +#' `scale * sum(rscales * (t_r - t)^2)` is the variance [ht_total()] gives +#' for `t`: +#' +#' * the jackknife of `jackknife_layout()`, one replicate per unit, which +#' sets the unit's rows to 0 and the other free rows of its stratum to +#' `m / (m - 1)`, with `rscales` each stratum's `fpc * (m - 1) / m`; +#' * for a systematic sample with one start, and for strata walked in +#' order, which the jackknife declines, successive-difference replicates +#' in walk order (`successive_factors()`); +#' * for a systematic sample with several starts, the jackknife over the +#' starts, whose variance is the random group variance of +#' `replicate_variance()`. +#' +#' Rows above a certainty design's threshold keep a factor of 1 in every +#' replicate. A sample whose every row is certain gets one replicate equal +#' to the sample, with a variance of 0. Returns `note` in place of +#' `factors` when there are no replicates to give. +#' +#' @noRd +replicate_factors <- function(design, units, pop, rows, pi_i, type, + ctx = NULL) { + n <- length(rows) + if (inherits(design, "drawn_design_certainty")) { + sp <- certainty_parts(design, pop, ctx) + free <- !(rows %in% sp$keep[sp$take]) + if (!any(free)) { + if (length(sp$rest)) { + return(list(note = empty_rest(design, length(sp$rest))$note)) + } + return(census_factors(n, type)) } - }, error = function(e) NA_real_) - if (!is.finite(total) || total <= m) return(1) - 1 - m / total + rest <- replicate_factors(design$rest, units[free, , drop = FALSE], + sp$rest_data, + match(rows[free], sp$keep[sp$rest]), + pi_i[free], type, sub_context(ctx, "rest")) + if (is.null(rest$factors)) return(rest) + f <- matrix(1, n, ncol(rest$factors)) + f[free, ] <- rest$factors + rest$factors <- f + return(rest) + } + if (all(is_certain(pi_i))) return(census_factors(n, type)) + if (inherits(design, "drawn_design_systematic")) { + refuse_fixed_start(design) + walk <- from_context(ctx, "walk", systematic_positions(design, pop)) + if (replicated(design)) return(start_factors(design, walk, rows, type)) + return(walk_factors(design, walk, rows)) + } + if (walks_strata(design)) { + return(strata_walk_factors(design, pop, rows, ctx)) + } + if (inherits(design, "drawn_design_weighted") && design$method == "poisson") { + return(list(note = paste0( + "Poisson sampling selects rows independently, so its sample size is ", + "random, and deleting rows from such a sample understates its ", + "variance. Estimate with ht_total() or ht_mean(), or hand the sample ", + "to `survey` with as_svydesign(), which models Poisson sampling."))) + } + lay <- jackknife_layout(design, units, pop, pi_i, ctx = ctx) + if (!is.null(lay$note)) return(list(note = lay$note)) + if (lay$certain) return(census_factors(n, type)) + jackknife_factors(lay, n, type) } +#' One replicate equal to the sample, for a sample with no variance #' @noRd -jackknife_groups <- function(design, sample) { - col <- if (inherits(design, c("drawn_design_cluster", - "drawn_design_multistage"))) { - design$clusters - } else { - NULL # rows are the sampling units +census_factors <- function(n, type) { + list(factors = matrix(1, n, 1L), scale = 1, rscales = 1, type = type) +} + +#' Delete-a-unit replicates from a jackknife layout +#' +#' `"JK1"` deletes across the whole sample, so it is given only for a +#' jackknife with one stratum, where it is the same replicates as `"JKn"` +#' with the correction in `scale`. +#' +#' @noRd +jackknife_factors <- function(lay, n, type) { + if (type == "JK1" && lay$n_strata > 1L) { + return(list(note = paste0( + "`type = \"JK1\"` deletes units across the whole sample, but this ", + "sample's jackknife has ", lay$n_strata, " strata, and deleting ", + "across them counts the differences between strata as sampling ", + "variance. Use `type = \"JKn\"`, which deletes within them."))) } - if (!is.null(col) && col %in% names(sample)) { - as.character(sample[[col]]) - } else { - as.character(seq_len(nrow(sample))) + groups <- Filter(function(g) g$m >= 2L, lay$groups) + R <- sum(vapply(groups, function(g) g$m, integer(1))) + # Every stratum with free units was sampled whole, so nothing varies. + if (R == 0L) return(census_factors(n, type)) + check_replicate_size(n, R) + f <- matrix(1, n, R) + rscales <- numeric(R) + at <- 0L + for (g in groups) { + cols <- at + seq_len(g$m) + f[g$rows, cols] <- g$m / (g$m - 1) + f[cbind(g$rows, at + match(g$psu, unique(g$psu)))] <- 0 + rscales[cols] <- g$fpc * (g$m - 1) / g$m + at <- at + g$m + } + jackknife_form(f, rscales, type) +} + +#' Replicate factors with their `scale` and `rscales`, as JKn or JK1 +#' +#' JKn keeps each replicate's correction in `rscales`; JK1, which has one +#' correction for every replicate, keeps it in `scale`. +#' +#' @noRd +jackknife_form <- function(f, rscales, type) { + if (type == "JK1") { + return(list(factors = f, scale = rscales[1L], + rscales = rep(1, length(rscales)), type = "JK1")) } + list(factors = f, scale = 1, rscales = rscales, type = "JKn") +} + +#' The jackknife over the starts of a replicated systematic sample +#' +#' Deleting start `r` sets its rows to 0 and the others to `m / (m - 1)`, +#' and a start that drew no rows still has its replicate, which scales +#' every row. With the correction `1 - 1 / interval`, the variance is +#' `replicate_variance()`'s `(1 - 1 / interval) * var(t_r) / m`. +#' +#' @noRd +start_factors <- function(design, walk, rows, type) { + m <- systematic_starts(design) + n <- length(rows) + check_replicate_size(n, m) + id <- systematic_replicates(design, walk, rows) + f <- matrix(m / (m - 1), n, m) + f[cbind(seq_len(n), match(id, unique(id)))] <- 0 + jackknife_form(f, rep((1 - 1 / design$interval) * (m - 1) / m, m), type) +} + +#' Successive-difference replicates for a systematic sample +#' +#' The variance is that of `ht_variance.drawn_design_systematic()`, the +#' term for a random sample size included. +#' +#' @noRd +walk_factors <- function(design, walk, rows) { + n <- length(rows) + if (n < 2L) { + return(list(note = "A variance needs at least two sampled rows.")) + } + step <- walk_step(design, sum(!is.na(walk))) + k <- step$k + r <- step$r + successive_factors(list(list(at = order(walk[rows]), + c = (1 - 1 / k) * n / (n - 1), + e = (r / k) * (1 - r / k))), n) +} + +#' Successive-difference replicates for strata walked in order +#' +#' The variance is that of `walk_strata_variance()`, each stratum's +#' successive differences at its own sampling fraction, and a stratum with +#' one sampled row of several is refused in the same words. +#' +#' @noRd +strata_walk_factors <- function(design, data, rows, ctx = NULL) { + g <- srs_groups(design, data, ctx) + group <- structure(g$code, levels = g$labels, class = "factor") + note <- lonely_note(group, rows, c("stratum", "strata"), lonely_fix(design)) + if (!is.null(note)) return(list(note = note)) + k <- length(g$N_g) + pos <- from_context(ctx, "walk", walk_positions(design, data, g$code, k)) + h <- g$code[rows] + o <- order(h, pos[rows]) + f <- as.numeric(g$n_g) / as.numeric(g$N_g) + walks <- lapply(seq_len(k), function(s) { + at <- o[which(h[o] == s)] + m <- length(at) + list(at = at, c = if (m >= 2L) (1 - f[s]) * m / (m - 1) else 0, e = 0) + }) + successive_factors(walks, length(rows)) +} + +#' Successive-difference replicate factors over one or more walks +#' +#' Each element of `walks` holds the positions in the sample of a walk's +#' rows, in walk order (`at`), the coefficient `c` of half the sum of its +#' squared successive differences of `u = y / pi`, and the coefficient `e` +#' of `mean(u)^2`, the term for a random sample size. The variance of the +#' replicates is the sum over walks of +#' `c / 2 * sum(diff(u)^2) + e * mean(u)^2`. +#' +#' Each pair of neighbours in a walk gets its own row `a` of a Sylvester +#' Hadamard matrix of order `R`, and the `i`-th row of a walk of `m` gets +#' `1 + b * (a_i - a_(i - 1))`, with `a_0` and `a_m` zero and +#' `b = sqrt(c / 8)`. A replicate total then moves by +#' `b * sum(a_i * (u_i - u_(i + 1)))`, and since the rows of the matrix +#' are orthogonal and, past the first, sum to 0, `4 / R` times the sum of +#' squared moves over the `R` replicates is `c / 2 * sum(diff(u)^2)`, and +#' the replicates average the sample's total. The first and last rows of a +#' walk are not paired with each other. The circular form, which pairs +#' them, adds their squared difference, which is large on a frame sorted on +#' something related to `y`. One more row of the matrix moves every row of +#' a walk by `sqrt(e) / (2 * m)` for the random size. Every factor stays +#' above 0, because `c` is below 2 and `e` at most `1 / 4`. +#' +#' The factors are filled in blocks of about a million entries, so the +#' memory beyond the result stays a few blocks whatever the sample size. +#' +#' @noRd +successive_factors <- function(walks, n) { + pairs <- vapply(walks, function(w) { + if (length(w$at) >= 2L && w$c > 0) length(w$at) - 1L else 0L + }, integer(1)) + sized <- vapply(walks, function(w) w$e > 0, logical(1)) + R <- 2^ceiling(log2(sum(pairs) + sum(sized) + 1)) + check_replicate_size(n, R) + # Row 1 of the matrix, all ones, is left unused. Each walk takes the + # next rows for its pairs, then one for its random size. + before <- 1L + cumsum(c(0L, (pairs + sized)[-length(walks)])) + f <- matrix(1, n, R) + width <- max(1L, 2^20 %/% max(n, 1L)) + for (from in seq(1L, R, by = width)) { + cols <- from:min(R, from + width - 1L) + for (i in seq_along(walks)) { + w <- walks[[i]] + if (pairs[i] > 0L) { + a <- hadamard_entries(before[i] + seq_len(pairs[i]), cols) + d <- rbind(a, 0) + d[-1L, ] <- d[-1L, ] - a + f[w$at, cols] <- f[w$at, cols] + sqrt(w$c / 8) * d + } + if (sized[i]) { + m <- length(w$at) + h <- hadamard_entries(before[i] + pairs[i] + 1L, cols) + f[w$at, cols] <- f[w$at, cols] + outer(rep(sqrt(w$e) / (2 * m), m), + h[1L, ]) + } + } + } + list(factors = f, scale = 4 / R, rscales = rep(1, R), type = "other") +} + +#' Entries of a Sylvester Hadamard matrix +#' +#' The entry in row `i` and column `j` is `-1` to the number of bits set in +#' both `i - 1` and `j - 1`. Only the rows `k` and columns `cols` asked +#' for are built, as a matrix, with the parity of each 16 bits looked up. +#' +#' @noRd +hadamard_entries <- function(k, cols) { + x <- outer(as.integer(k) - 1L, as.integer(cols) - 1L, bitwAnd) + odd <- bitwXor(bit_parity[bitwAnd(x, 65535L) + 1L], + bit_parity[bitwShiftR(x, 16L) + 1L]) + matrix(1 - 2 * odd, nrow = length(k)) +} + +#' The parity of the bits of 0 to 65535 +#' +#' Each doubling appends the complement of the parities so far, since +#' setting one more bit flips the parity. +#' +#' @noRd +bit_parity <- local({ + p <- 0L + for (i in seq_len(16L)) p <- c(p, 1L - p) + p +}) + +#' Refuse replicate weights too large to hold in memory +#' @noRd +check_replicate_size <- function(n, R) { + bytes <- 8 * as.numeric(n) * R + if (bytes <= pair_limit()) return(invisible(NULL)) + stop("replicate_weights() would build ", format(R, big.mark = ","), + " replicates of the ", format(n, big.mark = ","), " sampled rows, ", + "which needs about ", format_gb(bytes), " of memory. Estimate with ", + "ht_total() or ht_mean(), or hand the sample to `survey` with ", + "as_svydesign().", call. = FALSE) } #' @export print.drawn_ht <- function(x, ...) { - print_estimate(x, "total", "Horvitz-Thompson total") + if (is.null(x$x)) { + return(print_estimate(x, "total", "Horvitz-Thompson total")) + } + print_estimate(x, "total", "Ratio estimate of the total", lines = c( + ratio = paste0(format(x$ratio), ", ", ratio_name(x$variable, "y"), " / `", + x$x, "` in the sample"), + `x total` = paste0(format(x$frame_total, big.mark = ","), ", `", x$x, + "` over the frame") + )) } diff --git a/README.Rmd b/README.Rmd index ac2d40e..9380c58 100644 --- a/README.Rmd +++ b/README.Rmd @@ -90,7 +90,7 @@ tapply(inclusion_prob(invoices, plan), invoices$site, unique) ``` **3. Draw,** with `weights = TRUE` to attach each row's inclusion probability -(`.prob`) and design weight (`.weight`). +(`.prob`), design weight (`.weight`) and frame row (`.row`). **4. Check what you got.** @@ -98,9 +98,9 @@ tapply(inclusion_prob(invoices, plan), invoices$site, unique) sample_summary(s) ``` -**5. Estimate** a total, a mean or a proportion, overall or by domain. Domain -estimates use the whole sample, not a subset of it, which is what keeps their -standard errors right: +**5. Estimate** a total, a mean, a proportion or a quantile, overall or by +domain. Domain estimates use the whole sample, not a subset of it, which is +what keeps their standard errors right: ```{r estimate} ht_mean(s, "value", by = "site") @@ -110,28 +110,32 @@ ht_mean(s, "value", by = "site") ```r des <- as_svydesign(s) # a survey.design, with matching SEs -survey::svyquantile(~value, des, 0.5) +survey::svyglm(value ~ site, des) ``` ## The designs -| Design | Selects | Size | Variance estimator | +| Design | Selects | Size | Variance `method` | |---|---|---|---| -| `design_simple()` | rows uniformly at random | `n` | exact | -| `design_stratified()` | a share of each stratum: proportional, equal or Neyman | `n` total | exact | -| `design_systematic()` | every *k*-th row from a random start | `interval` | successive-difference approx. | -| `design_cluster()` | whole clusters | `n_clusters` | exact | -| `design_multistage()` | clusters, then rows within them | `n_clusters`, `n` | exact two-stage | -| `design_weighted()` | probability proportional to size | `n` | exact (Poisson), Deville (systematic) | -| `design_certainty()` | everything above a threshold, plus any design below it | `rest`'s own | `rest`'s own | -| `design_spread()` | a sample spread evenly over a map or covariates | `n` | local-mean approx. | -| `design_temporal()` | a fixed number per time interval | `per_interval` | exact | -| `design_spatial()` | a simple random sample inside a region | `n` | exact | -| `design_reservoir()` | a fixed-size sample from a stream, in one pass | `n` | exact | -| `design_bootstrap()` | resampled replicates, simple or block | `n_replicates` | not a survey design | - -Every estimate says which estimator produced its variance, and any -approximation is named when it prints. +| `design_simple()` | rows uniformly at random | `n` | analytic | +| `design_stratified()` | a share of each stratum: proportional, equal or Neyman, at random or with `within` systematically | `n` total | analytic; successive difference (an approximation) with `within` | +| `design_systematic()` | every *k*-th row from one or several random starts, or `n` rows at an even step | `interval` or `n` | successive difference (an approximation); analytic with `n_starts` | +| `design_cluster()` | whole clusters | `n_clusters` | analytic | +| `design_multistage()` | clusters, at random or in proportion to size, then rows within them | `n_clusters`, `n` | analytic, two-stage; deville (an approximation) for the clusters with `size` | +| `design_weighted()` | probability proportional to size, within strata if asked | `n` total | analytic (Poisson); deville (an approximation) for systematic, summed over strata | +| `design_certainty()` | everything above a threshold, plus any design below it | rows above the threshold + `rest`'s | `rest`'s own | +| `design_spread()` | a sample spread evenly over a map or covariates | `n` | local mean (an approximation) | +| `design_temporal()` | a fixed number per time interval | `per_interval` | analytic | +| `design_spatial()` | a simple random sample inside a region | `n` | analytic | +| `design_reservoir()` | a fixed-size sample from a stream, in one pass | `n` | analytic | +| `design_bootstrap()` | resampled replicates of rows (simple) or of runs of rows (block or circular) | `n_replicates` | not a survey design | + +Every estimate says in `method` which estimator produced its variance, under +the names in this table, which are also the ones a printed estimate and the +`method` column of a `by` table show. An approximation is called one when it +prints. Under the default `variance = "auto"`, the jackknife takes over +where the design's own estimator declines, and `method` then says +`jackknife`. ## Spread the sample, not just the rows @@ -148,7 +152,7 @@ plots$biomass <- 100 + 80 * plots$x + 60 * sin(4 * plots$y) + rnorm(400, 0, 10) op <- par(mfrow = c(1, 2)) plot(design_simple(n = 40), plots, type = "map", coords = c("x", "y"), seed = 3, - main = "simple random") + main = "simple random", asp = 1) plot(design_spread(c("x", "y"), n = 40, scale = FALSE), plots, type = "map", seed = 3, main = "spread (local pivotal method)") par(op) diff --git a/README.md b/README.md index 598a8eb..bb73628 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ tapply(inclusion_prob(invoices, plan), invoices$site, unique) ``` **3. Draw,** with `weights = TRUE` to attach each row’s inclusion -probability (`.prob`) and design weight (`.weight`). +probability (`.prob`), design weight (`.weight`) and frame row (`.row`). **4. Check what you got.** @@ -103,6 +103,8 @@ sample_summary(s) #> Sample of 60 from 600 (stratified design) #> sampling fraction 0.1 #> design weights 10 to 10 (cv 0) +#> effective n 60 (Kish, from the weights alone) +#> drawn with seed 1, by drawn 0.2.0.9000 on 2026-11-16 #> #> by site: #> group drawn in frame rate @@ -112,9 +114,9 @@ sample_summary(s) #> west 3 30 0.100 ``` -**5. Estimate** a total, a mean or a proportion, overall or by domain. -Domain estimates use the whole sample, not a subset of it, which is what -keeps their standard errors right: +**5. Estimate** a total, a mean, a proportion or a quantile, overall or +by domain. Domain estimates use the whole sample, not a subset of it, +which is what keeps their standard errors right: ``` r ht_mean(s, "value", by = "site") @@ -130,28 +132,32 @@ ht_mean(s, "value", by = "site") ``` r des <- as_svydesign(s) # a survey.design, with matching SEs -survey::svyquantile(~value, des, 0.5) +survey::svyglm(value ~ site, des) ``` ## The designs -| Design | Selects | Size | Variance estimator | -|-----------------------|--------------------------------------------------------|-------------------|---------------------------------------| -| `design_simple()` | rows uniformly at random | `n` | exact | -| `design_stratified()` | a share of each stratum: proportional, equal or Neyman | `n` total | exact | -| `design_systematic()` | every *k*-th row from a random start | `interval` | successive-difference approx. | -| `design_cluster()` | whole clusters | `n_clusters` | exact | -| `design_multistage()` | clusters, then rows within them | `n_clusters`, `n` | exact two-stage | -| `design_weighted()` | probability proportional to size | `n` | exact (Poisson), Deville (systematic) | -| `design_certainty()` | everything above a threshold, plus any design below it | `rest`’s own | `rest`’s own | -| `design_spread()` | a sample spread evenly over a map or covariates | `n` | local-mean approx. | -| `design_temporal()` | a fixed number per time interval | `per_interval` | exact | -| `design_spatial()` | a simple random sample inside a region | `n` | exact | -| `design_reservoir()` | a fixed-size sample from a stream, in one pass | `n` | exact | -| `design_bootstrap()` | resampled replicates, simple or block | `n_replicates` | not a survey design | - -Every estimate says which estimator produced its variance, and any -approximation is named when it prints. +| Design | Selects | Size | Variance `method` | +|-----------------------|---------------------------------------------------------------------------------------------------|-------------------------------------|-----------------------------------------------------------------------------------| +| `design_simple()` | rows uniformly at random | `n` | analytic | +| `design_stratified()` | a share of each stratum: proportional, equal or Neyman, at random or with `within` systematically | `n` total | analytic; successive difference (an approximation) with `within` | +| `design_systematic()` | every *k*-th row from one or several random starts, or `n` rows at an even step | `interval` or `n` | successive difference (an approximation); analytic with `n_starts` | +| `design_cluster()` | whole clusters | `n_clusters` | analytic | +| `design_multistage()` | clusters, at random or in proportion to size, then rows within them | `n_clusters`, `n` | analytic, two-stage; deville (an approximation) for the clusters with `size` | +| `design_weighted()` | probability proportional to size, within strata if asked | `n` total | analytic (Poisson); deville (an approximation) for systematic, summed over strata | +| `design_certainty()` | everything above a threshold, plus any design below it | rows above the threshold + `rest`’s | `rest`’s own | +| `design_spread()` | a sample spread evenly over a map or covariates | `n` | local mean (an approximation) | +| `design_temporal()` | a fixed number per time interval | `per_interval` | analytic | +| `design_spatial()` | a simple random sample inside a region | `n` | analytic | +| `design_reservoir()` | a fixed-size sample from a stream, in one pass | `n` | analytic | +| `design_bootstrap()` | resampled replicates of rows (simple) or of runs of rows (block or circular) | `n_replicates` | not a survey design | + +Every estimate says in `method` which estimator produced its variance, +under the names in this table, which are also the ones a printed +estimate and the `method` column of a `by` table show. An approximation +is called one when it prints. Under the default `variance = "auto"`, the +jackknife takes over where the design’s own estimator declines, and +`method` then says `jackknife`. ## Spread the sample, not just the rows @@ -168,7 +174,7 @@ plots$biomass <- 100 + 80 * plots$x + 60 * sin(4 * plots$y) + rnorm(400, 0, 10) op <- par(mfrow = c(1, 2)) plot(design_simple(n = 40), plots, type = "map", coords = c("x", "y"), seed = 3, - main = "simple random") + main = "simple random", asp = 1) plot(design_spread(c("x", "y"), n = 40, scale = FALSE), plots, type = "map", seed = 3, main = "spread (local pivotal method)") par(op) @@ -202,7 +208,7 @@ inclusion_prob(invoices, design_weighted("value", n = 60)) #> Its weights govern each successive draw, not each row's chance of ending up in #> the sample. Use method = "systematic" or "poisson" for a design whose inclusion #> probabilities really are proportional to the weights. -#> Or pass simulate = TRUE to estimate it by Monte Carlo. +#> Or estimate it by Monte Carlo with inclusion_prob(data, design, simulate = TRUE). ``` ``` r @@ -215,10 +221,9 @@ ht_total(one_each, "value") #> #> No variance is available for this sample. 4 strata `east`, `north`, #> `south`, `west` each have a single sampled row, so the variation -#> within them cannot be measured and leaving it out would understate +#> within them cannot be measured and leaving them out would understate #> the standard error. Draw at least two rows per stratum -#> (min_per_stratum = 2). The stratified jackknife needs two units per -#> stratum as well. +#> (min_per_stratum = 2). ``` ## Learn more diff --git a/_pkgdown.yml b/_pkgdown.yml index 64098ff..e420208 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -24,7 +24,6 @@ reference: - designs - plot.drawn_design - is_design - - draw_design - title: What a design knows before you draw desc: The probabilities that make a sample estimable. @@ -32,22 +31,40 @@ reference: - inclusion_prob - sampling_weight - joint_prob + - certainty_set + - allocation_table - title: Estimating from a sample desc: > - Totals, means and proportions, overall or by domain, with the variance - estimator the design calls for and a design effect. + Totals, means, ratios, proportions and quantiles, overall or by domain, + with the variance estimator the design calls for and a design effect. contents: - ht_total - ht_mean + - ht_ratio + - ht_quantile - deff +- title: From fieldwork to estimate + desc: > + Join fieldwork results to a sample, replace units found unavailable from + a reserve list, rebuild a sample read back from a file, and drop frame + columns before saving or sharing one. + contents: + - add_fieldwork + - use_reserves + - as_drawn + - compact_sample + - title: Planning and checking desc: How many rows to draw, what you actually got, and where to go next. contents: - plan_size + - deff_cluster - sample_summary - as_svydesign + - replicate_weights + - frame_totals - title: Equal-probability designs desc: Every unit equally likely, or equally likely within a group. @@ -82,6 +99,11 @@ reference: contents: - design_bootstrap +- title: Extending + desc: A design class of your own, drawn by its own method. + contents: + - draw_design + articles: - title: Guides navbar: Guides diff --git a/cran-comments.md b/cran-comments.md index b9e22e9..dd92d24 100644 --- a/cran-comments.md +++ b/cran-comments.md @@ -3,11 +3,21 @@ ## Test environments * local: Ubuntu 24.04, R 4.3.3 -* GitHub Actions: macOS, Windows and Ubuntu, on R-release, R-devel and oldrel-1 +* GitHub Actions: macOS and Windows on R-release; Ubuntu on R-devel, + R-release, oldrel-1 and R 4.1, the oldest version DESCRIPTION allows. One + more Ubuntu run on R-release builds the PDF manual and fails on any NOTE, + with the CRAN incoming checks turned off. ## R CMD check results -0 errors | 0 warnings | 0 notes +0 errors | 0 warnings | 1 note + +* This is a new submission. + +If the NOTE also lists possibly misspelled words in DESCRIPTION, they are +names spelled as published: Grafström, Lundström and Schelin proposed the +local pivotal method, Deville the variance approximation, and Horvitz is one +of the two names in Horvitz-Thompson. ## What this package is for @@ -22,8 +32,10 @@ draw(data, plan, seed = 1, weights = TRUE) Twelve designs share one contract: `n` always means the total drawn, `allocation` always means how a total is split, `na_rm` always means the same thing on both the draw and the probability path, `replace` always rules out -design weights, the caller's RNG stream is restored on exit, and the result is a -data frame with the input's class and column order. A design can also report its +design weights, a `seed` is applied with R's default generator and the caller's +RNG stream is restored on exit (with `seed = NULL` the draw uses and advances +that stream), and the result is a data frame with the input's class and column +order. A design can also report its own first- and second-order inclusion probabilities, so `ht_total()` and `ht_mean()` return an estimate — overall or by domain — with a standard error from the variance estimator the literature recommends for that design, a @@ -43,9 +55,9 @@ three, provides joint inclusion probabilities for several of them, and adds calibration, balanced sampling via the cube method, and ratio and regression estimators. Anyone who needs Brewer, Midzuno, Sampford, Tillé, pivotal or maximum-entropy sampling should use `sampling`, and the documentation for -`design_weighted()` and `joint_prob()` says so by name. +`design_weighted()` says so by name. -`drawn` differs in three ways rather than in statistical novelty: +`drawn` differs in four ways rather than in statistical novelty: 1. **Interface.** `sampling` is a library of functions over vectors that return index tables, which you then join back to your data. `drawn` takes a data @@ -82,8 +94,10 @@ expresses a `drawn` design in `survey`'s own terms — strata, cluster ids, two stages, `survey::poisson_sampling()`, Brewer's PPS approximation, or a taken-whole certainty stratum — so that the two packages' totals, standard errors, domain estimates, degrees of freedom and proportion intervals agree to -floating point wherever `survey` models the same design. The tests assert that -agreement design by design. +floating point wherever `survey` models the same design. Units taken with +certainty go to `survey` as one sampling unit per stratum, taken whole, so +neither package counts them among the degrees of freedom. The tests assert +that agreement design by design, certainty designs included. **`spsurvey`** implements GRTS spatially balanced designs and an environmental monitoring workflow; it is the deeper tool for that field. @@ -127,10 +141,21 @@ fails it on a function defined in more than one file. Documented in `?as_svydesign` and asserted in the tests: * systematic PPS — neither package has its joint probabilities; `ht_total()` - uses Deville's approximation and `survey` Brewer's, and they agree within - about 0.2%; + uses Deville's approximation and `survey` Brewer's. The degrees of freedom + agree. In simulations on frames of 100 to 300 rows with gamma and + lognormal sizes, standard errors of totals agreed within 3%, usually + within 0.5%, and those of means differed typically by 3 to 7%, and by up + to 12%, at a sampling fraction of one half. Where the probabilities below + certainty spread from 0.05 to 0.95, totals differed by up to 9% and means + by up to 17%; +* a census — both packages report a variance of 0, and `survey::degf()` + gives `n - 1` where `ht_total()` gives `Inf`; * `design_spread()` — `survey` has no estimator for a spatially balanced sample - and is given the first-order design, so its standard error is larger; + and is given the first-order design. Its standard error is larger than + `ht_total()`'s when `y` varies smoothly over the coordinates, and smaller in + most samples when `y` has no spatial pattern or the sampling fraction is + large, because `ht_total()`'s local mean approximation has no finite + population correction; * systematic sampling — `survey`, told only `ids = ~1`, returns the simple-random variance; `ht_total()` uses the successive-difference approximation. Neither is design-unbiased, because no such estimator exists. diff --git a/inst/WORDLIST b/inst/WORDLIST new file mode 100644 index 0000000..46507ea --- /dev/null +++ b/inst/WORDLIST @@ -0,0 +1,102 @@ +0s +1s +6k +Billard +Biometrika +CCTZ +CMD +CRS +CRSs +Clopper +Dever +Deville +Deville's +EPSG +Environmetrics +GRTS +Godambe +Grafström +Graubard +Graubard's +Hajek +Horvitz +Hájek +Ids +JKn +Kish +Kish's +Kreuter +Künsch +L's +LePage +Lumley +Lundström +MULTIPOLYGON +Madow +Matei +POSIXct +PSU +Politis +R's +README's +SYG +Sao +Schelin +Sen +Sprott +Swensson +Särndal +Tillé +Valliant +Vitter +Walkthrough +Walkthroughs +Wolter +Wretman +antimeridian +bg +bound's +cdot +deville +doi +draw's +drawn's +ed +estimate's +frac +frac12 +frac1k +ht +ids +ij +km2 +lat +lfloor +lon +lubridate +lwgeom +mathrm +mean's +mk +ne +nonrespondent +nonresponse +nonzero +plotmath +py +reserve's +reweights +rfloor +s2 +selfref +sfc +svydesign +th +tibble +unbiasedness +unioned +unparseable +val +walkthrough +xlim +’s diff --git a/man/add_fieldwork.Rd b/man/add_fieldwork.Rd new file mode 100644 index 0000000..97ee741 --- /dev/null +++ b/man/add_fieldwork.Rd @@ -0,0 +1,53 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/state.R +\name{add_fieldwork} +\alias{add_fieldwork} +\title{Join fieldwork results to a weighted sample} +\usage{ +add_fieldwork(sample, field, by) +} +\arguments{ +\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}, or +by \code{\link[=as_drawn]{as_drawn()}}.} + +\item{field}{A data frame of results: the \code{by} columns and the columns to +add.} + +\item{by}{The names of one or more columns of \code{sample} and \code{field} that +identify a sampled row.} +} +\value{ +\code{sample} with the other columns of \code{field} added after its own. +} +\description{ +Fieldwork results usually come back as a table of their own, keyed by an +id and in another order. \code{add_fieldwork()} adds its columns to \code{sample}, +row by row through the id, and keeps the sample's rows, their order and +the attributes that hold its design. \code{\link[=merge]{merge()}} reorders the rows and drops +those attributes, and a join that matches a row twice would repeat it. +} +\details{ +A sampled row with no row in \code{field} gets missing values, as a +nonrespondent should: \code{\link[=ht_total]{ht_total()}} refuses them, and \code{ht_mean(na_rm = TRUE)} +estimates the mean over the rows with a result (see "Missing values and +nonresponse" in \code{\link[=ht_total]{ht_total()}}). An id that appears twice in \code{field}, an id +that is not in \code{sample}, a missing id, and a column of \code{field} that +\code{sample} already has are refused. Ids are compared as in \code{\link[=as_drawn]{as_drawn()}}. + +A list from a design with \code{reserve} takes fieldwork columns too, such as +which units were found unavailable, before \code{\link[=use_reserves]{use_reserves()}} turns it into +the sample to estimate from. +} +\examples{ +pop <- data.frame(id = 1:200, site = rep(c("a", "b"), times = c(150, 50))) +s <- draw(pop, design_stratified("site", n = 40), seed = 1, weights = TRUE) + +# Results for 36 of the 40 rows, in the order they came in +field <- data.frame(id = rev(s$id)[1:36], spend = seq(20, 370, by = 10)) +s <- add_fieldwork(s, field, by = "id") +ht_mean(s, "spend", na_rm = TRUE) + +} +\seealso{ +\code{\link[=as_drawn]{as_drawn()}}, \code{\link[=ht_mean]{ht_mean()}}, \code{\link[=use_reserves]{use_reserves()}} +} diff --git a/man/allocation_table.Rd b/man/allocation_table.Rd new file mode 100644 index 0000000..ba3606d --- /dev/null +++ b/man/allocation_table.Rd @@ -0,0 +1,71 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/design-stratified.R +\name{allocation_table} +\alias{allocation_table} +\title{How a design splits its sample over the strata of a frame} +\usage{ +allocation_table(data, design) +} +\arguments{ +\item{data}{A data frame.} + +\item{design}{\code{\link[=design_stratified]{design_stratified()}}, \code{\link[=design_spread]{design_spread()}} or +\code{\link[=design_weighted]{design_weighted()}} with \code{strata}, or \code{\link[=design_certainty]{design_certainty()}} whose \code{rest} +is one of these. For the last the +table describes \code{rest} over the rows below the threshold, and the rows +at or above it, which are taken with certainty, are not counted in any +stratum. Other designs are refused.} +} +\value{ +A data frame with one row per stratum of \code{data}, in key order (see +\code{\link[=design_stratified]{design_stratified()}}): the \code{strata} columns, then +\describe{ +\item{\code{N}}{Rows in the stratum.} +\item{\code{n}}{Rows drawn from it.} +\item{\code{prob}}{The inclusion probability of each of its rows, as +\code{\link[=inclusion_prob]{inclusion_prob()}} gives it. \code{NA} for \code{\link[=design_spread]{design_spread()}} with \code{size} +and for \code{\link[=design_weighted]{design_weighted()}}, whose rows in one stratum have +different probabilities; there \code{\link[=inclusion_prob]{inclusion_prob()}} gives them row by +row.} +\item{\code{sd}}{Under Neyman allocation, the stratum's standard deviation +that the split used: of the \code{allocation_by} column within the +stratum, or as given. \code{NA} under other allocations.} +\item{\code{cost}}{The cost of one row, when the design has \code{cost}, and +\code{NA} otherwise.} +\item{\code{status}}{Why the stratum got \code{n}: \code{"rule"} for its share under +the allocation rule, rounded; \code{"count"} for a count given in +\code{allocation}; \code{"floor"} for a stratum raised to \code{min_per_stratum} +from a smaller share; \code{"capped"} for one the rule asked more rows of +than it holds, so it is taken whole and the rows it could not give +go to the other strata; \code{"take-all"} for one taken whole for another +reason, such as a size below \code{min_per_stratum} or a count equal to +its size; and \code{"empty"} for one allocated no rows, whose rows can +never be drawn. With \code{replace = TRUE} no stratum is capped or taken +whole.} +} +} +\description{ +The rows \code{\link[=draw]{draw()}} takes from each stratum, the inclusion probability that +gives each row there, and the reason for any stratum held at the floor, +capped at its size or left with no rows, all before anything is drawn. +Under Neyman allocation it also shows the standard deviation of each +stratum the split used, and the cost per row when the design has costs. +The numbers come from the same computation as \code{\link[=draw]{draw()}} and +\code{\link[=inclusion_prob]{inclusion_prob()}}, so they always agree with both. +} +\examples{ +df <- data.frame(id = 1:300, + site = rep(c("a", "b", "c", "d"), c(150, 100, 45, 5)), + v = c(1:150 \%\% 7, 1:100 \%\% 19, 1:45 \%\% 3, 1:5 * 40)) +d <- design_stratified("site", n = 30, allocation = "neyman", + allocation_by = "v", min_per_stratum = 2) +allocation_table(df, d) + +# The same counts as a draw, and the same probabilities as inclusion_prob() +table(draw(df, d, seed = 1)$site) +tapply(inclusion_prob(df, d), df$site, unique) + +} +\seealso{ +\code{\link[=design_stratified]{design_stratified()}}, \code{\link[=design_spread]{design_spread()}}, \code{\link[=inclusion_prob]{inclusion_prob()}} +} diff --git a/man/as_drawn.Rd b/man/as_drawn.Rd new file mode 100644 index 0000000..62ed25c --- /dev/null +++ b/man/as_drawn.Rd @@ -0,0 +1,136 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/state.R +\name{as_drawn} +\alias{as_drawn} +\title{Rebuild a weighted sample from its rows} +\usage{ +as_drawn(data, design, frame, by = NULL) +} +\arguments{ +\item{data}{The sampled rows as read back: a data frame with the \code{.row} +column \code{\link[=draw]{draw()}} added, or with the id column or columns named in \code{by}.} + +\item{design}{The design the sample was drawn with.} + +\item{frame}{The data frame the sample was drawn from, as it was then.} + +\item{by}{\code{NULL} to match rows through \code{.row}, or the names of one or more +columns of \code{data} and \code{frame} that identify a frame row.} +} +\value{ +A data frame of the class of \code{data}, ready for \code{\link[=ht_total]{ht_total()}}, +\code{\link[=ht_mean]{ht_mean()}}, \code{\link[=as_svydesign]{as_svydesign()}} and \code{\link[=sample_summary]{sample_summary()}}. +} +\description{ +A weighted sample carries its design, a copy of its frame and its +inclusion probabilities as attributes. A CSV or spreadsheet file, a +database table and \code{\link[=merge]{merge()}} keep none of them, so \code{\link[=ht_total]{ht_total()}}, +\code{\link[=ht_mean]{ht_mean()}}, \code{\link[=as_svydesign]{as_svydesign()}} and \code{\link[=sample_summary]{sample_summary()}} refuse the rows that +come back. \code{as_drawn()} puts the attributes back. It matches each row of +\code{data} to its row of \code{frame}, works out the inclusion probabilities again +from \code{design}, and sets \code{.prob}, \code{.weight} and \code{.row} as \code{\link[=draw]{draw()}} sets +them. +} +\section{Matching rows to the frame}{ + +With \code{by = NULL}, each row is matched through its \code{.row} column, the frame +row \code{\link[=draw]{draw()}} recorded for it. \code{frame} must then be the frame the sample was +drawn from, with its rows in the same order. A frame in another order, such +as a database table read without \verb{ORDER BY}, holds other rows at those +positions, and its strata and clusters would be wrong for the sample. Each +column \code{data} shares with \code{frame} is therefore compared with the frame rows +\code{.row} names, and a column whose values differ is refused. Numbers need to +agree to about eight significant digits, fewer than a CSV file keeps, and a +number read back from text, such as \code{"007"}, is compared as the number 7. +Text such as \code{"T"}, \code{"F"}, \code{"t"} or \code{"f"} that a file gave back as a logical +column is compared as \code{TRUE} or \code{FALSE}, as \code{readr::read_csv()} reads it. A +date-time read back in another time zone agrees when it is the same instant +or shows the same clock time, since \code{readr::read_csv()} and +\code{data.table::fread()} read the clock time a CSV file holds as UTC. A missing +value on either side is not compared, so a frame column that fieldwork fills +in is accepted. Nor is a date that a file gave back as text, whose format a +spreadsheet may have changed. A column changed after the draw, such as a +corrected address, is refused too; rename it in \code{data}, or match on an id. A +\code{data} that shares no column with \code{frame} besides those \code{\link[=draw]{draw()}} adds cannot +be checked, so keep an id column in the file. + +With \code{by}, rows are matched on the values of one or more id columns that +\code{data} and \code{frame} share. Values are compared as \code{\link[=match]{match()}} compares them, +and as text when the two columns have different classes, so an id stored +as \code{"007"} does not match the number 7 that a CSV file gives back. + +When \code{data} has both \code{.row} and the \code{by} columns, they must agree. A frame +row found through \code{by} that is not the one \code{.row} names means \code{frame} is +not in the order it had when the sample was drawn, which changes the +probabilities of designs that depend on that order, such as +\code{\link[=design_systematic]{design_systematic()}}; the rebuild is refused. + +A row with a missing id, an id that appears twice in \code{data}, an id that +\code{frame} does not have or holds more than once, and a row the design gives a +probability of 0 are refused, with the ids named. +} + +\section{Every row drawn}{ + +\code{data} must hold every row that was drawn, with or without a fieldwork +result. A subset, such as the rows that responded, is not a sample from +the design, and its standard errors would be wrong. For a design that +draws a fixed number of rows (simple, stratified, spread, temporal, +spatial and reservoir designs, systematic designs given \code{n}, and +\code{\link[=design_weighted]{design_weighted()}} with \code{method = "systematic"}, alone or as the \code{rest} +of \code{\link[=design_certainty]{design_certainty()}}), a \code{data} with another number of rows is refused. +A \code{\link[=design_cluster]{design_cluster()}} or \code{\link[=design_multistage]{design_multistage()}} sample, also as the \code{rest} +of \code{\link[=design_certainty]{design_certainty()}}, is refused when its rows are not of \code{n_clusters} +clusters or a cluster does not hold the rows the design takes from it, +which are all of its rows for whole clusters, and the same number from +each cluster when that number does not depend on which clusters were +selected. A design weighted conditional on its clusters (see "Design +weights" in \code{\link[=draw]{draw()}}) is rebuilt from the clusters its rows belong to, +which must hold the rows the design takes from each given that selection. +A frame row the design takes with certainty, with probability 1, is in +every sample, and a \code{data} without it is refused whatever the design. Keep +the rows with no response, with \code{y} missing, and estimate a mean with +\code{ht_mean(na_rm = TRUE)}; see "Missing values and nonresponse" in +\code{\link[=ht_total]{ht_total()}}. + +A list from a design with \code{reserve} is rebuilt whole, the main sample and +every reserve, with the \code{.reserve} column \code{\link[=draw]{draw()}} added, which records +the order the reserves are used in. Pass the result to \code{\link[=use_reserves]{use_reserves()}}. +} + +\section{What comes back}{ + +The rows of \code{data} in their own order, with \code{.prob}, \code{.weight} and \code{.row} +first and the other columns of \code{data} after them. \code{.prob} and \code{.weight} +come from \code{design}. A numeric \code{.prob} in \code{data} must agree with them, or +the design or the frame is not the one the sample was drawn with. A +\code{.weight} adjusted after the draw is replaced by \code{1 / .prob}, so the +adjustment has to be made again. + +Strata, clusters and the other design columns are read from the copy of +\code{frame} stored with the result, as for a sample from \code{\link[=draw]{draw()}}, so \code{data} +needs only the columns to estimate from: \code{y} and the \code{by} columns of the +estimates. \code{\link[=add_fieldwork]{add_fieldwork()}} joins results that come back keyed by an id. +} + +\examples{ +pop <- data.frame(id = 1:200, site = rep(c("a", "b"), times = c(150, 50))) +by_site <- design_stratified("site", n = 40) +s <- draw(pop, by_site, seed = 1, weights = TRUE) + +# A file keeps the rows and loses the design +path <- tempfile(fileext = ".csv") +write.csv(s, path, row.names = FALSE) +back <- as_drawn(read.csv(path), by_site, pop) +sample_summary(back) + +# Without `.row`, match on an id column +ids <- read.csv(path)[, c("id", "site")] +back <- as_drawn(ids, by_site, pop, by = "id") +unlink(path) + +} +\seealso{ +\code{\link[=add_fieldwork]{add_fieldwork()}} to join fieldwork results, \code{\link[=compact_sample]{compact_sample()}} +to drop frame columns before saving or sharing a sample, and \code{\link[=draw]{draw()}}. +} diff --git a/man/as_svydesign.Rd b/man/as_svydesign.Rd index b72dc86..64a1604 100644 --- a/man/as_svydesign.Rd +++ b/man/as_svydesign.Rd @@ -7,19 +7,21 @@ as_svydesign(sample, ...) } \arguments{ -\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}.} +\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}. See +"Weights and design columns".} -\item{...}{Passed to \code{\link[survey:svydesign]{survey::svydesign()}}. Anything named here overrides -what the mapping above would have supplied, so \code{nest = TRUE} or a -replacement \code{fpc} is yours to set.} +\item{...}{Passed to \code{\link[survey:svydesign]{survey::svydesign()}} by name, and an unnamed +argument is refused. Anything named here overrides what the mapping +above would have supplied, so \code{nest = TRUE} or a replacement \code{fpc} is +yours to set.} } \value{ A \code{survey.design} object. } \description{ -Builds a \code{\link[survey:svydesign]{survey::svydesign()}} object from a drawn sample, so the analysis -this package does not do — regression, calibration, quantiles with proper -standard errors, replicate weights — can be done by the package that does. +Builds a \code{\link[survey:svydesign]{survey::svydesign()}} object from a drawn sample, so that the +survey package can do the analysis this package does not, such as +regression, calibration and analysis with replicate weights. } \details{ The two packages compute variance from different starting points. This one @@ -35,45 +37,180 @@ in \code{survey}'s own terms rather than hand over a weight column and hope. \code{\link[=design_reservoir]{design_reservoir()}} \tab \code{ids = ~1} with \code{fpc} the rows the stream reached \tab identical \cr \code{\link[=design_stratified]{design_stratified()}} \tab \code{strata} from the strata columns, \code{fpc} each stratum's size \tab identical \cr \code{\link[=design_temporal]{design_temporal()}} \tab \code{strata} from the sampling intervals, \code{fpc} each interval's size \tab identical \cr -\code{\link[=design_cluster]{design_cluster()}} \tab \code{ids} the cluster column, \code{fpc} the number of clusters \tab identical \cr -\code{\link[=design_multistage]{design_multistage()}} \tab two stages, \code{ids = ~cluster + row}, \code{fpc} the number of clusters and each cluster's size \tab identical \cr -\code{\link[=design_weighted]{design_weighted()}}, \code{"poisson"} \tab \code{survey::poisson_sampling()}, which models the random size \tab identical \cr -\code{\link[=design_certainty]{design_certainty()}} \tab the certainty rows as their own stratum, taken whole \tab as \code{rest} \cr -\code{\link[=design_weighted]{design_weighted()}}, \code{"systematic"} \tab \code{pps = "brewer"} with the inclusion probabilities \tab within about 0.2 percent \cr -\code{\link[=design_spread]{design_spread()}} \tab as its first-order design: \code{ids = ~1}, or \code{pps = "brewer"} with \code{size} \tab \strong{\code{survey}'s is larger} \cr -\code{\link[=design_systematic]{design_systematic()}} \tab \code{ids = ~1} with \code{fpc} the frame size \tab \strong{differ} \cr +\code{\link[=design_cluster]{design_cluster()}} \tab \code{ids} a \code{.cluster} column numbering the clusters, \code{fpc} the number of clusters \tab identical \cr +\code{\link[=design_multistage]{design_multistage()}}, and \code{\link[=design_cluster]{design_cluster()}} with \code{balanced = TRUE} \tab two stages, \code{ids} the \code{.cluster} numbers then the rows, \code{fpc} the number of clusters and each cluster's size; with one sampled row from a selected cluster of several, one stage, \code{ids} the \code{.cluster} numbers and no \code{fpc} \tab identical \cr +\code{\link[=design_weighted]{design_weighted()}}, \code{"poisson"} \tab \code{survey::poisson_sampling()}, which models the random size; with \code{strata}, the strata too, which change only the degrees of freedom \tab identical \cr +\code{\link[=design_certainty]{design_certainty()}} \tab the certainty rows as one unit in a stratum of their own, taken whole, beside \code{rest} as it maps alone; over a Poisson \code{rest}, \code{survey::poisson_sampling()} from the whole sample's \code{.prob} \tab as \code{rest} \cr +\code{\link[=design_weighted]{design_weighted()}}, \code{"systematic"} \tab \code{pps = "brewer"} with the inclusion probabilities; with \code{strata}, \code{strata} from the strata columns and Brewer's within them \tab close for totals, less so for means \cr +\code{\link[=design_multistage]{design_multistage()}} with \code{size} \tab two stages, \code{ids} the \code{.cluster} numbers then the rows, \code{pps = "brewer"} with each cluster's stage-one probability and \code{m / N_i} at the second stage; each cluster taken with certainty a stratum of its own, whose rows are its units; with one sampled row from a selected cluster of several, one stage, \code{ids} the \code{.cluster} numbers and no \code{fpc} \tab close; identical in one stage \cr +\code{\link[=design_spread]{design_spread()}} \tab as its first-order design: \code{ids = ~1}, or \code{pps = "brewer"} with \code{size}; with \code{strata}, \code{strata} from the strata columns and \code{fpc} each stratum's size, or Brewer's within them \tab \strong{differ} \cr +\code{\link[=design_systematic]{design_systematic()}} with \code{n_starts} of 2 or more \tab \code{ids} a \code{.cluster} column numbering the replicates, \code{fpc} the \code{n_starts * interval} possible starts \tab identical \cr +\code{\link[=design_systematic]{design_systematic()}} \tab \code{ids = ~1} with \code{fpc} the rows the walk can reach \tab \strong{differ} \cr +\code{\link[=design_stratified]{design_stratified()}} with \code{within} \tab \code{strata} from the strata columns, \code{fpc} each stratum's rows walked \tab \strong{differ} \cr } -"Identical" means to floating point, and is checked by this package's tests -against \code{survey::svytotal()}, as are domain estimates against -\code{survey::svyby()} and degrees of freedom against \code{survey::degf()}. The -exceptions are real and worth knowing: +"Identical" means to floating point under \code{survey}'s default options, and +is checked by this package's tests against \code{survey::svytotal()}, as are +domain estimates against \code{survey::svyby()} and degrees of freedom against +\code{survey::degf()}. The exceptions are real and worth knowing: \itemize{ \item \strong{Systematic PPS.} Neither package has its joint probabilities. This one -uses Deville's approximation and \code{survey} uses Brewer's; the two are close -relatives and agree to a fraction of a percent. +uses Deville's approximation and \code{survey} uses Brewer's. In simulations +on frames of 100 to 300 rows with gamma and lognormal sizes, the +standard errors of totals usually agreed within 0.5 percent, and within +3 percent in every sample. Those of means differed more, and more as the +sampling fraction grew: typically by under 2 percent at a fraction of a +tenth or a fifth, 2 to 4 percent at a third and 3 to 7 percent at a +half, where single samples differed by up to 12 percent. On a frame +whose units below certainty had probabilities from 0.05 to 0.95, with +about 17 of them in each sample, totals differed by about 1 percent +typically and by up to 9 percent, and means by 7 to 9 percent typically +and by up to 17 percent. The degrees of freedom agree. With \code{strata}, +each stratum is handed over the same way. +\code{\link[=design_multistage]{design_multistage()}} with \code{size} meets the same two approximations at +the first stage, while the variance within the selected clusters is the +same in both packages. Where the clusters below certainty had +stage-one probabilities of 0.12 to 0.41, the standard errors of totals +agreed within 0.3 percent over 200 samples. With a cluster at 0.93 among +them, \code{survey}'s came out 0.97 to 1.48 times this package's: Brewer's +approximation centres on the plain mean of the clusters' totals over +their probabilities, which that cluster pulls, where Deville's weights +each by \code{1 - pi}. \item \strong{Spread.} \code{survey} has no estimator for a spatially balanced sample, so it is told only the first-order design and computes a variance that -ignores the spreading. That errs conservative, often substantially. +ignores the spreading. Relative to the true variance that errs +conservative, often substantially. Relative to \code{\link[=ht_total]{ht_total()}}'s local mean +approximation it goes either way. In simulations drawing 30 of 300 +points spread over a square, \code{survey}'s standard error was the larger in +every sample when \code{y} varied smoothly over the square, three times as +large at the median. When \code{y} had no spatial pattern it was the smaller +in 67 to 79 percent of samples, by 4 to 6 percent at the median, and +drawing 150 of the 300 it was the smaller in every sample, by 30 percent +at the median, because the local mean has no finite population +correction. \item \strong{Systematic.} \code{survey}, told only \code{ids = ~1}, computes the simple-random variance; \code{\link[=ht_total]{ht_total()}} uses the successive-difference approximation, which -can see a trend along the sort order. Neither is design-unbiased, because -no such estimator exists for one systematic sample. +can see a trend along the sort order. Neither is design-unbiased, and at +a step of 2 rows or more no such estimator exists for one systematic +sample. Within strata, \code{survey} computes the stratified simple-random +variance and \code{\link[=ht_total]{ht_total()}} adds up the strata's successive-difference +approximations. With \code{n_starts} of 2 or more the replicates are clusters +and the two agree. A replicated sample with a start that drew no rows, +which happens only when \code{n_starts * interval} exceeds the rows walked, is +refused, because \code{survey} would count one replicate fewer. } -Certainty rows arrive in a stratum where \code{n == N}, so \code{survey}'s own finite -population correction zeroes them out, matching this package's treatment. +Units taken with certainty are in every sample and add nothing to the +variance: the rows above a \code{\link[=design_certainty]{design_certainty()}} threshold, strata and +intervals taken whole, the units \code{\link[=design_weighted]{design_weighted()}} and +\code{\link[=design_spread]{design_spread()}} with \code{size} put at probability 1, and the clusters +\code{\link[=design_multistage]{design_multistage()}} and \code{\link[=design_cluster]{design_cluster()}} with \code{balanced = TRUE} take +whole when they select every cluster. Each group of them goes to \code{survey} +as one primary sampling unit in a stratum of its own, with an \code{fpc} of 1, +so \code{survey} gives them no variance and \code{survey::degf()} leaves them out +of the degrees of freedom, as \code{\link[=ht_total]{ht_total()}} does. For the PPS designs this +also keeps them out of Brewer's approximation, which left among the other +units inflated \code{survey}'s standard error, by a factor of 23 on a frame +with four dominant units. Beside a \code{rest} of clusters, or of the +replicates of several systematic starts, the certainty rows form one more +primary sampling unit. In two stages, such a unit is taken whole at the +second stage too. -Two compositions have no single \code{survey} design and are refused rather than -approximated: \code{\link[=design_certainty]{design_certainty()}} over a cluster, multistage or Poisson -\code{rest}, where the certainty rows and the rest are different kinds of sampling -unit. \code{\link[=design_bootstrap]{design_bootstrap()}} is refused outright — it resamples the sample, so +A sample in which every row was taken with certainty, a census, goes to +\code{survey} as \code{ids = ~1} with \code{fpc} the number of rows. Both packages then +report a variance of 0, and \code{survey::degf()} gives \code{n - 1} where +\code{\link[=ht_total]{ht_total()}} gives \code{Inf}. A sample with no rows is refused, and so is a +certainty sample whose \code{rest} drew none of the rows below the threshold, +whose total \code{survey} would report as exact where \code{\link[=ht_total]{ht_total()}} reports no +variance. + +\code{\link[=design_certainty]{design_certainty()}} over a Poisson \code{rest} goes to \code{survey} as +\code{survey::poisson_sampling()} built from the whole sample's \code{.prob}, so the +certainty rows enter at probability 1 and add no variance. +\code{\link[=design_bootstrap]{design_bootstrap()}} is refused outright — it resamples the sample, so there is no finite population for \code{svydesign()} to represent. A stratum or interval with a single sampled row makes \code{survey} stop with "Stratum has only one PSU" unless \code{options(survey.lonely.psu)} says otherwise; \code{\link[=ht_total]{ht_total()}} declines in the same situation. Draw at least two -per stratum. +per stratum. Under \code{\link[=design_multistage]{design_multistage()}} with \code{size}, a cluster taken with +certainty is a stratum of its sampled rows, so one that gives a single row +of several is such a stratum. +\code{options(survey.ultimate.cluster = TRUE)} makes \code{survey} leave out the +second stage of every two-stage design, so its standard errors then +differ from \code{\link[=ht_total]{ht_total()}}'s. The agreement the table states holds under +the default, \code{FALSE}. + +A sample weighted conditional on the clusters selected (see "Design +weights" in \code{\link[=draw]{draw()}}) goes over in two stages too. \code{survey} works out +each cluster's second-stage sampling fraction from the rows sampled in +it, which is the take given that selection, so its estimate and standard +error are those of \code{\link[=ht_total]{ht_total()}}. + +One sampled row from a selected cluster of several leaves the variation +within clusters unmeasured. \code{\link[=ht_total]{ht_total()}} then falls back to the +delete-a-cluster jackknife, which is the ultimate-cluster variance with no +finite population correction, and \code{survey} gets that design: one stage, +\code{ids} the \code{.cluster} numbers and no \code{fpc}. So does a certainty design's +\code{rest} of balanced clusters, which \code{\link[=draw]{draw()}} weights without regard to the +clusters selected, leaving no two-stage estimator. Under +\code{\link[=design_multistage]{design_multistage()}} with \code{size} the jackknife runs over the clusters +below certainty, and a cluster taken whole is held fixed in a stratum of +its own in both packages. +} + +\section{Weights and design columns}{ + +\code{survey} gets the sample's \code{.weight} column as its weights. Weights adjusted +after the draw, for nonresponse or by trimming, and written into \code{.weight} +are therefore estimated here, while \code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} keep to the +design probabilities in \code{.prob} and warn that \code{.weight} differs. \code{.prob} +itself must stay as \code{\link[=draw]{draw()}} set it: it supplies the probabilities of the +PPS mappings above, and a sample whose \code{.prob} was changed is refused. + +Strata, intervals, cluster labels and population counts come from the copy +of the frame stored with the sample, not from the sample's own columns, and +are passed in the columns \code{.stratum}, \code{.cluster}, \code{.psu}, \code{.fpc}, \code{.fpc2} +and \code{.unit}. Renaming or recoding a design column in the sample after the draw +does not change the survey design. Those six names are reserved: a sample +with a column of one of them is refused rather than overwritten. Rename +the column in the sample, which leaves the design as drawn. +} + +\section{Replicate weights and calibration}{ + +\code{survey::as.svrepdesign()} turns the design returned here into one with +replicate weights. For samples from \code{\link[=design_simple]{design_simple()}}, +\code{\link[=design_stratified]{design_stratified()}} without \code{within}, \code{\link[=design_cluster]{design_cluster()}} without +\code{balanced}, \code{\link[=design_temporal]{design_temporal()}}, \code{\link[=design_spatial]{design_spatial()}} and \code{\link[=design_spread]{design_spread()}} +without \code{size}, its jackknife gives the standard errors of +\code{ht_total(variance = "jackknife")}. It stops with an error on the +designs handed over with Brewer's approximation or as Poisson sampling, +those of \code{\link[=design_weighted]{design_weighted()}}, \code{\link[=design_spread]{design_spread()}} and \code{\link[=design_multistage]{design_multistage()}} +with \code{size}, and \code{\link[=design_certainty]{design_certainty()}} over them, because \code{survey} builds +no replicates for its own probability-proportional-to-size and Poisson +designs. That is a +limitation of \code{survey}. For a systematic sample, alone or within strata, +it builds a jackknife that ignores the order of the walk. For +\code{\link[=design_cluster]{design_cluster()}} with \code{balanced = TRUE} and \code{\link[=design_multistage]{design_multistage()}} +without \code{size} it keeps the finite population correction of the first +stage, which \code{ht_total(variance = "jackknife")} leaves out, and warns +that it dropped the corrections after the first stage. Its variance is +then the jackknife's times \code{1 - n / N}, for \code{n} of the \code{N} clusters +selected. + +\code{\link[=replicate_weights]{replicate_weights()}} builds replicate weights from the sample itself, +for \code{\link[survey:svrepdesign]{survey::svrepdesign()}}: the jackknife of +\code{ht_total(variance = "jackknife")}, for balanced clusters and the designs +handed over with Brewer's approximation too, and successive differences +along the walk for systematic samples. Poisson sampling, which the +jackknife understates, has none, and \code{survey} estimates it from the +design returned here. + +\code{\link[=frame_totals]{frame_totals()}} gives the population totals that \code{survey::calibrate()} +and \code{survey::postStratify()} take, from the frame stored with the +sample, over the rows the design could reach. Calibration is left to +\code{survey}, on the design returned here. } \examples{ @@ -93,9 +230,10 @@ survey::svytotal(~spend, des) ht_total(s, "spend") # Now the analysis this package does not do -survey::svyquantile(~spend, des, quantiles = 0.5) +coef(summary(survey::svyglm(spend ~ site, des))) \dontshow{\}) # examplesIf} } \seealso{ -\code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}} +\code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}}, \code{\link[=replicate_weights]{replicate_weights()}}, +\code{\link[=frame_totals]{frame_totals()}} } diff --git a/man/certainty_set.Rd b/man/certainty_set.Rd new file mode 100644 index 0000000..0e9aefe --- /dev/null +++ b/man/certainty_set.Rd @@ -0,0 +1,56 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/inclusion.R +\name{certainty_set} +\alias{certainty_set} +\title{Rows a size-proportional design takes with certainty} +\usage{ +certainty_set(data, design) +} +\arguments{ +\item{data}{A data frame.} + +\item{design}{\code{\link[=design_weighted]{design_weighted()}} with \code{method = "systematic"} or +\code{"poisson"}, or \code{\link[=design_spread]{design_spread()}} with a \code{size} column. Other designs are +refused, since none of them has inclusion probabilities proportional to +size.} +} +\value{ +An integer vector of the rows of \code{data} whose inclusion probability +is 1, in frame order, the same rows as +\code{which(inclusion_prob(data, design) == 1)}. Its attribute \code{threshold} is +the smallest size among them, or \code{NA} when there are none. Of the rows +the design can select, those whose size is at least \code{threshold} are the +set. With \code{strata}, \code{\link[=design_weighted]{design_weighted()}} and \code{\link[=design_spread]{design_spread()}} put the +cut-off in each stratum at its own size, so there \code{threshold} is \code{NA}. +For \code{\link[=design_weighted]{design_weighted()}} without \code{strata}, \code{\link[=design_certainty]{design_certainty()}} with +that \code{threshold} on the weights column therefore takes the same rows +with certainty, and a \code{rest} of the same +method with \code{n} reduced by the number of rows in the set gives the other +rows the same probabilities too. +} +\description{ +A design whose inclusion probabilities are proportional to size gives a +row whose share of \code{n} reaches 1 a probability of exactly 1, and spreads +what is left of \code{n} over the other rows, repeating until no share passes +\enumerate{ +\item \code{certainty_set()} says which rows of \code{data} those are, and where the +cut-off falls, before any sample is drawn. +} +} +\examples{ +df <- data.frame(id = 1:10, w = c(1, 2, 3, 4, 5, 6, 7, 8, 60, 90)) +d <- design_weighted("w", n = 4, method = "systematic") +cs <- certainty_set(df, d) +df[cs, ] +attr(cs, "threshold") + +# The same probabilities, with the cut-off made explicit +same <- design_certainty("w", attr(cs, "threshold"), + rest = design_weighted("w", n = 4 - length(cs), + method = "systematic")) +all.equal(inclusion_prob(df, same), inclusion_prob(df, d)) + +} +\seealso{ +\code{\link[=inclusion_prob]{inclusion_prob()}}, \code{\link[=design_certainty]{design_certainty()}} +} diff --git a/man/compact_sample.Rd b/man/compact_sample.Rd new file mode 100644 index 0000000..f082077 --- /dev/null +++ b/man/compact_sample.Rd @@ -0,0 +1,61 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/state.R +\name{compact_sample} +\alias{compact_sample} +\title{Drop the frame columns a sample's design does not need} +\usage{ +compact_sample(sample, keep = NULL) +} +\arguments{ +\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}, or +by \code{\link[=as_drawn]{as_drawn()}}.} + +\item{keep}{Names of other columns of the frame to keep, such as the \code{by} +columns of the estimates.} +} +\value{ +\code{sample}, with a smaller copy of the frame. +} +\description{ +A weighted sample holds its own copy of the whole frame, every column of +it, so that \code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}}, \code{\link[=as_svydesign]{as_svydesign()}} and +\code{\link[=sample_summary]{sample_summary()}} can work from the sample alone. That copy is kept in +memory and written to every file the sample is saved to, which costs as +much as the frame each time, and hands the frame, with any names, +addresses or other personal data in it, to whoever receives the file. +\code{compact_sample()} replaces the copy with one that holds only the columns +the design reads (strata, clusters, size measures, \code{order_by}, time +stamps, coordinates and the like) and the columns named in \code{keep}. +} +\details{ +Estimates, standard errors, \code{\link[=as_svydesign]{as_svydesign()}} and \code{\link[=sample_summary]{sample_summary()}} are +unchanged, with two exceptions that read other frame columns. A \code{by} +domain's size in the frame, which \code{ht_mean(estimator = "ht")} with \code{by} +divides by, needs the \code{by} columns in the stored frame; without them that +estimator is refused with a message naming \code{keep}. And a stratum with a +single sampled row leaves a domain's variance unmeasured unless the +stored frame's \code{by} columns show the stratum holds none of the domain (see +"Domains" in \code{\link[=ht_total]{ht_total()}}). Keep the \code{by} columns of the estimates in +\code{keep}, and the columns \code{\link[=frame_totals]{frame_totals()}} is asked for. Whether a column of +the frame left out holds only 0 and 1, which makes \code{\link[=ht_mean]{ht_mean()}} treat it as +a proportion, is recorded. + +The sample's own columns are not changed: drop columns of the sample with +\code{s$col <- NULL}. The inclusion probabilities of every frame row are kept, +one number per row. +} +\examples{ +pop <- data.frame(id = 1:5000, site = rep(c("a", "b"), each = 2500), + note = strrep("x", 40), spend = (1:5000) \%\% 97) +s <- draw(pop, design_stratified("site", n = 100), seed = 1, weights = TRUE) +small <- compact_sample(s) + +# The same estimate from a fraction of the bytes +c(full = length(serialize(s, NULL)), + compact = length(serialize(small, NULL))) +all.equal(ht_total(s, "spend")$se, ht_total(small, "spend")$se) + +} +\seealso{ +\code{\link[=draw]{draw()}}, \code{\link[=as_drawn]{as_drawn()}} +} diff --git a/man/deff.Rd b/man/deff.Rd index b681664..f59c3e0 100644 --- a/man/deff.Rd +++ b/man/deff.Rd @@ -4,28 +4,67 @@ \alias{deff} \title{Design effect} \usage{ -deff(x) +deff(object, ...) } \arguments{ -\item{x}{A result from \code{\link[=ht_total]{ht_total()}} or \code{\link[=ht_mean]{ht_mean()}}.} +\item{object}{A result from \code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}}, \code{\link[=ht_ratio]{ht_ratio()}} or +\code{\link[=ht_quantile]{ht_quantile()}}, or an object from \code{survey} that holds a design effect.} + +\item{...}{Passed to \code{survey::deff()} for an object from \code{survey}, such as +its \code{quietly}. Not used for an estimate made here.} } \value{ -A single number, or \code{NA} when the design has no variance estimate. +A single number, or \code{NA} when the design has no variance +estimate, \code{y} is constant in the sample, or the estimate is a mean from +\code{ht_mean(na_rm = TRUE)} with \code{y} missing in some sampled rows. For an +object from \code{survey}, what \code{survey::deff()} returns. } \description{ How much precision the design costs against simple random sampling of the same size (Kish 1965). \code{deff = 1} means the design is doing as well as a -coin flip over the frame; above 1 it is doing worse, which is the usual price -of clustering; below 1 it is doing better, which is what stratification and -probability-proportional-to-size buy you. +simple random sample from the rows it can reach; above 1 it is doing worse, +which is the usual price of clustering; below 1 it is doing better, which is +what stratification and probability-proportional-to-size buy you. } \details{ Read it as an exchange rate on sample size: at \code{deff = 2}, a sample of 400 carries about as much information as 200 drawn at random. -\code{survey} has a \code{deff()} of its own, and attaching \code{survey} after this -package masks this one. Both work on an estimate from \code{\link[=ht_total]{ht_total()}} or -\code{\link[=ht_mean]{ht_mean()}}, so the masking is harmless. +The simple random sample it is measured against is drawn from the rows the +design gives a probability above 0, \code{sum(inclusion_prob(design, frame) > 0)} +of them, because those are the rows a total or a Hajek mean estimates +over. Rows past \code{max_items}, outside a region or time window, dropped by +\code{na_rm} or in a stratum allocated no rows are left out. Counting them set +an equal-probability sample of 20 from the first 100 rows of a 400-row +frame at a design effect of 0.05 for a total, "better than simple random +sampling", where the right figure is 1. +\code{survey} measures against the sum of the weights, which is that count for +an equal-probability design, and gives the same design effect there. A +Horvitz-Thompson mean +(\code{estimator = "ht"}) divides the total by the frame's row count, so its +design effect is the total's. + +The design effect is \code{NA} when there is no variance, and when \code{y} takes +one value in every sampled row, where there is no spread for a simple +random sample to be measured by. It is \code{NA} too for a mean from +\code{ht_mean(na_rm = TRUE)} with \code{y} missing in some sampled rows, since the +rows with \code{y} are a domain of the sample, and a domain's design effect is +not estimated. + +A table of domain estimates from \code{by}, of several variables, of the +levels of a factor or of quantiles carries no design effect, and \code{deff()} +refuses it with a message saying so. A contrast's design effect is \code{NA}, +and so is a quantile's from \code{\link[=ht_quantile]{ht_quantile()}}. A ratio from \code{\link[=ht_ratio]{ht_ratio()}}, +and a total from the ratio estimator, are measured against the same +estimator from a simple random sample, through the variance of its +linearised residuals, as \code{survey::svyratio(deff = TRUE)} measures a +ratio. + +\code{survey} has a \code{deff()} of its own, and whichever of the two packages is +attached last masks the other's. Either one answers for both. This +\code{deff()} is a generic that passes an object it has no method for, such as +\code{survey::svymean(..., deff = TRUE)}, to \code{survey::deff()}, and \code{survey}'s +generic finds the methods for the estimates made here. } \examples{ set.seed(1) diff --git a/man/deff_cluster.Rd b/man/deff_cluster.Rd new file mode 100644 index 0000000..20939d8 --- /dev/null +++ b/man/deff_cluster.Rd @@ -0,0 +1,59 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plan.R +\name{deff_cluster} +\alias{deff_cluster} +\title{Design effect of a cluster sample, from the intraclass correlation} +\usage{ +deff_cluster(m, icc) +} +\arguments{ +\item{m}{Rows taken from each cluster, 1 or more. With one row a +cluster, the design effect is 1 whatever \code{icc} is.} + +\item{icc}{Intraclass correlation, from a pilot or a published study of +the same measure, between \code{-1 / (m - 1)} and 1. A negative one, rows +of a cluster less alike than rows taken at random, gives a design +effect below 1.} +} +\value{ +The design effect, a number. \code{m} and \code{icc} may be vectors, +recycled to a common length, and give one design effect per pair. +} +\description{ +The design effect of taking \code{m} rows from each cluster, for +\code{\link[=plan_size]{plan_size()}} before a pilot has measured one with \code{\link[=deff]{deff()}}: +\code{1 + (m - 1) * icc}, with \code{icc} the intraclass correlation of the +measure, the correlation between two rows of one cluster (Kish 1965). +Rows of one cluster tend to be alike, so each row taken from a cluster +already sampled adds less than a row from a new cluster would, and the +more alike they are and the more taken from each, the larger the design +effect. +} +\details{ +The formula assumes every cluster gives the same number of rows, drawn +by simple random sampling of clusters. \code{plan_size()} counts rows, so a +plan of \code{n} rows in clusters of \code{m} takes \code{ceiling(n / m)} clusters, and +the "Where the formula comes from" section of \code{\link[=plan_size]{plan_size()}} explains why +a few clusters call for more than the plan. +} +\examples{ +deff_cluster(m = 10, icc = 0.05) + +# Rows to draw, and the clusters of ten rows that hold them +p <- plan_size(margin = 5, sd = 40, N = 20000, + deff = deff_cluster(m = 10, icc = 0.05)) +p$n +ceiling(p$n / 10) + +# Takes of 5, 10 and 20 rows a cluster, side by side +plan_size(margin = 5, sd = 40, N = 20000, + deff = deff_cluster(m = c(5, 10, 20), icc = 0.05)) + +} +\references{ +Kish, L. (1965). \emph{Survey Sampling}. Wiley. +} +\seealso{ +\code{\link[=plan_size]{plan_size()}}, \code{\link[=deff]{deff()}} to measure the design effect of a past +sample. +} diff --git a/man/design_bootstrap.Rd b/man/design_bootstrap.Rd index 3079300..ffefe97 100644 --- a/man/design_bootstrap.Rd +++ b/man/design_bootstrap.Rd @@ -7,34 +7,63 @@ design_bootstrap( n_replicates = 1000L, n = NULL, - method = c("simple", "block"), - block_length = NULL + method = c("simple", "block", "circular"), + block_length = NULL, + output = c("rows", "indices", "weights") ) } \arguments{ \item{n_replicates}{Number of replicates to generate.} \item{n}{Rows per replicate. \code{NULL} uses \code{nrow(data)}, the standard -nonparametric bootstrap.} +nonparametric bootstrap. \code{n = 0} gives replicates with no rows. The +frame then has no rows but keeps its \code{.replicate} column, so \code{split()} +returns no replicates at all, while +\code{split(out, factor(out$.replicate, seq_len(n_replicates)))} returns +\code{n_replicates} empty ones. A plan from \code{\link[=plan_size]{plan_size()}} gives its \code{n}.} -\item{method}{\code{"simple"} or \code{"block"}.} +\item{method}{\code{"simple"}, \code{"block"} or \code{"circular"}.} -\item{block_length}{Block length for \code{method = "block"}, and an error for -\code{method = "simple"}, where it would have no effect. \code{NULL} uses -\code{floor(nrow(data)^(1/3))}, a common rule of thumb.} +\item{block_length}{Run length for \code{method = "block"} and \code{"circular"}, and +an error for \code{method = "simple"}, where it would have no effect. \code{NULL} +uses \code{floor(nrow(data)^(1/3))}, a common rule of thumb.} + +\item{output}{What \code{\link[=draw]{draw()}} returns. +\itemize{ +\item \code{"rows"}, the default, returns the resampled rows of every replicate in +one data frame, with a leading \code{.replicate} column. +\item \code{"indices"} returns an integer matrix with \code{n} rows and a column per +replicate, holding the rows of \code{data} that each replicate drew, in +order. Row \code{i} of replicate \code{r} is \code{data[out[i, r], ]}. +\item \code{"weights"} returns an integer matrix with a row for each row of \code{data} +and a column per replicate, holding the number of times each replicate +drew that row. With the default \code{n}, these are replicate weights for +\code{survey::svrepdesign(type = "bootstrap", combined.weights = TRUE)}. +} + +For one seed, all three hold the same replicates.} } \value{ A design object, for use with \code{\link[=draw]{draw()}}. } \description{ -Generates bootstrap replicates. \code{"simple"} resamples rows independently; -\code{"block"} is a moving-block bootstrap, which preserves the serial dependence -in ordered data by concatenating \code{ceiling(n / block_length)} independently -chosen blocks per replicate. +Generates bootstrap replicates. \code{"simple"} resamples rows independently. +\code{"block"} is the moving-block bootstrap (Künsch 1989), which keeps the +serial dependence in ordered data by concatenating \code{ceiling(n / block_length)} runs of \code{block_length} consecutive rows per replicate, each +starting at a row chosen at random. A run must fit inside the frame, so +fewer runs cover the first and last \code{block_length - 1} rows, and the first +row and the last turn up only \code{1 / block_length} as often as a row in the +middle. \code{"circular"} (Politis and Romano 1992) joins the last row to the +first, so a run can wrap around the end and every row turns up equally +often on average. } \details{ -\code{\link[=draw]{draw()}} returns all replicates in one data frame with a leading \code{.replicate} -column. Split them with \code{split(out, out$.replicate)}. +By default \code{\link[=draw]{draw()}} returns all replicates in one data frame with a leading +\code{.replicate} column. Split them with \code{split(out, out$.replicate)}. That +frame holds \code{n_replicates * n} rows, a copy of the data for each replicate, +and \code{\link[=draw]{draw()}} warns, with class \code{drawn_bootstrap_size}, when it would exceed +10 million rows. \code{output = "indices"} and \code{output = "weights"} return the +same replicates as a matrix instead. } \section{Not a survey design}{ @@ -42,9 +71,16 @@ 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 \code{\link[=ht_total]{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). +or mean, use the estimators there. + +Resampling rows treats them as independent draws from one distribution. +For such data and a statistic those estimators do not cover, such as a +median, the bootstrap is the standard tool. A sample drawn with strata or +clusters is not such data, and resampling its rows one by one ignores the +strata and treats the rows of a cluster as independent. Resample the +clusters within strata instead, for example with +\code{survey::as.svrepdesign(as_svydesign(s), type = "subbootstrap")}. Runs of +rows keep short-range dependence in ordered data (Künsch 1989). } \examples{ @@ -56,6 +92,17 @@ table(reps$.replicate) # A statistic per replicate vapply(split(reps, reps$.replicate), function(r) mean(r$value), numeric(1)) +# The same replicates as row numbers, without copying the data +idx <- draw(df, design_bootstrap(n_replicates = 5, n = 20, + output = "indices"), seed = 1) +apply(idx, 2, function(i) mean(df$value[i])) + +# Runs of 10 rows that may wrap from the last row to the first +circ <- draw(df, design_bootstrap(n_replicates = 200, method = "circular", + block_length = 10, output = "weights"), + seed = 1) +range(rowMeans(circ)) + } \references{ Efron, B. (1979). Bootstrap methods: another look at the jackknife. @@ -63,6 +110,10 @@ Efron, B. (1979). Bootstrap methods: another look at the jackknife. Künsch, H. R. (1989). The jackknife and the bootstrap for general stationary observations. \emph{Annals of Statistics}, 17, 1217–1241. + +Politis, D. N. and Romano, J. P. (1992). A circular block-resampling +procedure for stationary data. In R. LePage and L. Billard (eds.), +\emph{Exploring the Limits of Bootstrap}, 263–270. Wiley. } \seealso{ \code{\link[=draw]{draw()}} diff --git a/man/design_certainty.Rd b/man/design_certainty.Rd index a91ed2f..64d1952 100644 --- a/man/design_certainty.Rd +++ b/man/design_certainty.Rd @@ -32,6 +32,14 @@ Certainty rows have an inclusion probability of exactly 1, so they contribute their own value to a Horvitz-Thompson total with a weight of 1 and add nothing to its variance. That is the whole point: the uncertainty in the estimate comes only from the part you sampled. + +A \code{rest} with a random sample size, such as +\code{design_weighted(method = "poisson")} with a small \code{n}, can draw none of the +rows below the threshold. Those rows then went unobserved, so \code{\link[=ht_total]{ht_total()}} +and \code{\link[=ht_mean]{ht_mean()}} report no variance rather than an exact total. +\code{draw(weights = TRUE)} refuses a \code{rest} that can never draw any of them, +such as one with \code{n = 0}; without weights the draw is a cut-off sample of +the rows above the threshold. } \examples{ set.seed(1) diff --git a/man/design_cluster.Rd b/man/design_cluster.Rd index ad7ae69..641f982 100644 --- a/man/design_cluster.Rd +++ b/man/design_cluster.Rd @@ -12,7 +12,7 @@ design_cluster(clusters, n_clusters, balanced = FALSE, na_rm = FALSE) \item{n_clusters}{Number of clusters to select.} \item{balanced}{Take an equal number of rows from each selected cluster, -equal to the smallest selected cluster's size.} +equal to the smallest selected cluster's size. See "Balanced clusters".} \item{na_rm}{Drop rows whose cluster label is \code{NA} instead of raising an error. When \code{FALSE}, missing labels are never treated as a cluster of their @@ -26,10 +26,46 @@ Selects whole clusters at random and returns all of their rows. The row count follows from which clusters were picked, so there is no \code{n}; use \code{\link[=design_multistage]{design_multistage()}} when you need to control it. } +\section{Balanced clusters}{ + +With \code{balanced = TRUE}, each of the \code{a} clusters selected out of \code{A} +gives \code{m} rows by simple random sampling, \code{m} being the size of the +smallest of them. A row of a cluster of \code{N_i} rows has inclusion +probability \code{(a / A) * E(m) / N_i}, where \code{E(m)} is the average take +over the selections that include its cluster. \code{\link[=inclusion_prob]{inclusion_prob()}} +computes it exactly: given that cluster \code{i} is selected, the take is at +least \code{s} rows when the other \code{a - 1} clusters selected all hold \code{s} rows +or more, which happens with probability +\code{choose(c_s - 1, a - 1) / choose(A - 1, a - 1)}, \code{c_s} being the number +of clusters of \code{s} rows or more, and \code{E(m)} adds these up for \code{s} from 1 +to \code{N_i}. On clusters of 2, 4, 6 and 8 rows with two selected, that gives +0.5, 0.417, 0.333 and 0.25. + +\code{draw(weights = TRUE)} weights a balanced sample conditional on the +clusters it selected instead: \code{.prob} is \code{(a / A) * m / N_i} for the \code{m} +taken in this draw. The estimate of a total is then \code{A / a} times the sum +of the selected clusters' estimated totals, which is unbiased whichever +clusters were selected, and so over all of them. \code{\link[=ht_total]{ht_total()}} and +\code{\link[=ht_mean]{ht_mean()}} use the two-stage variance of \code{\link[=design_multistage]{design_multistage()}}, with the +variance between the estimated cluster totals and within each cluster, +and \code{\link[=as_svydesign]{as_svydesign()}} hands the sample to \code{survey} in two stages. The +smallest selected cluster is taken whole and adds no variance within it. +When it holds one row, every cluster gives one, the variation within +clusters cannot be measured, and the variance falls back to the +delete-a-cluster jackknife. Joint probabilities have no closed form; +\code{\link[=joint_prob]{joint_prob()}} estimates them with \code{simulate = TRUE}. +} + \examples{ df <- data.frame(id = 1:100, site = rep(paste0("s", 1:10), each = 10)) unique(draw(df, design_cluster("site", n_clusters = 3), seed = 1)$site) +# Balanced: the take is the smallest selected cluster's size, so a row of +# a large cluster is less likely to be drawn +uneven <- data.frame(site = rep(c("a", "b", "c", "d"), c(2, 4, 6, 8))) +bal <- design_cluster("site", n_clusters = 2, balanced = TRUE) +round(tapply(inclusion_prob(uneven, bal), uneven$site, unique), 3) + } \seealso{ \code{\link[=draw]{draw()}} diff --git a/man/design_multistage.Rd b/man/design_multistage.Rd index 3cc9b92..4f5d37f 100644 --- a/man/design_multistage.Rd +++ b/man/design_multistage.Rd @@ -11,7 +11,8 @@ design_multistage( allocation = c("equal", "proportional"), min_per_cluster = 0L, replace = FALSE, - na_rm = FALSE + na_rm = FALSE, + size = NULL ) } \arguments{ @@ -19,24 +20,41 @@ design_multistage( \item{n_clusters}{Number of clusters to select at stage one.} -\item{n}{Total rows to draw across the selected clusters. Make it a -multiple of \code{n_clusters}, and no larger than \code{n_clusters} times the -smallest cluster, if you intend to estimate: otherwise the per-cluster take -depends on which clusters were selected and there is no closed-form -inclusion probability. See \code{\link[=inclusion_prob]{inclusion_prob()}}.} +\item{n}{Total rows to draw across the selected clusters, at least +\code{n_clusters}, or a plan from \code{\link[=plan_size]{plan_size()}}. A multiple of \code{n_clusters}, +no larger than \code{n_clusters} times the smallest cluster, gives every +selected cluster the same take and every row a closed-form inclusion +probability. Otherwise the take depends on which clusters were +selected, and \code{draw(weights = TRUE)} weights the sample conditional on +them. See "When the take depends on the clusters selected".} \item{allocation}{\code{"equal"} splits \code{n} evenly across the selected clusters; -\code{"proportional"} splits it in proportion to their size.} +\code{"proportional"} splits it in proportion to their size, and its weights +are conditional on the clusters selected. Proportional allocation can +give a small selected cluster no rows; \code{\link[=draw]{draw()}} then warns with class +\code{drawn_empty_cluster} and names it.} \item{min_per_cluster}{Minimum rows from each selected cluster. Defaults to -\code{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 -\code{\link[=ht_total]{ht_total()}} falls back to the ultimate-cluster jackknife.} +\code{0}, and \code{n_clusters * min_per_cluster} must not exceed \code{n}. A cluster +smaller than the minimum is taken whole. \code{draw(weights = TRUE)} needs at +least 1 under proportional allocation. Take at least two rows per +cluster if you intend to estimate a variance: with one, the variation +within clusters cannot be measured and \code{\link[=ht_total]{ht_total()}} falls back to the +ultimate-cluster jackknife.} -\item{replace}{Sample with replacement within each cluster?} +\item{replace}{Sample with replacement within each cluster? A selected +cluster then gives its full share of \code{n} however small it is, and a row's +inclusion probability is the chance of being drawn at least once, +\code{(n_clusters / N_clusters) * (1 - (1 - 1 / N_h)^m)} for a take of \code{m} +from a cluster of \code{N_h} rows.} -\item{na_rm}{Drop rows whose cluster label is \code{NA} instead of raising an -error.} +\item{na_rm}{Drop rows whose cluster label, or \code{size}, is \code{NA} instead of +raising an error.} + +\item{size}{Optional column holding each cluster's size measure, the same +on every row of a cluster: positive, finite and numeric. Clusters are +then selected with probability proportional to it. See "Clusters in +proportion to size".} } \value{ A design object, for use with \code{\link[=draw]{draw()}}. @@ -46,10 +64,92 @@ Selects clusters at the first stage, then draws rows within them at the second. \code{n} is the total across the selected clusters under both allocations, matching \code{\link[=design_stratified]{design_stratified()}}. } +\section{When the take depends on the clusters selected}{ + +Without \code{size}, the \code{n} rows are split over the clusters selected, so a +cluster's take is the same in every sample only under \code{"equal"} +allocation of an \code{n} that divides by \code{n_clusters}, with no cluster +smaller than \code{n / n_clusters}. Otherwise, under \code{"proportional"} +allocation, with a remainder that goes to the largest clusters selected, +or with a small cluster capped at its size and its shortfall dealt to the +others, a row's inclusion probability depends on which other clusters +were selected. It is the chance of drawing the row given the clusters +selected, averaged over every possible selection, which has no closed +form, so \code{\link[=inclusion_prob]{inclusion_prob()}} refuses it. + +\code{draw(weights = TRUE)} weights such a sample conditional on the clusters +it selected. With \code{a} of \code{A} clusters selected and \code{m_i} of the \code{N_i} +rows of cluster \code{i} taken, \code{.prob} is \code{(a / A) * m_i / N_i}, and the +estimate of a total is \code{A / a} times the sum of the selected clusters' +estimated totals. That is unbiased whichever clusters were selected, and +so over all of them. \code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} estimate its variance +with the two-stage formula, the variance between the estimated cluster +totals plus that within each cluster at its own take, on \code{a - 1} degrees +of freedom, and \code{\link[=as_svydesign]{as_svydesign()}} hands it to \code{survey} in two stages, +where the standard errors agree. The variance falls back to the +delete-a-cluster jackknife when a selected cluster gives one row of +several. Proportional allocation needs \code{min_per_cluster} of at least 1 +for weights, since a selected cluster with no rows would count as a +cluster total of 0. +} + +\section{Clusters in proportion to size}{ + +With \code{size}, the clusters are selected with probability proportional to a +size measure, such as a count of households from a census, by +systematic PPS as in \code{\link[=design_weighted]{design_weighted()}}: cluster \code{i} gets +\code{pi_i = n_clusters * M_i / sum(M)}, and a cluster large enough that this +passes 1 is taken with certainty, the rest of \code{n_clusters} being spread +over the others. Each selected cluster then gives the same \code{m = n / n_clusters} rows by simple random sampling, so a row of cluster \code{i}, of +\code{N_i} rows, has inclusion probability \code{pi_i * m / N_i}. When the measure +is the cluster's row count and no cluster is certain, every row gets +\code{n / N}: the design is self-weighting, with a fixed number of interviews +per cluster. + +The measure is a property of the cluster, so every row of a cluster must +carry the same value; a cluster with two values is refused. \code{n} must be a +multiple of \code{n_clusters}, and \code{allocation} must be \code{"equal"}. + +\code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} estimate the variance as Deville's +approximation over the estimated totals of the selected clusters below +certainty, each scaled by its own \code{1 - pi_i}, plus the variance within the +selected clusters, each divided by its \code{pi_i}. That is the two-stage +estimator of \code{\link[=design_multistage]{design_multistage()}} without \code{size} when every \code{pi_i} is +equal. A cluster taken with certainty is a stratum, and adds only the +variance of the simple random sample within it. The degrees of freedom +count the clusters below certainty less one, and in each certain cluster +the sampled rows less one. The variance is declined when one cluster +below certainty is selected. With one row taken per cluster, whose +variation within clusters cannot be measured, \code{\link[=ht_total]{ht_total()}} falls back to +the delete-a-cluster jackknife over the clusters below certainty, with no +finite population correction, and declines if a cluster taken with +certainty gives one row of several. In simulations of 2,000 draws +each from frames of 78 or 80 clusters of 10 to 600 rows, taking 2 or 5 +rows from each of 12 or 20 clusters, with and without clusters taken +with certainty, the variance averaged 0.94 to 1.02 times the true +variance of the total, and 95\% intervals covered 93\% to 95\% of the time. + +\code{\link[=as_svydesign]{as_svydesign()}} hands the design to \code{survey} in two stages with +Brewer's approximation at the first. A sample with one row from a +selected cluster of several goes over in one stage instead, as the +clusters of that jackknife, and the standard errors agree. Joint +probabilities have no closed form; \code{\link[=joint_prob]{joint_prob()}} estimates them with +\code{simulate = TRUE}. +} + \examples{ df <- data.frame(id = 1:100, site = rep(paste0("s", 1:10), each = 10)) nrow(draw(df, design_multistage("site", n_clusters = 4, n = 12), seed = 1)) +# Villages selected in proportion to their households, then 5 households +# from each: every household has the same chance, 20 / 260 +hh <- data.frame(village = rep(paste0("v", 1:8), + times = c(10, 20, 30, 40, 20, 50, 60, 30))) +hh$households <- ave(seq_len(nrow(hh)), hh$village, FUN = length) +pps <- design_multistage("village", n_clusters = 4, n = 20, + size = "households") +unique(round(inclusion_prob(hh, pps), 4)) + } \seealso{ \code{\link[=draw]{draw()}} diff --git a/man/design_reservoir.Rd b/man/design_reservoir.Rd index 2015ece..a06031a 100644 --- a/man/design_reservoir.Rd +++ b/man/design_reservoir.Rd @@ -4,16 +4,24 @@ \alias{design_reservoir} \title{Reservoir sampling} \usage{ -design_reservoir(n, max_items = Inf) +design_reservoir(n, max_items = Inf, batches = FALSE) } \arguments{ -\item{n}{Reservoir size. Fewer items come back if the stream is shorter; the -result is never padded.} +\item{n}{Reservoir size, or a plan from \code{\link[=plan_size]{plan_size()}}. Fewer items come +back if the stream is shorter; the result is never padded.} -\item{max_items}{Stop after reading this many items. Rows past it are never -read, so \code{\link[=inclusion_prob]{inclusion_prob()}} gives them \code{0} and gives the rows before it -\code{n / max_items} rather than \code{n / N}. \code{Inf} reads the whole -stream. Warns when the cap actually truncates.} +\item{max_items}{Stop after this many items, or rows with +\code{batches = TRUE}. Items past the cap are never sampled, so +\code{\link[=inclusion_prob]{inclusion_prob()}} gives rows past it \code{0} and gives the rows before it +\code{n / max_items} rather than \code{n / N}. A stream is read one item past the +cap; see "What is read". \code{Inf} reads the whole stream. Warns when the cap +truncates.} + +\item{batches}{If \code{TRUE}, \code{data} is a function that returns a data frame of +rows on each call and \code{NULL} at the end, and the reservoir samples rows +rather than whole data frames. \code{\link[=draw]{draw()}} then returns a data frame. A data +frame given as \code{data} is sampled by rows either way; a list or a +connection is refused.} } \value{ A design object, for use with \code{\link[=draw]{draw()}}. @@ -24,12 +32,61 @@ single pass, using Algorithm L (Li 1994), which skips ahead geometrically instead of drawing a random number for every item (Vitter 1985). } \details{ -A data frame is not a stream: its length is already known and it already fits -in memory, so \code{\link[=draw]{draw()}} takes a direct vectorised path for one. Reach for the -streaming path when the data genuinely does not fit — pass a connection, or a -function that returns the next item and \code{NULL} at end of stream. For those, -\code{\link[=draw]{draw()}} returns a list rather than a data frame. +A data frame or a list is not a stream: its length is already known and it +already fits in memory, so \code{\link[=draw]{draw()}} picks \code{n} positions in it at random and +returns them in their original order. Every element of a list is an item, +\code{NULL} included, and the elements keep their names. The streaming path is +for data that does not fit in memory. Pass it a connection, or a function +that returns the next item and \code{NULL} at end of stream. It holds at most \code{n} +items at a time, plus the block it is reading, and returns them in the order +they arrived. For a list, a connection or a function, \code{\link[=draw]{draw()}} returns a +list rather than a data frame, except with \code{batches = TRUE}. + +The two paths use different algorithms, so for one seed a stream gives a +different sample from a data frame or list holding the same items. Each +path on its own gives the same sample for the same seed. } +\section{Items in a stream}{ + +Each line of a connection is one item, a character string as \code{\link[=readLines]{readLines()}} +returns it, and a header line is an item like any other. To leave a CSV +header out of the sample, open the connection, read the header with +\code{readLines(con, n = 1)} and then draw from the connection, which is read +from where the header left off. \code{read.csv(text = c(header, unlist(lines)))} +turns the sampled lines into a data frame (see the examples). \code{\link[=draw]{draw()}} +reads a connection in blocks of 10,000 lines, which gives the same sample +for a seed as reading it line by line. + +A function is called once for each item, and whatever it returns is that +item, a data frame included, so a function that returns blocks of rows +gives a sample of whole blocks. With \code{batches = TRUE} the rows are the +items instead: each call returns a data frame of rows, every batch with the +same columns in the same order, and \code{\link[=draw]{draw()}} returns \code{n} of those rows as +one data frame, bound with \code{\link[=rbind]{rbind()}} in the order they arrived. \code{\link[=draw]{draw()}} +compares only the column names. A column whose type differs between +batches, such as one that \code{\link[=read.csv]{read.csv()}} reads as logical in a batch where it +is empty, takes the type \code{\link[=rbind]{rbind()}} gives the sampled rows. Cutting the same +rows into batches of other sizes gives the same sample for a seed. Between +batches it keeps at most \code{max(2 * n, 1024)} rows, some of them already +dropped from the sample, besides the batch being read. +} + +\section{What is read}{ + +A connection that is not open is opened, read to its end (or to one line +past a finite \code{max_items}) and closed, as \code{\link[=read.csv]{read.csv()}} does, so it cannot +be drawn from twice. A connection that is already open is read from where +it stands and left open. + +With a finite \code{max_items}, \code{\link[=draw]{draw()}} reads one item past the cap, because +only that read tells a stream of exactly \code{max_items} items from a longer +one. On an open connection in text mode the line goes back with +\code{\link[=pushBack]{pushBack()}}, so the next read starts with it. A connection opened in +binary mode (\code{"rb"}) cannot take a line back, and loses it. A function is +called once past the cap and what it returns is dropped; with +\code{batches = TRUE}, so are the rows of a batch that run past the cap. +} + \examples{ nrow(draw(data.frame(id = 1:1000), design_reservoir(n = 10), seed = 1)) @@ -41,6 +98,28 @@ gen <- function() { } unlist(draw(gen, design_reservoir(n = 5), seed = 1)) +# A CSV file read line by line, with its header left out of the sample +path <- tempfile(fileext = ".csv") +write.csv(data.frame(id = 1:200, value = (1:200) \%\% 7), path, + row.names = FALSE) +con <- file(path, "r") +header <- readLines(con, n = 1) +lines <- draw(con, design_reservoir(n = 5), seed = 1) +close(con) +read.csv(text = c(header, unlist(lines))) + +# The same file parsed 50 rows at a time, sampling rows: the same five +# rows as above for the same seed +con <- file(path, "r") +header <- readLines(con, n = 1) +next_rows <- function() { + lines <- readLines(con, n = 50) + if (length(lines) == 0) NULL else read.csv(text = c(header, lines)) +} +draw(next_rows, design_reservoir(n = 5, batches = TRUE), seed = 1) +close(con) +unlink(path) + } \references{ Vitter, J. S. (1985). Random sampling with a reservoir. \emph{ACM Transactions diff --git a/man/design_simple.Rd b/man/design_simple.Rd index 201c369..93e965c 100644 --- a/man/design_simple.Rd +++ b/man/design_simple.Rd @@ -4,15 +4,21 @@ \alias{design_simple} \title{Simple random sampling} \usage{ -design_simple(n, replace = FALSE) +design_simple(n, replace = FALSE, reserve = 0) } \arguments{ -\item{n}{Number of rows to draw. A single non-negative whole number.} +\item{n}{Number of rows to draw. A single non-negative whole number, or a +plan from \code{\link[=plan_size]{plan_size()}}.} \item{replace}{Sample with replacement? Note that \code{draw(weights = TRUE)} declines a with-replacement design: \code{.prob} would be the chance of appearing at least once, which does not weight a sample holding duplicates. See \code{\link[=draw]{draw()}}.} + +\item{reserve}{Number of reserve units to list after the main sample, to +replace units found unavailable in the field. A single non-negative whole +number; \code{n + reserve} cannot exceed the rows of the frame. Not available +with \code{replace = TRUE} or \code{n = 0}. See "Reserves".} } \value{ A design object, for use with \code{\link[=draw]{draw()}}. @@ -20,14 +26,46 @@ A design object, for use with \code{\link[=draw]{draw()}}. \description{ Draws \code{n} rows uniformly at random. } +\section{Reserves}{ + +Fieldwork often finds that some sampled units cannot be reached: a site +with no access, a business that has closed, a plot under water. \code{reserve} +draws that many more units with the main sample, as a list to replace them +from. \code{\link[=draw]{draw()}} returns the \code{n} units of the main sample followed by the +\code{reserve} units, with an integer \code{.reserve} column: 0 for the main sample, +and 1, 2, ... for the reserves, in the order they are used. The list is +one random draw of \code{n + reserve} units in random order, so the main sample +is a simple random sample of \code{n}, the one the design without \code{reserve} +draws with the same seed, and the first \code{k} units of the list are a +simple random sample of \code{k} for any \code{k}. + +Visit every unit of the main sample, and for each one found unavailable, +visit the next reserve. \code{\link[=use_reserves]{use_reserves()}} takes the list and what the +visits found, and returns the sample to estimate from: the first \code{n} units +of the list found available. They are a simple random sample of \code{n} from +the units of the frame that are available, and \code{\link[=use_reserves]{use_reserves()}} weights +them as one, with probability \code{n / (N - u)} when \code{u} listed units were +found unavailable. Replacing units changes what is estimated: the totals +and means are those of the units that can be reached, not of the whole +frame. "What the estimates describe" in \code{\link[=use_reserves]{use_reserves()}} has the details. + +Until then the list is not a sample to estimate from. \code{\link[=inclusion_prob]{inclusion_prob()}} +and the \code{.prob} column give every row the main sample's probability, +\code{n / N}, and \code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}}, \code{\link[=as_svydesign]{as_svydesign()}} and +\code{\link[=sample_summary]{sample_summary()}} refuse the list. +} + \examples{ df <- data.frame(id = 1:100) draw(df, design_simple(n = 10), seed = 1) draw(df, design_simple(n = 150, replace = TRUE), seed = 1) +# Ten units and three reserves, used in the order of `.reserve` +draw(df, design_simple(n = 10, reserve = 3), seed = 1) + } \seealso{ -\code{\link[=draw]{draw()}} +\code{\link[=draw]{draw()}}, \code{\link[=use_reserves]{use_reserves()}} Other designs: \code{\link{design_bootstrap}()}, diff --git a/man/design_spatial.Rd b/man/design_spatial.Rd index e391cd6..fc2a1a4 100644 --- a/man/design_spatial.Rd +++ b/man/design_spatial.Rd @@ -7,15 +7,19 @@ design_spatial(coords, region, n, crs = 4326, na_rm = FALSE) } \arguments{ -\item{coords}{Two column names, \code{c(x, y)} — longitude then latitude.} +\item{coords}{Two column names, \code{c(x, y)} with longitude first, or the +name of one POINT geometry column. See "Coordinate order".} -\item{region}{An \code{sf} or \code{sfc} geometry, or a list of them, which is unioned. -Reprojected to \code{crs} when it differs.} +\item{region}{An \code{sf} or \code{sfc} geometry of POLYGON or MULTIPOLYGON +features, or a list of them. A row inside any of them is inside the +region. Each is reprojected to the coordinates' CRS when its own differs.} -\item{n}{Number of rows to draw from inside the region.} +\item{n}{Number of rows to draw from inside the region, or a plan from +\code{\link[=plan_size]{plan_size()}}.} \item{crs}{Coordinate reference system of the coordinate columns. Defaults to -EPSG:4326.} +EPSG:4326. A geometry column named in \code{coords} keeps its own CRS when it +has one.} \item{na_rm}{Drop rows with missing coordinates instead of raising an error.} } @@ -33,7 +37,49 @@ restricted to the region if need be. \code{coords} is \code{c(x, y)} — longitude first, then latitude — matching \code{\link[sf:st_as_sf]{sf::st_as_sf()}}. Getting this backwards puts your points somewhere else -entirely, so it is worth checking against a known landmark once. +entirely, so it is worth checking against a known landmark once. When the +coordinates are longitude and latitude, a latitude outside -90 to 90 or a +longitude outside -180 to 360 is refused, since it means the columns are +the wrong way round or hold projected coordinates. + +A POINT geometry column, such as the geometry of an \code{sf} frame, can stand +in for the two columns: name it alone, as in \code{coords = "geometry"}, and +each row's position is read with \code{\link[sf:st_coordinates]{sf::st_coordinates()}}. The column's own +CRS is used when it has one, and \code{region} is reprojected to it. +} + +\section{Edges of a longitude/latitude region}{ + +With spherical geometry (\code{\link[sf:s2]{sf::sf_use_s2()}}, the default), each edge of a +longitude/latitude \code{region} follows the great circle between its two +corners, the shortest path on the globe. On a flat longitude/latitude map +that path bows towards the nearer pole wherever the edge runs east-west +away from the equator; edges along a meridian or the equator do not bow. +A wide box is therefore a different shape from the rectangle it looks like +on such a map. The top edge of a box from -50 to 50 degrees of longitude +and -30 to 30 of latitude reaches latitude 41.9 at longitude 0, so a row +at (0, 41) is inside it, and its bottom edge reaches -41.9. A box from -5 +to 5 degrees of longitude and 40 to 50 of latitude takes in a row at +(0, 50.05) and leaves out one at (0, 40.05). + +\code{\link[=draw]{draw()}}, \code{\link[=inclusion_prob]{inclusion_prob()}}, \code{\link[=joint_prob]{joint_prob()}} and +\link[=plot.drawn_design]{plot()} warn, with class \code{drawn_geodesic_edges}, when +an edge of \code{region} passes more than 0.1 degrees (about 11 km) from the +straight line between its corners on a longitude/latitude map. To make the +edges follow those straight lines, add vertices along them in degree space +before you build the design: + +\if{html}{\out{
}}\preformatted{flat <- sf::st_set_crs(region, NA) # coordinates as plain numbers +flat <- sf::st_segmentize(flat, 0.1) # a vertex at least every 0.1 degrees +region <- sf::st_set_crs(flat, 4326) +}\if{html}{\out{
}} + +An edge 0.1 degrees long bows by about a metre at most. The CRS has to come +off for the middle step: on a region that keeps it, +\code{\link[sf:geos_unary]{sf::st_segmentize()}} needs the lwgeom package and places the new vertices +along the great circles, under either s2 setting, and the bow stays. A +region larger than a hemisphere needs splitting first; see the next +section. } \section{Regions that cross the antimeridian}{ @@ -47,13 +93,57 @@ against the roughly 510 million km2 of the globe -- and contains almost nothing. Ring orientation is not the cause and reversing it does not help: \code{sf} -normalises winding, so both directions give the same strip. Adding -intermediate vertices does not reliably help either, because the intermediate -edges still bow along geodesics. +normalises winding, so both directions give the same strip. Adding vertices +along the edges in degree space, as in the previous section, does not +rescue a region this large either. s2 takes the smaller of the two areas a +ring divides the globe into as its inside, so a ring around more than half +the globe encloses the rest of the globe instead. + +The short way is the right reading for a region meant to cross the +antimeridian, such as a box from longitude 179 to -179. \code{\link[=draw]{draw()}}, +\code{\link[=inclusion_prob]{inclusion_prob()}}, \code{\link[=joint_prob]{joint_prob()}} and \link[=plot.drawn_design]{plot()} warn, +with class \code{drawn_antimeridian}, whenever an edge of \code{region} joins two +longitudes more than 180 degrees apart, and the warning gives both +readings. An edge from -180 to 180 is one of them: both ends lie on the +same meridian, so under spherical geometry the edge spans no longitude, +and a box from -180 to 180 encloses nothing. An edge along a pole, where +every longitude meets, does not warn, so a cap around a pole closed along +it does not either. If you meant the short way, \code{region} is what you +drew. If you meant the long way, split the region into parts smaller than +a hemisphere, add vertices to each as in the previous section, and pass +the parts as a list; or switch to planar interpretation with +\code{sf::sf_use_s2(FALSE)}. +Splitting works under the default setting. Switching has to happen before +\code{\link[=draw]{draw()}} and stay in force for every estimate from the sample; see the next +section. +} + +\section{The s2 setting at draw time and after}{ + +Which rows fall inside \code{region} depends on \code{\link[sf:s2]{sf::sf_use_s2()}}. With spherical +geometry the edges of a longitude/latitude region are great-circle arcs, and +without it they are straight lines in longitude and latitude, so rows near an +edge can be inside under one setting and outside under the other. Use the +same setting when you draw a sample and whenever you analyse it. + +\code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}}, \code{\link[=as_svydesign]{as_svydesign()}} and \code{\link[=sample_summary]{sample_summary()}} find the +region's rows again each time they run, because the variance, the design +effect and \code{survey}'s population count all depend on them. They compare the +result with the inclusion probabilities stored at draw time, or with the +\code{.prob} column of a sample saved by drawn 0.2.0, and refuse the sample when +the two differ, naming \code{sf::sf_use_s2()}. The comparison catches any change +in which rows are inside, including one that comes with another version of +sf. A region that holds fewer than \code{n} rows under the current setting +leaves nothing to compare, and the sample is refused the same way. The +point estimate would not have moved, since it uses the stored \code{.prob}, but +the standard error would. -\code{\link[=draw]{draw()}} warns whenever any edge of \code{region} spans more than 180 degrees of -longitude. If you hit it, either split the region at the antimeridian into two -polygons, or switch to planar interpretation with \code{sf::sf_use_s2(FALSE)}. +\code{sf_use_s2()} is a session setting, and a new R session starts with it +\code{TRUE} unless the \verb{_SF_USE_S2} environment variable says otherwise. A sample +drawn under \code{sf::sf_use_s2(FALSE)} and saved with \code{\link[=saveRDS]{saveRDS()}} needs +\code{sf::sf_use_s2(FALSE)} again after \code{\link[=readRDS]{readRDS()}}. +\code{\link[=inclusion_prob]{inclusion_prob()}} and \code{\link[=joint_prob]{joint_prob()}} on the frame follow the current +setting too. } \examples{ diff --git a/man/design_spread.Rd b/man/design_spread.Rd index fecc2ad..eb01c38 100644 --- a/man/design_spread.Rd +++ b/man/design_spread.Rd @@ -4,13 +4,27 @@ \alias{design_spread} \title{Spatially balanced sampling} \usage{ -design_spread(across, n, size = NULL, scale = TRUE, na_rm = FALSE) +design_spread( + across, + n, + size = NULL, + scale = TRUE, + na_rm = FALSE, + strata = NULL, + allocation = c("proportional", "equal"), + reserve = 0 +) } \arguments{ \item{across}{Column names to spread the sample across: two coordinates for -a map, or any numeric auxiliary variables. At least one.} +a map, or any numeric auxiliary variables. At least one. A Date or +date-time column, and a POINT geometry column, are read as numbers; see +"Spreading over more than space".} -\item{n}{Number of rows to draw. Fixed, not expected.} +\item{n}{Number of rows to draw, the total across \code{strata} when given, or +a plan from \code{\link[=plan_size]{plan_size()}}. +Fixed, not expected. With counts in \code{allocation} it can be left out and +is their sum; when given, it must equal that sum.} \item{size}{Optional column of positive size measures. When given, rows are included with probability proportional to size — \code{n * size / sum(size)}, @@ -20,8 +34,26 @@ with rows past certainty taken whole, exactly as \item{scale}{Standardise each column of \code{across} to unit standard deviation before measuring distance. See "Spreading over more than space".} -\item{na_rm}{Drop rows with a missing value in \code{across} or \code{size} instead of -raising an error.} +\item{na_rm}{Drop rows with a missing value in \code{across}, \code{size} or +\code{strata} instead of raising an error.} + +\item{strata}{Optional column name(s) defining strata, to spread the +sample within each one. Several columns are cross-classified. See +"Strata".} + +\item{allocation}{How \code{n} is split across \code{strata}: \code{"proportional"} to +each stratum's size, or \code{"equal"}, by the largest-remainder method of +\code{\link[=design_stratified]{design_stratified()}}, with a stratum that would get more rows than it +holds taken whole; or the count for each stratum, as a named vector such +as \code{c(north = 10, south = 5)} when \code{strata} is one column, or a data +frame of the \code{strata} columns and \code{n}. Counts follow the rules of +\code{\link[=design_stratified]{design_stratified()}}: every stratum of the frame needs one, a count for +a stratum the frame does not have is refused, and no count may exceed +the rows in its stratum. Only with \code{strata}.} + +\item{reserve}{Number of reserve rows to list after the main sample, to +replace rows found unavailable in the field. Not available with \code{size}, +\code{strata} or \code{n = 0}. See "Reserves".} } \value{ A design object, for use with \code{\link[=draw]{draw()}}. @@ -60,6 +92,16 @@ boundaries (Grafström and Schelin 2014). With \code{scale = TRUE}, the default, each column is standardised first so that one measured in larger units does not decide the distances alone; set \code{scale = FALSE} for coordinates that already share a unit, such as projected metres. + +A Date column in \code{across} counts in days and a date-time (POSIXct) column +in seconds since 1970, so time can be spread over alongside space. Keep +\code{scale = TRUE} when mixing them with coordinates, or the column in the +larger unit decides the distances. \code{size} has to be numeric. + +A POINT geometry column, such as the geometry of an \code{sf} frame, counts as +its two coordinates, read with \code{\link[sf:st_coordinates]{sf::st_coordinates()}}: \code{across = "geometry"} spreads over the map. Distances are measured in the +geometry's own units, so longitude and latitude are treated as plain +numbers; a projected CRS gives distances in metres. } \section{Variance}{ @@ -70,17 +112,94 @@ the spreading bought. \code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_me mean variance estimator (Stevens and Olsen 2003; Grafström and Schelin 2014), which compares each sampled row with the mean of itself and its three nearest sampled neighbours. It is an approximation, reported as -\code{method = "local mean"}, and errs on the conservative side: in the -package's simulations it runs from about 1 to 1.6 times the true variance, -higher for small samples and large sampling fractions. +\code{method = "local mean"}, and usually overstates the variance. The table +gives the ratio of its average to the true variance of the total, over +1,000 draws from one frame per cell, by \code{n} and the sampling fraction +\code{f = n / N}. The frames are uniform on the unit square, spread with +\code{scale = FALSE}; the smooth surface is the one in the examples, and the +other variable is normal noise unrelated to position.\tabular{lrrrrr}{ + Variable \tab \code{n} \tab \code{f} = 0.05 \tab 0.2 \tab 0.5 \tab 0.8 \cr + smooth surface \tab 8 \tab 2.2 \tab 2.5 \tab 2.3 \tab 3.6 \cr + \tab 20 \tab 1.6 \tab 1.5 \tab 2.3 \tab 1.4 \cr + \tab 40 \tab 1.1 \tab 1.3 \tab 1.9 \tab 2.1 \cr + unrelated to position \tab 8 \tab 1.0 \tab 1.4 \tab 1.8 \tab 4.7 \cr + \tab 20 \tab 1.0 \tab 1.2 \tab 1.8 \tab 4.5 \cr + \tab 40 \tab 1.0 \tab 1.3 \tab 1.9 \tab 4.9 \cr +} + + +For a variable unrelated to position the ratio is close to \code{1 / (1 - f)}, +since the estimator then reduces to the with-replacement variance of a +simple random sample. It also varies from frame to frame: with \code{n = 20} +and \code{f = 0.05}, four frames of 400 rows gave 0.96 to 1.15 for that +variable and 1.36 to 1.52 for the smooth surface, so a ratio slightly +below 1 occurs too. Below about 10 sampled rows the ratio climbs: \code{n = 4} +gave 2.4 for the smooth surface at \code{f = 0.05}, and 18.9 on a frame of 8 +rows. + +\code{\link[=deff]{deff()}} divides this variance by a simple random sample's, so it carries +the same overstatement: at a ratio of 2, a spread sample with a true design +effect of 0.8 reports 1.6, worse than a simple random sample when it is +better. Rows taken with certainty, because their \code{size} puts them past it +or because \code{n} is the whole frame, are in every sample and add no variance, +so the estimator leaves them out. +} + +\section{Strata}{ + +With \code{strata}, \code{n} is split over the strata as \code{\link[=design_stratified]{design_stratified()}} +splits it, by \code{allocation}, and each stratum is then spread on its own, as +if it were a frame of its own: \code{scale} standardises the columns within the +stratum, \code{size} sets probabilities proportional to size within it, and a +row competes only with rows of its own stratum. \code{\link[=inclusion_prob]{inclusion_prob()}} gives +\code{n_h / N_h} within stratum \code{h}, or \code{n_h * p_i} with \code{size}, exactly. + +The strata are drawn independently, so \code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} add up +the local mean variance of each stratum, and the degrees of freedom are +the sampled rows below certainty less the strata that hold them. A stratum +with one sampled row below certainty has no neighbour to compare it with, +and the variance is refused with the stratum named, as a stratified +sample's is; draw at least two rows in every stratum. \code{\link[=as_svydesign]{as_svydesign()}} +hands the strata to \code{survey}, \code{\link[=allocation_table]{allocation_table()}} shows the split before +anything is drawn, and \code{\link[=sample_summary]{sample_summary()}} lists the rows drawn from each +stratum. + +Drawing each stratum with a design of its own and binding the samples with +\code{\link[=rbind]{rbind()}} does not give a sample to estimate from. The bound sample keeps +the first draw's frame and design, so \code{\link[=ht_total]{ht_total()}} refuses it; use +\code{strata} instead. +} + +\section{Reserves}{ + +\code{reserve} lists that many more rows after the main sample, to visit in +place of rows found unavailable in the field, as \code{\link[=design_simple]{design_simple()}} does. +The reserves are a second spread sample, of \code{reserve} rows at equal +probability from the rows the main sample left, so they cover the space +as evenly as the main sample does, and they come in random order. +\code{\link[=draw]{draw()}} returns the main sample in frame order followed by the reserves, +with an integer \code{.reserve} column: 0 for the main sample, and 1, 2, ... +for the reserves, in the order they are used. The main sample is the one +the design without \code{reserve} draws with the same seed. + +\code{\link[=use_reserves]{use_reserves()}} takes the list and what the visits found, and returns +the sample to estimate from. It weights the rows used as a spread sample +of \code{n} from the frame without the \code{u} rows found unavailable, at +probability \code{n / (N - u)}. That is the average of the rows' probabilities, +not each row's own, so the weights are an approximation. The variance is +the local mean estimator, as for any spread sample. Only an unstratified +design without \code{size}, whose rows all have probability \code{n / N}, takes +\code{reserve}. } \section{Cost}{ Each step finds a nearest neighbour among the rows still undecided, so the draw takes time proportional to \code{N^2}: under a second for 5,000 rows, and -several seconds at 20,000. For much larger frames, spread within strata or -thin the frame first. +several seconds at 20,000. With \code{strata}, the walk runs within each +stratum and the time grows with the square of each stratum's size: 20,000 +rows in four strata of 5,000 took under a third of the time they took as +one frame. For much larger frames, use strata, or thin the frame first. } \examples{ @@ -106,6 +225,13 @@ plot(design_simple(n = 40), plots, type = "map", coords = c("x", "y"), plot(spread, plots, type = "map", seed = 1) par(op) +# Spread within two regions, each given rows in proportion to its size +plots$region <- ifelse(plots$x < 0.5, "west", "east") +by_region <- design_spread(c("x", "y"), n = 40, scale = FALSE, + strata = "region") +allocation_table(plots, by_region) +ht_total(draw(plots, by_region, seed = 1, weights = TRUE), "biomass") + } \references{ Deville, J.-C. and Tillé, Y. (1998). Unequal probability sampling without @@ -127,7 +253,9 @@ natural resources. \emph{Journal of the American Statistical Association}, 99, } \seealso{ \code{\link[=draw]{draw()}}, \code{\link[=design_spatial]{design_spatial()}} to restrict sampling to a region, -\code{\link[=design_weighted]{design_weighted()}} for size-proportional selection without spreading. +\code{\link[=design_weighted]{design_weighted()}} for size-proportional selection without spreading, +\code{\link[=design_stratified]{design_stratified()}} for the allocation rules, \code{\link[=allocation_table]{allocation_table()}}, +\code{\link[=use_reserves]{use_reserves()}}. Other designs: \code{\link{design_bootstrap}()}, diff --git a/man/design_stratified.Rd b/man/design_stratified.Rd index 5d215f3..b5fdb34 100644 --- a/man/design_stratified.Rd +++ b/man/design_stratified.Rd @@ -11,29 +11,59 @@ design_stratified( allocation_by = NULL, min_per_stratum = 0L, replace = FALSE, - na_rm = FALSE + na_rm = FALSE, + cost = NULL, + within = NULL ) } \arguments{ \item{strata}{One or more column names defining the strata. Several columns are cross-classified.} -\item{n}{Total rows to draw across all strata, under either allocation.} +\item{n}{Total rows to draw across all strata, under any allocation, or a +plan from \code{\link[=plan_size]{plan_size()}}. With counts in \code{allocation} it can be left out +and is their sum; when given, it must equal that sum.} -\item{allocation}{How \code{n} is split across strata. \code{"proportional"} gives each -stratum a share of \code{n} in proportion to its size; \code{"equal"} splits \code{n} -evenly; \code{"neyman"} gives shares proportional to \code{size * sd}, using the -column named by \code{allocation_by} (Neyman 1934). Neyman minimises the -variance of a total for a fixed \code{n} by putting more rows where the values -vary most, and is the right choice when you have a frame variable -correlated with what you are measuring. Under any rule, a stratum that -would be allocated more rows than it holds is taken whole and the rest of -\code{n} re-split over the others by the same rule (Cochran 1977, section 5.9).} +\item{allocation}{How \code{n} is split across strata: a rule, or the count for +each stratum. Of the rules, \code{"proportional"} gives each stratum a share +of \code{n} in proportion to its size; \code{"equal"} splits \code{n} evenly; +\code{"neyman"} gives shares proportional to \code{size * sd}, with the standard +deviation of each stratum from \code{allocation_by} (Neyman 1934). Neyman +minimises the variance of a total for a fixed \code{n} by putting more rows +where the values vary most, and is the right choice when you have a +frame variable correlated with what you are measuring, or estimates of +each stratum's standard deviation from a pilot or an earlier survey. +Under any rule, a stratum that would be +allocated more rows than it holds is taken whole, one that would get +fewer than \code{min_per_stratum} gets that many, and the rest of \code{n} is +re-split over the others by the same rule (Cochran 1977, section 5.9). -\item{allocation_by}{Column whose within-stratum standard deviation drives -\code{allocation = "neyman"}. Ignored otherwise.} +Counts are a named vector, such as \code{c(north = 10, south = 5, east = 5)}, +when \code{strata} is one column, its names matched to that column's values +as text; or a data frame holding the \code{strata} columns and a column \code{n}, +matched on the values themselves. Every stratum of the frame needs a +count, 0 included, and a count for a stratum the frame does not have is +refused, so a misspelt name cannot quietly leave a stratum out. Without +replacement no count may exceed the rows in its stratum. The design then +draws exactly those counts, and the inclusion probabilities, variances +and \code{\link[=as_svydesign]{as_svydesign()}} follow them.} -\item{min_per_stratum}{Minimum rows from each stratum. With the default of +\item{allocation_by}{The standard deviation of each stratum, for +\code{allocation = "neyman"}. Ignored otherwise. Either a column of the +frame, whose standard deviation within each stratum is used, and which +needs a finite value on every row allocated over; or the standard +deviations themselves, so the frame needs no such column. Those are a +named vector, such as \code{c(north = 40, south = 15)}, when \code{strata} is one +column, its names matched to that column's values as text; or a data +frame holding the \code{strata} columns and a column \code{sd}, matched on the +values themselves. Every stratum of the frame needs one, and each must +be finite and 0 or more. A value for a stratum the frame does not have +is ignored, so the same values serve a part of the frame, such as the +\code{rest} of \code{\link[=design_certainty]{design_certainty()}} when every row of a stratum is above the +threshold. A stratum with a standard deviation of 0 gets no share.} + +\item{min_per_stratum}{Minimum rows from each stratum, under an allocation +rule. With the default of \code{0}, a stratum smaller than about \code{N / n} can be allocated no rows at all; its rows then have inclusion probability 0 and a total estimated from the sample silently leaves them out, so \code{\link[=draw]{draw()}} warns when that happens. \code{1} @@ -41,20 +71,102 @@ makes every stratum reachable, which is what an unbiased Horvitz-Thompson total needs, and \code{2} also lets every stratum contribute to the variance estimate. Over-sampling a small stratum this way does \emph{not} bias an estimate made with the design weights, which correct for it; -it only moves precision around.} +it only moves precision around. Without replacement a stratum smaller +than the floor is taken whole, so \code{n} must cover \code{min_per_stratum} rows +from each stratum, or all of a smaller one. With counts in \code{allocation}, +give each stratum its count there instead.} \item{replace}{Sample with replacement within each stratum?} \item{na_rm}{Drop rows whose stratum key is \code{NA} instead of raising an error.} + +\item{cost}{The cost of sampling one row in each stratum, for +\code{allocation = "neyman"} only. In the same forms as standard deviations +given in \code{allocation_by}, with the column of a data frame named \code{cost}, +so one data frame of the \code{strata} columns, \code{sd} and \code{cost} can serve +both. Each must be finite and above 0. The shares become proportional to +\code{size * sd / sqrt(cost)}, which gives the smallest variance among the +splits of the same total cost, \code{sum(cost * n_h)} over strata (Cochran +1977, section 5.5). Before any stratum is held at its floor or its +size, the \code{n} that spends a budget \code{C}, net of any fixed cost, is +\code{C * sum(N_h * S_h / sqrt(c_h)) / sum(N_h * S_h * sqrt(c_h))}, rounded +down. When no stratum has any spread, the shares are +proportional to \code{size / sqrt(cost)}, as for equal spreads, and without +\code{cost} to \code{size}.} + +\item{within}{How rows are drawn inside each stratum: \code{NULL}, the +default, for a simple random sample, or \code{\link[=design_systematic]{design_systematic()}} without +\code{interval} or \code{n}, to walk each stratum in the order of its \code{order_by} +column, or in frame order without one. Each stratum gets the rows the +allocation gives it, at an even step from a random start of its own; +see "Systematic sampling within strata". Needs \code{replace = FALSE}.} } \value{ -A design object, for use with \code{\link[=draw]{draw()}}. +A design object, for use with \code{\link[=draw]{draw()}}. \code{\link[=allocation_table]{allocation_table()}} shows +the rows it takes from each stratum of a frame before anything is drawn. } \description{ Draws a sample from each stratum. Allocation uses the largest-remainder method, so the returned row count matches \code{n} exactly rather than drifting with per-stratum rounding. } +\section{Rounding, ties and the order of strata}{ + +Each stratum first gets the whole part of its share of \code{n}. The rows left +over go one at a time to the strata with the largest fractional parts. When +two strata tie, the one with more rows not yet allocated goes first, and +after that the one that comes first in key order. \code{min_per_stratum} and +the size of each stratum bound the shares before they are rounded, so the +rounding never takes a stratum below its floor or past its size. + +Key order is the order of the levels for a factor column and the sorted +values for any other column, with text sorted byte by byte as in the C +locale (\code{"B"} before \code{"a"}). With several \code{strata} columns the first varies +slowest. Strata are also drawn from in this order, so a seed selects the +same rows in every locale. Renaming a stratum, or reordering a factor's +levels, can move a tied row from one stratum to another; the inclusion +probabilities always follow the allocation used. + +An empty string is a stratum like any other, shown as \code{(blank)} in +messages. +} + +\section{Systematic sampling within strata}{ + +With \code{within = design_systematic(order_by = "x")}, the strata are +allocated as without it, each stratum is sorted on \code{x}, and the \code{n_h} +rows allocated to a stratum of \code{N_h} are taken as +\code{design_systematic(n = n_h)} takes them from a frame of \code{N_h} rows: a +start drawn from (0, 1) and a step of \code{N_h / n_h} rows, which need not be +whole. Strata draw their starts in key order. Every row has probability +\code{n_h / N_h}, as under simple random sampling within strata, so the +allocation, \code{\link[=allocation_table]{allocation_table()}} and the weights are the same; what +changes is which rows can be drawn together. Two rows of one stratum have +the joint probability of the systematic design there, which is 0 for +rows at most \code{N_h / n_h - 1} rows apart, and two rows of different strata +the product of their probabilities. Rows whose \code{x} is missing are refused, +or with the \code{na_rm = TRUE} of the systematic design left out of their +stratum before it is allocated. + +Each stratum has one random start, so when any stratum is walked at a +step of 2 rows or more no design-unbiased variance exists, as for +\code{\link[=design_systematic]{design_systematic()}} on its own. \code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} +add up the strata's successive-difference approximations, +\code{(1 - n_h / N_h) * n_h / (2 * (n_h - 1)) * sum(diff(y / pi)^2)} over each +stratum's sampled rows in the order it was walked (Wolter 2007), with +the degrees of freedom of a stratified sample, the sampled rows less the +strata. A stratum with one sampled row from several is refused, as +without \code{within}. So is the jackknife: a stratum's rows all come from one +start, and deleting them one at a time does not mirror the design. +\code{\link[=as_svydesign]{as_svydesign()}} hands \code{survey} the strata, whose simple-random variance +differs. + +Only \code{\link[=design_systematic]{design_systematic()}} is taken as \code{within}, with one start and no +\code{interval} or \code{n}: the allocation sets the size of each stratum. To walk +a stratum by several columns, give \code{order_by} a column of ranks, as in +the examples of \code{\link[=design_systematic]{design_systematic()}}. +} + \examples{ df <- data.frame(id = 1:100, site = rep(letters[1:4], each = 25)) table(draw(df, design_stratified("site", n = 20), seed = 1)$site) @@ -64,15 +176,35 @@ table(draw(df, design_stratified("site", n = 20), seed = 1)$site) skewed <- data.frame(id = 1:1000, g = c(rep("common", 999), "rare")) draw(skewed, design_stratified("g", n = 10, min_per_stratum = 1), seed = 1)$g +# A count for each stratum, drawn as given; `n` is their sum +fixed <- design_stratified("site", allocation = c(a = 8, b = 4, c = 4, d = 4)) +table(draw(df, fixed, seed = 1)$site) + +# Neyman from standard deviations known from an earlier survey, with the +# cost of reaching a row in each stratum +pilot <- design_stratified("site", n = 20, allocation = "neyman", + allocation_by = c(a = 4, b = 1, c = 2, d = 8), + cost = c(a = 1, b = 1, c = 4, d = 4)) +allocation_table(df, pilot) + +# Each stratum walked in order of `size`, from a start of its own +df$size <- (df$id * 37) \%\% 101 +walked <- design_stratified("site", n = 20, + within = design_systematic(order_by = "size")) +draw(df, walked, seed = 1) + } \references{ Neyman, J. (1934). On the two different aspects of the representative method. \emph{Journal of the Royal Statistical Society}, 97, 558–625. Cochran, W. G. (1977). \emph{Sampling Techniques}, 3rd ed. Wiley. + +Wolter, K. M. (2007). \emph{Introduction to Variance Estimation}, 2nd ed. +Springer. } \seealso{ -\code{\link[=draw]{draw()}} +\code{\link[=draw]{draw()}}, \code{\link[=allocation_table]{allocation_table()}} Other designs: \code{\link{design_bootstrap}()}, diff --git a/man/design_systematic.Rd b/man/design_systematic.Rd index 8668580..3e13c1f 100644 --- a/man/design_systematic.Rd +++ b/man/design_systematic.Rd @@ -4,45 +4,130 @@ \alias{design_systematic} \title{Systematic sampling} \usage{ -design_systematic(interval, start = NULL, order_by = NULL, na_rm = FALSE) +design_systematic( + interval = NULL, + start = NULL, + order_by = NULL, + na_rm = FALSE, + n = NULL, + n_starts = 1L +) } \arguments{ -\item{interval}{Sampling interval. A whole number of 1 or more. Fractional -intervals are rejected: they produce uneven gaps, which is not a systematic -design.} +\item{interval}{Sampling interval, a whole number of 1 or more: every +\code{interval}-th row of the walk is taken. Give \code{interval} or \code{n}, not both. +For a step that is not a whole number, give \code{n}.} -\item{start}{Starting row, in \code{1:interval}. Drawn at random from that range -when \code{NULL}.} +\item{start}{Position in the walk of the first row taken, in +\code{1:interval}. The walk is the frame's rows in their order, or sorted by +\code{order_by} when given, so with \code{order_by} a \code{start} of 3 takes the row +with the third smallest value, not the frame's third row. Drawn at +random from that range when \code{NULL}. A fixed start makes the design +deterministic: each row is selected with probability 0 or 1, so +\code{\link[=inclusion_prob]{inclusion_prob()}}, +\code{\link[=sampling_weight]{sampling_weight()}}, \code{\link[=joint_prob]{joint_prob()}}, \code{draw(weights = TRUE)}, +\code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} refuse it, while +\code{inclusion_prob(simulate = TRUE)} reports those 0s and 1s. Not used with +\code{n} or \code{n_starts}, whose starts are always random.} \item{order_by}{Optional column to sort by before walking the data. It changes which rows can appear together, so \code{\link[=inclusion_prob]{inclusion_prob()}} and -\code{\link[=joint_prob]{joint_prob()}} compute against the sorted order too.} +\code{\link[=joint_prob]{joint_prob()}} compute against the sorted order too. Text is sorted byte +by byte, as in the C locale, so the walk is the same in every session; +ties keep frame order, so where the column has ties a seed is sure to +draw the same rows only from a frame with its rows in the same order. +Without ties the walk does not depend on frame order. One column: to +walk by several, add a column of ranks built from them and give its +name, as in the examples.} \item{na_rm}{When \code{order_by} is given, drop rows whose sort key is \code{NA} instead of raising an error.} + +\item{n}{Number of rows to draw, in place of \code{interval}. With \code{N} rows +walked, each row covers a stretch of length \code{n / N} on a line from 0 to +\code{n}, a start \code{u} is drawn uniformly from (0, 1), and the rows under \code{u}, +\code{u + 1}, ..., \code{u + n - 1} are taken. The step is \code{N / n} rows, every row +has probability \code{n / N}, and the sample always holds \code{n} rows. When \code{n} +divides \code{N} the probabilities are those of \code{interval = N / n}. A plan +from \code{\link[=plan_size]{plan_size()}} gives its \code{n}.} + +\item{n_starts}{Number of random starts, 1 by default. With +\code{n_starts = m} and \code{interval = k}, \code{m} different starts are drawn from +\code{1:(m * k)} and each is walked at a step of \code{m * k} rows. Every row +still has probability \code{1 / k}, and the expected sample size is that of +one start at \code{interval}. Each start gives a replicate, a systematic +sample of its own, and two or more of them give a design-unbiased +variance (see "Variance"). Needs \code{interval}, and a random \code{start}.} } \value{ A design object, for use with \code{\link[=draw]{draw()}}. } \description{ -Takes every \code{interval}-th row, beginning at \code{start}. The number of rows drawn -follows from the interval and the size of the data, so there is no \code{n}. +Walks the rows at a fixed step. Give \code{interval} to take every +\code{interval}-th row, beginning at \code{start}, which is drawn at random unless +given; the number of rows drawn then follows from the interval and the size +of the data. Give \code{n} instead to draw exactly \code{n} rows from a random start: +the step is the number of rows walked divided by \code{n}, and need not be a +whole number. With \code{n_starts}, several random starts are walked at a +longer step, which gives the sample a design-unbiased variance. Given +neither \code{interval} nor \code{n}, the design walks each stratum of +\code{\link[=design_stratified]{design_stratified()}} as its \code{within} argument. } \section{Variance}{ -A systematic sample has a single random start, so no design-unbiased +A systematic sample has a single random start. At a step of 2 rows or +more, which is every \code{interval} above 1 and every \code{n} up to half the rows +walked, neighbouring rows are never drawn together, so no design-unbiased variance estimator exists. \code{\link[=ht_total]{ht_total()}} uses the successive-difference approximation (Wolter 2007), which compares neighbouring sampled rows in -the order the design walked. Sorting on a variable related to what you +the order the design walked. With \code{n} above half the rows walked, every +pair of rows can be drawn together (see \code{\link[=joint_prob]{joint_prob()}}), and \code{\link[=ht_total]{ht_total()}} +uses the same approximation. Sorting on a variable related to what you measure (\code{order_by}) is what makes systematic sampling efficient, and this estimator is the one that can see it; see \code{\link[=ht_total]{ht_total()}} for its limits. +When \code{interval} does not divide the number of rows walked, the sample size +is random, and a term for that is added to the variance. A design given +\code{n} has a fixed size and needs no such term. + +With \code{n_starts = m} of 2 or more, the \code{m} starts are a simple random +sample of the \code{m * k} possible ones, and each replicate \code{r} gives a total +of its own, \code{t_r}, which is \code{m} times the sum of \code{y / pi} over its rows. +The sample's total is their mean, and \code{\link[=ht_total]{ht_total()}} uses the random group +variance (Wolter 2007), \code{(1 - 1 / k) * var(t_r) / m}, on \code{m - 1} degrees +of freedom. It is design-unbiased whether or not \code{m * k} divides the rows +walked, a replicate that drew no rows counting with a total of 0. +\code{\link[=as_svydesign]{as_svydesign()}} gives the same standard error with each replicate as a +primary sampling unit, and refuses a sample with a replicate that drew no +rows, which \code{survey} would leave out of its count of replicates. The price +is precision: \code{m} starts spread the sample over the walk less evenly than +one start at \code{interval} does, and few replicates give few degrees of +freedom and a wide interval. + +Within strata, as \code{design_stratified(within = design_systematic())}, each +stratum has a start of its own and the variance is the sum of the +strata's successive-difference approximations; see \code{\link[=design_stratified]{design_stratified()}}. } \examples{ -df <- data.frame(id = 1:100, value = (1:100) / 10) +df <- data.frame(id = 1:100, value = (1:100) / 10, + site = rep(c("b", "a"), each = 50)) draw(df, design_systematic(interval = 10, start = 3)) draw(df, design_systematic(interval = 25, order_by = "value"), seed = 1) +# 30 rows from 100, a step of 3.33 +draw(df, design_systematic(n = 30), seed = 1)$id + +# Four starts from 1:40, each walked at a step of 40: ten rows on +# average, as with one start, and a variance from the spread of the four +# replicates +s <- draw(df, design_systematic(interval = 10, n_starts = 4), seed = 1, + weights = TRUE) +ht_total(s, "value") + +# Walking by two columns: rank the rows by both, then walk the ranks +df$walk <- order(order(df$site, -df$value, method = "radix")) +draw(df, design_systematic(interval = 20, order_by = "walk"), seed = 1) + } \references{ Madow, W. G. and Madow, L. H. (1944). On the theory of systematic sampling, @@ -52,7 +137,7 @@ Wolter, K. M. (2007). \emph{Introduction to Variance Estimation}, 2nd ed. Springer. } \seealso{ -\code{\link[=draw]{draw()}} +\code{\link[=draw]{draw()}}, \code{\link[=design_stratified]{design_stratified()}} Other designs: \code{\link{design_bootstrap}()}, diff --git a/man/design_temporal.Rd b/man/design_temporal.Rd index 6774881..b9f7768 100644 --- a/man/design_temporal.Rd +++ b/man/design_temporal.Rd @@ -16,11 +16,23 @@ design_temporal( ) } \arguments{ -\item{time}{Column of timestamps. \code{POSIXct} and \code{Date} columns are used as -they are; character columns are parsed with \code{\link[lubridate:ymd_hms]{lubridate::ymd_hms()}}.} +\item{time}{Column of timestamps: \code{POSIXct}, \code{POSIXlt}, \code{Date}, character +or factor. Strings are read as year-month-day with an optional time, in +the forms \code{\link[lubridate:ymd_hms]{lubridate::ymd_hms()}} accepts, such as \code{"2024-03-01 14:30:00"} +or \code{"2024-03-01T14:30:00Z"}, and also \code{"2024-03-01 14:30"}, +\code{"2024-03-01 14"} and \code{"2024-03-01"}.} -\item{from, to}{Window bounds, as timestamps or strings. The window is -half-open: \verb{[from, to)}. Trailing partial intervals are dropped.} +\item{from, to}{Window bounds, each a single \code{POSIXct}, \code{Date} or string +read as \code{time} is. The window is half-open: \verb{[from, to)}. Trailing +partial intervals are dropped. Both are checked when the design is +built, and \code{to} must come after \code{from}. Without \code{tz}, a bound that names +an instant (a \code{POSIXct}, or a string ending in \code{Z} or an offset) paired +with a clock time (a \code{Date}, or a string without an offset) can fall in +either order depending on the zone. Such a pair is refused when the +design is built if, with the clock time read in UTC, \code{to} comes a day or +more before \code{from}, since no zone's offset from UTC can undo that. +Otherwise its order is checked when the design is used, in the zone the +window is laid out in (see "Time zones and calendar steps").} \item{interval}{Interval width, in units of \code{unit}.} @@ -28,12 +40,12 @@ half-open: \verb{[from, to)}. Trailing partial intervals are dropped.} rows contribute all of them.} \item{unit}{One of \code{"seconds"}, \code{"minutes"}, \code{"hours"}, \code{"days"}, \code{"weeks"}, -\code{"months"} or \code{"years"}. \code{"months"} and \code{"years"} step by calendar units, -not by fixed 30.44-day durations.} +\code{"months"} or \code{"years"}. See "Time zones and calendar steps".} -\item{tz}{Time zone the timestamps are expressed in. Applied when the column -\emph{and} both bounds are parsed, so it genuinely shifts the window rather than -relabelling the output.} +\item{tz}{Time zone, a name from \code{\link[=OlsonNames]{OlsonNames()}}, in which the bounds, any +\code{Date} or string timestamps and the calendar steps are read. \code{NULL}, the +default, takes the zone of a \code{POSIXct} \code{time} column and UTC otherwise. +It shifts the window rather than relabelling the output.} \item{na_rm}{Drop rows whose timestamp is missing or unparseable instead of raising an error.} @@ -42,15 +54,41 @@ raising an error.} A design object, for use with \code{\link[=draw]{draw()}}. } \description{ -Divides a time window into equal intervals and samples within each one. -\code{per_interval} is named for what it is: unlike \code{n} elsewhere in the package, -it is a per-group figure, not a total. +Divides a time window into intervals of \code{interval} units and samples within +each one. \code{per_interval} is named for what it is: unlike \code{n} elsewhere in +the package, it is a per-group figure, not a total. } \details{ -Buckets are assigned arithmetically in a single pass rather than by -re-filtering the data per interval, so cost scales with the data rather than -with the number of intervals. +Each row's interval is found in a single pass over the data, so the draw +and the inclusion probabilities take time that grows with the number of +rows rather than with rows times intervals. } +\section{Time zones and calendar steps}{ + +The window and the intervals are laid out in one time zone: \code{tz} when it +is given, otherwise the zone of a \code{POSIXct} \code{time} column, otherwise UTC. +A \code{POSIXct} column with an empty \code{tzone}, which R shows in the session's +zone, also gets UTC, so a design gives the same intervals on every +machine. + +A \code{Date}, in the column or as a bound, is its midnight in that zone, and a +string without an offset is a clock time there. A clock time that a +daylight-saving change skips moves to the moment the clocks jump, and one +that happens twice takes its first occurrence, so a \code{Date} stands for the +first instant of its day: 01:00 where the change skips midnight, as in +Santiago or Cairo, and the first of two midnights where it repeats one, as +in the Azores. A string ending in \code{Z} or an offset such as \code{+01:00} keeps +the instant it names. + +\code{"seconds"}, \code{"minutes"} and \code{"hours"} are fixed durations counted from +\code{from}, so hourly intervals ignore the clock change. \code{"days"} and +\code{"weeks"} step by calendar days, so each interval starts at the same +clock time as \code{from} and lasts 23 or 25 hours across a change. +\code{"months"} and \code{"years"} step by calendar units counted from \code{from}, and a +day the month lacks moves to its last day: a window starting on 31 +January 2024 has intervals starting on 29 February, 31 March and 30 April. +} + \examples{ df <- data.frame( id = 1:48, diff --git a/man/design_weighted.Rd b/man/design_weighted.Rd index b653e51..0b468fb 100644 --- a/man/design_weighted.Rd +++ b/man/design_weighted.Rd @@ -9,14 +9,22 @@ design_weighted( n, replace = FALSE, method = c("successive", "systematic", "poisson"), - na_rm = FALSE + na_rm = FALSE, + strata = NULL, + allocation = c("proportional", "equal") ) } \arguments{ -\item{weights}{Column of positive, finite weights.} +\item{weights}{Column of positive, finite, numeric weights. A weight of 0 +is refused under every method, not given a probability of 0; drop such +rows from the frame first, since a design that selects in proportion to +size could never select them.} -\item{n}{Number of rows to draw. Under \code{method = "poisson"} this is the -expected number, not a guarantee.} +\item{n}{Number of rows to draw, the total across \code{strata} when given, or +a plan from \code{\link[=plan_size]{plan_size()}}. +Under \code{method = "poisson"} this is the expected number, not a guarantee. +With counts in \code{allocation} it can be left out and is their sum; when +given, it must equal that sum.} \item{replace}{Sample with replacement? Only available for \code{method = "successive"}.} @@ -24,7 +32,24 @@ expected number, not a guarantee.} \item{method}{One of \code{"successive"}, \code{"systematic"} or \code{"poisson"}. See "Choosing a method".} -\item{na_rm}{Drop rows whose weight is \code{NA} instead of raising an error.} +\item{na_rm}{Drop rows whose weight or stratum key is \code{NA} instead of +raising an error.} + +\item{strata}{Optional column name(s) defining strata, to sample in +proportion to size within each one. Several columns are +cross-classified. Needs \code{method = "systematic"} or \code{"poisson"}. See +"Strata".} + +\item{allocation}{How \code{n} is split across \code{strata}: \code{"proportional"} to +the number of rows in each stratum, or \code{"equal"}, by the +largest-remainder method of \code{\link[=design_stratified]{design_stratified()}}, with a stratum that +would get more rows than it holds taken whole; or the count for each +stratum, as a named vector such as \code{c(north = 10, south = 5)} when +\code{strata} is one column, or a data frame of the \code{strata} columns and \code{n}. +Counts follow the rules of \code{\link[=design_stratified]{design_stratified()}}: every stratum of the +frame needs one, a count for a stratum the frame does not have is +refused, and no count may exceed the rows in its stratum. Only with +\code{strata}.} } \value{ A design object, for use with \code{\link[=draw]{draw()}}. @@ -46,7 +71,8 @@ up in the sample, and the realised inclusion probabilities are \strong{not} proportional to the weights. How far off depends on the weights: with a single dominant unit the two nearly coincide (about 1\% apart), but with a moderate spread the gap is large — weights \code{1:10} at \code{n = 5} give -inclusion probabilities up to 35\% away from proportional. Treating them as +inclusion probabilities up to about 36\% away from proportional, by +exact enumeration of the ordered draws. Treating them as if they were proportional biases a Horvitz-Thompson total by around 1\% at \code{n = 15} out of 30 in simulation, small in size but unmistakable in sign. There is no closed form for \code{pi}, so \code{\link[=inclusion_prob]{inclusion_prob()}} refuses to give @@ -62,15 +88,55 @@ rows can appear together, but their joint probabilities have no closed form, so \code{\link[=ht_total]{ht_total()}} uses Deville's approximation for the variance, which needs only the first-order probabilities.} \item{\code{"poisson"}}{Each row is included independently with probability -\code{pi_i = n * p_i}, capped at 1. Inclusion probabilities are exactly -proportional to size and every pair can co-occur, at the cost of a -\strong{random sample size} averaging \code{n}.} +\code{pi_i = n * p_i}. Rows heavy enough that \code{n * p_i > 1} are taken with +certainty and the rest rescaled, repeatedly, as for \code{"systematic"}, so +the probabilities still sum to \code{n}. Inclusion probabilities are exactly +proportional to size among the rows below certainty, and every pair can +co-occur, at the cost of a \strong{random sample size} averaging \code{n}.} } \code{replace = TRUE} is with-replacement PPS and applies only to \code{method = "successive"}. } +\section{Strata}{ + +With \code{strata}, \code{n} is split over the strata by \code{allocation}, as +\code{\link[=design_stratified]{design_stratified()}} splits it over the rows in each stratum, and each +stratum is then sampled in proportion to size on its own: a row of stratum +\code{h} gets \code{n_h * w_i / sum(w)}, the sum running over the stratum, with rows +past certainty taken with certainty within it. Under \code{"systematic"} each +stratum is shuffled and walked from a start of its own, in key order; +under \code{"poisson"} every row is included independently with the probability +its stratum gives it, so the size of each stratum's sample is random. +\code{"successive"} has no closed-form inclusion probability and is refused with +\code{strata}. To split \code{n} in proportion to each stratum's total size rather +than its rows, work out the counts and give them as \code{allocation}. + +The strata are sampled independently. \code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} add up +Deville's approximation over the strata for \code{"systematic"}, and the +Poisson variance needs no change. The degrees of freedom are the sampled +rows below certainty less the strata that hold them. A stratum with one +sampled row below certainty has nothing to compare it with, and the +variance is refused with the stratum named; draw at least two in each. + +In simulations of 2,000 draws each from frames of 600 rows in four strata, +drawing 24 or 60 rows by \code{"systematic"}, the variance averaged 0.94 to +1.04 times the true variance of the total, and 95\% intervals covered 89\% +to 96\% of the time. The low coverage came where \code{y / pi} was skewed, so +that samples with a low total also had a low estimated variance; the same +frames without strata covered 92\% to 94\%. + +\code{\link[=as_svydesign]{as_svydesign()}} hands the strata to \code{survey}, with Brewer's approximation +within each, \code{\link[=allocation_table]{allocation_table()}} shows the split before anything is +drawn, and \code{\link[=sample_summary]{sample_summary()}} counts the rows drawn from each stratum. + +Drawing each stratum with a design of its own and binding the samples with +\code{\link[=rbind]{rbind()}} does not give a sample to estimate from. The bound sample keeps +the first draw's frame and design, so \code{\link[=ht_total]{ht_total()}} refuses it; use +\code{strata} instead. +} + \examples{ df <- data.frame(id = 1:20, w = 1:20) draw(df, design_weighted("w", n = 5), seed = 1) @@ -83,6 +149,13 @@ round(inclusion_prob(df, d), 3) s <- draw(df, d, seed = 1, weights = TRUE) sum(s$w * s$.weight) # estimates sum(df$w) = 210 +# In proportion to size within each of two regions +df$region <- rep(c("east", "west"), each = 10) +by_region <- design_weighted("w", n = 8, method = "systematic", + strata = "region") +allocation_table(df, by_region) +round(inclusion_prob(df, by_region), 3) + } \references{ Madow, W. G. (1949). On the theory of systematic sampling, II. \emph{Annals of @@ -98,7 +171,8 @@ Probabilities}. Springer. Tillé, Y. (2006). \emph{Sampling Algorithms}. Springer. } \seealso{ -\code{\link[=draw]{draw()}}, \code{\link[=inclusion_prob]{inclusion_prob()}}, \code{\link[=design_spread]{design_spread()}} to select in +\code{\link[=draw]{draw()}}, \code{\link[=inclusion_prob]{inclusion_prob()}}, \code{\link[=certainty_set]{certainty_set()}} for the rows +taken with certainty, \code{\link[=design_spread]{design_spread()}} to select in proportion to size \emph{and} spread the sample across a map. The \code{sampling} package implements further fixed-size unequal-probability algorithms (Brewer, Sampford, Tillé, maximum entropy) as vector functions. diff --git a/man/designs.Rd b/man/designs.Rd index e9ec078..9299b30 100644 --- a/man/designs.Rd +++ b/man/designs.Rd @@ -13,11 +13,15 @@ passed around. \describe{ \item{\code{\link[=design_simple]{design_simple()}}}{Rows uniformly at random.} -\item{\code{\link[=design_stratified]{design_stratified()}}}{A share of each stratum.} -\item{\code{\link[=design_systematic]{design_systematic()}}}{Every \emph{k}-th row.} +\item{\code{\link[=design_stratified]{design_stratified()}}}{A share of each stratum, at random or +walked in order.} +\item{\code{\link[=design_systematic]{design_systematic()}}}{Every \emph{k}-th row, or \code{n} rows at an even +step, from one random start or several.} \item{\code{\link[=design_cluster]{design_cluster()}}}{Whole clusters.} -\item{\code{\link[=design_multistage]{design_multistage()}}}{Clusters, then rows within them.} -\item{\code{\link[=design_weighted]{design_weighted()}}}{Rows with probability governed by a weight.} +\item{\code{\link[=design_multistage]{design_multistage()}}}{Clusters, at random or in proportion to +size, then rows within them.} +\item{\code{\link[=design_weighted]{design_weighted()}}}{Rows with probability governed by a weight, +within strata if asked.} \item{\code{\link[=design_certainty]{design_certainty()}}}{Everything above a threshold, plus a sample of the rest.} \item{\code{\link[=design_reservoir]{design_reservoir()}}}{A fixed-size sample from a stream.} @@ -25,7 +29,7 @@ the rest.} \item{\code{\link[=design_temporal]{design_temporal()}}}{A share of each time interval.} \item{\code{\link[=design_spatial]{design_spatial()}}}{Rows inside a region.} \item{\code{\link[=design_spread]{design_spread()}}}{A sample spread evenly across a map or across -auxiliary variables.} +auxiliary variables, within strata if asked.} } } @@ -36,26 +40,44 @@ Arguments mean the same thing everywhere they appear: \item \code{n} is always the \strong{total} number of rows drawn, never a per-group figure. \code{\link[=design_temporal]{design_temporal()}} uses \code{per_interval} precisely because that one \emph{is} per group, and \code{\link[=design_cluster]{design_cluster()}} has no \code{n} at all because the row count -follows from which clusters were selected. -\item \code{allocation} always says how a total is split across groups, either -\code{"proportional"} or \code{"equal"}. Splitting is exact: the largest-remainder -method is used, so a request for 60 rows returns 60 rather than drifting -with per-group rounding. +follows from which clusters were selected. A plan from \code{\link[=plan_size]{plan_size()}} can +be given as \code{n}, and its \code{n} is used. +\item \code{allocation} always says how a total is split across groups: +\code{"proportional"}, \code{"equal"} or, in \code{\link[=design_stratified]{design_stratified()}} only, +\code{"neyman"}. \code{\link[=design_stratified]{design_stratified()}}, \code{\link[=design_spread]{design_spread()}} and +\code{\link[=design_weighted]{design_weighted()}} also take the count for each stratum in place of a +rule, and \code{n} is then their total. +Splitting is exact: the largest-remainder method is used, so a request +for 60 rows returns 60 rather than drifting with per-group rounding. \item \code{na_rm} always decides whether rows with a missing key are dropped or raise an error. It is never silently assumed either way. +\item Groups always come in key order, whether strata, \code{by} domains or the +rows of \code{\link[=sample_summary]{sample_summary()}}: a factor's levels, or the sorted values of any +other column, with text sorted byte by byte as in the C locale. A seed +therefore draws the same rows in every locale, and an \code{order_by} column +of text is walked in the same order everywhere. \item \code{replace} always means sampling with replacement within whatever group the design works on, and always rules out \code{draw(weights = TRUE)}: an inclusion probability describes distinct units, and a sample holding duplicates cannot be weighted by one. -\item \code{\link[=draw]{draw()}} always restores the caller's random number stream before -returning, and always gives back a data frame with the input's class and -column order. +\item With a \code{seed}, \code{\link[=draw]{draw()}} always restores the caller's random number +stream and generator before returning, and a seed draws the same sample +whatever generator the session has selected. With \code{seed = NULL} it draws +from, and advances, the caller's stream. See "Seeding" in \code{\link[=draw]{draw()}}. +\item \code{\link[=draw]{draw()}} always gives back a data frame with the input's class and +column order, and the frame's own row names on the rows drawn. +\code{\link[=design_bootstrap]{design_bootstrap()}} with \code{output = "indices"} or +\code{"weights"} gives a matrix instead, and \code{\link[=design_reservoir]{design_reservoir()}} a list +when \code{data} is not a data frame, unless \code{batches = TRUE}. \item Rows come back in frame order for every design that selects a set of rows, -including \code{\link[=design_systematic]{design_systematic()}} with \code{order_by}. -The two exceptions are the ones where draw order is meaningful: -\code{\link[=design_simple]{design_simple()}} and \code{\link[=design_weighted]{design_weighted()}} return rows in the order they -were drawn, and \code{\link[=design_bootstrap]{design_bootstrap()}} returns replicates in order with a -leading \code{.replicate} column. +including \code{\link[=design_systematic]{design_systematic()}} with \code{order_by} and \code{\link[=design_weighted]{design_weighted()}} +with \code{method = "systematic"} or \code{"poisson"}. +The exceptions are the ones where draw order is meaningful: +\code{\link[=design_simple]{design_simple()}} and \code{design_weighted(method = "successive")} return +rows in the order they were drawn, and \code{\link[=design_bootstrap]{design_bootstrap()}} returns +replicates in order with a leading \code{.replicate} column. A design with +\code{reserve} returns its main sample and then its reserves, in the order +they are used, with a leading \code{.reserve} column. } } @@ -64,18 +86,35 @@ leading \code{.replicate} column. Because a design is a value, it can report its own inclusion probabilities before any sampling happens. \code{\link[=inclusion_prob]{inclusion_prob()}} gives first-order probabilities and \code{\link[=sampling_weight]{sampling_weight()}} their reciprocals — the number of -population rows each sampled row stands for. \code{\link[=joint_prob]{joint_prob()}} gives +population rows each sampled row stands for, and \code{\link[=certainty_set]{certainty_set()}} the rows +a design that selects in proportion to size takes with certainty. +\code{\link[=allocation_table]{allocation_table()}} shows how a design with strata splits \code{n} over the +strata of a frame, and which strata it holds at the floor, takes whole or +leaves empty. \code{\link[=joint_prob]{joint_prob()}} gives second-order probabilities, and \code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} turn a sample -into a population total, mean or proportion — overall or by domain — with a -standard error from the variance estimator suited to the design and a -confidence interval on the design's degrees of freedom. \code{\link[=deff]{deff()}} reports +into a population total, mean or proportion, overall or by domain and for +one variable or several, with a standard error from the variance +estimator suited to the design and a confidence interval on the design's +degrees of freedom. A factor \code{y} gives the count or share of each level. +\code{\link[=ht_ratio]{ht_ratio()}} estimates a ratio of two totals the same way, +\code{ht_total(ratio =)} the ratio estimator of a total, and \code{\link[=ht_quantile]{ht_quantile()}} +medians and other quantiles with Woodruff intervals. \code{\link[=deff]{deff()}} reports what the design cost in precision against simple random sampling, and \code{\link[=sample_summary]{sample_summary()}} reports what was actually drawn against what was in the -frame. +frame. \code{\link[=add_fieldwork]{add_fieldwork()}} joins fieldwork results to a sample by an id, +\code{\link[=use_reserves]{use_reserves()}} replaces the units of a list from \code{\link[=design_simple]{design_simple()}} or +\code{\link[=design_spread]{design_spread()}} with \code{reserve} that were found unavailable, +\code{\link[=as_drawn]{as_drawn()}} rebuilds a sample read back from a file or a database, and +\code{\link[=compact_sample]{compact_sample()}} drops the frame columns its design does not read before +it is saved or shared. Going the other way, \code{\link[=plan_size]{plan_size()}} solves for the sample size a given margin -of error requires — the step \emph{before} choosing a design. For analysis this -package does not do, \code{\link[=as_svydesign]{as_svydesign()}} hands a sample to the \code{survey} package. +of error requires — the step \emph{before} choosing a design. It plans a sample +overall or split over strata, and \code{\link[=deff_cluster]{deff_cluster()}} gives the design effect +of a cluster sample to plan with. For analysis this package does not do, +\code{\link[=as_svydesign]{as_svydesign()}} hands a sample to the \code{survey} package, +\code{\link[=replicate_weights]{replicate_weights()}} builds replicate weights for it from the design, and +\code{\link[=frame_totals]{frame_totals()}} gives the frame's totals to calibrate it to. Not every design has a closed form for these — see \code{\link[=inclusion_prob]{inclusion_prob()}} for which, why, and what to do instead. Those that do not say so rather than @@ -92,9 +131,12 @@ returning an approximation. \code{min_per_stratum} if rare groups must appear.} \item{Fieldwork cost matters more than efficiency}{\code{\link[=design_cluster]{design_cluster()}} or \code{\link[=design_multistage]{design_multistage()}} — visiting five sites is cheaper than visiting -fifty, at the cost of precision.} +fifty, at the cost of precision. With \code{size}, \code{\link[=design_multistage]{design_multistage()}} +selects the sites in proportion to size and takes the same number of +rows from each.} \item{Large units matter more}{\code{\link[=design_weighted]{design_weighted()}}, with -\code{method = "systematic"} or \code{"poisson"} if you intend to estimate.} +\code{method = "systematic"} or \code{"poisson"} if you intend to estimate, and +\code{strata} to sample in proportion to size within each stratum.} \item{A few units dominate the total}{\code{\link[=design_certainty]{design_certainty()}} — take those with certainty and sample the tail, which removes them from the variance entirely.} diff --git a/man/draw.Rd b/man/draw.Rd index 0e526d8..9b7c754 100644 --- a/man/draw.Rd +++ b/man/draw.Rd @@ -12,9 +12,10 @@ connection, or a zero-argument generator function.} \item{design}{A design built by one of the \code{\link[=design_simple]{design_simple()}} family.} -\item{seed}{Optional seed, applied only for this draw.} +\item{seed}{Optional seed, applied only for this draw. See "Seeding".} -\item{weights}{Attach \code{.prob} and \code{.weight} columns. See "Design weights".} +\item{weights}{Attach \code{.prob}, \code{.weight} and \code{.row} columns. See "Design +weights".} } \value{ The sampled rows. See "What you get back". @@ -25,46 +26,126 @@ Applies a sampling design to data. \section{What you get back}{ A data frame with the same class and the same columns, in the same order, as -\code{data}. Two designs qualify that: +\code{data}. \code{weights = TRUE} prepends three columns (see "Design weights"), and +some designs qualify it further: \itemize{ \item \code{\link[=design_bootstrap]{design_bootstrap()}} prepends a \code{.replicate} column identifying which replicate each row belongs to, so all replicates come back in one frame. -Split them with \code{split(out, out$.replicate)} if you need a list. -\item \code{\link[=design_reservoir]{design_reservoir()}} returns a list when \code{data} is a stream rather than a -data frame, because there is nothing to make a data frame out of. +Split them with \code{split(out, out$.replicate)} if you need a list. With +\code{output = "indices"} or \code{"weights"} it returns a matrix of row numbers or +counts instead, with a column per replicate. +\item \code{\link[=design_reservoir]{design_reservoir()}} returns a list when \code{data} is a list or a stream +rather than a data frame, because there is nothing to make a data frame +out of. With \code{batches = TRUE} it returns the rows sampled from a +function's data frames as one data frame. +\item \code{\link[=design_simple]{design_simple()}} and \code{\link[=design_spread]{design_spread()}} with \code{reserve} return a list: +the main sample, then the reserves, with a leading integer \code{.reserve} +column that is 0 for the main sample and numbers the reserves 1, 2, ... +in the order they are used. With \code{weights = TRUE} it follows \code{.row}, +and \code{.prob} is the main sample's probability for every row. +\code{\link[=use_reserves]{use_reserves()}} turns the list into the sample to estimate from. } + +Row names of the frame's own, such as the car names of \code{mtcars}, stay with +their rows. A row drawn more than once, by a design with \code{replace = TRUE} +or by \code{\link[=design_bootstrap]{design_bootstrap()}}, gets names made unique by \code{\link[=make.unique]{make.unique()}}: +\code{"Mazda RX4"}, then \code{"Mazda RX4.1"}. The automatic row names 1, 2, ... +number the sample's rows afresh, and \code{weights = TRUE} records each row's +place in \code{data} in \code{.row}. A tibble has no row names to keep. } \section{Design weights}{ -\code{weights = TRUE} prepends two columns: \code{.prob}, the probability that the row -was included in the sample, and \code{.weight}, its reciprocal — the number of -population units the row stands for. Those are what an unbiased estimate -needs: a Horvitz-Thompson total is \code{sum(y * .weight)}. +\code{weights = TRUE} prepends three columns: \code{.prob}, the probability that the +row was included in the sample; \code{.weight}, its reciprocal, the number of +population units the row stands for; and \code{.row}, the row of \code{data} it came +from. \code{.prob} and \code{.weight} are what an unbiased estimate needs: a +Horvitz-Thompson total is \code{sum(y * .weight)}. They come from the design applied to the population, not from the drawn sample, and some designs have no closed form for them. \code{\link[=inclusion_prob]{inclusion_prob()}} documents which, why, and what to do instead. -The sample also carries its design, the frame rows it came from and the -frame itself as attributes, which is what lets \code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}}, -\code{\link[=sample_summary]{sample_summary()}} and \code{\link[=as_svydesign]{as_svydesign()}} work from the sample alone. Two -consequences: estimate before subsetting (use \code{by} for groups), since -\code{[} drops the attributes; and saving the sample with \code{\link[=saveRDS]{saveRDS()}} saves the -frame with it. +Two kinds of design are weighted conditional on the clusters the draw +selected: \code{\link[=design_cluster]{design_cluster()}} with \code{balanced = TRUE}, and +\code{\link[=design_multistage]{design_multistage()}} without \code{size} when the rows taken from a cluster +depend on which other clusters were selected. With \code{a} of \code{A} clusters +selected and \code{m_i} of the \code{N_i} rows of cluster \code{i} taken, \code{.prob} is +\code{(a / A) * m_i / N_i}, the chance of the cluster being selected times the +chance of the row being drawn given these clusters. The total estimated +from it is unbiased given the clusters selected, and so over every +selection. \code{\link[=sample_summary]{sample_summary()}} says when a sample is weighted this way. + +Keep \code{.prob} as it is: \code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}} and \code{\link[=as_svydesign]{as_svydesign()}} refuse +a sample whose \code{.prob} was changed. Weights adjusted after the draw, for +nonresponse say, go in \code{.weight}, and \code{\link[=as_svydesign]{as_svydesign()}} is the way to +estimate from them; \code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} keep to \code{.prob} and warn +when \code{.weight} no longer matches it. + +The sample also carries its design, the frame rows it came from and a copy +of the frame as attributes, which is what lets \code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}}, +\code{\link[=sample_summary]{sample_summary()}} and \code{\link[=as_svydesign]{as_svydesign()}} work from the sample alone. +\itemize{ +\item The frame is copied when the sample is drawn, every column of it. Later +edits to \code{data}, including data.table's in-place \verb{:=}, \code{setorder()} and +\code{setkey()}, do not reach the sample. Each sample holds its own copy, in +memory and in every file it is saved to with \code{\link[=saveRDS]{saveRDS()}}, so a list of +samples from a large frame holds the frame once per sample, and a +sample sent to someone sends them the frame, with any personal data in +it. \code{\link[=compact_sample]{compact_sample()}} keeps only the columns the design reads. +\item Reordering the sample by \code{[}, \code{dplyr::arrange()} or +\code{data.table::setorder()} is safe, because each row finds its frame row +through \code{.row}. +\item Estimate from the whole sample and use \code{by} for groups. Row subsets +(\code{head()}, \code{s[cond, ]}, \code{dplyr::filter()}), \code{\link[=rbind]{rbind()}} of samples and joins +that repeat rows keep the attributes but no longer match the rows that +were drawn, and the functions above refuse them. \code{\link[=merge]{merge()}}, column +selection (\code{s[, cols]}), \code{\link[=subset]{subset()}} and \code{\link[=transform]{transform()}} drop the attributes +altogether. Add fieldwork results with \code{\link[=add_fieldwork]{add_fieldwork()}}, which matches +them on an id, or with \code{s$col <- value}. +\item A CSV or spreadsheet file and a database table keep the rows and the +\code{.row} column but not the attributes. \code{\link[=as_drawn]{as_drawn()}} rebuilds the sample +from them, the design and the frame. +} \code{weights = TRUE} is not available for a design that samples \strong{with -replacement}. \code{.prob} there is the probability of being selected \emph{at least -once}, but the sample holds duplicates, so \code{sum(y * .weight)} over it counts -each duplicate at the distinct-unit weight and comes out around 15\% high. -Use \code{replace = FALSE}, or the Hansen-Hurwitz form \code{N / n * sum(y)}. +replacement}, or a \code{\link[=design_certainty]{design_certainty()}} whose \code{rest} does. \code{.prob} there +is the probability of being selected \emph{at least once}, but the sample holds +duplicates, so \code{sum(y * .weight)} over it counts each duplicate at the +distinct-unit weight. The total comes out high by a factor of +\code{(n / N) / (1 - (1 - 1 / N)^n)}, which is about 5\% at \code{n = N / 10}, 15\% at +\code{n = 0.3 * N}, 58\% at \code{n = N} and more beyond, applied within each stratum +of a stratified design. Use \code{replace = FALSE}, or the Hansen-Hurwitz form +\code{N / n * sum(y)}, summed over strata as \code{N_h / n_h * sum(y_h)} for a +stratified design. } \section{Seeding}{ -\code{seed} is saved, applied, and unwound: \code{.Random.seed} is restored on exit, so -drawing a sample inside a simulation does not shift the simulation's own -random number stream. Leave it \code{NULL} to draw from the current stream. +With a \code{seed}, \code{draw()} saves the caller's random number state, seeds, +draws, and restores the state on exit, so drawing a sample inside a +simulation does not shift the simulation's own random number stream. With +\code{seed = NULL} it draws from the caller's stream and advances it, as any +function that draws random numbers does. + +A seed is applied with R's default generator, +\code{set.seed(seed, kind = "Mersenne-Twister", normal.kind = "Inversion", sample.kind = "Rejection")}, whatever generator the session has selected, +and the session's generator is restored on exit with its state. A seed +therefore draws the same sample after \code{RNGkind("L'Ecuyer-CMRG")}, which +parallel code often selects, or under \code{sample.kind = "Rounding"} as it +does in a session left at R's defaults. It must be a whole number from +\code{-.Machine$integer.max} to \code{.Machine$integer.max}. The same holds for the +\code{seed} of \code{\link[=inclusion_prob]{inclusion_prob()}}, \code{\link[=joint_prob]{joint_prob()}} and \link[=plot.drawn_design]{plot()}. +Most designs select rows by their position in \code{data}, so a seed is sure +to draw the same rows again only from a frame with the same rows in the +same order. + +With \code{weights = TRUE} the sample records how it was drawn in its +\code{drawn_meta} attribute: \code{seed} (\code{NULL} without one), \code{rng_kind} (the +generator used, as \code{\link[=RNGkind]{RNGkind()}} gives it), \code{version} (of drawn), \code{time}, +\code{frame_rows} (the rows of \code{data}) and \code{made_by} (\code{"draw()"}, or +\code{"as_drawn()"} for a sample rebuilt from a file). \code{\link[=sample_summary]{sample_summary()}} +prints it. } \examples{ diff --git a/man/draw_design.Rd b/man/draw_design.Rd index 8f8689a..6b8d073 100644 --- a/man/draw_design.Rd +++ b/man/draw_design.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/draw.R \name{draw_design} \alias{draw_design} -\title{Design-specific draw method} +\title{Draw method for a design class} \usage{ draw_design(design, data) } @@ -12,9 +12,40 @@ draw_design(design, data) \item{data}{The data to sample from.} } \value{ -The sampled rows. +The sampled rows. The cluster and multistage methods attach the +codes of the clusters they selected as the attribute \code{drawn_selection}, +which \code{\link[=draw]{draw()}} removes or, for a sample weighted conditional on its +clusters, keeps. } \description{ -Design-specific draw method +The generic \code{\link[=draw]{draw()}} calls to make a sample from a design. Each design in +the package has a method, and a design of your own can have one too. +} +\section{Writing a design of your own}{ + +A design is a list with a class vector ending in \code{"drawn_design"}, so that +\code{\link[=is_design]{is_design()}} accepts it, such as +\code{structure(list(n = 5), class = c("first_rows", "drawn_design"))}. Its +method takes \code{design} and \code{data} and returns rows of \code{data}, with every +column of \code{data}, as \code{data[idx, , drop = FALSE]} gives them. It draws its +random numbers from the current stream; \code{\link[=draw]{draw()}} applies the seed around +it. A package registers the method with \verb{@exportS3Method drawn::draw_design}, and a script with \code{\link[=.S3method]{.S3method()}}. + +That is enough for \code{\link[=draw]{draw()}} without weights, and for \code{\link[=inclusion_prob]{inclusion_prob()}} +and \code{\link[=joint_prob]{joint_prob()}} with \code{simulate = TRUE}, which count how often each row +is drawn and find the rows through a column they add to \code{data}. The exact +probabilities, \code{draw(weights = TRUE)} and the estimators need the +design's inclusion probabilities, which the package computes for its own +designs only, so they refuse a design of your own. +} + +\examples{ +first_rows <- structure(list(n = 3), class = c("first_rows", "drawn_design")) +.S3method("draw_design", "first_rows", function(design, data) { + data[seq_len(design$n), , drop = FALSE] +}) + +df <- data.frame(id = 1:10) +draw(df, first_rows) +inclusion_prob(df, first_rows, simulate = TRUE, R = 20, seed = 1) } -\keyword{internal} diff --git a/man/drawn-package.Rd b/man/drawn-package.Rd index 748d6c7..5e642d7 100644 --- a/man/drawn-package.Rd +++ b/man/drawn-package.Rd @@ -6,7 +6,7 @@ \alias{drawn-package} \title{drawn: Design-Based Sampling with Known Inclusion Probabilities} \description{ -Draws probability samples from data frames under an explicit, 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. +Draws probability samples from data frames under an explicit, 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 Grafström, Lundström and Schelin (2012) \doi{10.1111/j.1541-0420.2011.01699.x}), 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, the exact Horvitz-Thompson variance for Poisson sampling, the approximation of Deville (1999) for systematic probability-proportional-to-size samples, 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. } \seealso{ Useful links: diff --git a/man/figures/README-spread-1.png b/man/figures/README-spread-1.png index 232fbed..03fa1f9 100644 Binary files a/man/figures/README-spread-1.png and b/man/figures/README-spread-1.png differ diff --git a/man/frame_totals.Rd b/man/frame_totals.Rd new file mode 100644 index 0000000..1d9199d --- /dev/null +++ b/man/frame_totals.Rd @@ -0,0 +1,81 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/survey.R +\name{frame_totals} +\alias{frame_totals} +\title{Population totals from the frame behind a sample} +\usage{ +frame_totals(sample, formula, table = FALSE) +} +\arguments{ +\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}.} + +\item{formula}{A one-sided formula of frame columns, such as +\code{~ w + site}, as \code{\link[survey:calibrate]{survey::calibrate()}} takes it. A name in it that is +not a column of the frame, such as \code{cutoff} in \code{~ I(w > cutoff)}, is +read from the environment of \code{formula}, as \code{\link[stats:model.frame]{stats::model.frame()}} +reads it. A term with no frame column in it, as in \code{~ cutoff}, has no +value for each row and is refused, and so is one that gives a single +value for the frame, such as \code{I(sum(w))}.} + +\item{table}{\code{FALSE}, the default, for the column totals of the model +matrix of \code{formula}, which \code{\link[survey:calibrate]{survey::calibrate()}} takes. \code{TRUE} for the +count of rows in each cell of the variables in \code{formula}, as a table, +which \code{\link[survey:postStratify]{survey::postStratify()}} and \code{\link[survey:rake]{survey::rake()}} take.} +} +\value{ +With \code{table = FALSE}, a named numeric vector: the totals of the +columns of \code{model.matrix(formula)} over the rows the design could +reach, \code{(Intercept)} being the number of those rows. With +\code{table = TRUE}, a table of counts of those rows from \code{\link[stats:xtabs]{stats::xtabs()}}. +} +\description{ +Totals the columns of the frame a sample was drawn from, as stored with +the sample, in the form \code{\link[survey:calibrate]{survey::calibrate()}} takes as \code{population}. A +design handed over by \code{\link[=as_svydesign]{as_svydesign()}} can then be calibrated, or +post-stratified, to the frame without building the totals by hand. +} +\details{ +The totals run over the rows the design could have drawn, those with an +inclusion probability above 0 when the sample was drawn: the rows inside +the region of \code{\link[=design_spatial]{design_spatial()}} or the window of \code{\link[=design_temporal]{design_temporal()}}, +those \code{\link[=design_reservoir]{design_reservoir()}} read before \code{max_items}, and not the rows +\code{na_rm} dropped. Those are the rows the sample's weights stand for. For +a sample weighted conditional on the clusters selected (see "Design +weights" in \code{\link[=draw]{draw()}}), the rows of the clusters left out count too, +since another selection could have drawn them. A missing value of a +variable in \code{formula} in any of those rows is refused, since its total +is unknown. + +A value of a column in \code{formula} that no sampled row has cannot be +calibrated to. \code{survey::calibrate()} stops on such a factor level, and +leaves out the total of such a character value with a warning that it +reordered the totals. Calibration itself is left to \code{survey}, which gives +the calibrated estimates their standard errors. +} +\examples{ +\dontshow{if (requireNamespace("survey", quietly = TRUE)) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf} +pop <- data.frame( + id = 1:400, + site = rep(c("a", "b", "c", "d"), times = c(200, 100, 60, 40)), + size = 20 + (1:400 * 53) \%\% 300 +) +pop$spend <- 3 * pop$size + (1:400 * 37) \%\% 90 +s <- draw(pop, design_simple(n = 60), seed = 1, weights = TRUE) +des <- as_svydesign(s) + +# Calibrate to the frame's row count and total size +totals <- frame_totals(s, ~size) +totals +cal <- survey::calibrate(des, ~size, population = totals) +survey::svytotal(~spend, cal) +ht_total(s, "spend") + +# Post-stratify on site +counts <- frame_totals(s, ~site, table = TRUE) +post <- survey::postStratify(des, ~site, counts) +survey::svytotal(~spend, post) +\dontshow{\}) # examplesIf} +} +\seealso{ +\code{\link[=as_svydesign]{as_svydesign()}} +} diff --git a/man/ht_mean.Rd b/man/ht_mean.Rd index 0423f0e..fbc5264 100644 --- a/man/ht_mean.Rd +++ b/man/ht_mean.Rd @@ -11,25 +11,58 @@ ht_mean( variance = c("auto", "analytic", "jackknife", "none"), level = 0.95, by = NULL, - df = NULL + df = NULL, + proportion = NULL, + ci_method = c("logit", "beta"), + alternative = c("two.sided", "less", "greater"), + contrast = NULL, + na_rm = FALSE ) } \arguments{ -\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}.} +\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}. It is +read as \code{\link[=ht_total]{ht_total()}} reads it: \code{.prob} for the probabilities, and the +stored frame for the design's columns. See "Which columns are read" there.} -\item{y}{The variable to average: a column name, or a numeric vector as long -as \code{sample}.} +\item{y}{The variable to average: a column name, several column names, a +numeric vector as long as \code{sample}, or a single number, which stands +for that value in every row. A factor or character column, or a factor +as long as \code{sample}, gives the share of each level. See "Several +variables" and "Categories" in \code{\link[=ht_total]{ht_total()}}.} \item{estimator}{\code{"hajek"} or \code{"ht"}. See above.} -\item{variance, level, by, df}{As for \code{\link[=ht_total]{ht_total()}}.} +\item{variance, level, by, df, alternative, contrast}{As for \code{\link[=ht_total]{ht_total()}}.} + +\item{proportion}{Whether \code{y} is a proportion, which decides the shape of +the interval. \code{NULL} decides from \code{y}: a logical \code{y}, or a column of the +frame whose values are all 0 or 1, is a proportion, and a numeric vector +or a column added after the draw is one when it is 0 or 1 in every +sampled row. \code{TRUE} treats \code{y} as one, and needs it to be 0 or 1 in every +sampled row; \code{FALSE} gives the symmetric interval. See "Proportions".} + +\item{ci_method}{The interval for a proportion: \code{"logit"}, or \code{"beta"} for +Korn and Graubard's. A proportion of exactly 0 or 1 gets \code{"beta"} either +way. See "Proportions".} + +\item{na_rm}{\code{FALSE} refuses a missing \code{y}. \code{TRUE} estimates the mean over +the rows with \code{y} present, as a domain of the sample. See "Missing +values".} } \value{ A list with a \code{print()} method, holding \code{mean}, \code{estimator}, -\code{variance}, \code{se}, \code{ci}, \code{level}, \code{df}, \code{n}, \code{design}, \code{deff}, \code{method} and -\code{note}. See \code{\link[=ht_total]{ht_total()}} for what \code{method}, \code{df} and \code{note} say, and -\code{\link[=deff]{deff()}} for the design effect. With \code{by}, a data frame with one row per -domain. +\code{variable}, \code{variance}, \code{se}, \code{ci}, \code{level}, \code{alternative}, \code{df}, \code{n}, +\code{n_random}, \code{design}, \code{deff}, \code{method}, \code{note}, \code{ci_scale} (\code{"linear"}, +\code{"logit"} or \code{"beta"}), \code{unreachable} and \code{n_missing}, the sampled rows +with \code{y} missing that \code{na_rm = TRUE} left out. See \code{\link[=ht_total]{ht_total()}} for what +\code{variable}, \code{n_random}, \code{method}, \code{df}, \code{note} and \code{unreachable} say, +and \code{\link[=deff]{deff()}} for the design effect. With \code{by}, a data frame with one row +per domain, and with \code{contrast} a \code{drawn_contrast}, as for \code{\link[=ht_total]{ht_total()}}. +With several column names as \code{y}, a \code{drawn_by} table with a row per +variable, and with a factor or character \code{y} one with a row per level, +as for \code{\link[=ht_total]{ht_total()}}. Each has \code{coef()}, \code{vcov()}, \code{confint()}, +\code{as.data.frame()} and \code{tidy()} methods; see "Working with the result" in +\code{\link[=ht_total]{ht_total()}}. } \description{ The Hajek estimator, \code{sum(y / pi) / sum(1 / pi)}, is the default. It divides @@ -38,25 +71,66 @@ that happens to over-represent heavy-weight rows inflates numerator and denominator together and they partly cancel. \code{estimator = "ht"} divides by the true \code{N} instead. } -\details{ +\section{Proportions}{ + For a 0/1 or logical variable either one estimates a proportion, and the confidence interval is then formed on the logit scale and transformed back (Korn and Graubard 1999, section 5.3). A symmetric interval around a small proportion runs below zero; this one cannot, and matches \code{survey::svyciprop(method = "xlogit")}. + +Whether \code{y} is a proportion is read from what \code{y} is, not from the values +the sample happened to draw. A logical \code{y} is one, and so is a column of +the frame whose values are all 0 or 1. A count that came out 0 or 1 in +every sampled row is not: a logit interval cannot pass 1, so it would never +cover a mean of 1.2. A numeric vector, or a column added to the sample after +the draw, such as a 0/1 result recorded in fieldwork, has no column of the +frame to read. It is taken for a proportion when it is 0 or 1 in every +sampled row, and \code{note} says the choice came from the sample. +\code{proportion = FALSE} asks for the symmetric interval whatever \code{y} is, and +is the choice for a count. + +\code{ci_method = "beta"} gives the Korn and Graubard (1998) interval instead, +a Clopper-Pearson interval at an effective sample size of \code{p(1 - p) / v}, +with \code{p} the estimate and \code{v} its variance, capped at \code{n} and then scaled +by \code{(qt(a, n - 1) / qt(a, df))^2} for the design's degrees of freedom. +Here \code{n} is the number of sampled rows below certainty behind the estimate +and \code{a} the tail probability of the interval. The scaled size is capped at +\code{n} too, so a domain whose design has more degrees of freedom than the +domain has rows gets no narrower an interval than Clopper-Pearson's over +those rows. With no rows taken with certainty it matches +\code{survey::svyciprop(method = "beta")} whenever neither cap binds. It +ignores the finite population correction, so it errs wide when the sample +is a large share of the frame. + +An estimate of exactly 0 or 1, such as no deviations found in 60 sampled +invoices, has a variance of 0, and a logit interval around it has no +width. It gets the beta interval whatever \code{ci_method} says, with the +effective sample size set to \code{n}, and \code{note} says so. For 0 of 60 from a +simple random sample, the 95\% upper bound (\code{alternative = "less"}) is +4.87\%. The interval needs no variance, so a design that leaves 0 degrees of +freedom, such as a Poisson sample of one row, gets Clopper-Pearson's over +the sampled rows. When every sampled row behind the estimate was taken +with certainty, the estimate is exact and the interval has no width. } + \section{When the two differ, and which to use}{ They coincide \strong{exactly} whenever the design weights of the rows you drew -sum to \code{N} — which covers every fixed-size equal-probability design and every -\code{\link[=design_stratified]{design_stratified()}} without replacement, because each stratum contributes -\code{n_h * N_h / n_h = N_h}. There is nothing to choose between them there. +sum to \code{N} — which covers every fixed-size equal-probability design that +can reach every row of the frame, and every \code{\link[=design_stratified]{design_stratified()}} without +replacement that draws from every stratum, because each stratum +contributes \code{n_h * N_h / n_h = N_h}. There is nothing to choose between +them there. A \code{\link[=design_spatial]{design_spatial()}} sample from a region, or a +\code{\link[=design_reservoir]{design_reservoir()}} sample whose stream ran past \code{max_items}, is a simple +random sample of the rows it can reach, and its weights sum to their +number instead; see the caveat on \code{"ht"} below. They differ when that sum is random or uneven: \itemize{ \item the sample size itself is random — \code{\link[=design_weighted]{design_weighted()}} with \code{method = "poisson"}, \code{\link[=design_cluster]{design_cluster()}} over clusters of unequal size, or -\code{\link[=design_systematic]{design_systematic()}} where the interval does not divide \code{N}; +\code{\link[=design_systematic]{design_systematic()}} with an \code{interval} that does not divide \code{N}; \item the weights vary within a fixed-size sample — probability-proportional-to- size selection. } @@ -66,13 +140,19 @@ Hajek is usually the steadier of the two and is the default for that reason knowing: when \code{y} is close to proportional to the size measure that drove selection, \code{y / pi} is nearly constant, the Horvitz-Thompson numerator barely moves, and dividing it by the known \code{N} beats dividing by an -estimate. +estimate. The Hajek mean's ratio bias, and a variance estimate that runs 11 +to 12\% low, also lower the coverage of its interval there. Drawing with +\code{n = 30} from 240 rows by Poisson PPS, its 95\% interval covered 91\% of the +time and that of \code{"ht"} 94\%. By systematic PPS both covered about 90\%. +"Confidence intervals" in \code{\link[=ht_total]{ht_total()}} gives the figures and the reasons. One caveat on \code{"ht"}. It is unbiased for the frame mean \emph{provided every row -could have been selected}. Rows with inclusion probability 0 — outside a time -window, outside a region, zero weight — sit inside the \code{N} it divides by but -can never enter the numerator, so the estimate is biased low by exactly their -share of the frame. \code{\link[=sample_summary]{sample_summary()}} reports how many such rows there are. +could have been selected}. Rows with inclusion probability 0, such as rows +outside a time window or a region, past \code{max_items} or dropped under +\code{na_rm = TRUE}, sit inside the \code{N} it divides by but can never enter the +numerator, so the estimate is biased low by exactly their share of the +frame. +\code{\link[=sample_summary]{sample_summary()}} reports how many such rows there are. The Hajek mean is unaffected, because it estimates the mean of the part of the frame the design can actually reach. } @@ -82,8 +162,59 @@ the frame the design can actually reach. The Hajek mean is a ratio, and its variance is the variance of the total of the linearised residuals \code{(y - mean) / N_hat} (Deville 1999), computed with whichever estimator suits the design — see \code{\link[=ht_total]{ht_total()}}, which also explains -the confidence interval's degrees of freedom and how \code{by} estimates domain -means from the whole sample rather than a subset of it. +the confidence interval's degrees of freedom, how \code{by} estimates domain +means from the whole sample rather than a subset of it, and what an empty +sample gives. + +The residuals sum to zero inside a primary sampling unit that holds every +sampled row of the domain, so a Hajek mean over one unit, such as a domain +with one sampled row or a Poisson sample of one row, gets no standard +error. The "Domains" section of \code{\link[=ht_total]{ht_total()}} says more. + +With \code{estimator = "ht"} each domain's total is divided by the domain's +number of rows in the frame, read from the frame's \code{by} columns. A frame +row with a \code{by} value missing could be in any domain, so such a frame is +refused. + +\code{contrast} gives a weighted sum of domain means, such as the difference +between two, with its standard error; see "Contrasts" in \code{\link[=ht_total]{ht_total()}}. +Its interval is symmetric whatever \code{proportion} and \code{ci_method} say. + +When \code{y} has the same value in every sampled row, the residuals are 0 and +the Hajek mean's variance is set to exactly 0, with a note, rather than +left to rounding error, which gave standard errors near \code{1e-16} and design +effects that changed from seed to seed. The design effect is then \code{NA}. +} + +\section{Shares and counts of categories}{ + +A factor or character column named as \code{y}, or a factor as long as +\code{sample}, gives the share of each of its levels: a \code{drawn_by} table led +by a \code{level} column, with a proportion's interval for each level and the +covariances between the shares in \code{vcov()}. \code{\link[=ht_total]{ht_total()}} gives the +estimated number of frame rows at each level the same way; see +"Categories" there. The share of one level is also the mean of its +indicator, \code{ht_mean(s, s$habitat == "forest")}, which takes \code{contrast} +as any \code{y} does. + +A single number as \code{y} stands for that value in every row, so +\code{ht_total(s, 1)} estimates the number of frame rows the design can +reach, and \code{ht_total(s, 1, by = "habitat")} the number in each domain. +} + +\section{Missing values}{ + +A missing \code{y} is refused unless \code{na_rm = TRUE}. Then the mean is the +Hajek mean over the rows with \code{y} present, treated as a domain of the +whole sample, with the design's own variance estimator, and equals +\code{survey::svymean(na.rm = TRUE)} on \code{\link[=as_svydesign]{as_svydesign()}}. It assumes the values +are missing completely at random, and the printed result says so. \code{n} +counts the rows with \code{y} present, \code{n_missing} the others, and the design +effect is \code{NA}, as for a domain. With \code{by}, each domain is the rows of +its \code{by} values with \code{y} present. \code{estimator = "ht"} is refused, since +the number of frame rows that would have a \code{y} is unknown. See "Missing +values and nonresponse" in \code{\link[=ht_total]{ht_total()}} for when the assumption fails and +what to do then. } \examples{ @@ -101,9 +232,18 @@ mean(pop$spend) # the truth # A mean for each site, estimated from the whole sample ht_mean(s, "spend", by = "site") +# The difference between the two sites' means +ht_mean(s, "spend", by = "site", contrast = c(a = 1, b = -1)) + # A proportion is the mean of a 0/1 variable ht_mean(s, s$spend > 250) +# The share of each level of a factor, with the covariances between them +s$band <- cut(s$spend, c(0, 100, 250, 500)) +shares <- ht_mean(s, "band") +shares +vcov(shares) + # Stratified without replacement: the weights sum to N, so the two agree all.equal(ht_mean(s, "spend", estimator = "ht")$mean, ht_mean(s, "spend")$mean) @@ -115,6 +255,10 @@ c(hajek = ht_mean(p, "spend", variance = "none")$mean, } \references{ +Korn, E. L. and Graubard, B. I. (1998). Confidence intervals for +proportions with small expected number of positive counts estimated from +survey data. \emph{Survey Methodology}, 24, 193–201. + Korn, E. L. and Graubard, B. I. (1999). \emph{Analysis of Health Surveys}. Wiley. @@ -130,5 +274,6 @@ estimators: linearization and residual techniques. \emph{Survey Methodology}, 25, 193–203. } \seealso{ -\code{\link[=ht_total]{ht_total()}}, \code{\link[=deff]{deff()}}, \code{\link[=sample_summary]{sample_summary()}} +\code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_ratio]{ht_ratio()}}, \code{\link[=ht_quantile]{ht_quantile()}}, \code{\link[=deff]{deff()}}, +\code{\link[=sample_summary]{sample_summary()}} } diff --git a/man/ht_quantile.Rd b/man/ht_quantile.Rd new file mode 100644 index 0000000..9a54d60 --- /dev/null +++ b/man/ht_quantile.Rd @@ -0,0 +1,196 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/quantile.R +\name{ht_quantile} +\alias{ht_quantile} +\title{Estimate population quantiles from a sample} +\usage{ +ht_quantile( + sample, + y, + probs = 0.5, + by = NULL, + variance = c("auto", "analytic", "jackknife", "none"), + level = 0.95, + df = NULL +) +} +\arguments{ +\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}. See +"Which columns are read".} + +\item{y}{The variable: a numeric column name of \code{sample}, or a numeric +vector as long as \code{sample}. A logical \code{y} is refused, since its +quantiles are 0 or 1; \code{\link[=ht_mean]{ht_mean()}} estimates the share that is \code{TRUE}.} + +\item{probs}{The probabilities, each from 0 to 1, such as \code{0.5} for the +median or \code{c(0.25, 0.5, 0.75)} for the quartiles.} + +\item{by}{Optional column name(s) in \code{sample} defining domains. When given, +the result is one row per domain. See "Domains". A column named like +one of the table's own, such as \code{n} or \code{se}, is refused.} + +\item{variance}{How to compute it. \code{"auto"} uses the design's own estimator +(see "Variance") and falls back to the jackknife when that declines; +\code{"analytic"} insists on the design's own estimator, returning \code{NA} with +the reason in \code{note} rather than falling back; \code{"jackknife"} uses the +jackknife, and returns \code{NA} with the reason in \code{note} for systematic and +Poisson samples, where it does not apply; \code{"none"} skips it. The result +reports which was used in \code{method}, and \code{"none"} when nothing could +produce a figure.} + +\item{level}{Confidence level for the interval.} + +\item{df}{Degrees of freedom for the interval. \code{NULL} uses the design's +(see "Confidence intervals"); \code{Inf} gives a normal interval; otherwise a +single number of 1 or more.} +} +\value{ +For one probability without \code{by}, a list of class +\code{drawn_quantile} with a \code{print()} method, holding \code{quantile}, the +estimate; \code{prob}; \code{variable}, the name of \code{y} when it is a column name, +else \code{NULL}; \code{cdf} and \code{cdf_se}, the estimated distribution function +at the estimate and its standard error; \code{steps}, the estimated +distribution function as the sorted sampled values \code{x} and the share +of the weight \code{F} at or below each, which \code{confint()} reads to form the +interval at another level; and \code{variance}, \code{se}, \code{ci}, \code{level}, +\code{alternative} (always \code{"two.sided"}), \code{df}, \code{n}, \code{n_random}, \code{design}, +\code{deff}, \code{method}, \code{note} and \code{unreachable} as for \code{\link[=ht_total]{ht_total()}}, with +\code{ci_scale} \code{"woodruff"}. + +For several probabilities, or with \code{by}, a \code{drawn_by} table with a row +for each domain and probability: the \code{by} columns, \code{prob}, \code{n}, +\code{quantile}, \code{variance}, \code{se}, \code{ci_lower}, \code{ci_upper} and \code{method}. + +Both have \code{coef()}, \code{vcov()}, \code{confint()}, \code{as.data.frame()} and +\code{tidy()} methods, as described under "Working with the result" in +\code{\link[=ht_total]{ht_total()}}. \code{confint()} at another level carries the interval for +\code{F(q)} at that level back through the quantile rule. \code{vcov()} holds +the variances, and \code{NA} for the covariances between quantiles, which +are not estimated. +} +\description{ +\code{ht_quantile()} estimates quantiles of \code{y}, such as the median or the +quartiles, from the Hajek estimate of its distribution function, +\code{F(t) = sum(w * (y <= t)) / sum(w)} with \code{w = 1 / pi}, and gives each a +Woodruff confidence interval and a standard error from the design's own +variance estimator. +} +\section{The quantile rule}{ + +The estimate at \code{p} is the smallest sampled value of \code{y} whose estimated +distribution function is \code{p} or more, which inverts the step function +\code{F} without interpolating between sampled values. It is always a value +some sampled row has. This is the rule of +\code{survey::svyquantile(qrule = "math")}, survey's default, and with equal +weights it is \code{stats::quantile(type = 1)}, apart from the tolerance +below. \code{p = 0} gives the smallest sampled value and \code{p = 1} the largest. + +A share of the weight equal to \code{p} can come out of the sums a rounding +error below \code{p}, so a share within \code{1e-9} below \code{p} counts as reaching it. +A \code{p} that is a rounding error above a share therefore gives the value +at that share. \code{seq(0, 1, 0.01)[71]}, which is 0.7 plus a rounding error, +gives the 21st of 30 equally weighted values, where +\code{stats::quantile(type = 1)} and \code{survey::svyquantile()} give the 22nd. +} + +\section{Interval and standard error}{ + +The interval is Woodruff's (1952). At the estimate \code{q}, \code{F(q)} is a Hajek +mean of the indicator \code{y <= q}, and its variance is the variance of the +total of the linearised residuals \code{((y <= q) - F(q)) / N_hat}, with +\code{N_hat = sum(w)}, from the design's own estimator, as for \code{\link[=ht_mean]{ht_mean()}}. +"Variance" and "Confidence intervals" in \code{\link[=ht_total]{ht_total()}} describe the +estimators, the fallback to the jackknife, the degrees of freedom and the +notes. The interval \code{F(q)} plus or minus \code{t} standard errors, with \code{t} on +the design's degrees of freedom, is carried back through the quantile +rule, so its ends are the estimated quantiles at its two ends. The standard +error is the interval's width divided by \verb{2 t}, and \code{variance} is its +square. \code{cdf} and \code{cdf_se} in the result hold \code{F(q)} and its standard +error. + +Where the interval for \code{F(q)} runs below 0 or above 1, the sample bounds +the quantile on one side only. That end of \code{ci} is then \code{NA}, and so are +\code{se} and \code{variance}, with a note. + +At the largest sampled value \code{F(q)} is 1 and its residuals are 0, so its +estimated variance is 0 whatever the spread of \code{y}, and the interval +would have no width. A quantile there, which a \code{p} close to 1 or a \code{y} +with one value gives, gets no standard error, with a note, unless every +frame row the design can reach was taken with certainty, when it is +exact. A quantile whose sampled rows lie in one primary sampling unit +gets none either, as a Hajek mean does, because its residuals sum to +zero over that unit. + +A quantile has no design effect, and \code{deff} is \code{NA}. +} + +\section{Domains}{ + +\code{by} gives the quantiles of each domain, each from the distribution +function of the domain's sampled rows. The variance of \code{F(q)} is that of +the domain's Hajek mean of \code{y <= q}, from the whole sample, as described +under "Domains" in \code{\link[=ht_total]{ht_total()}}, and the degrees of freedom are the +design's. The result is a \code{drawn_by} table with a row for each domain +and probability. +} + +\section{Comparison with survey}{ + +For the designs \code{\link[=as_svydesign]{as_svydesign()}} maps with identical standard errors, +the estimate, the interval and the standard error equal those of +\code{survey::svyquantile(ci = TRUE, interval.type = "mean")} on its result, +whose interval is also centred on \code{F(q)} rather than on \code{p}. They differ +in these places: +\itemize{ +\item At the largest sampled value survey gives an interval of no width and a +standard error of 0, where \code{ht_quantile()} gives none. +\item Where the interval for \code{F(q)} passes 0 or 1, survey gives \code{NaN} for +that end and the standard error, where \code{ht_quantile()} gives \code{NA}. +\item For a \code{p}, or an end of the interval for \code{F(q)}, below the share of the +weight held by the smallest sampled value, survey's rule gives the +second smallest value and \code{ht_quantile()} the smallest. +\item For a \code{p} within \code{1e-9} above a share of the weight, \code{ht_quantile()} +gives the value at that share and survey the next one, as "The quantile +rule" describes. +\item With \code{by}, \code{survey::svyby()} with \code{survey::svyquantile()} forms each +interval on the degrees of freedom of the domain's own units, and +\code{ht_quantile()} on the design's, as for every domain estimate here. +With \code{df = Inf} in both, the standard errors agree. +} + +For systematic, spread and systematic PPS samples the variance of \code{F(q)} +comes from the estimator this package uses for their totals, which +\code{survey} does not have. + +A missing \code{y} is refused. \code{survey::svyquantile(na.rm = TRUE)} on +\code{\link[=as_svydesign]{as_svydesign()}} estimates the quantiles over the rows that have one. +} + +\examples{ +set.seed(1) +pop <- data.frame( + id = 1:300, + site = rep(c("a", "b", "c"), each = 100), + spend = round(stats::rlnorm(300, 4, 0.8)) +) +s <- draw(pop, design_stratified("site", n = 60), seed = 1, weights = TRUE) + +# The median, and its Woodruff interval +ht_quantile(s, "spend") +stats::median(pop$spend) # the truth + +# The quartiles of each site, from the whole sample +ht_quantile(s, "spend", probs = c(0.25, 0.5, 0.75), by = "site") + +} +\references{ +Woodruff, R. S. (1952). Confidence intervals for medians and other +position measures. \emph{Journal of the American Statistical Association}, +47, 635–646. + +Särndal, C.-E., Swensson, B. and Wretman, J. (1992). \emph{Model Assisted Survey +Sampling}. Springer. +} +\seealso{ +\code{\link[=ht_mean]{ht_mean()}}, \code{\link[=ht_total]{ht_total()}}, \code{\link[=as_svydesign]{as_svydesign()}} +} diff --git a/man/ht_ratio.Rd b/man/ht_ratio.Rd new file mode 100644 index 0000000..d48e3e5 --- /dev/null +++ b/man/ht_ratio.Rd @@ -0,0 +1,144 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/estimate.R +\name{ht_ratio} +\alias{ht_ratio} +\title{Estimate a ratio of two population totals} +\usage{ +ht_ratio( + sample, + y, + x, + by = NULL, + variance = c("auto", "analytic", "jackknife", "none"), + level = 0.95, + df = NULL, + alternative = c("two.sided", "less", "greater") +) +} +\arguments{ +\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}. See +"Which columns are read".} + +\item{y, x}{The numerator and the denominator: each a column name of +\code{sample}, or a numeric vector as long as \code{sample}.} + +\item{by}{Optional column name(s) in \code{sample} defining domains. When given, +the result is one row per domain. See "Domains". A column named like +one of the table's own, such as \code{n} or \code{se}, is refused.} + +\item{variance}{How to compute it. \code{"auto"} uses the design's own estimator +(see "Variance") and falls back to the jackknife when that declines; +\code{"analytic"} insists on the design's own estimator, returning \code{NA} with +the reason in \code{note} rather than falling back; \code{"jackknife"} uses the +jackknife, and returns \code{NA} with the reason in \code{note} for systematic and +Poisson samples, where it does not apply; \code{"none"} skips it. The result +reports which was used in \code{method}, and \code{"none"} when nothing could +produce a figure.} + +\item{level}{Confidence level for the interval.} + +\item{df}{Degrees of freedom for the interval. \code{NULL} uses the design's +(see "Confidence intervals"); \code{Inf} gives a normal interval; otherwise a +single number of 1 or more.} + +\item{alternative}{\code{"two.sided"} for a confidence interval, \code{"less"} for a +one-sided upper bound or \code{"greater"} for a lower bound, each at \code{level}. +See "Confidence intervals".} +} +\value{ +A list of class \code{drawn_ratio} with a \code{print()} method, holding +\code{ratio}, the estimate; \code{variable} and \code{x}, the names of \code{y} and \code{x} +when they are column names, else \code{NULL}; \code{total_y} and \code{total_x}, +their estimated totals; and \code{variance}, \code{se}, \code{ci}, \code{level}, +\code{alternative}, \code{df}, \code{n}, \code{n_random}, \code{ci_scale}, \code{design}, \code{deff}, +\code{method}, \code{note} and \code{unreachable} as for \code{\link[=ht_total]{ht_total()}}. With \code{by}, a +\code{drawn_by} table with a row per domain and a \code{ratio} column, as for +\code{\link[=ht_total]{ht_total()}}. Both have \code{coef()}, \code{vcov()}, \code{confint()}, +\code{as.data.frame()} and \code{tidy()} methods; see "Working with the result" +in \code{\link[=ht_total]{ht_total()}}. +} +\description{ +\code{ht_ratio()} estimates \code{R = Y / X}, the ratio of the population totals of +\code{y} and \code{x}, by \code{sum(y / pi) / sum(x / pi)}: audited value per unit of +book value, spend per visit, or yield per hectare. A Hajek mean is the +ratio with \code{x} equal to 1 in every row. \code{\link[=ht_total]{ht_total()}} with \code{ratio} +multiplies the ratio by the frame's total of \code{x} to estimate the total of +\code{y}. +} +\section{Variance}{ + +The ratio is linearised. Its variance is that of the Horvitz-Thompson +total of the residuals \verb{(y - R x) / X_hat}, with \code{X_hat = sum(x / pi)} +(Särndal, Swensson and Wretman 1992; Deville 1999), and is computed with +the design's own estimator, as for a total: see "Variance" and +"Confidence intervals" in \code{\link[=ht_total]{ht_total()}} for the estimators, the fallback +to the jackknife, the degrees of freedom and the notes. For the designs +\code{\link[=as_svydesign]{as_svydesign()}} hands to \code{survey} with identical standard errors, the +standard error equals that of \code{survey::svyratio()} on its result. For +systematic, spread and systematic PPS samples it comes from the +estimator this package uses for their totals, which \code{survey} does not +have. + +The residuals sum to zero over the sample, weighted by \code{1 / pi}, so a +ratio whose sampled rows lie in one primary sampling unit, one row or one +cluster, gets no standard error, as a Hajek mean does. When \code{y} is +proportional to \code{x} in every sampled row the residuals are 0, the +variance is set to exactly 0 rather than left to rounding error, and +\code{note} says so. + +The ratio of two estimated totals is biased, by an amount of order +\code{1 / n}, which is small against its standard error except in small +samples. The design effect compares its variance with that of the same +ratio from a simple random sample of the same size, as +\code{survey::svyratio(deff = TRUE)} does. +} + +\section{Domains}{ + +\code{by} gives a ratio for each domain, \code{R_d = Y_d / X_d} over the rows of +the domain, estimated from the whole sample. Each domain's residuals, +\verb{(y - R_d x) / X_hat_d}, are 0 outside it, as for the domain totals and +means described under "Domains" in \code{\link[=ht_total]{ht_total()}}, and the standard errors +are those of +\code{survey::svyby(~y, ~d, design, survey::svyratio, denominator = ~x)}. A +domain whose estimated total of \code{x} is 0 is refused by name. + +A missing \code{y} or \code{x} is refused. \code{survey::svyratio(na.rm = TRUE)} on +\code{\link[=as_svydesign]{as_svydesign()}} estimates the ratio over the rows that have both. +} + +\examples{ +set.seed(1) +pop <- data.frame( + id = 1:300, + site = rep(c("a", "b", "c"), each = 100), + book = round(stats::rlnorm(300, 6, 1)) +) +pop$audited <- round(pop$book * stats::runif(300, 0.9, 1.05)) +s <- draw(pop, design_stratified("site", n = 45), seed = 1, weights = TRUE) + +# Audited value per unit of book value +ht_ratio(s, "audited", "book") +sum(pop$audited) / sum(pop$book) # the truth + +# For each site, from the whole sample +ht_ratio(s, "audited", "book", by = "site") + +# The ratio estimator of the total uses the frame's total of `book`, and +# is far more precise than the Horvitz-Thompson total here +ht_total(s, "audited", ratio = "book") +ht_total(s, "audited") +sum(pop$audited) + +} +\references{ +Deville, J.-C. (1999). Variance estimation for complex statistics and +estimators: linearization and residual techniques. \emph{Survey Methodology}, +25, 193–203. + +Särndal, C.-E., Swensson, B. and Wretman, J. (1992). \emph{Model Assisted Survey +Sampling}. Springer. +} +\seealso{ +\code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}}, \code{\link[=as_svydesign]{as_svydesign()}} +} diff --git a/man/ht_total.Rd b/man/ht_total.Rd index eced2bc..7e387a2 100644 --- a/man/ht_total.Rd +++ b/man/ht_total.Rd @@ -10,47 +10,111 @@ ht_total( variance = c("auto", "analytic", "jackknife", "none"), level = 0.95, by = NULL, - df = NULL + df = NULL, + alternative = c("two.sided", "less", "greater"), + contrast = NULL, + ratio = NULL ) } \arguments{ -\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}.} +\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}. See +"Which columns are read".} -\item{y}{The variable to total: a column name, or a numeric vector as long as -\code{sample}.} +\item{y}{The variable to total: a column name, several column names, a +numeric vector as long as \code{sample}, or a single number, which stands +for that value in every row. A factor or character column, or a factor +as long as \code{sample}, gives the count of each level. See "Several +variables" and "Categories".} \item{variance}{How to compute it. \code{"auto"} uses the design's own estimator (see "Variance") and falls back to the jackknife when that declines; \code{"analytic"} insists on the design's own estimator, returning \code{NA} with -the reason in \code{note} rather than falling back; \code{"jackknife"} always -resamples; \code{"none"} skips it. The result reports which was used in -\code{method}, and \code{"none"} when nothing could produce a figure.} +the reason in \code{note} rather than falling back; \code{"jackknife"} uses the +jackknife, and returns \code{NA} with the reason in \code{note} for systematic and +Poisson samples, where it does not apply; \code{"none"} skips it. The result +reports which was used in \code{method}, and \code{"none"} when nothing could +produce a figure.} \item{level}{Confidence level for the interval.} \item{by}{Optional column name(s) in \code{sample} defining domains. When given, -the result is one row per domain. See "Domains".} +the result is one row per domain. See "Domains". A column named like +one of the table's own, such as \code{n} or \code{se}, is refused.} \item{df}{Degrees of freedom for the interval. \code{NULL} uses the design's -(see "Confidence intervals"); \code{Inf} gives a normal interval.} +(see "Confidence intervals"); \code{Inf} gives a normal interval; otherwise a +single number of 1 or more.} + +\item{alternative}{\code{"two.sided"} for a confidence interval, \code{"less"} for a +one-sided upper bound or \code{"greater"} for a lower bound, each at \code{level}. +See "Confidence intervals".} + +\item{contrast}{Optional weights over the \code{by} domains, as a named numeric +vector such as \code{c(a = 1, b = -1)} for domain \code{a} less domain \code{b}. A name +is the domain's value of a single \code{by} column, or the values of several +joined by \code{" . "}, as in \code{"a . east"}, the way the notes of a \code{by} table +name domains. Needs \code{by}. See "Contrasts".} + +\item{ratio}{Optional name of a numeric column \code{x} of the frame, for the +ratio estimator of the total, \code{sum(y / pi) / sum(x / pi)} times the +frame's total of \code{x}. Not with \code{by}. See "Ratio estimation".} } \value{ A list with a \code{print()} method, holding: \describe{ \item{\code{total}}{The Horvitz-Thompson total, \code{sum(y / pi)}.} -\item{\code{variance}, \code{se}, \code{ci}, \code{level}, \code{df}}{Its estimated variance, -standard error, confidence interval, and the degrees of freedom the -interval used. \code{NA} where the design supports no variance.} -\item{\code{n}, \code{design}}{Rows used, and the design's type.} +\item{\code{variance}, \code{se}, \code{ci}, \code{level}, \code{alternative}, \code{df}}{Its +estimated variance, standard error, confidence interval or one-sided +bound, and the degrees of freedom the interval used. \code{NA} where the +design supports no variance.} +\item{\code{ci_scale}}{The scale the interval was formed on: \code{"linear"} +for a total, and \code{"logit"} or \code{"beta"} for a proportion from +\code{\link[=ht_mean]{ht_mean()}}.} +\item{\code{variable}}{The name of \code{y} when it is a column name, and +\code{NULL} when it is a vector.} +\item{\code{n}, \code{n_random}, \code{design}}{Rows used, those of them not taken +with certainty, which the beta interval of a proportion counts as +its sample size, and the design's type.} \item{\code{deff}}{The design effect — see \code{\link[=deff]{deff()}}.} \item{\code{method}}{Which estimator produced the variance. See "Variance".} \item{\code{note}}{Why a variance is missing, what approximation was used, or which fallback was taken. \code{NULL} when an exact estimator applied cleanly.} +\item{\code{unreachable}}{Rows of the frame with inclusion probability 0, +which the estimate does not cover; \code{NA} for a sample saved by drawn +0.2.0. See "Rows the design cannot reach".} +\item{\code{unavailable}}{For a sample from \code{\link[=use_reserves]{use_reserves()}} only, the +number of those rows found unavailable. The estimate takes every +frame row nobody visited as available; see "What the estimates +describe" in \code{\link[=use_reserves]{use_reserves()}}.} } +With \code{ratio}, the list also holds \code{ratio}, the estimated ratio of \code{y} +to \code{x}, \code{x}, the column's name, and \code{frame_total}, its total over the +frame. + With \code{by}, a data frame of class \code{drawn_by} instead: one row per domain, -with the domain columns, \code{n}, \code{total}, \code{se}, \code{ci_lower}, \code{ci_upper} and -\code{method}. +with the domain columns, \code{n} (an integer), \code{total}, \code{variance}, \code{se}, +\code{ci_lower}, \code{ci_upper} and \code{method}, and the level, alternative, scale, +degrees of freedom, notes, unreachable count and \code{variable} as +attributes. It prints without \code{variance}, which is the square of \code{se}. +A \code{by} table has no design effect. + +With \code{contrast}, a list of class \code{drawn_contrast} with a \code{print()} +method, holding \code{contrast}, the weighted sum; \code{weights} and \code{estimates}, +the weight and estimate of each domain it weighs; \code{what} (\code{"total"} or +\code{"mean"}), \code{estimator} for a mean, and \code{by}; and \code{variable}, +\code{variance}, \code{se}, \code{ci}, \code{level}, \code{alternative}, \code{df}, \code{n}, \code{n_random}, +\code{ci_scale}, \code{design}, \code{method}, \code{note} and \code{unreachable} as above. +\code{deff} is \code{NA}. + +With several column names as \code{y}, a \code{drawn_by} table with a row for +each variable, or each variable and domain, led by a \code{variable} column; +see "Several variables". With a factor or character \code{y}, the same +table with a row for each level, led by a \code{level} column; see +"Categories". + +Each has \code{coef()}, \code{vcov()}, \code{confint()}, \code{as.data.frame()} and +\code{tidy()} methods; see "Working with the result". } \description{ Forms the Horvitz-Thompson total \code{sum(y / pi)} with a standard error, a @@ -64,12 +128,22 @@ it, and \code{method} in the result says which one was used: \describe{ \item{\code{"analytic"}}{Exact and design-unbiased. Fixed-size designs with -known joint probabilities use the Sen-Yates-Grundy estimator; Poisson -sampling, whose rows are independent, uses \code{sum((1 - pi) / pi^2 * y^2)}; -cluster designs apply the estimator at the cluster level, because taking -whole clusters makes the row count random; certainty designs hand the -problem to \code{rest}, since certainty rows are in every sample and add -nothing.} +known joint probabilities use the Sen-Yates-Grundy estimator. For +simple random, reservoir and spatial samples, strata and intervals it +reduces to the textbook formula built from the variance of \code{y} within +each stratum or interval, and for an equal-take \code{\link[=design_multistage]{design_multistage()}} +to the two-stage formula built from the variance between the estimated +cluster totals and within clusters (Särndal, Swensson and Wretman +1992). Those formulas are what is computed, in time and memory that +grow with the number of sampled rows rather than with its square. +Poisson sampling, whose rows are independent, uses +\code{sum((1 - pi) / pi^2 * y^2)}; cluster designs apply the estimator at +the cluster level, because taking whole clusters makes the row count +random; certainty designs hand the problem to \code{rest}, since certainty +rows are in every sample and add nothing. A \code{\link[=design_systematic]{design_systematic()}} +sample with \code{n_starts} of 2 or more uses the variance between its +replicates' totals, the random group estimator (Wolter 2007), on +\code{n_starts - 1} degrees of freedom.} \item{\code{"deville"}}{Systematic probability-proportional-to-size (\code{\link[=design_weighted]{design_weighted()}} with \code{method = "systematic"}). Its joint probabilities have no closed form, so this uses Deville's (1999) @@ -78,42 +152,91 @@ best-performing of the standard approximations for high-entropy designs (Matei and Tillé 2005). Randomised systematic selection is close to high entropy (Hartley and Rao 1962). Unlike a plain jackknife, each row's contribution is scaled by its own \code{1 - pi}, so rows near certainty stop -adding variance they do not have.} -\item{\code{"successive difference"}}{\code{\link[=design_systematic]{design_systematic()}}. No -design-unbiased estimator exists — the design has one random start, and -most pairs of rows can never be drawn together — so this uses the -successive-difference approximation, which compares each sampled row with -its neighbour in the order the design walked (Wolter 2007). It removes a -trend along that order rather than counting it as noise, which is why it -beats treating the sample as simple random: on a frame sorted by a -variable related to \code{y}, the simple random formula overstated the -variance two- to thirtyfold in the package's simulations, where this one -stayed near the truth. Two limits no estimator from a single systematic -sample can escape: it is understated if the frame cycles with a period -matching \code{interval}, and when a smooth trend so dominates \code{y} that the -random start is almost the only source of variation, it runs low (0.3 to -0.7 of the truth when the trend spanned 25 noise standard deviations).} +adding variance they do not have. With \code{strata} it is added up over +the strata. \code{\link[=design_multistage]{design_multistage()}} with \code{size} applies it to the +estimated totals of the clusters, and adds the variance within them.} +\item{\code{"successive difference"}}{\code{\link[=design_systematic]{design_systematic()}}. The design has +one random start, and at a step of 2 rows or more neighbouring rows are +never drawn together, so no design-unbiased estimator exists. This uses +the successive-difference approximation, which compares each sampled +row with its neighbour in the order the design walked (Wolter 2007), at +every step, including a step under 2 rows, where every pair of rows can +be drawn together. It removes a trend along that order rather than +counting it as noise, which is why it beats treating the sample as +simple random: on a frame sorted by a variable related to \code{y}, the +simple random formula overstated the variance two- to thirtyfold in the +package's simulations. This one came closer, but its average over the +random starts depends on the frame, and on the estimation article's +example it was 1.6 times the true variance. No estimator from a single +systematic sample escapes its limits. A frame that cycles with a period +equal to the step, or one that divides it, such as 5 rows at a step of +10, puts every row of one sample at the same phase of the cycle, and the +variance is understated, to under 0.001 of the truth in one simulation. +A period of twice the step puts neighbouring sampled rows at opposite +phases, and the variance is overstated, 29-fold in the same simulation. +When a smooth trend so dominates \code{y} that the random start is almost the +only source of variation, it runs low, and has no floor. It was 0.3 to +0.7 of the truth when the trend spanned 25 noise standard deviations, +0.2 at 100 and 0.06 at 1,000. With \code{y} a straight line along the walk +and no noise, it is \code{6 * k / (n * (k + 1))} times the truth, about +\code{6 / n}, for \code{n} rows sampled at a step of \code{k}. +When \code{interval} does not divide the number of rows walked, the sample +size is random, one of two values, and the total moves with it in a way +successive differences cannot see. A term for that, +\code{mean(y / pi)^2 * (r / k) * (1 - r / k)} with \code{k} the interval and \code{r} +the remainder, is added, and the note says so. Without it a constant +\code{y} had a standard error of 0, and a variable with a coefficient of +variation of 0.02 an interval that never covered the truth. A design +given \code{n} draws exactly \code{n} rows at a step of \code{N / n} and needs no +such term. \code{\link[=design_stratified]{design_stratified()}} with +\code{within = design_systematic()} adds up this estimator over its +strata.} \item{\code{"local mean"}}{\code{\link[=design_spread]{design_spread()}}. A spatially balanced sample is well spread precisely because neighbours are rarely taken together, so this compares each sampled row with the local mean of its nearest -sampled neighbours (Stevens and Olsen 2003; Grafström and Schelin 2014).} +sampled neighbours (Stevens and Olsen 2003; Grafström and Schelin 2014). +With \code{strata} it runs within each stratum, and the strata's variances +are added.} \item{\code{"jackknife"}}{The delete-one-unit jackknife, by stratum (JKn) where the design has strata, and deleting whole clusters where it has them. Used when requested, and as the fallback under \code{variance = "auto"}.} } +Rows taken with certainty are in every possible sample and add nothing to +the variance. That covers rows above a \code{\link[=design_certainty]{design_certainty()}} threshold, rows +whose size puts them past certainty in \code{\link[=design_weighted]{design_weighted()}} or +\code{\link[=design_spread]{design_spread()}}, strata taken whole, clusters taken whole by a two-stage +design that selects every cluster, and a census. Every estimator leaves +them out. The jackknife holds them fixed instead of deleting them, and its +finite population correction counts only the other units. A sample made of +nothing else has a variance of 0 under the design's own estimator. + The analytic estimator declines — returning \code{NA} with the reason in \code{note} -— rather than understate. Two cases matter in practice: +— rather than understate. Only a decline sends \code{variance = "auto"} to the +jackknife. Any other error inside an estimator, such as running out of +memory, stops \code{ht_total()} with that error. Two cases matter in practice: \itemize{ \item \strong{A stratum or interval with a single sampled row.} There is no variation inside it to measure, and simply leaving it out, as the Sen-Yates-Grundy sum does, reports a standard error that is too small — zero, if every stratum is like that. Draw at least two per stratum (\code{min_per_stratum = 2}, \code{per_interval = 2}). -\item \strong{One row per cluster in a multistage design.} The within-cluster -variation is unmeasurable and the exact estimator understates by around -a third. \code{variance = "auto"} falls back to the delete-a-cluster jackknife, -which is the ultimate-cluster approximation standard in survey practice. +\item \strong{One row per cluster in a multistage design.} Two rows of one cluster +are never drawn together, so the within-cluster variation is +unmeasurable. With \code{f1 = n_clusters / N_clusters}, the share of clusters +selected, the exact estimator understates by \code{f1} times the +within-cluster component of the variance. \code{variance = "auto"} falls back +to the delete-a-cluster jackknife, the ultimate-cluster approximation +standard in survey practice. It has no first-stage finite population +correction, so it overstates by \code{f1} times the between-cluster component, +the variance the cluster totals would have if clusters were drawn with +replacement. The excess is small when few clusters are selected. With 30 +of 40 clusters whose totals differed widely, the jackknife averaged 3.3 +times the true variance. Whenever \code{f1} is above 0.2, the note gives the +factor by which the jackknife inflates the between-cluster part. When +every cluster is selected, the clusters are strata and the variance +between them is zero by design, so \code{\link[=design_stratified]{design_stratified()}} with the cluster +column as \code{strata} and two rows in each gives an exact variance instead. } A Sen-Yates-Grundy estimate that comes out negative is treated the same way: @@ -129,6 +252,73 @@ with hundreds of units and decisive with a handful: at four clusters a normal interval covers about 87\% where it claims 95\%, and the t interval restores most of that. The degrees of freedom used are reported as \code{df}; pass \code{df = Inf} for the normal interval. + +Units taken with certainty count in neither number. They are in every +sample and carry no variance, and counting them made the interval too +narrow. With eight certain units among ten, systematic PPS reported 9 +degrees of freedom where the variance rests on two units, and its interval +covered 79\%. A stratum or interval with no other unit drops out of the +count of strata. With no unit below certainty the variance is 0 and \code{df} +is \code{Inf}. \code{\link[=as_svydesign]{as_svydesign()}} hands certain units to \code{survey} in a form that +makes \code{survey::degf()} give the same count, except for a census, where it +gives \code{n - 1}. + +An estimate whose variance is 0 is exact and gets a zero-width interval +whatever \code{df} is. Otherwise a design that leaves 0 degrees of freedom, such +as Poisson sampling that drew one row, gives a standard error but no +interval, and \code{note} says why. \code{df} set by hand must be at least 1. A +proportion of 0 or 1 is the exception to the first rule; see +"Proportions" in \code{\link[=ht_mean]{ht_mean()}}. + +The t interval assumes the estimate is close to normally distributed over +repeated samples. When \code{y / pi} is skewed and the sample small it is not, +and the interval covers less often than \code{level} says, even where the +variance estimate is close to unbiased. In 2,000 draws with \code{n = 30} from +240 rows in proportion to a size whose coefficient of variation was 0.66, +with \code{y} close to proportional to size, the 95\% interval for the total +covered 90\% of the time under systematic PPS and 94\% under Poisson PPS. The +mean with \code{estimator = "ht"}, which \code{\link[=ht_mean]{ht_mean()}} recommends in that case, is +the total divided by \code{N} and covered as often. The default Hajek mean +covered 91\% under both methods. Skew is one reason. The Hajek mean also has +a ratio bias, here 1.5\% of the mean under systematic PPS and 1.8\% under +Poisson PPS, and its estimated variance averaged 0.89 and 0.88 times the +variance of the mean over the draws. Skew lowers coverage under equal +probabilities too. A simple random sample of 30 from 600 lognormal values +with a coefficient of variation of 1.5 covered 87\%. A larger sample brings +the coverage closer to \code{level}. The audit-sampling article checks a bound's +coverage by drawing the design many times, which is how to check it on a +frame of your own. + +\code{alternative = "less"} gives a one-sided upper bound, the figure an auditor +signs off against, and \code{"greater"} a lower bound. The other end of \code{ci} is +then \code{-Inf} or \code{Inf}, or 0 or 1 for a proportion, and the printout labels +the bound. A one-sided bound at \code{level} is the end of a two-sided interval +at \code{1 - 2 * (1 - level)}, so the 95\% upper bound is the upper end of the +90\% interval, which \code{level = 0.90} also gives. +} + +\section{Rows the design cannot reach}{ + +Rows with inclusion probability 0, such as rows past \code{max_items}, outside +a region or time window, dropped by \code{na_rm} or in a stratum allocated no +rows, can never be drawn, so a total covers the other rows only. +\code{\link[=draw]{draw()}} warns about some of them by name. The estimate keeps their +number in \code{unreachable} and prints it on a line of its own, since a sample +saved and read back, or drawn with the warning muffled, would otherwise +give no sign of them. The design effect is measured against a simple +random sample of the rows the design can reach; see \code{\link[=deff]{deff()}}. +} + +\section{An empty sample}{ + +A design of random size, such as Poisson sampling or a systematic sample +whose random start falls past the last row, can draw nothing. \code{ht_total()} +then returns a total of 0, which keeps the estimator unbiased over repeated +draws, with \code{df} 0, the variance, standard error and interval \code{NA}, and a +note that the sample is empty. \code{\link[=ht_mean]{ht_mean()}} refuses the Hajek mean of an +empty sample, which is 0 / 0; \code{estimator = "ht"} gives 0. An empty sample +from a design that gives every row a probability of 0, such as one with +\code{n = 0}, is refused, and so is any empty sample in \code{\link[=as_svydesign]{as_svydesign()}}. } \section{Domains}{ @@ -140,6 +330,258 @@ number of rows that happen to fall in a domain is itself random. Here each domain's total is estimated from \verb{y * (row in domain)} over the whole sample, so the same design and the same variance machinery apply (Särndal, Swensson and Wretman 1992, section 10.3). + +Domains come out in key order: a factor's levels, numbers and dates in +sequence, and text sorted byte by byte as in the C locale, the same in every +session. A domain with no sampled row is left out, as \code{survey::svyby()} +leaves it out. + +A stratum or interval with a single sampled row stops a domain's variance, +as it stops the whole sample's, unless it holds no unit of the domain. That +is read from the \code{by} columns of the frame stored with the sample, so it +needs them in the frame, with the same values as in the sample. A domain +made of strata taken whole is then exact, with a zero-width interval. A +lonely stratum whose one sampled row lies outside the domain still stops +it when other units of the stratum belong to the domain, because their +variation went unmeasured. A frame row whose \code{by} value is missing may +belong to any domain, so a lonely stratum holding one stops every domain. + +A domain's Hajek mean (\code{\link[=ht_mean]{ht_mean()}}) needs sampled rows in at least two +primary sampling units, rows or clusters. Its linearised residuals sum to +zero inside the unit that holds the whole domain, so with one unit every +estimator gives a standard error of about 0, and \code{survey} does the same. Such +a domain gets no standard error, with a note. When stage one of a cluster +design takes every cluster, the analytic estimator's units are rows, since +each cluster is then in every sample and only its rows were drawn at random. +The jackknife still deletes whole clusters, so a domain inside one cluster +gets no standard error from it, whether \code{variance = "jackknife"} asks for it +or \code{"auto"} turns to it after the analytic estimator declines. Rows taken +with certainty count as one unit, since every estimator holds them fixed and +\code{as_svydesign()} hands them to \code{survey} together, so a domain whose sampled +rows were all taken with certainty gets no standard error either, unless +every row of it that the design could reach is certain, which makes its mean +exact. A domain total, and the \code{estimator = "ht"} mean, keep the standard +error of 0 their estimators give such a domain, since those estimators are +unbiased over samples, and a note says the interval has no width because the +sampled rows were all certain. A domain with a handful of sampled rows has a +standard error that is itself unreliable, and the interval covers less often +than \code{level} says. In one simulation of a skewed variable, a 95\% interval for +the mean of a domain with two or three sampled rows covered 65\% of the time, +and 85\% with four or five. + +A sample grouped with \code{dplyr::group_by()} is estimated as a whole, with a +warning of class \code{drawn_grouped_df}; the groups play no part. Use \code{by}. + +The strata, clusters and other pieces the variance reads from the frame +are worked out once for all the domains. For simple random, reservoir, +spatial, stratified and temporal samples the analytic variances of all +the domains come from one pass over the sample, in time that grows with +the number of sampled rows rather than with rows times domains. A domain +with units in a stratum or interval of one sampled row, and every domain +under \code{variance = "jackknife"}, is estimated on its own. +} + +\section{Contrasts}{ + +\code{contrast} weighs the domain estimates of \code{by} and gives their weighted +sum, such as the difference between two sites' totals or means, with a +standard error, an interval and \code{df} as for any other estimate. Each +domain's estimate is the total, over the whole sample, of a variable that +is 0 outside the domain: \code{y} for a total, the linearised residual for a +Hajek mean and \code{y / N_d} for a Horvitz-Thompson mean. The weighted sum of +the estimates is the total of the same weighted sum of those variables, so +one run of the design's variance estimator gives its variance, with the +covariances between domains included. For simple random, stratified, +cluster and multistage samples the standard error equals that of +\code{survey::svycontrast()} applied to \code{survey::svyby(..., covmat = TRUE)}. + +The interval is symmetric, for a proportion too, since a difference of +proportions can be negative. Domains left out of \code{contrast} have a weight +of 0. A name that is not a domain with a sampled row is refused, and so is +a contrast whose weights are all 0. When a Hajek mean that the contrast +weighs rests on one primary sampling unit, the contrast gets no standard +error, for the reason given under "Domains". +} + +\section{Ratio estimation}{ + +\code{ratio} names a column \code{x} of the frame, and the total of \code{y} is then +estimated by the ratio estimator \code{sum(y / pi) / sum(x / pi) * X}, where +\code{X} is the total of \code{x} over the frame rows the design can reach, read +from the frame stored with the sample, as \code{\link[=frame_totals]{frame_totals()}} reads it. +When \code{y} is close to proportional to \code{x}, such as an audited value and +the book value it was drawn on, the residuals \verb{y - R x} vary far less +than \code{y}, and the estimate is more precise than the Horvitz-Thompson +total. Its variance is \code{X^2} times that of the +ratio from \code{\link[=ht_ratio]{ht_ratio()}}, estimated from the residuals +\verb{X (y - R x) / X_hat} with the design's own estimator, and it equals +\code{predict(survey::svyratio(~y, ~x, design), total = X)} for the designs +\code{\link[=as_svydesign]{as_svydesign()}} maps with identical standard errors. The sampled rows' +values of \code{x} come from the frame too. A value of \code{x} missing from a +frame row the design can reach is refused, since \code{X} is then unknown, +and so is \code{ratio} with \code{by}. The result holds the ratio as \code{ratio}, the +column as \code{x} and \code{X} as \code{frame_total}, and prints them. + +The ratio estimator is biased, by an amount of order \code{1 / n}, and its +design effect compares it with the same estimator from a simple random +sample of the same size. Calibration in \code{survey}, with the totals from +\code{\link[=frame_totals]{frame_totals()}}, covers several auxiliary columns at once. +} + +\section{Several variables}{ + +\code{y} may name several columns, such as \code{c("spend", "visits")}. The result +is then a \code{drawn_by} table with a row for each variable, or for each +variable and domain with \code{by}, led by a \code{variable} column. Each row holds +what a call for that variable alone gives: the same estimate, standard +error, interval and method, with the same refusals for a missing or +infinite value, named by its column. Notes that hold for every variable +are printed once, and the others after the variable's name. + +\code{vcov()} of the table gives the covariances between the variables' +estimates as well as their variances. Every variance estimator here is a +quadratic form in the variable it totals, so the covariance of two +estimates whose variables are \code{z_a} and \code{z_b} is +\code{(V(z_a + z_b) - V(z_a) - V(z_b)) / 2}, one more run of the same +estimator. For a total these variables are the \code{y} columns, and for a +Hajek mean their linearised residuals. For the designs \code{\link[=as_svydesign]{as_svydesign()}} +maps with identical standard errors, the matrix equals +\code{vcov(survey::svytotal(~a + b, design))}, or that of \code{survey::svymean()} +for means. With \code{by}, the covariances between the variables within each +domain are estimated, and those between domains are not, as for a \code{by} +table of one variable. A covariance is \code{NA} when either +variance is missing, or when the two variances, or the variance of their +sum, did not come from one estimator, as when the design's own declined +for one and the jackknife stood in. + +A \code{by} column named \code{variable} is refused, and so is \code{contrast}. The +table has no design effect. +} + +\section{Categories}{ + +A factor or character column named as \code{y}, or a factor as long as +\code{sample}, is split into a 0/1 indicator for each of its levels: +\code{ht_total()} gives the estimated number of frame rows at each level, and +\code{\link[=ht_mean]{ht_mean()}} the share of each, with a proportion's interval. The result +is the table of "Several variables" with a row for each level, or each +level and domain with \code{by}, led by a \code{level} column in place of +\code{variable}, and \code{vcov()} holds the covariances between levels. The +levels are a factor's levels, unused ones included, and the values of a +character column sorted byte by byte. A missing value is a missing \code{y}. +For the designs \code{\link[=as_svydesign]{as_svydesign()}} maps with identical standard errors, the +estimates and \code{vcov()} equal those of \code{survey::svytotal(~f, design)} and +\code{survey::svymean(~f, design)}. A character vector given as \code{y} is read +as column names, so pass categories held in a vector as a factor. A +\code{by} column named \code{level} is refused, and so is \code{contrast}; the +indicator of one level, such as \code{sample$f == "a"}, takes it. + +A single number as \code{y} stands for that value in every row: +\code{ht_total(sample, 1)} estimates the number of frame rows the design can +reach, and with \code{by} the number in each domain. +} + +\section{Working with the result}{ + +\code{coef()} gives the estimate, named after \code{y} when \code{y} is a column name, +\code{vcov()} its variance as a 1 by 1 matrix, and \code{confint()} its interval as +a matrix with a column for each end. At the estimate's own \code{level}, +\code{confint()} returns the interval the estimate holds. At another level it +forms the interval again on the design's degrees of freedom and on the +estimate's scale (\code{ci_scale}), so it gives what \verb{level =} in \code{ht_total()} +or \code{\link[=ht_mean]{ht_mean()}} would have given. \code{survey::SE()} and \code{survey::cv()} work +through \code{coef()} and \code{vcov()}. + +\code{as.data.frame()} gives one row of \code{variable}, \code{n}, the estimate, +\code{variance}, \code{se}, \code{ci_lower}, \code{ci_upper}, \code{level}, \code{df}, \code{deff} and +\code{method}, so estimates of several variables can be bound with \code{rbind()}. +With the generics package installed, \code{generics::tidy()}, and so +\code{broom::tidy()}, gives \code{term}, \code{estimate} and \code{std.error}, with +\code{conf.low} and \code{conf.high} when \code{conf.int = TRUE}, at \code{conf.level}, which +is the estimate's own level unless given. + +A \code{by} table has the same methods. \code{coef()} names each domain as +\code{contrast} names it, \code{confint()} and \code{tidy()} give a row per domain, +\code{tidy()} with the \code{by} columns, and \code{as.data.frame()} drops the table's +class and attributes. \code{vcov()} holds the domains' variances. The +covariances between domains are not estimated, and its entries for them +are \code{NA}, except 0 for two domains of a \code{\link[=design_stratified]{design_stratified()}} sample +whose sampled rows share no stratum, since strata are sampled +independently. The standard error of a difference between domains comes +from \code{contrast}, not from \code{vcov()}. A table of +several variables names each row by its variable, then its domain, as in +\code{"spend . a"}, and its \code{vcov()} holds the covariances between variables +described under "Several variables". Selecting +columns of the table with \code{[} or \code{subset()} drops the attributes these +methods read, and the result prints as a plain data frame. Selecting rows +keeps them. A \code{drawn_contrast} has the same methods, with the estimate +named by its weights, as in \code{"a - b"}, and so does a ratio from +\code{\link[=ht_ratio]{ht_ratio()}}, named as \code{"y/x"}. +} + +\section{Missing values and nonresponse}{ + +\code{ht_total()} refuses a missing \code{y}, from a nonresponse or a measurement +that failed. A total over the rows with \code{y} present counts the others as +0, so it is low by about the share of the weight they hold, the weighted +nonresponse rate, and the message gives that share. + +\code{ht_mean(na_rm = TRUE)} estimates the mean over the rows with \code{y} +present. They are a domain of the whole sample, as a \code{by} domain is: the +estimate is the Hajek mean over them, and its variance comes from the +linearised residuals over every sampled row, 0 for the rows left out, +with the design's own estimator and degrees of freedom. +\code{survey::svymean(na.rm = TRUE)} on \code{\link[=as_svydesign]{as_svydesign()}} gives the same +estimate and standard error. With \code{by}, each domain's mean is over its +rows with \code{y} present, and a domain whose sampled rows all have \code{y} +missing has no mean, no row in the table and no place in \code{contrast}; the +note names it. \code{\link[=add_fieldwork]{add_fieldwork()}} joins results keyed by an id and leaves +\code{y} missing for a sampled row with none. + +That mean is unbiased for the frame's mean only if the values are missing +completely at random, with no relation between whether a row has a \code{y} +and its \code{y}. +When response rates differ between groups whose \code{y} differs, such as +sites, the rows with \code{y} present over-represent the groups that responded +more. A weighting-class adjustment corrects for that, under the weaker +assumption that response is unrelated to \code{y} within each group. Multiply +the \code{.weight} of each row with \code{y} present by its group's sum of +\code{.weight} over all its sampled rows, divided by the same sum over its rows +with \code{y} present, and estimate totals and means from \code{\link[=as_svydesign]{as_svydesign()}} +with \code{survey}'s \code{na.rm = TRUE}. \code{survey} treats the adjusted weights as +fixed, so its standard errors leave out that the adjustment factors were +estimated from the sample. \code{ht_total()} and \code{\link[=ht_mean]{ht_mean()}} keep to \code{.prob} +and do not see the adjustment. The estimation article shows the steps. + +A unit that cannot be reached at all, rather than one that does not +answer, can be replaced from a reserve list drawn with the sample: +\code{reserve} in \code{\link[=design_simple]{design_simple()}} and \code{\link[=design_spread]{design_spread()}}, then +\code{\link[=use_reserves]{use_reserves()}}. The estimates then describe the units that can be +reached. +} + +\section{Which columns are read}{ + +\code{ht_total()} and \code{\link[=ht_mean]{ht_mean()}} divide by \code{.prob}, the inclusion probabilities +\code{\link[=draw]{draw()}} attached, find each sampled row's frame row through \code{.row}, and +read strata, clusters, time stamps and the other design columns from the +copy of the frame stored with the sample. Of the sample's own columns they +read \code{.prob}, \code{.row}, \code{y} and \code{by}, and \code{.weight} only to warn when it was +edited, so renaming, recoding or dropping a design column in the sample +changes nothing. + +\code{.weight} is not used in the estimate. A weight adjusted after the draw, for +nonresponse or by trimming, and written into \code{.weight} is ignored with a +warning of class \code{drawn_weight_edited}; \code{\link[=as_svydesign]{as_svydesign()}} hands \code{.weight} to +\code{survey}, which is where adjusted weights are estimated from. A sample +whose \code{.prob} was changed or removed is refused. So is one whose design +gives the frame different inclusion probabilities in the current session +than it did at draw time, which a change of \code{\link[sf:s2]{sf::sf_use_s2()}} does to a +\code{\link[=design_spatial]{design_spatial()}} sample: the variance is recomputed from the design and +would describe another one. A sample saved by drawn 0.2.0 has no \code{.row} +and records no probabilities for the frame, so its rows are matched by +position and it is refused when the design gives a sampled row a +probability other than its \code{.prob}. } \examples{ @@ -159,6 +601,15 @@ sum(pop$spend) # the truth ht_total(s, "spend", by = "site") tapply(pop$spend, pop$site, sum) +# How much more site a spent than site b +ht_total(s, "spend", by = "site", contrast = c(a = 1, b = -1)) + +# Two variables at once, with the covariance between their totals +s$visits <- round(s$spend / 50) + 1 +both <- ht_total(s, c("spend", "visits")) +both +vcov(both) + } \references{ Horvitz, D. G. and Thompson, D. J. (1952). A generalization of sampling @@ -195,5 +646,6 @@ Särndal, C.-E., Swensson, B. and Wretman, J. (1992). \emph{Model Assisted Surve Sampling}. Springer. } \seealso{ -\code{\link[=ht_mean]{ht_mean()}}, \code{\link[=deff]{deff()}}, \code{\link[=joint_prob]{joint_prob()}}, \code{\link[=inclusion_prob]{inclusion_prob()}} +\code{\link[=ht_mean]{ht_mean()}}, \code{\link[=ht_ratio]{ht_ratio()}}, \code{\link[=ht_quantile]{ht_quantile()}}, \code{\link[=deff]{deff()}}, +\code{\link[=joint_prob]{joint_prob()}}, \code{\link[=inclusion_prob]{inclusion_prob()}} } diff --git a/man/inclusion_prob.Rd b/man/inclusion_prob.Rd index a46c7f5..d504575 100644 --- a/man/inclusion_prob.Rd +++ b/man/inclusion_prob.Rd @@ -18,17 +18,27 @@ sampling_weight(data, design, simulate = FALSE, R = 5000, seed = NULL) closed form. Required for the designs listed above; allowed for any probability design, which is a convenient way to check the exact formulas.} -\item{R}{Number of simulated draws when \code{simulate = TRUE}.} +\item{R}{Number of simulated draws when \code{simulate = TRUE}. See "What a +simulation costs".} -\item{seed}{Optional seed for the simulation.} +\item{seed}{Optional seed for the simulation, applied as in \code{\link[=draw]{draw()}} (see +"Seeding" there). Checked whether or not \code{simulate} is \code{TRUE}.} } \value{ A numeric vector with one element per row of \code{data}. -Rows the design can never select — outside the region, outside the time -window, at zero weight — get \code{0} from \code{inclusion_prob()} and \code{NA} from -\code{sampling_weight()}, since no finite number of population rows is -represented by a row that cannot be drawn. \code{\link[=sample_summary]{sample_summary()}} counts them. +A row the design can never select gets \code{0} from \code{inclusion_prob()} and +\code{NA} from \code{sampling_weight()}, since no finite number of population rows +is represented by a row that cannot be drawn. Such a row lies outside +the region or the time window, comes past \code{max_items}, or was dropped +under \code{na_rm = TRUE}. +\code{\link[=sample_summary]{sample_summary()}} counts them. A weight of 0 is not one of these. The +designs that select in proportion to size refuse it, so drop such rows +from \code{data} first. + +A design that \code{\link[=draw]{draw()}} refuses, such as an \code{n} larger than the frame or +than the rows inside a region, is refused here too, with the same +message, rather than given probabilities above 1 or a census. } \description{ \code{inclusion_prob()} returns the first-order inclusion probability of every row @@ -49,43 +59,59 @@ Most do, and those are computed exactly: \tabular{ll}{ \code{\link[=design_simple]{design_simple()}} \tab \code{n / N} \cr \code{\link[=design_stratified]{design_stratified()}} \tab \code{n_h / N_h} within each stratum \cr -\code{\link[=design_systematic]{design_systematic()}} \tab \code{1 / interval}, for every row, exactly \cr -\code{\link[=design_cluster]{design_cluster()}} \tab \code{n_clusters / N_clusters} \cr -\code{\link[=design_multistage]{design_multistage()}} \tab \code{(n_clusters / N_clusters) * (n_h / N_h)}, when the per-cluster take is constant \cr -\code{\link[=design_weighted]{design_weighted()}} \tab \code{n * p_i} for the \code{"systematic"} and \code{"poisson"} methods \cr +\code{\link[=design_systematic]{design_systematic()}} \tab \code{1 / interval} with a random \code{start}, or \code{n / N} with \code{n}, for every row walked, exactly \cr +\code{\link[=design_cluster]{design_cluster()}} \tab \code{n_clusters / N_clusters}; with \code{balanced = TRUE}, that times the cluster's average take over its size, worked out exactly (see \code{\link[=design_cluster]{design_cluster()}}) \cr +\code{\link[=design_multistage]{design_multistage()}} \tab \code{(n_clusters / N_clusters) * (n_h / N_h)}, when the per-cluster take \code{n_h} is constant; with replacement, \code{(n_clusters / N_clusters) * (1 - (1 - 1 / N_h)^n_h)}; with \code{size}, the cluster's \code{pi_h = n_clusters * M_h / sum(M)} in place of \code{n_clusters / N_clusters} \cr +\code{\link[=design_weighted]{design_weighted()}} \tab \code{n * p_i} for the \code{"systematic"} and \code{"poisson"} methods, with rows past 1 taken with certainty and the rest rescaled to sum to \code{n}; with \code{strata}, \code{n_h * p_i} within each stratum \cr \code{\link[=design_certainty]{design_certainty()}} \tab \code{1} above the threshold, \code{rest}'s own below it \cr \code{\link[=design_reservoir]{design_reservoir()}} \tab \code{n / min(N, max_items)}, and \code{0} past \code{max_items} \cr \code{\link[=design_temporal]{design_temporal()}} \tab \code{per_interval / N_bucket} within each interval \cr \code{\link[=design_spatial]{design_spatial()}} \tab \code{n / N_in_region} \cr -\code{\link[=design_spread]{design_spread()}} \tab \code{n / N}, or \code{n * p_i} with a \code{size} column \cr +\code{\link[=design_spread]{design_spread()}} \tab \code{n / N}, or \code{n * p_i} with a \code{size} column; with \code{strata}, the same within each stratum \cr } -Five cases have no closed form, and the package refuses to invent one: +A design with \code{reserve} gives the probabilities of its main sample, which +the reserves do not change. The design of a sample from \code{\link[=use_reserves]{use_reserves()}} +gives \code{n / (N - u)}, and \code{0} for the \code{u} rows found unavailable. + +Four cases have no closed form, and the package refuses to invent one: \itemize{ -\item \code{design_cluster(balanced = TRUE)} — the per-cluster take is the smallest -\emph{selected} cluster's size, which is itself random. Simulation on clusters of -2/4/6/8 gives 0.50, 0.41, 0.34, 0.25, against the 0.50 a naive -\code{n_clusters / N_clusters} would claim for every row. \item \code{design_multistage(allocation = "proportional")} — the stage-two allocation depends on which clusters were selected. Simulation on clusters of 3/5/7/9 gives 0.17, 0.20, 0.17, 0.15, against a naive 0.33, 0.20, 0.14, 0.11. \item \code{design_multistage()} where the per-cluster take is not constant — \code{n} not -divisible by \code{n_clusters}, or a cluster smaller than \code{n / n_clusters}. The -allocation runs over the \emph{selected} clusters, so the remainder goes to the -largest of them and an undersized cluster is capped with its shortfall -dealt to whichever clusters came with it. A row's probability then depends -on the company it keeps. On clusters of 20/10/8/6 with \code{n = 7} over 2 -clusters, the average take is out by up to 17\%, and a cluster smaller than -the take can push the figure above 1. +divisible by \code{n_clusters}, or, without replacement, a cluster smaller than +\code{n / n_clusters}. The allocation runs over the \emph{selected} clusters, so the +remainder goes to the largest of them and an undersized cluster is capped +with its shortfall dealt to whichever clusters came with it. A row's +probability then depends on the company it keeps. On clusters of +20/10/8/6 with \code{n = 7} over 2 clusters, the average take is out by up to +17\%, and a cluster smaller than the take can push the figure above 1. + +For these two, the exact probability is the probability given the +clusters selected, averaged over every possible selection, and that +average has no formula. \code{draw(weights = TRUE)} weights the sample +conditional on the clusters it selected instead, which gives an +unbiased total without the average; see "Design weights" in \code{\link[=draw]{draw()}}. \item \code{design_weighted(method = "successive")} — the default. Successive sampling has no closed-form inclusion probability; this is the whole reason the other two methods exist. Note that its realised probabilities are not merely unknown but genuinely different from proportional-to-size: for weights -\code{1:10} at \code{n = 5}, simulation puts them up to 35\% away. +\code{1:10} at \code{n = 5}, enumerating every ordered draw puts them up to about +36\% away. \item \code{\link[=design_bootstrap]{design_bootstrap()}} — resampling with replacement from the sample is not a probability sample of a finite population, so there is no \code{pi} to report. } +A \code{\link[=design_systematic]{design_systematic()}} with a fixed \code{start} is refused too, for another +reason. It is deterministic: each row has probability 0 or 1, and +\code{simulate = TRUE} reports exactly that. Without \code{simulate} those values +are refused, because \code{draw(weights = TRUE)} would give every sampled row a +weight of 1 and \code{\link[=ht_total]{ht_total()}} would report the sum over the sample as the +total of the frame. So are \code{\link[=sampling_weight]{sampling_weight()}}, \code{\link[=joint_prob]{joint_prob()}}, +\code{draw(weights = TRUE)} and the estimators. Leave \code{start} as \code{NULL} for a +probability sample. + For all but the bootstrap, pass \code{simulate = TRUE} to estimate them by Monte Carlo instead. The estimate carries \code{R}-sized error, which is fine for checking a design and not fine for publishing a variance. Simulating a @@ -93,6 +119,24 @@ bootstrap is refused rather than answered: every row turns up in some replicate, so the count converges to 1 for all of them. } +\section{What a simulation costs}{ + +\code{simulate = TRUE} makes \code{R} draws, 5,000 by default, so it takes \code{R} +times as long as one \code{\link[=draw]{draw()}}. Most designs draw from a frame of 10,000 +rows in well under a second. The local pivotal method of \code{\link[=design_spread]{design_spread()}} +does work in proportion to \code{N^2} on every draw, so at 10,000 rows each +draw takes seconds and the default \code{R} takes hours. When the draws after +the first two, which carry one-off costs, project a run of more than 30 +seconds, a message says how long it will take, and an interactive session +shows a progress bar. Lower \code{R} for a +quicker answer with more Monte Carlo error: its standard error is +\code{sqrt(p * (1 - p) / R)}, at most 0.007 for \code{R = 5000}. + +A warning that every draw raises, such as a stratum allocated no rows or +\code{max_items} cutting a frame short, is given once at the end, with the +number of draws that raised it. +} + \examples{ df <- data.frame(id = 1:20, site = rep(c("a", "b"), times = c(15, 5))) diff --git a/man/joint_prob.Rd b/man/joint_prob.Rd index 6408fd3..c77ec15 100644 --- a/man/joint_prob.Rd +++ b/man/joint_prob.Rd @@ -11,9 +11,13 @@ joint_prob(data, design, rows = NULL, simulate = FALSE, R = 5000, seed = NULL) \item{design}{A design object.} -\item{rows}{Optional row indices. Supply these — usually the rows you drew — -to get the submatrix for them instead of the full \code{nrow(data)} square, -which is what makes this usable on a large population.} +\item{rows}{Optional row indices, usually the rows you drew, which are +\code{s$.row} for a sample \code{s} from \code{draw(weights = TRUE)}. The result is then +the submatrix for these rows instead of the full \code{nrow(data)} square, +which is what makes this usable on a large population. See "Size". +Indices must be whole numbers. A row given more than once is one unit, +so its entry with itself, off the diagonal too, is its own inclusion +probability.} \item{simulate}{Estimate the probabilities by repeated draws rather than in closed form. Works for every probability design, including the ones with no @@ -21,9 +25,11 @@ closed form, at the cost of Monte Carlo error. Refused for \code{\link[=design_bootstrap]{design_bootstrap()}}, where every row appears in some replicate and the count converges to 1 for all of them.} -\item{R}{Number of simulated draws when \code{simulate = TRUE}.} +\item{R}{Number of simulated draws when \code{simulate = TRUE}. A simulation +costs \code{R} draws; see "What a simulation costs" in \code{\link[=inclusion_prob]{inclusion_prob()}}.} -\item{seed}{Optional seed for the simulation.} +\item{seed}{Optional seed for the simulation, applied as in \code{\link[=draw]{draw()}} (see +"Seeding" there). Checked whether or not \code{simulate} is \code{TRUE}.} } \value{ A square matrix with one row and column per element of \code{rows} @@ -43,27 +49,53 @@ independent across groups or a simple random sample within them: \code{\link[=design_simple]{design_simple()}} \tab \code{n(n-1) / (N(N-1))} for a pair, without replacement \cr \code{\link[=design_stratified]{design_stratified()}} \tab within a stratum as above; across strata, independent \cr \code{\link[=design_cluster]{design_cluster()}} \tab same cluster: \code{a/A}; different clusters: \code{a(a-1)/(A(A-1))} \cr -\code{\link[=design_multistage]{design_multistage()}} \tab the two stages multiplied, where the per-cluster take is constant \cr +\code{\link[=design_multistage]{design_multistage()}} \tab the two stages multiplied, where the per-cluster take is constant and \code{size} is not given \cr \code{\link[=design_certainty]{design_certainty()}} \tab \code{1} between certainty rows; otherwise the other row's own \code{pi} \cr \code{\link[=design_reservoir]{design_reservoir()}} \tab simple random sampling over the first \code{max_items} rows \cr \code{\link[=design_temporal]{design_temporal()}} \tab within an interval as above; across intervals, independent \cr \code{\link[=design_spatial]{design_spatial()}} \tab simple random sampling inside the region \cr \code{\link[=design_weighted]{design_weighted()}} \tab \code{"poisson"} only, where rows are independent: \code{pi_i * pi_j} \cr -\code{\link[=design_systematic]{design_systematic()}} \tab \code{1/interval} for rows sharing a residue class, otherwise \strong{zero} \cr +\code{\link[=design_systematic]{design_systematic()}} \tab \code{1/interval} for rows sharing a residue class, otherwise \strong{zero}; with \code{n}, the overlap of the two rows' stretches, from 0 to \code{n / N}; with \code{n_starts = m}, \code{1/interval} for rows sharing a residue class modulo \code{m * interval}, otherwise \code{m(m-1) / (mk(mk-1))} with \code{k} the interval \cr } -Systematic sampling is the awkward one. Most pairs can never co-occur, so -their joint probability is genuinely 0 and no design-unbiased variance -estimator exists; \code{\link[=ht_total]{ht_total()}} uses the successive-difference approximation -instead, and says so. Its residue classes follow the order the design walks, -so \code{order_by} changes which pairs can co-occur. +Systematic sampling is the awkward one. At a step of 2 rows or more, which +is every \code{interval} above 1 and every \code{n} up to half the rows walked, +neighbouring rows and many other pairs can never co-occur, so their joint +probability is genuinely 0 and no design-unbiased variance estimator +exists; \code{\link[=ht_total]{ht_total()}} uses the successive-difference approximation instead, +and says so. Its residue classes follow the order the design walks, so +\code{order_by} changes which pairs can co-occur. Given \code{n}, the design walks at +a step of \code{N / n} rows from a start \code{u} uniform on (0, 1), each row +covering a stretch of length \code{n / N}, and a pair is drawn together when \code{u} +falls where both stretches, moved into (0, 1), overlap. With \code{n} above +\code{N / 2} the stretches are longer than 1/2, any two of them overlap, and +every pair has a positive joint probability; \code{\link[=ht_total]{ht_total()}} uses the +successive-difference approximation there too. With a fixed \code{start} the +design is deterministic, and it is refused as in \code{\link[=inclusion_prob]{inclusion_prob()}}. With +several starts (\code{n_starts}), rows in different residue classes can be drawn +together too, which is what gives a replicated sample its unbiased +variance. Within the strata of +\code{design_stratified(within = design_systematic())}, pairs in one stratum +get the overlap of their stretches, as with \code{n}, and pairs in two strata +the product of their probabilities. -Two designs have joint probabilities that are positive but have no closed -form: \code{design_weighted(method = "systematic")}, which shuffles the rows -before walking them so every pair can co-occur, and \code{\link[=design_spread]{design_spread()}}. For -both, \code{\link[=ht_total]{ht_total()}} uses a variance approximation that needs only -first-order probabilities, and \code{simulate = TRUE} here estimates the joint -probabilities themselves. +Three designs have joint probabilities that are positive but have no +closed form: \code{design_weighted(method = "systematic")}, which shuffles the +rows before walking them so every pair can co-occur, with or without +\code{strata}; \code{\link[=design_multistage]{design_multistage()}} with \code{size}, which does the same with the +clusters; and \code{\link[=design_spread]{design_spread()}}. For all three, \code{\link[=ht_total]{ht_total()}} uses a +variance approximation that needs only first-order probabilities, and +\code{simulate = TRUE} here estimates the joint probabilities themselves. +} + +\section{Size}{ + +The matrix has a row and a column for each of \code{rows}, by default every row +of \code{data}, and holds 8 bytes for each pair: 800 MB for 10,000 rows. Past +about 1 GB, from about 11,200 rows, \code{joint_prob()} refuses and gives the +size, rather than risk exhausting memory, which can end the R session. +\code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} do not build this matrix for any design in +the package. } \examples{ diff --git a/man/plan_size.Rd b/man/plan_size.Rd index 3498a67..1d56b7b 100644 --- a/man/plan_size.Rd +++ b/man/plan_size.Rd @@ -12,46 +12,112 @@ plan_size( level = 0.95, deff = 1, response = 1, - target = c("mean", "proportion", "total") + target = c("mean", "proportion", "total"), + strata = NULL, + allocation = c("proportional", "equal", "neyman"), + min_per_stratum = 2L ) } \arguments{ -\item{margin}{Half-width of the confidence interval you want.} +\item{margin}{Half-width of the confidence interval you want, the +half-width the plan expects (see "Where the formula comes from"). For a +proportion it is a proportion, and a \code{margin} of 1 or more is refused. +Several margins give several plans (see "Several plans at once").} \item{sd}{Standard deviation of the measure, for \code{target = "mean"} or -\code{"total"}.} +\code{"total"}, as \code{\link[stats:sd]{stats::sd()}} computes it. Not used with \code{strata}.} -\item{p}{Expected proportion, for \code{target = "proportion"}.} +\item{p}{Expected proportion, for \code{target = "proportion"}. Not used with +\code{strata}.} -\item{N}{Population size. \code{Inf} for an effectively unbounded frame.} +\item{N}{Population size, at least 1. \code{Inf} for an effectively unbounded +frame. An estimated \code{N} need not be a whole number; \code{n} is at most +\code{floor(N)}. Not used with \code{strata}, whose sizes add up to it.} \item{level}{Confidence level.} -\item{deff}{Design effect to inflate by. \code{1} assumes simple random sampling.} +\item{deff}{Design effect to inflate by: a positive number, or the result +of \code{\link[=ht_mean]{ht_mean()}} for a mean or a proportion, or of \code{\link[=ht_total]{ht_total()}} for a +total, on a pilot sample. \code{1} assumes simple random sampling. A number +should come from \code{\link[=deff]{deff()}} on the estimator you will report, rounded up, +or from \code{\link[=deff_cluster]{deff_cluster()}} (see "The corrections"). With \code{strata} it +inflates the variance of the stratified sample, as for clusters sampled +within strata.} \item{response}{Expected response rate, between 0 and 1.} \item{target}{\code{"mean"}, \code{"proportion"} or \code{"total"}. For \code{"total"} the margin is on the population total and \code{N} must be finite.} + +\item{strata}{\code{NULL}, or a data frame with a row per stratum, to plan a +stratified sample (see "Planning a stratified sample"). Its columns +are those that name the strata; \code{N}, the rows of the frame in each +stratum; \code{sd}, the standard deviation of the measure within each +stratum, or for a proportion \code{p}, the expected proportion within it; +and, with \code{allocation = "neyman"} only, an optional \code{cost}, the cost +of one row in each stratum.} + +\item{allocation}{How \code{n} is split over \code{strata}: \code{"proportional"}, +\code{"equal"} or \code{"neyman"}, as in \code{\link[=design_stratified]{design_stratified()}}. Neyman shares are +proportional to \code{N_h * S_h}, or \code{N_h * S_h / sqrt(cost_h)} with a +\code{cost} column.} + +\item{min_per_stratum}{The fewest rows a stratum is allocated, as in +\code{\link[=design_stratified]{design_stratified()}}, 1 or more. A stratum smaller than this is taken +whole. The default of 2 is the fewest that give each stratum a +variance, which \code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} need from every stratum +not taken whole. 0, the default of \code{\link[=design_stratified]{design_stratified()}}, is refused, +since a split without a floor can leave a small stratum without rows, +and the estimate then leaves it out.} } \value{ -A list with a \code{print()} method, holding: +A plan, a list of class \code{drawn_plan} with a \code{print()} method, +or for several plans a data frame (see "Several plans at once"). A plan +holds: \describe{ -\item{\code{n}}{Draw this many. Never more than \code{N}.} +\item{\code{n}}{Draw this many. Never more than \code{N}, and without \code{strata} +at least two when the frame has two rows or more.} \item{\code{n_effective}}{What you expect to analyse once \code{response} has taken its share.} -\item{\code{capped}}{\code{TRUE} when the frame is not large enough to reach the -margin at all, however you sample it.} -\item{\code{short}}{\code{TRUE} when the frame could reach the margin but not at -this \code{response} rate, so \code{n} is the whole frame and the margin -achieved will be wider than the one asked for.} +\item{\code{capped}}{\code{TRUE} when only a census meets the margin, so \code{n} is +every row of the frame. A census meets any margin when everyone +responds.} +\item{\code{short}}{\code{TRUE} when a sample smaller than the frame would meet +the margin if everyone responded, but not at this \code{response} rate, +so \code{n} is the whole frame and the margin achieved will be wider than +the one asked for. It is never \code{TRUE} with \code{capped}.} +\item{\code{raised}}{\code{TRUE} when the margin alone needs one row, and +\code{n_effective} was raised to two, the fewest that give a standard +error and an interval.} \item{\code{margin}, \code{level}, \code{N}, \code{deff}, \code{response}, \code{target}}{The inputs, -returned so the assumptions travel with the number.} +returned so the assumptions travel with the number. \code{deff} is the +number used, also when an estimate was passed.} +\item{\code{p}}{The expected proportion for a proportion, and \code{NA} for a +mean or a total.} \item{\code{n_needed}}{Rows that would reach the margin if everyone -responded. Equal to \code{n_effective} unless \code{short} is \code{TRUE}.} -\item{\code{spread}}{The standard deviation used — \code{sd}, or -\code{sqrt(p * (1 - p))} for a proportion.} +responded, two at least as for \code{n_effective}. Equal to \code{n_effective} +unless the whole frame is drawn at a \code{response} below 1.} +\item{\code{spread}}{The standard deviation used, \code{sd}, or +\code{sqrt(p * (1 - p))} for a proportion. \code{NA} with \code{strata}.} } + +With \code{strata} there are four more, and \code{raised} is always \code{FALSE}, +since \code{min_per_stratum} sets the floor: +\describe{ +\item{\code{allocation}}{The rows to draw from each stratum, a data frame +of the strata columns and \code{n}, in the order of \code{strata}. Pass it to +\code{\link[=design_stratified]{design_stratified()}} as \code{allocation} to draw that split.} +\item{\code{strata}}{The strata as given, checked, with \code{n} added.} +\item{\code{rule}, \code{min_per_stratum}}{The \code{allocation} rule and the floor +used.} +} + +A plan can be passed as \code{n} to any design that takes \code{n}, such as +\code{design_simple(n = plan)}, which draws \code{plan$n} rows. \code{as.data.frame()} +turns it into a data frame of one row, with a column for each field +above, except that a stratified plan has the number of \code{strata} in +place of the two data frames. Several plans at once give a data frame +of those rows, one per plan. } \description{ Solves for \code{n} given the precision you want, rather than asking you to guess @@ -67,29 +133,120 @@ varies: range divided by four as a rough stand-in. \item For a \strong{proportion}, a \code{p}. Leave it at \code{0.5}, the most pessimistic value, unless you have a better guess; that is the honest default because it -maximises the required size. +maximises the required size. The margin is a proportion too, \code{0.03} for +3 percentage points. } + +\code{sd} given for a proportion, or \code{p} for a mean or a total, is not used, +and \code{plan_size()} warns that it is ignored. + +For a stratified sample, give the size and the spread of each stratum in +\code{strata} instead (see "Planning a stratified sample"). } \section{The corrections}{ \code{N} applies a finite population correction: sampling 400 from 500 is very different from 400 from 500,000, and past a certain point a bigger frame -stops mattering. \code{deff} inflates for the design — pass the \code{\link[=deff]{deff()}} from a -comparable past sample, since a clustered design of 400 may carry the -information of 100. \code{response} inflates for non-response: at \code{0.6} you draw +stops mattering. \code{response} inflates for non-response: at \code{0.6} you draw enough to end up with what you need. + +\code{deff} inflates for the design, since a clustered design of 400 may carry +the information of 100. Before any pilot, \code{\link[=deff_cluster]{deff_cluster()}} gives the +design effect of taking \code{m} rows from each cluster from their intraclass +correlation. Measure it with \code{\link[=deff]{deff()}} on a comparable past +sample, using the estimator you will report: \code{\link[=ht_mean]{ht_mean()}} for a mean or a +proportion, and \code{\link[=ht_total]{ht_total()}} for a total. The two design effects differ for +the same sample, and can differ many times over. In one cluster sample +with clusters of 2 to 40 rows, the total's design effect was 28 and the +mean's 0.66, and a total planned with the mean's figure came out a small +fraction of the size it needed. A total reported as \code{N} times a mean takes +the mean's design effect, and is planned as a mean with \code{margin / N}. You +can pass the result of \code{ht_mean()} or \code{ht_total()} itself as \code{deff}, and +\code{plan_size()} refuses one of the wrong kind for \code{target}. + +A design effect from one pilot is an estimate, and a noisy one, which +comes out below the truth more often than above it. Round it up. \code{\link[=deff]{deff()}} +gives \code{NA} for a pilot without a variance estimate, such as one taken with +\code{variance = "none"}, a census, or one with a single cluster, and for one in +which \code{y} took a single value. It is \code{NA} too for a mean from +\code{ht_mean(na_rm = TRUE)} with \code{y} missing in some sampled rows, since the +rows with \code{y} are a domain, whose design effect is not estimated. Such a +pilot cannot supply a design effect, and \code{plan_size()} refuses an \code{NA}. +It refuses an estimate from \code{survey} too, such as +\code{survey::svymean(deff = TRUE)}, whose value is the estimate itself; pass +\code{survey::deff()} of it instead. +} + +\section{Planning a stratified sample}{ + +With \code{strata}, \code{plan_size()} plans a stratified simple random sample, as +\code{\link[=design_stratified]{design_stratified()}} draws one. For each total \code{n} it splits \code{n} over +the strata as that design would, by the same \code{allocation} rule, the +floor \code{min_per_stratum} and largest-remainder rounding, with no stratum +given more rows than it has, and works out the variance of the +stratified mean, +\code{deff * sum(W_h^2 * (1 / n_h - 1 / N_h) * S_h^2)} with \code{W_h = N_h / N} +(Cochran 1977, chapter 5). For a proportion \code{S_h^2} is +\code{N_h * p_h * (1 - p_h) / (N_h - 1)}. The plan is the smallest \code{n} whose +variance is at most \code{(margin / z)^2}, with \code{margin / N} for a total. +\code{min_per_stratum} must be 1 or more, since an estimate leaves a stratum +without rows out. Without a floor, proportional allocation gives a +stratum of one row in a frame of 200,000 its first row at \code{n} of about +100,000, and the plan would be that large. The rounded split can take a +row from one stratum as \code{n} grows, so the variance does not always fall +with \code{n}, and the search checks each \code{n} from the first that could meet +the margin. + +\code{response} divides \code{n} as without strata, and the rows to draw are split +by the same rule. The split is returned as \code{allocation}, which +\code{\link[=design_stratified]{design_stratified()}} takes as the count for each stratum. Passing the +plan as \code{n} instead lets the design split \code{n} again by its own rule and +\code{min_per_stratum}, whose default there is 0, which can leave a small +stratum without rows. +} + +\section{Several plans at once}{ + +\code{margin}, \code{sd}, \code{p}, \code{deff} and \code{response} each take one value, or +several for several plans. Those with one value are used for every plan, +and those with several must have the same number, one per plan, so +\code{plan_size(margin = c(3, 5, 10), sd = 40)} plans three margins at the +same spread. The result is then a data frame with a row per plan, as +\code{as.data.frame()} gives for each, without the split over strata or the +printed notes. } \section{Where the formula comes from}{ -\code{n0 = (z * spread / margin)^2 * deff}, then Cochran's finite population -correction \code{n0 / (1 + (n0 - 1) / N)}, then division by \code{response} (Cochran -1977, section 4.4; Valliant, Dever and Kreuter 2018, chapter 3). \code{z} is the -normal quantile. The interval \code{\link[=ht_total]{ht_total()}} reports uses t on the design's -degrees of freedom, which is slightly wider when those are few — with a -handful of clusters, plan on more clusters rather than trusting the margin -to the last digit. +\code{n0 = (z * spread / margin)^2 * deff} is the size for an unbounded frame, +with \code{z} the normal quantile for \code{level} and, for a total, \code{margin / N} as +the margin on the mean. For a mean or a total the finite population +correction gives \code{n0 / (1 + n0 / N)}, the smallest \code{n} with +\code{(1 / n - 1 / N) * deff * sd^2 <= (margin / z)^2}. For a proportion, whose +variance \code{p * (1 - p)} has the divisor \code{N} rather than \code{N - 1}, it gives +\code{n0 / (1 + (n0 - 1) / N)}. The result is rounded up, raised to two when it +is one, and divided by \code{response} (Cochran 1977, chapter 4; Valliant, +Dever and Kreuter 2018, chapter 3). + +\code{margin} is the half-width the plan expects, the usual convention for +sizing a sample: the estimate from a sample of size \code{n} lands within +\code{margin} of the truth with probability about \code{level}. The interval a +sample reports is built from that sample's own estimate of the variance, +which comes out above the planned variance about as often as below it, so +the reported half-width is wider than \code{margin} about half the time. + +That interval also uses t on the design's degrees of freedom rather than +\code{z}, which matters when the primary sampling units are few. With 3, 4 and +6 clusters in one stratum, which give 2, 3 and 5 degrees of freedom, the +95\% t quantile is 2.2, 1.6 and 1.3 times \code{z}. \code{plan_size()} counts rows +and knows nothing of clusters, so when you turn \code{n} into a few clusters, +plan more of them. + +For a proportion, \code{\link[=ht_mean]{ht_mean()}} reports an interval on the logit scale, which +is asymmetric. When \code{p} is small its upper arm is longer than its lower one, +and exceeds \code{margin} in most samples even when the estimate is as precise +as planned. } \examples{ @@ -105,6 +262,35 @@ plan_size(margin = 5, sd = 40, N = 20000, deff = 2.5, response = 0.7) # A total, to within 100,000 across a 20,000-row frame plan_size(margin = 1e5, sd = 40, N = 20000, target = "total") +# Clusters of ten rows, whose rows correlate at 0.05, before any pilot +plan_size(margin = 5, sd = 40, N = 20000, + deff = deff_cluster(m = 10, icc = 0.05)) + +# Three margins at once, one plan per row +plan_size(margin = c(3, 5, 10), sd = 40, N = 20000) + +# A plan is a valid `n` +design_simple(n = plan_size(margin = 5, sd = 40, N = 20000)) + +# Three strata, with the spread of each from an earlier survey +bands <- data.frame(band = c("small", "medium", "large"), + N = c(1200, 600, 200), sd = c(10, 25, 80)) +plan <- plan_size(margin = 2, strata = bands, allocation = "neyman") +plan +frame <- data.frame(id = 1:2000, + band = rep(bands$band, times = bands$N)) +s <- draw(frame, design_stratified("band", allocation = plan$allocation), + seed = 1) +table(s$band) + +# The design effect of a cluster pilot, passed as the estimate itself +pop <- data.frame(cl = rep(paste0("c", 1:50), each = 8)) +pop$y <- rep(seq(10, 59), each = 8) + rep(c(-3, 3), 200) +pilot <- draw(pop, design_cluster("cl", n_clusters = 6), seed = 1, + weights = TRUE) +plan_size(margin = 3, sd = sd(pilot$y), N = nrow(pop), + deff = ht_mean(pilot, "y")) + } \references{ Cochran, W. G. (1977). \emph{Sampling Techniques}, 3rd ed. Wiley. @@ -115,6 +301,7 @@ Valliant, R., Dever, J. A. and Kreuter, F. (2018). \emph{Practical Tools for Designing and Weighting Survey Samples}, 2nd ed. Springer. } \seealso{ -\code{\link[=deff]{deff()}} to measure the design effect of a past sample, \code{\link[=draw]{draw()}} to +\code{\link[=deff]{deff()}} to measure the design effect of a past sample, +\code{\link[=deff_cluster]{deff_cluster()}} for one from an intraclass correlation, \code{\link[=draw]{draw()}} to take the sample. } diff --git a/man/plot.drawn_design.Rd b/man/plot.drawn_design.Rd index f1942ff..ae89e49 100644 --- a/man/plot.drawn_design.Rd +++ b/man/plot.drawn_design.Rd @@ -14,6 +14,7 @@ main = NULL, palette = NULL, coords = NULL, + sub = NULL, ... ) } @@ -30,18 +31,40 @@ reproducible.} \item{ncol}{Dots per row in the \code{"selection"} grid. Defaults to whatever fills the panel at its current aspect ratio.} -\item{max_dots}{Frames larger than this are shown as an evenly spaced -subset, noted under the title. Keeps individual dots visible.} +\item{max_dots}{The most dots or steps to draw, which keeps them visible. +A larger frame is shown in runs of consecutive rows: in \code{"selection"} a +dot stands for a run and is filled when any row in it is selected, and in +\code{"probability"} a step spans the lowest and highest probability in its +run. \code{"map"} draws every selected row and at most \code{max_dots} of the +others, evenly spaced through the frame. The counts under the title +cover the whole frame.} -\item{main}{Title. Defaults to a description of the design.} +\item{main}{Title, a single string, or one expression, a call or a name +such as \code{quote(alpha)} drawn as plotmath. Defaults to a description of +the design: its constructor and the arguments that differ from their +defaults.} -\item{palette}{Named list overriding any of \code{surface}, \code{ink}, \code{secondary}, -\code{muted}, \code{recessive}, \code{accent}, \code{fill}, \code{rule}.} +\item{palette}{Named list, or named character vector, of colours +overriding any of \code{surface}, \code{ink}, \code{secondary}, \code{muted}, \code{recessive}, +\code{accent}, \code{fill}, \code{rule}. Each entry is one colour, a name from +\code{\link[grDevices:colors]{grDevices::colors()}} or a code such as \code{"#1B6B52"}. Other names are +refused.} -\item{coords}{For \code{type = "map"}, the two columns to place rows by, \code{c(x, y)}. Defaults to the design's own \code{across} (\code{\link[=design_spread]{design_spread()}}) or -\code{coords} (\code{\link[=design_spatial]{design_spatial()}}); required for any other design.} +\item{coords}{For \code{type = "map"}, the two columns to place rows by, \code{c(x, y)}, or one POINT geometry column. Defaults to the design's own \code{across} +(\code{\link[=design_spread]{design_spread()}}) or \code{coords} (\code{\link[=design_spatial]{design_spatial()}}); required for any +other design. Date and date-time columns get date axes.} -\item{...}{Passed to the underlying plot call.} +\item{sub}{A single string, added to the end of the line under the title, +after the counts the plot puts there.} + +\item{...}{Graphical parameters for the call that sets up the panel, such +as \code{xlim}, \code{ylim}, \code{asp} or \code{log}. They replace the plot's own: \code{asp = 1} +gives any map the same scale on both axes, and \code{xlim} and \code{ylim} zoom in, +with the rules and the mean line of \code{"probability"} following them. +Axes and labels drawn by base graphics are off (\code{axes = FALSE}, \code{ann = FALSE}) unless turned on here. The dots, steps and titles keep their +own look, so \code{col}, \code{cex} and \code{pch} here change nothing visible; their +colours come from \code{palette}. A name that is not a graphical parameter is +refused.} } \value{ \code{x}, invisibly. Called for the plot. @@ -57,19 +80,37 @@ the selected ones filled in. Designs look distinct: simple random sampling scatters, systematic makes a lattice, cluster sampling takes solid contiguous runs, and probability-proportional-to-size thickens wherever the weight is large. If your frame is sorted by something -meaningful, an unintended pattern shows up immediately.} +meaningful, an unintended pattern shows up immediately. A design that +samples with replacement rings each row it drew more than once, and the +count under the title gives the draws and the distinct rows. A +bootstrap is shown by its first replicate.} \item{\code{"probability"}}{Each row's inclusion probability across the frame, -as a step. Flat means every row had the same chance; plateaus mean -strata; a rise means size-proportional selection. Rows the design can -never reach sit at zero and are marked, which is usually the thing worth -finding out.} +as a step, with frame rows along the axis. Flat means every row had the +same chance; plateaus mean strata; a rise means size-proportional +selection. Rows the design can never reach sit at zero and are marked, +which is usually the thing worth finding out. The count of those rows, +the count taken with certainty, the range and the mean cover every row +of the frame.} \item{\code{"map"}}{Every row placed by two columns — coordinates, or any two numeric variables — with the selected ones filled in. This is the view for \code{\link[=design_spread]{design_spread()}} and \code{\link[=design_spatial]{design_spatial()}}, where what matters is how evenly the sample covers the space: compare a simple random sample's -clumps and gaps against a spread one.} +clumps and gaps against a spread one. For \code{\link[=design_spatial]{design_spatial()}} the +outline of \code{region} is drawn as well, with each edge of a +longitude/latitude region following its great circle under spherical +geometry, which is how the design decides which rows are inside. +The coordinates of \code{\link[=design_spatial]{design_spatial()}}, and those of \code{\link[=design_spread]{design_spread()}} +with \code{scale = FALSE}, get the same scale on both axes (\code{asp = 1}, or +\code{1 / cos()} of the middle latitude for longitude and latitude), so the +map shows the distances the design works with; other columns fill the +panel. When \code{across} names more than two columns, the first two place +the rows. The line under the title names the columns left out, counts +the selected rows that have no position and so are not drawn, and says +when the background is thinned.} } +A design with \code{reserve} is shown by its main sample, without the reserves. + Base graphics, so there is no plotting dependency to install. } \examples{ diff --git a/man/replicate_weights.Rd b/man/replicate_weights.Rd new file mode 100644 index 0000000..c2344fc --- /dev/null +++ b/man/replicate_weights.Rd @@ -0,0 +1,132 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/survey.R +\name{replicate_weights} +\alias{replicate_weights} +\title{Replicate weights for a sample} +\usage{ +replicate_weights(sample, type = c("JKn", "JK1")) +} +\arguments{ +\item{sample}{A data frame returned by \code{\link[=draw]{draw()}} with \code{weights = TRUE}.} + +\item{type}{The form of the jackknife. \code{"JKn"}, the default, deletes +units within strata and keeps each stratum's correction in \code{rscales}. +\code{"JK1"} deletes across the whole sample, with the correction in +\code{scale}, and is given only where the jackknife has one stratum; with +more, it would count the differences between strata as sampling +variance, and is refused. A systematic sample with one start, and +strata walked in order, get successive-difference replicates of type +\code{"other"} whichever is given.} +} +\value{ +A numeric matrix with a row for each row of \code{sample}, in its +order, and a column for each replicate, holding replicate weights. +Its attributes \code{type}, \code{scale} and \code{rscales} are the arguments of the +same names of \code{\link[survey:svrepdesign]{survey::svrepdesign()}}, which with +\code{combined.weights = TRUE} computes the variance as +\code{scale * sum(rscales * (t_r - t)^2)} over the replicate estimates +\code{t_r}, with \code{t} their mean. For a total that mean is the sample's +estimate. +} +\description{ +Builds replicate weights from a drawn sample for \code{\link[survey:svrepdesign]{survey::svrepdesign()}}, +from the design the sample was drawn with. Each replicate is the +sample's \code{.weight} column times a factor, and the variance of a total +over the replicates is that of one of \code{\link[=ht_total]{ht_total()}}'s estimators: +} +\details{ +\itemize{ +\item For most designs, the delete-a-unit jackknife of +\code{ht_total(variance = "jackknife")}. Each replicate deletes one primary +sampling unit, a cluster where the design has them and a row +otherwise, and reweights the other units of its stratum; strata are +the design's strata, the intervals of \code{\link[=design_temporal]{design_temporal()}} and the +strata of \code{\link[=design_weighted]{design_weighted()}} and \code{\link[=design_spread]{design_spread()}}. \code{rscales} holds +\code{(m - 1) / m} for a stratum of \code{m} sampled units, times its finite +population correction. +Units taken with certainty keep their weight in every replicate, as +the jackknife holds them fixed. Where the default of \code{\link[=ht_total]{ht_total()}} is +another estimator, such as Deville's approximation for +\code{\link[=design_weighted]{design_weighted()}} with \code{method = "systematic"}, the local mean +approximation for \code{\link[=design_spread]{design_spread()}} or the two-stage variance for +\code{\link[=design_multistage]{design_multistage()}} and balanced \code{\link[=design_cluster]{design_cluster()}}, the replicates +give the jackknife's variance, not that default. +\item For \code{\link[=design_systematic]{design_systematic()}} with one start, and \code{\link[=design_stratified]{design_stratified()}} +with \code{within}, successive-difference replicates in the order the +design walked, whose variance is the successive-difference +approximation \code{\link[=ht_total]{ht_total()}} gives by default, with its term for a +random sample size. Each pair of neighbours in the walk shares a row of +a Hadamard matrix, which raises one of the two and lowers the other. +The first and last rows of a walk are not paired with each other: the +circular form of successive-difference replication pairs them, which +adds the squared difference between the two ends of the sort order. On +a frame of 240 rows sorted on a size measure related to \code{y}, at an +interval of 8, that more than doubled the variance in each of the 8 +possible samples. +\item For \code{\link[=design_systematic]{design_systematic()}} with \code{n_starts} of 2 or more, one replicate +per start, each deleting the rows its start drew. The variance is the +random group variance \code{\link[=ht_total]{ht_total()}} gives by default. +} + +Rows above the threshold of \code{\link[=design_certainty]{design_certainty()}} keep their weight in +every replicate, and the replicates for the rows below it are those of +\code{rest}. A sample whose every row was taken with certainty gets one +replicate equal to its weights, and a variance of 0. + +Poisson sampling, alone or as the \code{rest} of \code{\link[=design_certainty]{design_certainty()}}, is +refused: its sample size is random, and deleting rows from it +understates the variance. \code{\link[=as_svydesign]{as_svydesign()}} hands it to \code{survey}, which +models it. A sample the jackknife declines, such as one with a single +unit in a stratum, is refused with the jackknife's reason. + +Every replicate is a multiple of \code{.weight}, so an adjustment written into +\code{.weight} after the draw, such as trimming, is carried into each one +unchanged. One that depends on which rows responded is more accurately +made again within each replicate. + +The matrix of weights takes \code{8 * n * R} bytes for \code{n} sampled rows and +\code{R} replicates, and building it about twice that. The jackknife has a +replicate for each sampled unit, and successive differences have the +first power of 2 above the number of pairs of neighbours in the walks, +counting one more for each walk of random size, so the size grows with +the square of the sample. Past about 1 GB, \code{replicate_weights()} +refuses: from about 11,200 rows for a jackknife over rows, and about +8,200 for successive differences. Such a sample can still be estimated with +\code{\link[=ht_total]{ht_total()}}, or handed to \code{survey} with \code{\link[=as_svydesign]{as_svydesign()}}. +} +\examples{ +\dontshow{if (requireNamespace("survey", quietly = TRUE)) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf} +pop <- data.frame( + id = 1:400, + site = rep(c("a", "b", "c", "d"), times = c(200, 100, 60, 40)), + spend = 10 + (1:400 * 37) \%\% 490 +) +s <- draw(pop, design_stratified("site", n = 60), seed = 1, weights = TRUE) + +rw <- replicate_weights(s) +des <- survey::svrepdesign( + data = s, repweights = rw, weights = ~.weight, + type = attr(rw, "type"), scale = attr(rw, "scale"), + rscales = attr(rw, "rscales"), combined.weights = TRUE +) +survey::svytotal(~spend, des) + +# The same standard error as the jackknife here +ht_total(s, "spend", variance = "jackknife") + +# A systematic sample on a sorted frame: the replicates follow the walk +sys <- draw(pop, design_systematic(interval = 8, order_by = "spend"), + seed = 1, weights = TRUE) +rw <- replicate_weights(sys) +des <- survey::svrepdesign( + data = sys, repweights = rw, weights = ~.weight, + type = attr(rw, "type"), scale = attr(rw, "scale"), + rscales = attr(rw, "rscales"), combined.weights = TRUE +) +survey::SE(survey::svytotal(~spend, des)) +ht_total(sys, "spend")$se +\dontshow{\}) # examplesIf} +} +\seealso{ +\code{\link[=as_svydesign]{as_svydesign()}}, \code{\link[=ht_total]{ht_total()}} +} diff --git a/man/sample_summary.Rd b/man/sample_summary.Rd index d6b4bc9..29912bf 100644 --- a/man/sample_summary.Rd +++ b/man/sample_summary.Rd @@ -14,16 +14,70 @@ A list with a \code{print()} method, holding: \describe{ \item{\code{design}}{The design's type, as a string.} \item{\code{n}, \code{N}}{Rows drawn, and rows in the frame.} +\item{\code{N_reachable}}{Rows of the frame the design gives a probability +above 0, the population it samples. For weights conditional on the +clusters selected, the rows of the clusters not selected count, since +another selection could have drawn them. The printed sampling +fraction is \code{n / N_reachable}. \code{NA} only when the frame's +probabilities cannot be worked out, for an empty sample saved by +drawn 0.2.0, which records none, from a design with no closed-form +inclusion probability. The fraction is then \code{n / N}.} +\item{\code{expected_n}}{The sample size the design expects, the sum of +the inclusion probabilities over the frame. It is \code{n} for a design +of fixed size, and printed beside \code{n} when the two differ, as they +can under Poisson sampling, a \code{\link[=design_systematic]{design_systematic()}} \code{interval} that +does not divide the frame, or clusters of unequal size. \code{NA} where +\code{N_reachable} is, and for weights conditional on the clusters +selected.} \item{\code{weight_range}}{The smallest and largest design weight.} \item{\code{weight_cv}}{Their coefficient of variation. Large values mean a few rows carry most of the estimate.} -\item{\code{unreachable}}{Frame rows with inclusion probability 0 — the -design could never have selected them. \code{NA} if the design has no -closed-form inclusion probability.} +\item{\code{n_kish}}{Kish's effective sample size, \code{sum(w)^2 / sum(w^2)} +over the weights \code{w}, which is \code{n / (1 + cv^2)} with the +coefficient of variation computed with divisor \code{n}: the size of a +simple random sample that would estimate a mean as precisely if +unequal weights were the only cost. Clustering and stratification +are not in it; \code{\link[=deff]{deff()}} measures those.} +\item{\code{n_certain}}{Sampled rows taken with certainty, at a probability +of 1.} +\item{\code{certain_by}}{Those rows by why they are certain, a named count: +\code{threshold}, above the threshold of \code{\link[=design_certainty]{design_certainty()}}; \code{size}, +put at probability 1 by a size measure, in \code{\link[=design_weighted]{design_weighted()}} or +in \code{\link[=design_spread]{design_spread()}} or \code{\link[=design_multistage]{design_multistage()}} with \code{size}, which +includes the rows of a cluster put at 1 by its size and then taken +whole; and \code{whole}, in a stratum, interval or cluster taken whole, +or a census, with a size measure or without. Under a size measure a +group counts as taken whole when the design gives every row of it +probability 1, or every cluster of a multistage design a +first-stage probability of 1, so a Poisson sample that holds every +row of a stratum by chance files its certain rows under \code{size}.} +\item{\code{conditional}}{The number of clusters selected, when the +weights are conditional on them, as for \code{\link[=design_cluster]{design_cluster()}} with +\code{balanced = TRUE} (see "Design weights" in \code{\link[=draw]{draw()}}); otherwise +\code{NA}.} +\item{\code{unreachable}}{Frame rows with inclusion probability 0, which +the design could never have selected, such as rows \code{na_rm} drops. +\code{NA} where \code{N_reachable} is.} \item{\code{by_group}}{A data frame of \code{group}, \code{drawn}, \code{in_frame} and -\code{rate} per stratum or cluster, or \code{NULL} for a design with no -grouping.} +\code{rate} per stratum, interval or cluster, or \code{NULL} for a design with +no grouping. The strata are those of \code{\link[=design_stratified]{design_stratified()}}, and of +\code{\link[=design_spread]{design_spread()}} and \code{\link[=design_weighted]{design_weighted()}} when they have \code{strata}, +and every stratum of the frame is listed, one allocated no rows +included. A stratum's \code{in_frame} counts the rows the design can +draw from it, as \code{N} of \code{\link[=allocation_table]{allocation_table()}} does, so rows \code{na_rm} +drops are left out, and a stratum it empties is not listed. The +intervals of \code{\link[=design_temporal]{design_temporal()}} are listed in time +order and named by their start, such as \code{"2024-01-03 00:00"}. For +\code{\link[=design_cluster]{design_cluster()}} and \code{\link[=design_multistage]{design_multistage()}}, only the clusters +drawn are listed. For \code{\link[=design_certainty]{design_certainty()}}, the groups are those of +its \code{rest} over the rows below the threshold, after a \code{"(certain)"} +row for the rows above it.} \item{\code{group_col}}{The column(s) \code{by_group} is keyed on.} +\item{\code{drawn}}{How the sample was drawn, from its \code{drawn_meta} +attribute: \code{seed}, \code{rng_kind}, \code{version}, \code{time}, \code{frame_rows} and +\code{made_by} (see "Seeding" in \code{\link[=draw]{draw()}}). \code{NULL} for a sample from an +earlier version of drawn, which recorded none. The print shows the +seed, the version and the date.} } } \description{ diff --git a/man/use_reserves.Rd b/man/use_reserves.Rd new file mode 100644 index 0000000..65966c1 --- /dev/null +++ b/man/use_reserves.Rd @@ -0,0 +1,108 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/state.R +\name{use_reserves} +\alias{use_reserves} +\title{Replace unavailable units from a reserve list} +\usage{ +use_reserves(sample, unavailable) +} +\arguments{ +\item{sample}{A list from \code{\link[=draw]{draw()}} with \code{weights = TRUE} and a design +with \code{reserve}, or from \code{\link[=as_drawn]{as_drawn()}}.} + +\item{unavailable}{A logical vector with one value for each row of +\code{sample}, in its order, or the name of such a column of \code{sample}. See +"Marking the visits".} +} +\value{ +A weighted sample, ready for \code{\link[=ht_total]{ht_total()}}, \code{\link[=ht_mean]{ht_mean()}}, +\code{\link[=as_svydesign]{as_svydesign()}} and \code{\link[=sample_summary]{sample_summary()}}. +} +\description{ +\code{\link[=design_simple]{design_simple()}} and \code{\link[=design_spread]{design_spread()}} with \code{reserve} give a list: the +\code{n} units of the main sample, then the reserves, with a \code{.reserve} column +that numbers them 1, 2, ... in the order they are used. Visit every unit +of the main sample, and for each one found unavailable, visit the next +reserve, until the units found available make up \code{n}. +\code{use_reserves()} takes the list and what the visits found, and returns the +sample to estimate from: the units of the main sample found available, +and as many reserves, taken in order, as replace the others. +} +\section{What the estimates describe}{ + +Replacing units changes the population being estimated. The sample that +comes back stands for the units of the frame that can be reached, and its +totals and means are theirs, not the whole frame's. It is weighted as a +sample of \code{n} drawn at equal probability from the frame without the \code{u} +listed units found unavailable: each unit used has probability +\code{n / (N - u)}, and the units found unavailable have probability 0, so +\code{\link[=ht_total]{ht_total()}} and \code{\link[=ht_mean]{ht_mean()}} count them among the frame rows the estimate +does not cover. + +The probabilities assume that every unit of the frame nobody visited is +available. A frame that holds more unavailable units than were found has +fewer than \code{N - u} units that can be reached, and the totals are too high +by about the share of the frame those units make up. The Hajek mean of +\code{\link[=ht_mean]{ht_mean()}} does not depend on \code{N - u} and is not affected. An estimate +from the sample keeps \code{u} in \code{unavailable}, and its printed \code{unreachable} +line adds that the units nobody visited are taken as available. + +For \code{\link[=design_simple]{design_simple()}} the weighting is exact under that assumption, when +the reserves suffice. The list is one random draw in random order, so its +first \code{n} available units are a simple random sample of \code{n} from the +available units of the frame, and the variance is that of a simple random +sample from \code{N - u}. For +\code{\link[=design_spread]{design_spread()}} the reserves are a second spread sample from the rows +the main sample left, in random order. The units used are spread over the +space, and under the same assumption their probabilities average +\code{n / (N - u)}, but each unit's own probability is not known exactly, so +the weights are an approximation. The variance is the local mean +estimator over the units used. + +Reserves are for units that cannot be reached or measured at all. A unit +that is reached but gives no answer is nonresponse: keep it in the sample +with \code{y} missing, as "Missing values and nonresponse" in \code{\link[=ht_total]{ht_total()}} +describes. +} + +\section{Marking the visits}{ + +\code{unavailable} holds one value for each row of \code{sample}: \code{TRUE} for a unit +found unavailable, \code{FALSE} for one found available, and \code{NA} for one not +visited. Every unit of the main sample needs \code{TRUE} or \code{FALSE}, and so +does each reserve up to the one that completes the sample; a missing +value there is refused, with the frame row named. Reserves visited past +that one are not used, and those of them found unavailable count among +the \code{u} units outside the population. When the reserves run out first, +the sample holds fewer than \code{n} units and is weighted as a sample of that +many, with a warning. +} + +\section{What comes back}{ + +The units used, in the order of \code{sample}, with \code{.prob}, \code{.weight}, \code{.row} +and \code{.reserve} first. \code{.reserve} is 0 for a unit of the main sample and +the reserve's number for a unit that replaced one. The design stored with +the result is the list's design with \code{n} the number of units used, no +\code{reserve}, and the frame rows found unavailable recorded as +\code{unavailable}; \code{\link[=inclusion_prob]{inclusion_prob()}} of it gives those rows probability 0. +} + +\examples{ +pop <- data.frame(id = 1:200, spend = (1:200) \%\% 37) +s <- draw(pop, design_simple(n = 20, reserve = 5), seed = 1, weights = TRUE) +table(s$.reserve) + +# Two units of the main sample could not be reached, nor could the first +# reserve; reserves 2 and 3 replaced them, and 4 and 5 were not visited +gone <- c(s$id[c(3, 11)], s$id[s$.reserve == 1]) +found <- ifelse(s$.reserve <= 3, s$id \%in\% gone, NA) +used <- use_reserves(s, found) +table(used$.reserve) +ht_total(used, "spend") + +} +\seealso{ +\code{\link[=design_simple]{design_simple()}}, \code{\link[=design_spread]{design_spread()}}, \code{\link[=add_fieldwork]{add_fieldwork()}} to add +what the visits found to the list. +} diff --git a/tests/testthat/helper-fixtures.R b/tests/testthat/helper-fixtures.R index 21c4744..804b552 100644 --- a/tests/testthat/helper-fixtures.R +++ b/tests/testthat/helper-fixtures.R @@ -1,8 +1,31 @@ # Deterministic fixtures. Building a fixture from unseeded rnorm()/runif() means # any future failure arrives with no way to reproduce it. +# Seeds the random number stream until the calling function or test ends, and +# then puts back the stream the caller had, or none if there was none. A bare +# set.seed() in a fixture or a test resets the stream every later test draws +# from, so a test that forgot its own seed would pass only after that one. +# Restores run last-in first-out, so several calls in one test unwind to the +# stream from before the first. +local_seed <- function(seed, envir = parent.frame()) { + globals <- globalenv() + had <- exists(".Random.seed", envir = globals, inherits = FALSE) + old <- if (had) get(".Random.seed", envir = globals, inherits = FALSE) + restore <- function() { + if (had) { + assign(".Random.seed", old, envir = globals) + } else if (exists(".Random.seed", envir = globals, inherits = FALSE)) { + rm(".Random.seed", envir = globals) + } + } + do.call(on.exit, list(as.call(list(restore)), add = TRUE, after = FALSE), + envir = envir) + set.seed(seed) + invisible(seed) +} + make_df <- function(n = 100L) { - set.seed(20250218) + local_seed(20250218) data.frame( id = seq_len(n), value = stats::rnorm(n), @@ -28,17 +51,22 @@ make_ts <- function() { ) } -# A large but well-behaved region: every edge spans 160 degrees of longitude or -# less, so s2 draws it the way the coordinates read. +# A large but well-behaved region. Its edges are cut in degree space into +# pieces of at most 1 degree, so under s2 it is the box its corners describe: +# a single edge from -80 to 80 at latitude 60 would follow a great circle +# that bows about 24 degrees towards the pole. wide_poly <- function() { skip_if_not_installed("sf") - sf::st_sfc( - sf::st_polygon(list(cbind( - c(-80, 80, 80, -80, -80), - c(-60, -60, 60, 60, -60) - ))), - crs = 4326 - ) + flat_box(c(-80, 80), c(-60, 60)) +} + +# A longitude/latitude box whose edges follow its straight lines in degrees, +# by the recipe in ?design_spatial. +flat_box <- function(lon, lat) { + skip_if_not_installed("sf") + box <- sf::st_sfc(sf::st_polygon(list(cbind(lon[c(1, 2, 2, 1, 1)], + lat[c(1, 1, 2, 2, 1)])))) + sf::st_set_crs(sf::st_segmentize(box, 1), 4326) } # A lon/lat rectangle whose edges span nearly the whole globe. Under s2 this @@ -56,16 +84,283 @@ antimeridian_poly <- function() { three_boxes <- function() { skip_if_not_installed("sf") - lapply(list(c(0, 10), c(20, 30), c(40, 50)), function(r) { - sf::st_sfc( - sf::st_polygon(list(cbind(c(r[1], r[2], r[2], r[1], r[1]), - c(r[1], r[1], r[2], r[2], r[1])))), - crs = 4326 - ) - }) + lapply(list(c(0, 10), c(20, 30), c(40, 50)), function(r) flat_box(r, r)) } expect_same_schema <- function(out, input) { expect_identical(names(out), names(input)) expect_identical(class(out), class(input)) } + +# Evaluates `code` under a collation that sorts "a" before "B", as most +# non-C locales do, and restores the session's collation afterwards. Skips +# where no such locale is installed. R reads the collation for text from the +# LC_ALL and LC_COLLATE environment variables before the locale, and testthat +# sets the second to "C", so both are set here too. +with_other_collation <- function(code) { + old <- Sys.getlocale("LC_COLLATE") + old_env <- Sys.getenv(c("LC_ALL", "LC_COLLATE"), unset = NA) + on.exit({ + for (nm in names(old_env)) { + if (is.na(old_env[[nm]])) { + Sys.unsetenv(nm) + } else { + do.call(Sys.setenv, as.list(old_env[nm])) + } + } + Sys.setlocale("LC_COLLATE", old) + }, add = TRUE) + Sys.unsetenv("LC_ALL") + for (loc in c("en_US.UTF-8", "C.UTF-8", "C.utf8")) { + Sys.setenv(LC_COLLATE = loc) + if (nzchar(suppressWarnings(Sys.setlocale("LC_COLLATE", loc))) && + identical(sort(c("B", "a")), c("a", "B"))) { + return(code) + } + } + skip("No installed locale sorts \"a\" before \"B\".") +} + +# Evaluates `code` with a UTF-8 character type, or with the C locale's when +# `utf8` is FALSE, as in a session started in such a locale, and restores +# the session's character type afterwards. Skips where no such locale is +# installed. +with_ctype <- function(code, utf8 = TRUE) { + old <- Sys.getlocale("LC_CTYPE") + old_env <- Sys.getenv("LC_CTYPE", unset = NA) + on.exit({ + if (is.na(old_env)) Sys.unsetenv("LC_CTYPE") else + Sys.setenv(LC_CTYPE = old_env) + Sys.setlocale("LC_CTYPE", old) + }, add = TRUE) + candidates <- if (utf8) c("en_US.UTF-8", "C.UTF-8", "C.utf8") else "C" + for (loc in candidates) { + Sys.setenv(LC_CTYPE = loc) + if (nzchar(suppressWarnings(Sys.setlocale("LC_CTYPE", loc))) && + identical(isTRUE(l10n_info()[["UTF-8"]]), utf8)) { + return(code) + } + } + skip(if (utf8) "No UTF-8 locale is installed." else + "The C locale cannot be set.") +} + +# A point frame for the tests that pass an sf object as `data`. +sf_points <- function() { + skip_if_not_installed("sf") + d <- data.frame( + id = 1:60, + site = rep(c("a", "b", "c"), times = c(30, 20, 10)), + cl = rep(sprintf("c%02d", 1:12), each = 5), + x = (1:60 %% 7) / 7, + yy = (1:60 %% 11) / 11, + y = 10 + (1:60 %% 13) + ) + d$lon <- -60 + 2 * d$id + d$lat <- -30 + d$id + sf::st_as_sf(d, coords = c("lon", "lat"), crs = 4326, remove = FALSE) +} + +# ---- the design grid --------------------------------------------------------- + +# A frame every design in design_rows() draws from: 240 rows in strata of +# 120, 80 and 40, 24 clusters of 10, a size `w` with a long right tail (about +# ten rows at 100 or more), hourly times over ten days, points in a lon/lat +# box and on the unit square, and a `y` that rises with `w` and `x` and +# shares a part within each cluster. +grid_frame <- function() { + local_seed(20251112) + n <- 240 + d <- data.frame( + id = seq_len(n), + site = rep(c("a", "b", "c"), times = c(120, 80, 40)), + cl = rep(sprintf("c%02d", 1:24), each = 10), + w = round(stats::rgamma(n, 2, 0.05), 1) + 1, + ts = seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "hour", + length.out = n), + lon = stats::runif(n, -60, 60), + lat = stats::runif(n, -40, 40), + x = stats::runif(n), + yy = stats::runif(n), + stringsAsFactors = FALSE + ) + d$y <- 2 * d$w + 50 * d$x + rep(stats::rnorm(24, 0, 15), each = 10) + + stats::rnorm(n, 0, 10) + d$flag <- d$y > stats::median(d$y) + d$day <- as.Date(d$ts) + d +} + +# One entry per design and common variant, each with the frame it draws from +# and what test-grid.R checks it against: +# n the rows a draw returns, and `fixed` whether every draw does +# expected the sum of the inclusion probabilities, `n` unless given +# psu the frame column whose values are the sampling units, or NULL +# for rows; `strata` the strata columns, or a function of the +# frame giving each row's stratum, or NULL for one stratum +# method the variance method that variance = "auto" reports +# jackknife "same" where the jackknife is the analytic estimator, "own" +# where it is an estimate of its own, else the note it declines +# with +# survey "same" where survey gives the same standard error, "close" +# where it approximates the same estimator another way, "own" +# where it has another estimator +# refuse the paths the design refuses on purpose, with the start of +# the message: "weights", "inclusion" (also sampling_weight()), +# "joint", "probability" (that plot view) and "plot" (every view) +# warns the class of a warning the design gives on every draw +# conditional whether a weighted sample is weighted on the clusters +# selected, which leaves its expected size unknown +design_rows <- function() { + f <- grid_frame() + row <- function(design, n, fixed = TRUE, expected = n, frame = f, + psu = NULL, strata = NULL, method = "analytic", + jackknife = "same", survey = "same", refuse = list(), + warns = NULL, conditional = FALSE) { + list(design = design, frame = frame, n = n, fixed = fixed, + expected = expected, psu = psu, strata = strata, method = method, + jackknife = jackknife, survey = survey, refuse = refuse, + warns = warns, conditional = conditional) + } + no_joint <- "has no closed-form joint inclusion probability" + fixed_start <- "with a fixed `start` is not a probability sample" + resampling <- "it is not a probability sample of a finite population" + successive <- "has no closed-form inclusion probability" + systematic_jk <- "A systematic sample has one primary sampling unit" + poisson_jk <- "Poisson sampling selects rows independently" + hours <- function(d) { + start <- as.POSIXct("2024-01-01", tz = "UTC") + floor(as.numeric(difftime(d$ts, start, units = "hours")) / 24) + } + days <- function(d) floor(as.numeric(d$day - as.Date("2024-01-01")) / 2) + takes <- sum(f$w >= 100) + + rows <- list( + simple = row(design_simple(n = 30), 30), + simple_replace = row( + design_simple(n = 30, replace = TRUE), 30, + expected = 240 * (1 - (1 - 1 / 240)^30), + refuse = list(weights = "not available for a with-replacement design", + joint = no_joint) + ), + stratified = row(design_stratified("site", n = 30), 30, strata = "site"), + stratified_equal = row( + design_stratified("site", n = 30, allocation = "equal"), 30, + strata = "site" + ), + stratified_neyman = row( + design_stratified("site", n = 30, allocation = "neyman", + allocation_by = "w"), 30, strata = "site" + ), + stratified_two = row( + design_stratified(c("site", "flag"), n = 30, min_per_stratum = 2), 30, + strata = c("site", "flag") + ), + systematic = row(design_systematic(interval = 8), 30, + method = "successive difference", + jackknife = systematic_jk, survey = "own"), + systematic_order = row(design_systematic(interval = 8, order_by = "w"), 30, + method = "successive difference", + jackknife = systematic_jk, survey = "own"), + systematic_start = row( + design_systematic(interval = 8, start = 3), 30, + refuse = list(weights = fixed_start, inclusion = fixed_start, + joint = fixed_start, probability = fixed_start) + ), + cluster = row(design_cluster("cl", n_clusters = 5), 50, psu = "cl"), + cluster_balanced = row( + design_cluster("cl", n_clusters = 5, balanced = TRUE), 50, psu = "cl", + jackknife = "own", refuse = list(joint = no_joint), conditional = TRUE + ), + multistage = row(design_multistage("cl", n_clusters = 6, n = 24), 24, + psu = "cl", jackknife = "own"), + multistage_prop = row( + design_multistage("cl", n_clusters = 6, n = 24, + allocation = "proportional", min_per_cluster = 1), + 24, psu = "cl", jackknife = "own", conditional = TRUE, + refuse = list(inclusion = "has no closed-form inclusion probability", + joint = no_joint, + probability = "has no closed-form inclusion probability") + ), + weighted_successive = row( + design_weighted("w", n = 30), 30, + refuse = list(weights = successive, inclusion = successive, + joint = no_joint, probability = successive) + ), + weighted_systematic = row( + design_weighted("w", n = 30, method = "systematic"), 30, + method = "deville", jackknife = "own", survey = "close", + refuse = list(joint = no_joint) + ), + weighted_poisson = row( + design_weighted("w", n = 30, method = "poisson"), NA, fixed = FALSE, + expected = 30, jackknife = poisson_jk + ), + certainty_simple = row( + design_certainty("w", 100, design_simple(n = 20)), takes + 20 + ), + certainty_stratified = row( + design_certainty("w", 100, design_stratified("site", n = 20)), + takes + 20, strata = "site" + ), + certainty_systematic = row( + design_certainty("w", 100, + design_weighted("w", n = 20, method = "systematic")), + takes + 20, method = "deville", jackknife = "own", survey = "close", + refuse = list(joint = no_joint) + ), + certainty_poisson = row( + design_certainty("w", 100, + design_weighted("w", n = 20, method = "poisson")), + NA, fixed = FALSE, expected = takes + 20, jackknife = poisson_jk + ), + reservoir = row(design_reservoir(n = 30), 30), + reservoir_capped = row(design_reservoir(n = 30, max_items = 150), 30, + warns = "drawn_stream_truncated"), + reservoir_stream = row( + design_reservoir(n = 30), 30, frame = as.list(f$id), + refuse = list(weights = "needs a data frame, not a list", + inclusion = "must be a data frame, not a list", + joint = "must be a data frame, not a list", + plot = "must be a data frame, not a list") + ), + bootstrap = row( + design_bootstrap(n_replicates = 20, n = 30), 600, + refuse = list(weights = resampling, inclusion = resampling, + joint = "A bootstrap is not a probability sample", + probability = resampling) + ), + bootstrap_block = row( + design_bootstrap(n_replicates = 20, n = 30, method = "block", + block_length = 5), 600, + refuse = list(weights = resampling, inclusion = resampling, + joint = "A bootstrap is not a probability sample", + probability = resampling) + ), + temporal_hours = row( + design_temporal("ts", from = "2024-01-01", to = "2024-01-11", + interval = 24, per_interval = 3, unit = "hours"), + 30, strata = hours + ), + temporal_days = row( + design_temporal("day", from = "2024-01-01", to = "2024-01-11", + interval = 2, per_interval = 3, unit = "days"), + 15, strata = days + ), + spread = row(design_spread(c("x", "yy"), n = 30, scale = FALSE), 30, + method = "local mean", jackknife = "own", survey = "own", + refuse = list(joint = no_joint)), + spread_size = row( + design_spread(c("x", "yy"), n = 30, size = "w", scale = FALSE), 30, + method = "local mean", jackknife = "own", survey = "own", + refuse = list(joint = no_joint) + ) + ) + if (requireNamespace("sf", quietly = TRUE)) { + rows$spatial <- row( + design_spatial(c("lon", "lat"), flat_box(c(-50, 50), c(-30, 30)), + n = 30), 30 + ) + } + rows +} diff --git a/tests/testthat/test-design-bootstrap.R b/tests/testthat/test-design-bootstrap.R index 1547655..3c0631e 100644 --- a/tests/testthat/test-design-bootstrap.R +++ b/tests/testthat/test-design-bootstrap.R @@ -53,3 +53,221 @@ test_that("replicates can be split apart and summarised", { expect_length(means, 8) expect_true(all(is.finite(means))) }) + +# Each replicate drawn and subset on its own, then bound together, as +# design_bootstrap() built them before it subset the data once. +one_by_one <- function(data, R, n, method = "simple", block_length = NULL) { + N <- nrow(data) + parts <- lapply(seq_len(R), function(i) { + idx <- if (method == "simple") { + sample.int(N, size = n, replace = TRUE) + } else { + starts <- sample.int(N - block_length + 1L, ceiling(n / block_length), + replace = TRUE) + unlist(lapply(starts, function(s) s:(s + block_length - 1L)))[seq_len(n)] + } + out <- data[idx, , drop = FALSE] + rownames(out) <- NULL + out[[".replicate"]] <- rep(i, nrow(out)) + out[, c(".replicate", names(data)), drop = FALSE] + }) + out <- do.call(rbind, parts) + rownames(out) <- NULL + out +} + +test_that("the stacked rows are those of each replicate drawn on its own", { + d <- data.frame(id = 1:40, v = (1:40) / 3, + s = rep(c("p", "q"), 20), + f = factor(rep(c("x", "y", "z", "x"), 10)), + t = as.Date("2024-01-01") + 0:39) + expect_identical(draw(d, design_bootstrap(6, n = 15), seed = 4), + with_seed(4, one_by_one(d, 6, 15))) + expect_identical( + draw(d, design_bootstrap(5, n = 13, method = "block", block_length = 4), + seed = 4), + with_seed(4, one_by_one(d, 5, 13, "block", 4)) + ) + skip_if_not_installed("tibble") + tb <- tibble::as_tibble(d) + expect_identical(draw(tb, design_bootstrap(3), seed = 8), + with_seed(8, one_by_one(tb, 3, 40))) +}) + +test_that("indices and weights hold the replicates the rows hold", { + d <- data.frame(id = 1:12, y = (1:12)^2) + rows <- draw(d, design_bootstrap(5, n = 8), seed = 3) + idx <- draw(d, design_bootstrap(5, n = 8, output = "indices"), seed = 3) + w <- draw(d, design_bootstrap(5, n = 8, output = "weights"), seed = 3) + + expect_true(is.matrix(idx)) + expect_type(idx, "integer") + expect_identical(dim(idx), c(8L, 5L)) + expect_identical(as.vector(idx), rows$id) + + expect_type(w, "integer") + expect_identical(dim(w), c(12L, 5L)) + expect_identical(w, apply(idx, 2, tabulate, nbins = 12)) + expect_equal(colSums(w), rep(8, 5)) + + # One row per replicate is still a matrix. + expect_identical(dim(draw(d, design_bootstrap(3, n = 1, output = "indices"), + seed = 1)), c(1L, 3L)) +}) + +test_that("bootstrap counts are replicate weights for survey", { + skip_if_not_installed("survey") + d <- data.frame(y = c(3, 8, 1, 9, 4, 7, 2, 6, 5, 10, 12, 0, 11, 15, 13)) + w <- draw(d, design_bootstrap(60, output = "weights"), seed = 2) + reps <- survey::svrepdesign(data = d, repweights = w, + weights = rep(1, nrow(d)), type = "bootstrap", + combined.weights = TRUE) + means <- colSums(w * d$y) / colSums(w) + est <- survey::svymean(~y, reps) + expect_equal(unname(coef(est)), mean(d$y)) + expect_equal(unname(survey::SE(est))[1], stats::sd(means)) +}) + +test_that("circular runs wrap around and reach every row equally often", { + d <- data.frame(id = 1:10) + idx <- draw(d, design_bootstrap(200, n = 8, method = "circular", + block_length = 4, output = "indices"), + seed = 5) + runs <- matrix(idx, nrow = 4) + expect_true(all((diff(runs) %% 10L) == 1L)) + expect_true(any(diff(runs) == -9L)) + + d30 <- data.frame(id = 1:30) + counts <- function(method) { + rowSums(draw(d30, design_bootstrap(2000, n = 30, method = method, + block_length = 5, output = "weights"), + seed = 7)) + } + circ <- counts("circular") + expect_true(all(abs(circ / 2000 - 1) < 0.1)) + # The non-circular moving-block bootstrap reaches its end rows less often. + block <- counts("block") + expect_lt(block[1], 0.4 * 2000) + expect_lt(block[30], 0.4 * 2000) +}) + +test_that("the default block length is floor(N^(1/3)) at perfect cubes too", { + des <- design_bootstrap(1, method = "block") + expect_identical(bootstrap_block_length(des, 64L), 4L) + expect_identical(bootstrap_block_length(des, 63L), 3L) + expect_identical(bootstrap_block_length(des, 1000L), 10L) + expect_identical(bootstrap_block_length(des, 2L), 1L) + expect_identical( + bootstrap_block_length(design_bootstrap(1, method = "block", + block_length = 7), 64L), 7L) + + idx <- draw(data.frame(id = 1:64), + design_bootstrap(1, n = 64, method = "block", + output = "indices"), seed = 1) + expect_true(all(diff(matrix(idx, nrow = 4)) == 1L)) +}) + +test_that("duplicated column names come back as they went in", { + dd <- data.frame(a = 1:5, a = 6:10, check.names = FALSE) + out <- draw(dd, design_bootstrap(2, n = 3), seed = 1) + expect_identical(names(out), c(".replicate", "a", "a")) + expect_identical(out[[3]] - out[[2]], rep(5L, 6)) + + skip_if_not_installed("tibble") + tb <- tibble::as_tibble(dd, .name_repair = "minimal") + out_tb <- draw(tb, design_bootstrap(2, n = 3), seed = 1) + expect_s3_class(out_tb, "tbl_df") + expect_identical(names(out_tb), c(".replicate", "a", "a")) + expect_identical(out_tb[[3]] - out_tb[[2]], rep(5L, 6)) +}) + +test_that("n = 0 gives no rows but keeps the .replicate column", { + d <- data.frame(id = 1:5) + out <- draw(d, design_bootstrap(3, n = 0), seed = 1) + expect_identical(names(out), c(".replicate", "id")) + expect_equal(nrow(out), 0) + expect_type(out$.replicate, "integer") + expect_length(split(out, factor(out$.replicate, 1:3)), 3) + + expect_identical(dim(draw(d, design_bootstrap(3, n = 0, output = "indices"), + seed = 1)), c(0L, 3L)) + w <- draw(d, design_bootstrap(3, n = 0, output = "weights"), seed = 1) + expect_identical(w, matrix(0L, 5, 3)) +}) + +test_that("a stacked result past 10 million rows warns with its own class", { + d <- data.frame(id = 1:5) + cond <- tryCatch(draw(d, design_bootstrap(2, n = 5000001), seed = 1), + drawn_bootstrap_size = function(w) w) + expect_s3_class(cond, "drawn_bootstrap_size") + expect_s3_class(cond, "drawn_warning") + expect_match(conditionMessage(cond), "10,000,002 rows", fixed = TRUE) + expect_match(conditionMessage(cond), "output = \"indices\"", fixed = TRUE) + + skip_on_cran() + expect_no_warning( + draw(d, design_bootstrap(2, n = 5000001, output = "indices"), seed = 1) + ) +}) + +test_that("the refusals give the expected count the method gives", { + d <- data.frame(id = 1:20) + msg <- function(des, ...) { + tryCatch(inclusion_prob(d, des, ...), error = conditionMessage) + } + for (m in c("simple", "circular")) { + expect_match(msg(design_bootstrap(5, method = m)), + "that is n_replicates * n / nrow(data)", fixed = TRUE) + } + block <- design_bootstrap(5, method = "block") + for (got in list(msg(block), msg(block, simulate = TRUE, R = 10))) { + expect_match(got, "first and last block_length - 1 rows appear less often", + fixed = TRUE) + expect_no_match(got, "that is n_replicates", fixed = TRUE) + } +}) + +test_that("method and output are checked when the design is built", { + expect_error(design_bootstrap(5, output = "matrix"), + "^`output` must be one of \"rows\", \"indices\" or \"weights\"") + expect_error(design_bootstrap(5, block_length = 3), + "only applies to method = \"block\" or \"circular\"") + expect_silent(design_bootstrap(5, method = "circular", block_length = 3)) +}) + +test_that("a selection plot draws the rows whatever the output", { + d <- data.frame(id = 1:30) + f <- tempfile(fileext = ".png") + grDevices::png(f) + on.exit({grDevices::dev.off(); unlink(f)}, add = TRUE) + for (out in c("rows", "indices", "weights")) { + expect_no_error(plot(design_bootstrap(2, n = 4, output = out), d, + type = "selection", seed = 1)) + } +}) + +test_that("reindex() subsets a plain data frame as `[` does", { + d <- data.frame(i = 1:6, s = letters[1:6], + f = factor(c("a", "b", "a", "c", "b", "a"), + levels = c("c", "b", "a", "z")), + t = as.POSIXct("2024-01-01", tz = "America/New_York") + + 3600 * 0:5) + d$l <- I(list(1, "a", NULL, 1:3, NA, list(2))) + d$m <- matrix(1:12, nrow = 6, dimnames = list(letters[1:6], c("p", "q"))) + d$df <- data.frame(u = 6:1) + names(d)[2] <- "i" + rownames(d) <- paste0("r", 1:6) + attr(d, "note") <- "kept" + # Row names of the frame's own stay with their rows, made unique where a + # row repeats, as `[` gives them. + for (idx in list(c(2L, 2L, 5L, 1L), integer(0), 6:1)) { + expect_identical(reindex(d, idx), d[idx, , drop = FALSE]) + } + # Automatic row names are numbered afresh. + rownames(d) <- NULL + for (idx in list(c(2L, 2L, 5L, 1L), integer(0), 6:1)) { + ref <- d[idx, , drop = FALSE] + rownames(ref) <- NULL + expect_identical(reindex(d, idx), ref) + } +}) diff --git a/tests/testthat/test-design-certainty.R b/tests/testthat/test-design-certainty.R index befd8cc..2ef84d5 100644 --- a/tests/testthat/test-design-certainty.R +++ b/tests/testthat/test-design-certainty.R @@ -1,5 +1,5 @@ cert_pop <- function(N = 400) { - set.seed(909) + local_seed(909) d <- data.frame( id = seq_len(N), site = rep(c("a", "b"), times = c(N * 0.6, N * 0.4)), @@ -45,7 +45,7 @@ test_that("simulated inclusion matches the closed form", { des <- design_certainty("value", 1500, design_stratified("site", n = 20)) exact <- inclusion_prob(d, des) - set.seed(21) + local_seed(21) hits <- integer(nrow(d)) R <- 3000 for (i in seq_len(R)) { @@ -171,6 +171,17 @@ test_that("the design prints its parts", { expect_true(any(grepl("20000|20,000", out))) }) +test_that("a named threshold prints by its value alone", { + des <- design_certainty("value", stats::quantile(1:100, 0.9), + design_simple(n = 5)) + expect_output(print(des), "threshold 90.1\n", fixed = TRUE) + expect_match(design_label(des), "threshold = 90.1,", fixed = TRUE) + # Counts per stratum keep their names. + st <- design_stratified("site", allocation = c(north = 4, south = 6)) + expect_match(design_label(st), "allocation = c(north = 4, south = 6)", + fixed = TRUE) +}) + # ---- composition, which is where the bugs live ----------------------------- test_that("the variance defers to `rest` instead of assuming a fixed size", { @@ -231,6 +242,64 @@ test_that("every sampled row certain means an exact total, variance 0", { expect_match(r$note, "exact rather than estimated") }) +test_that("a random-size `rest` that drew nothing gives no variance", { + # With a Poisson `rest` the rows below the threshold can all be missed. + # They went unobserved, and the total was reported as exact with se 0. + d <- cert_pop(300) + des <- design_certainty("value", 2500, + design_weighted("value", n = 1, method = "poisson")) + n_below <- sum(d$value < 2500) + for (i in 1:50) { + s <- draw(d, des, seed = i, weights = TRUE) + if (all(s$.prob == 1)) break + } + expect_true(all(s$.prob == 1)) + + r <- ht_total(s, "value") + expect_true(is.na(r$variance)) + expect_equal(r$method, "none") + expect_true(all(is.na(r$ci))) + # No degrees of freedom either, where a total with nothing below the + # threshold would have Inf + expect_equal(r$df, 0) + expect_equal(ht_mean(s, "value")$df, 0) + expect_match(r$note, paste0("the ", n_below, " rows with `value` below ", + "2,500, because `rest` drew none of them"), + fixed = TRUE) + # The reason is given once, though both estimators gave it + expect_length(gregexpr("drew none", r$note)[[1]], 1L) + + expect_true(is.na(ht_total(s, "value", variance = "analytic")$variance)) + expect_true(is.na(ht_total(s, "value", variance = "jackknife")$variance)) + expect_true(is.na(ht_mean(s, "value")$se)) +}) + +test_that("weights are refused when `rest` can never draw a row", { + d <- cert_pop(100) + des <- design_certainty("value", 2500, design_simple(n = 0)) + expect_error(draw(d, des, seed = 1, weights = TRUE), + paste0("`rest` gives all ", sum(d$value < 2500), " rows with ", + "`value` below 2,500 an inclusion probability of 0"), + fixed = TRUE) + expect_error(draw(d, des, seed = 1, weights = TRUE), "weights = FALSE") + # Without weights the draw is a cut-off sample of the certainty rows + s <- draw(d, des, seed = 1) + expect_equal(s$id, d$id[d$value >= 2500]) +}) + +test_that("an error from `rest` says which rows it was given", { + d <- cert_pop(100) + n_below <- sum(d$value < 500) + des <- design_certainty("value", 500, design_simple(n = n_below + 1)) + prefix <- paste0("In `rest`, applied to the ", n_below, + " rows with `value` below 500: ") + expect_error(draw(d, des, seed = 1), prefix, fixed = TRUE) + expect_error(inclusion_prob(d, design_certainty("value", 500, + design_weighted("value", + n = 5))), + prefix, fixed = TRUE) +}) + test_that("dropping missing sizes does not shift the probabilities", { # certainty_split() removes rows, so positions in the reduced frame are not # positions in the original one. Getting that wrong shifts every probability @@ -258,3 +327,47 @@ test_that("dropping missing sizes does not shift the probabilities", { # And a draw never selects the dropped row for (i in 1:20) expect_false(1 %in% draw(d, des, seed = i)$id) }) + +test_that("rows above the threshold carry no degrees of freedom", { + d <- cert_pop(200) + n_above <- sum(d$value >= 2000) + s <- draw(d, design_certainty("value", 2000, design_simple(n = 20)), + seed = 1, weights = TRUE) + expect_equal(sum(s$.prob == 1), n_above) + expect_equal(ht_total(s, "value")$df, 19) + s2 <- draw(d, design_certainty("value", 2000, + design_stratified("site", n = 20)), + seed = 1, weights = TRUE) + expect_equal(ht_total(s2, "value")$df, 18) +}) + +test_that("a `rest` that drew nothing leaves no degrees of freedom", { + # The interval has no variance to stand on, and survey would call the total + # exact, so as_svydesign() refuses it. + d <- data.frame(id = 1:5, v = c(100, 200, 1, 2, 3), y = c(10, 20, 1, 2, 3)) + des <- design_certainty("v", 50, design_systematic(interval = 10)) + for (i in 1:50) { + s <- suppressWarnings(draw(d, des, seed = i, weights = TRUE)) + if (nrow(s) == 2L) break + } + expect_equal(s$id, 1:2) + r <- ht_total(s, "y") + expect_true(is.na(r$variance)) + expect_equal(r$df, 0) + + skip_if_not_installed("survey") + expect_error(as_svydesign(s), paste0("`sample` holds none of the 3 rows ", + "with `v` below 50"), fixed = TRUE) +}) + +test_that("a frame with the column the draw tags rows with is refused", { + d <- data.frame(id = 1:20, w = c(50, 1:19), .drawn_certainty_id = 0) + des <- design_certainty("w", 40, design_simple(n = 3)) + expect_error(draw(d, des, seed = 1), + "`data` already has a column called `.drawn_certainty_id`.", + fixed = TRUE) + names(d)[3] <- "tag" + s <- draw(d, des, seed = 1) + expect_equal(nrow(s), 4L) + expect_true(1L %in% s$id) +}) diff --git a/tests/testthat/test-design-cluster.R b/tests/testthat/test-design-cluster.R index 50b0e60..ac19b32 100644 --- a/tests/testthat/test-design-cluster.R +++ b/tests/testthat/test-design-cluster.R @@ -29,6 +29,228 @@ test_that("NA cluster labels are reported rather than treated as a cluster", { expect_equal(nrow(res), 20) }) +test_that("a single numeric cluster id is not read as a range", { + # sample(5, 1) samples from 1:5, so the only real cluster was never selected. + d <- data.frame(x = 1:10, cl = rep(5, 10)) + expect_equal(nrow(draw(d, design_cluster("cl", n_clusters = 1), seed = 1)), + 10) +}) + test_that("clusters must name a single column", { expect_error(design_cluster(c("a", "b"), n_clusters = 2), "a single column") }) + +test_that("the clusters chosen for a seed are sample(unique(labels))'s", { + d <- data.frame(id = 1:60, cl = rep(c(5, 2, 9, 1, 7, 3), each = 10)) + for (k in c(1, 3)) { + got <- unique(draw(d, design_cluster("cl", n_clusters = k), seed = 7)$cl) + want <- drawn:::with_seed(7, sample(unique(d$cl), k)) + expect_setequal(got, want) + } +}) + +test_that("two cluster ids that print alike stay two clusters", { + # 0.3 and 0.1 + 0.2 both print as 0.3. Compared as text they were one + # cluster: a two-cluster sample got no variance, and two rows of different + # clusters got the same-cluster joint probability. + d <- data.frame(id = 1:20, cl = rep(c(0.3, 0.1 + 0.2, 0.5, 0.7), each = 5), + y = c(1:5, 101:105, 21:25, 61:65)) + des <- design_cluster("cl", n_clusters = 3) + expect_equal(inclusion_prob(d, des), rep(0.75, 20)) + m <- joint_prob(d, des, rows = c(1, 2, 6)) + expect_equal(m[1, 2], 0.75) + expect_equal(m[1, 3], 3 * 2 / (4 * 3)) + + s <- draw(d, des, seed = 2, weights = TRUE) + expect_equal(sum(s$cl == 0.3), 5) + expect_equal(sum(s$cl == 0.1 + 0.2), 5) + u <- tapply(s$y / s$.prob, match(s$cl, unique(s$cl)), sum) + r <- ht_total(s, "y") + expect_equal(r$method, "analytic") + expect_equal(r$variance, (1 - 3 / 4) * 3 * stats::var(u)) + expect_equal(r$df, 2) + expect_equal(ht_total(s, "y", variance = "jackknife")$variance, r$variance) + expect_equal(nrow(sample_summary(s)$by_group), 3) + + skip_if_not_installed("survey") + des_sv <- as_svydesign(s) + expect_equal(survey::degf(des_sv), 2) + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, des_sv))), r$se) +}) + +test_that("a factor's unused levels are not clusters", { + d <- data.frame(id = 1:40, y = 1:40, + cl = factor(rep(c("a", "b", "c", "d"), each = 10), + levels = c("a", "b", "c", "d", "zz"))) + des <- design_cluster("cl", n_clusters = 2) + expect_equal(inclusion_prob(d, des), rep(0.5, 40)) + s <- draw(d, des, seed = 1, weights = TRUE) + expect_equal(nrow(s), 20) + r <- ht_total(s, "y") + expect_equal(r$method, "analytic") + expect_equal(r$df, 1) + expect_equal(nrow(sample_summary(s)$by_group), 2) +}) + +test_that("a missing cluster label is called that everywhere", { + d <- data.frame(id = 1:30, cl = c(NA, rep(c("a", "b", "c"), each = 10))[1:30]) + des <- design_cluster("cl", n_clusters = 2) + expect_error(draw(d, des, seed = 1), "1 row\\(s\\) have a missing cluster label") + expect_error(inclusion_prob(d, des), + "1 row\\(s\\) have a missing cluster label") + expect_error(inclusion_prob(d, design_multistage("cl", n_clusters = 2, n = 4)), + "1 row\\(s\\) have a missing cluster label") +}) + +test_that("selecting many clusters takes one pass over the frame", { + skip_on_cran() + # Each chosen cluster scanned the whole frame: 16 seconds for 1,000 + # clusters of a million rows. + N <- 1e6 + d <- data.frame(cl = sprintf("c%07d", (seq_len(N) - 1) %/% 50 + 1)) + took <- system.time({ + s <- draw(d, design_cluster("cl", n_clusters = 1000), seed = 1) + m <- draw(d, design_multistage("cl", n_clusters = 1000, n = 5000), seed = 1) + })[["elapsed"]] + expect_equal(nrow(s), 50000) + expect_equal(length(unique(s$cl)), 1000) + expect_equal(nrow(m), 5000) + expect_lt(took, 5) +}) + +# ---- balanced clusters ------------------------------------------------------ + +test_that("balanced clusters have exact inclusion probabilities", { + # The take is the smallest selected cluster's size. Given cluster i, the + # other cluster is one of three, so clusters of 2/4/6/8 average takes of + # 2, 10/3, 4 and 4. + d <- data.frame(cl = rep(c("a", "b", "c", "d"), c(2, 4, 6, 8))) + des <- design_cluster("cl", n_clusters = 2, balanced = TRUE) + p <- inclusion_prob(d, des) + expect_equal(as.numeric(tapply(p, d$cl, unique)), + c(1 / 2, 5 / 12, 1 / 3, 1 / 4)) + expect_equal(sampling_weight(d, des), 1 / p) + sim <- inclusion_prob(d, des, simulate = TRUE, R = 2000, seed = 1) + expect_lt(max(abs(tapply(sim, d$cl, mean) - tapply(p, d$cl, mean))), 0.03) + + # Every selection of 3 clusters out of 7, of sizes with ties, enumerated. + sizes <- c(3, 7, 1, 7, 4, 9, 4) + e <- data.frame(cl = rep(seq_along(sizes), sizes)) + got <- inclusion_prob(e, design_cluster("cl", n_clusters = 3, + balanced = TRUE)) + sets <- utils::combn(7, 3) + want <- numeric(7) + for (j in seq_len(ncol(sets))) { + s <- sets[, j] + want[s] <- want[s] + min(sizes[s]) / sizes[s] / ncol(sets) + } + expect_equal(as.numeric(tapply(got, e$cl, unique)), want) + + # The probability plot needs them too. + f <- tempfile(fileext = ".png") + grDevices::png(f) + on.exit({grDevices::dev.off(); unlink(f)}, add = TRUE) + expect_no_error(plot(des, d, type = "probability")) + + # One cluster selected is taken whole; all of them, at the smallest size. + expect_equal(inclusion_prob(e, design_cluster("cl", n_clusters = 1, + balanced = TRUE)), + rep(1 / 7, nrow(e))) + expect_equal(inclusion_prob(e, design_cluster("cl", n_clusters = 7, + balanced = TRUE)), + 1 / rep(sizes, sizes)) +}) + +test_that("a missing cluster label gets probability 0 under balance too", { + d <- data.frame(cl = c(NA, rep(c("a", "b", "c"), c(2, 4, 6)))) + des <- design_cluster("cl", n_clusters = 2, balanced = TRUE, na_rm = TRUE) + p <- inclusion_prob(d, des) + expect_equal(p[1], 0) + # Average takes of 2, 3 and 3, with two of three clusters selected. + expect_equal(p[-1], rep(c(2 / 3, 1 / 2, 1 / 3), c(2, 4, 6))) +}) + +test_that("a balanced sample is weighted conditional on its clusters", { + sizes <- c(3, 5, 7, 4, 6, 8, 5, 9) + d <- data.frame(id = seq_len(sum(sizes)), + cl = rep(paste0("k", 1:8), sizes)) + d$y <- (d$id * 37) %% 23 + rep(c(10, 40, 25, 60, 15, 30, 50, 20), sizes) + des <- design_cluster("cl", n_clusters = 4, balanced = TRUE) + s <- draw(d, des, seed = 3, weights = TRUE) + + sel <- attr(s, "drawn_selection") + expect_type(sel, "integer") + expect_setequal(sel, match(unique(s$cl), unique(d$cl))) + m <- min(sizes[sel]) + expect_equal(as.vector(table(s$cl)), rep(m, 4)) + expect_equal(s$.prob, 4 / 8 * m / sizes[match(s$cl, unique(d$cl))]) + pi_all <- attr(s, "drawn_pi") + expect_true(all(is.na(pi_all[!d$cl %in% s$cl]))) + expect_equal(pi_all[s$.row], s$.prob) + + # The two-stage formula, at the take of m rows from each cluster. + r <- ht_total(s, "y") + N_i <- sizes[sel] + g <- factor(s$cl, levels = unique(d$cl)[sel]) + tot <- N_i * tapply(s$y, g, mean) + s2 <- tapply(s$y, g, stats::var) + v <- 8^2 * (1 - 4 / 8) * stats::var(tot) / 4 + + 8 / 4 * sum(N_i^2 * (1 - m / N_i) * s2 / m) + expect_equal(r$total, 8 / 4 * sum(tot)) + expect_equal(r$method, "analytic") + expect_equal(r$variance, v) + expect_equal(r$df, 3) + expect_equal(ht_total(s, "y", variance = "jackknife")$method, "jackknife") + + sm <- sample_summary(s) + expect_equal(sm$conditional, 4L) + expect_equal(sm$N_reachable, nrow(d)) + expect_equal(sm$unreachable, 0L) + expect_output(print(sm), "conditional on the 4 clusters selected") + expect_true(is.na(sample_summary(draw(d, design_cluster("cl", 4), seed = 3, + weights = TRUE))$conditional)) + + # Without weights the selection is not attached. + expect_null(attr(draw(d, des, seed = 3), "drawn_selection")) +}) + +test_that("conditional weights are unbiased over every selection", { + # Given the clusters, each is estimated without bias; the clusters are a + # simple random sample. Averaging the expected estimate over all 35 + # selections gives the total. `.prob` is a / A times the chance of a row + # given the selection, and that chance averages to the exact probability. + sizes <- c(3, 7, 1, 7, 4, 9, 4) + d <- data.frame(cl = rep(seq_along(sizes), sizes)) + d$y <- seq_len(nrow(d))^2 %% 17 + d$cl * 5 + des <- design_cluster("cl", n_clusters = 3, balanced = TRUE) + sets <- utils::combn(7, 3) + est <- numeric(ncol(sets)) + avg <- numeric(nrow(d)) + for (j in seq_len(ncol(sets))) { + p <- drawn:::conditional_inclusion(des, d, sets[, j]) + take <- min(sizes[sets[, j]]) + hit <- !is.na(p) + # A row of cluster i is drawn with chance take / N_i given the clusters. + est[j] <- sum((d$y * take / sizes[d$cl] / p)[hit]) + avg[hit] <- avg[hit] + p[hit] * 7 / 3 / ncol(sets) + } + expect_equal(mean(est), sum(d$y)) + expect_equal(avg, inclusion_prob(d, des)) +}) + +test_that("a balanced design under certainty declines the two-stage form", { + # Inside a certainty design the cluster rows are weighted with the + # unconditional probabilities, which the two-stage estimator cannot use. + sizes <- rep(c(3, 5, 7), 4) + d <- data.frame(cl = rep(paste0("c", 1:12), sizes)) + d$v <- seq_len(nrow(d)) + d$y <- (d$v * 13) %% 11 + 2 + des <- design_certainty("v", 58, design_cluster("cl", n_clusters = 4, + balanced = TRUE)) + s <- draw(d, des, seed = 1, weights = TRUE) + expect_null(attr(s, "drawn_selection")) + r <- ht_total(s, "y") + expect_equal(r$method, "jackknife") + expect_match(r$note, "no closed-form joint inclusion probability") + expect_equal(ht_total(s, "y", variance = "analytic")$method, "none") +}) diff --git a/tests/testthat/test-design-multistage.R b/tests/testthat/test-design-multistage.R index 9f8d12a..eb82a95 100644 --- a/tests/testthat/test-design-multistage.R +++ b/tests/testthat/test-design-multistage.R @@ -41,6 +41,14 @@ test_that("NA cluster labels never fabricate rows", { seed = 1) expect_false(anyNA(res$x)) expect_equal(nrow(res), 5) + + # A guard reading the NA-inflated count would let this through, returning 15 + # rows from a 10-row cluster with replace = FALSE. + expect_error( + draw(df, design_multistage("cl", n_clusters = 1, n = 15, na_rm = TRUE), + seed = 1), + "exceeds the 10 row\\(s\\) available" + ) }) test_that("a single numeric cluster id is not read as a range", { @@ -48,3 +56,538 @@ test_that("a single numeric cluster id is not read as a range", { expect_equal(nrow(draw(d, design_multistage("cl", n_clusters = 1, n = 2), seed = 1)), 2) }) + +test_that("n below n_clusters, or below what min_per_cluster needs, is refused", { + expect_error(design_multistage("cl", n_clusters = 3, n = 0), + "`n` \\(0\\) is smaller than `n_clusters` \\(3\\)") + expect_error(design_multistage("cl", n_clusters = 5, n = 3), + "Raise `n` to at least 5") + expect_error(design_multistage("cl", n_clusters = 4, n = 6, + min_per_cluster = 2), + "needs at least 8 rows, but `n` is 6") + expect_s3_class(design_multistage("cl", n_clusters = 4, n = 8, + min_per_cluster = 2), + "drawn_design_multistage") +}) + +test_that("a selected cluster the allocation leaves empty is named", { + d <- data.frame(id = 1:31, cl = c("tiny", rep("big", 30))) + des <- design_multistage("cl", n_clusters = 2, n = 10, + allocation = "proportional") + expect_warning(s <- draw(d, des, seed = 1), + "selected cluster `tiny` none of the 10 rows", + class = "drawn_empty_cluster") + expect_equal(nrow(s), 10) + # A cluster smaller than the minimum is taken whole, which is no shortfall. + expect_no_warning( + s2 <- draw(d, design_multistage("cl", n_clusters = 2, n = 10, + allocation = "proportional", + min_per_cluster = 2), seed = 1) + ) + expect_equal(as.vector(table(s2$cl)), c(9L, 1L)) + # Simulation draws many times on purpose and warns once, with the count. + warned <- character(0) + withCallingHandlers( + inclusion_prob(d, des, simulate = TRUE, R = 20, seed = 1), + drawn_empty_cluster = function(w) { + warned <<- c(warned, conditionMessage(w)) + invokeRestart("muffleWarning") + }) + expect_length(warned, 1L) + expect_match(warned, "This happened in 20 of the 20 simulated draws.", + fixed = TRUE) + + # Which cluster is left empty changes from draw to draw. The message names + # the first draw's cluster, so its count is of warnings like it, not of + # draws that left that cluster empty. + d3 <- data.frame(id = 1:92, cl = rep(c("t1", "t2", "b1", "b2", "b3"), + c(1, 1, 30, 30, 30))) + des3 <- design_multistage("cl", n_clusters = 3, n = 10, + allocation = "proportional") + warned <- character(0) + withCallingHandlers( + inclusion_prob(d3, des3, simulate = TRUE, R = 40, seed = 1), + drawn_empty_cluster = function(w) { + warned <<- c(warned, conditionMessage(w)) + invokeRestart("muffleWarning") + }) + expect_length(warned, 1L) + expect_match(warned, "selected cluster `t[12]` none of the 10 rows") + expect_match(warned, paste0("This is the first of these warnings\\. [0-9]+ ", + "of the 40 simulated draws gave one like it, ", + "with details that differ from draw to draw\\.$")) +}) + +test_that("with replacement, a row's probability is that of being drawn at all", { + # m / N_h is the expected number of draws of a row, not its probability. + # Cluster `a` holds 4 rows and takes 5 draws, which replacement allows. + sizes <- c(4, 8, 12, 16) + d <- data.frame(id = 1:40, cl = rep(c("a", "b", "c", "d"), times = sizes)) + des <- design_multistage("cl", n_clusters = 2, n = 10, replace = TRUE) + p <- inclusion_prob(d, des) + expect_equal(p, 0.5 * (1 - (1 - 1 / rep(sizes, sizes))^5)) + expect_equal(sampling_weight(d, des), 1 / p) + sim <- inclusion_prob(d, des, simulate = TRUE, R = 2000, seed = 1) + expect_lt(max(abs(tapply(sim, d$cl, mean) - tapply(p, d$cl, mean))), 0.03) + expect_error(joint_prob(d, des), "no closed-form joint") +}) + +test_that("a row with no cluster co-occurs with nothing", { + d <- data.frame(id = 1:30, cl = c(rep("a", 10), rep("b", 10), NA, + rep("c", 9))) + des <- design_multistage("cl", n_clusters = 2, n = 4, na_rm = TRUE) + m <- joint_prob(d, des, rows = c(1, 21, 22)) + expect_equal(m[2, ], c(0, 0, 0)) + expect_equal(m[, 2], c(0, 0, 0)) + expect_false(anyNA(joint_prob(d, des))) + sim <- joint_prob(d, des, rows = c(1, 21, 22), simulate = TRUE, R = 2000, + seed = 1) + expect_lt(max(abs(sim - m)), 0.03) +}) + +test_that("a factor's unused levels are not clusters", { + d <- data.frame(id = 1:40, y = 1:40, + cl = factor(rep(c("a", "b", "c", "d"), each = 10), + levels = c("a", "b", "c", "d", "zz"))) + des <- design_multistage("cl", n_clusters = 2, n = 4) + expect_equal(inclusion_prob(d, des), rep(0.1, 40)) + expect_equal(diag(joint_prob(d, des, rows = 1:3)), rep(0.1, 3)) + s <- draw(d, des, seed = 1, weights = TRUE) + expect_equal(s$.prob, rep(0.1, 4)) + expect_true(is.finite(ht_total(s, "y")$se)) + expect_equal(nrow(sample_summary(s)$by_group), 2) +}) + +test_that("two cluster ids that print alike stay two clusters", { + d <- data.frame(id = 1:40, cl = rep(c(0.3, 0.1 + 0.2, 0.5, 0.7), each = 10), + y = rep(c(1, 100, 5, 9), each = 10) + 1:40) + des <- design_multistage("cl", n_clusters = 2, n = 4) + expect_equal(inclusion_prob(d, des), rep(0.1, 40)) + m <- joint_prob(d, des, rows = c(1, 2, 11)) + expect_equal(m[1, 2], 0.5 * (2 * 1) / (10 * 9)) + expect_equal(m[1, 3], (2 / 10)^2 * (2 * 1) / (4 * 3)) + + s <- draw(d, des, seed = 3, weights = TRUE) + expect_equal(sum(s$cl == 0.3), 2) + expect_equal(sum(s$cl == 0.1 + 0.2), 2) + r <- ht_total(s, "y") + expect_equal(r$method, "analytic") + expect_equal(r$df, 1) + expect_equal(nrow(sample_summary(s)$by_group), 2) + + skip_if_not_installed("survey") + des_sv <- as_svydesign(s) + expect_equal(survey::degf(des_sv), 1) + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, des_sv))), r$se) +}) + +test_that("a sample from one cluster has no variance, and says why", { + # Sen-Yates-Grundy is negative on every such sample, and was 0 for a + # constant `y`. + d <- data.frame(id = 1:40, cl = rep(c("a", "b", "c", "d"), each = 10), + y = rep(5, 40)) + s <- draw(d, design_multistage("cl", n_clusters = 1, n = 5), seed = 2, + weights = TRUE) + for (v in c("analytic", "auto")) { + r <- ht_total(s, "y", variance = v) + expect_true(is.na(r$variance)) + expect_match(r$note, "A variance needs at least two clusters; this sample has 1.", + fixed = TRUE) + expect_false(grepl("unlucky", r$note)) + } +}) + +test_that("a frame of one cluster gives a simple random sample's variance", { + # Stage one takes the only cluster, so the sample is a simple random sample + # within it, which the exact estimator measures. + d <- data.frame(id = 1:30, cl = "only", y = (1:30 * 7) %% 11 + 40) + for (des in list(design_multistage("cl", n_clusters = 1, n = 6), + design_multistage("cl", n_clusters = 1, n = 6, + allocation = "proportional", + min_per_cluster = 1))) { + s <- draw(d, des, seed = 1, weights = TRUE) + r <- ht_total(s, "y", variance = "analytic") + expect_equal(r$method, "analytic") + expect_equal(r$variance, 30^2 * (1 - 6 / 30) * var(s$y) / 6) + expect_false(any(grepl("at least two clusters", r$note))) + # The Hajek mean and a ratio were declined as if the cluster were the + # only unit, though its rows were drawn at random. + m <- ht_mean(s, "y") + expect_equal(m$method, "analytic") + expect_equal(m$variance, (1 - 6 / 30) * var(s$y) / 6) + expect_equal(ht_mean(s, "y", estimator = "ht")$variance, m$variance) + expect_true(is.finite(ht_ratio(s, "y", "id")$se)) + } +}) + +test_that("a domain inside one cluster of a census of clusters has an se", { + skip_if_not_installed("survey") + # Stage one takes both clusters, so each is a stratum whose rows were drawn + # at random, and a domain in one of them still varies. + d <- data.frame(id = 1:40, cl = rep(c("A", "B"), each = 20)) + d$y <- c(sin(1:20) * 5 + 10, cos(1:20) * 3 + 20) + s <- draw(d, design_multistage("cl", n_clusters = 2, n = 12), seed = 5, + weights = TRUE) + m <- ht_mean(s, "y", by = "cl") + expect_equal(m$method, c("analytic", "analytic")) + for (k in c("A", "B")) { + yk <- s$y[s$cl == k] + expect_equal(m$variance[m$cl == k], (1 - 6 / 20) * var(yk) / 6) + } + theirs <- survey::svyby(~y, ~cl, as_svydesign(s), survey::svymean) + expect_equal(m$se, unname(survey::SE(theirs)[match(m$cl, theirs$cl)])) + # A domain of one sampled row is still declined, naming the row. + s$solo <- ifelse(seq_len(nrow(s)) == 1L, "solo", "rest") + one <- ht_mean(s, "y", by = "solo") + expect_true(is.na(one$se[one$solo == "solo"])) + expect_match(attr(one, "notes"), "The domain `solo` has one sampled row", + fixed = TRUE, all = FALSE) +}) + +test_that("the jackknife declines a domain inside one cluster of a census", { + # The analytic estimator's units are the rows of each cluster, but the + # jackknife deletes whole clusters, and a linearised estimate sums to zero + # inside one. + d <- data.frame(id = 1:40, cl = rep(c("A", "B"), each = 20)) + d$y <- c(sin(1:20) * 5 + 10, cos(1:20) * 3 + 20) + s <- draw(d, design_multistage("cl", n_clusters = 2, n = 12), seed = 5, + weights = TRUE) + wording <- "has sampled rows in one cluster only" + m <- ht_mean(s, "y", by = "cl", variance = "jackknife") + expect_true(all(is.na(m$se))) + expect_equal(m$method, c("none", "none")) + expect_match(attr(m, "notes"), wording, fixed = TRUE) + r <- ht_ratio(s, "y", "id", by = "cl", variance = "jackknife") + expect_true(all(is.na(r$se))) + q <- ht_quantile(s, "y", probs = 0.25, by = "cl", variance = "jackknife") + expect_true(all(is.na(q$se))) + k <- ht_mean(s, "y", by = "cl", contrast = c(A = 1, B = -1), + variance = "jackknife") + expect_true(is.na(k$se)) + expect_match(k$note, "so it has no standard error either", fixed = TRUE) + # The whole sample spans both clusters. + expect_true(is.finite(ht_mean(s, "y", variance = "jackknife")$se)) + + # Under "auto" the jackknife takes over when the analytic estimator + # declines, here for the one row drawn from cluster A. + d <- data.frame(id = 1:40, cl = rep(c("A", "B"), c(3, 37))) + d$y <- (d$id * 7) %% 13 + 1 + d$g <- ifelse(d$id %% 2 == 0, "even", "odd") + s <- draw(d, design_multistage("cl", 2, 12, allocation = "proportional", + min_per_cluster = 1), + seed = 5, weights = TRUE) + expect_identical(sort(unique(s$g[s$cl == "A"])), "odd") + by_cl <- ht_mean(s, "y", by = "cl") + expect_true(all(is.na(by_cl$se))) + expect_match(attr(by_cl, "notes"), "The domain `B` has sampled rows in one", + fixed = TRUE, all = FALSE) + by_g <- ht_mean(s, "y", by = "g") + expect_true(is.na(by_g$se[by_g$g == "even"])) + expect_equal(by_g$method[by_g$g == "odd"], "jackknife") + expect_true(by_g$se[by_g$g == "odd"] > 0.1) +}) + +test_that("the jackknife fallback says when it inflates the between-cluster part", { + d <- data.frame(id = 1:100, cl = rep(sprintf("k%02d", 1:10), each = 10), + y = rep(1:10 * 10, each = 10) + 1:100 %% 7) + note_for <- function(a) { + ht_total(draw(d, design_multistage("cl", n_clusters = a, n = a), seed = 1, + weights = TRUE), "y")$note + } + half <- note_for(5) + expect_match(half, "With 5 of the 10 clusters selected", fixed = TRUE) + expect_match(half, "between clusters at 2 times its true size", fixed = TRUE) + expect_false(grepl("true size", note_for(2))) + all <- note_for(10) + expect_match(all, "Every cluster is selected", fixed = TRUE) + expect_match(all, "design_stratified()", fixed = TRUE) + + # A jackknife asked for is not a fallback, and says the same. + asked <- function(a) { + ht_total(draw(d, design_multistage("cl", n_clusters = a, n = 2 * a), + seed = 1, weights = TRUE), "y", variance = "jackknife")$note + } + expect_match(asked(5), "between clusters at 2 times its true size", + fixed = TRUE) + expect_false(grepl("true size", asked(2))) + expect_match(asked(10), "measures the variation within clusters only", + fixed = TRUE) +}) + +# ---- clusters in proportion to size ----------------------------------------- + +pps_clusters <- function() { + sizes <- c(40, 6, 8, 10, 6, 8, 10, 12) + d <- data.frame(cl = rep(sprintf("k%d", 1:8), times = sizes)) + d$rows <- rep(sizes, times = sizes) + d$y <- rep(c(50, 20, 35, 40, 25, 30, 45, 60), times = sizes) + + seq_len(nrow(d)) %% 5 * 3 + d +} + +test_that("size selects clusters in proportion to it, certain ones always", { + d <- pps_clusters() + des <- design_multistage("cl", n_clusters = 3, n = 6, size = "rows") + p <- inclusion_prob(d, des) + # k1 holds 40 of 100 rows: 3 * 0.4 passes 1, so it is certain, and the + # other two selections are spread over the 60 rows left. + first <- c(1, 2 * c(6, 8, 10, 6, 8, 10, 12) / 60) + expect_equal(p, rep(first * 2 / c(40, 6, 8, 10, 6, 8, 10, 12), + times = c(40, 6, 8, 10, 6, 8, 10, 12))) + expect_equal(sum(p), 6) + # Below certainty the design is self-weighting: (2 * N_i / 60) * (2 / N_i) + # for every row. + expect_equal(unique(round(p[d$cl != "k1"], 12)), round(4 / 60, 12)) + for (i in 1:10) { + s <- draw(d, des, seed = i) + expect_true("k1" %in% s$cl) + expect_identical(as.vector(table(s$cl)), rep(2L, 3)) + } +}) + +test_that("first-stage selection matches its probabilities in simulation", { + skip_on_cran() + d <- pps_clusters() + des <- design_multistage("cl", n_clusters = 3, n = 6, size = "rows") + sim <- inclusion_prob(d, des, simulate = TRUE, R = 2000, seed = 1) + claim <- inclusion_prob(d, des) + # Compared cluster by cluster, where the counts are large enough to test. + expect_equal(as.vector(tapply(sim, d$cl, sum)), + as.vector(tapply(claim, d$cl, sum)), tolerance = 0.06) +}) + +test_that("with equal measures the variance is the two-stage estimator", { + d <- pps_clusters() + d$one <- 1 + s <- draw(d, design_multistage("cl", n_clusters = 4, n = 12), seed = 3, + weights = TRUE) + des <- design_multistage("cl", n_clusters = 4, n = 12, size = "one") + expect_equal(inclusion_prob(d, des), + inclusion_prob(d, design_multistage("cl", 4, 12))) + expect_equal(pps_stage_variance(des, d, s$.row, s$y, s$.prob)$variance, + ht_total(s, "y")$variance) +}) + +test_that("a certain cluster is a stratum of its sampled rows", { + d <- pps_clusters() + s <- draw(d, design_multistage("cl", n_clusters = 4, n = 12, size = "rows"), + seed = 2, weights = TRUE) + r <- ht_total(s, "y") + expect_identical(r$method, "deville") + # Three clusters below certainty less one, and three rows of k1 less one. + expect_identical(r$df, 4) + k1 <- s$cl == "k1" + within <- 40^2 * (1 - 3 / 40) * stats::var(s$y[k1]) / 3 + rest <- !k1 + u <- rowsum(s$y[rest] / s$.prob[rest], s$cl[rest])[, 1] + p1 <- 3 * c(k2 = 6, k3 = 8, k4 = 10, k5 = 6, k6 = 8, k7 = 10, + k8 = 12)[names(u)] / 60 + w_i <- vapply(names(u), function(k) { + i <- s$cl == k + N <- d$rows[match(k, d$cl)] + N^2 * (1 - 3 / N) * stats::var(s$y[i]) / 3 + }, numeric(1)) + expect_equal(r$variance, deville_variance(u * p1, p1)$variance + within + + sum(w_i / p1)) + jk <- ht_total(s, "y", variance = "jackknife") + expect_match(jk$note, "Jackknife over 6 primary sampling unit(s) in 2 strata", + fixed = TRUE) +}) + +test_that("one row per cluster, or one cluster below certainty, declines", { + d <- pps_clusters() + s <- draw(d, design_multistage("cl", n_clusters = 3, n = 3, size = "rows"), + seed = 1, weights = TRUE) + r <- ht_total(s, "y") + expect_true(is.na(r$se)) + expect_match(r$note, "one row per selected cluster", fixed = TRUE) + expect_match(r$note, "cluster taken with certainty `k1` has a single", + fixed = TRUE) + # Measures that need not be row counts: k2 and k3 are certain, and one + # selection is left for the other six clusters. + big <- d + big$rows[big$cl %in% c("k2", "k3")] <- 500 + s2 <- draw(big, design_multistage("cl", n_clusters = 3, n = 6, + size = "rows"), seed = 1, weights = TRUE) + r2 <- ht_total(s2, "y", variance = "analytic") + expect_match(r2$note, "this sample has one, besides the 2 taken with", + fixed = TRUE) + expect_match(ht_total(s2, "y")$note, + "The jackknife needs at least two clusters below certainty", + fixed = TRUE) + # With no cluster certain the note does not count certain ones. + s1 <- draw(d, design_multistage("cl", n_clusters = 1, n = 3, size = "rows"), + seed = 1, weights = TRUE) + r1 <- ht_total(s1, "y", variance = "analytic") + expect_match(r1$note, "this sample has one.", fixed = TRUE) + expect_no_match(r1$note, "besides", fixed = TRUE) +}) + +test_that("a size that is not one per cluster, or not usable, is refused", { + d <- pps_clusters() + bad <- d + bad$rows[2] <- 7 + des <- design_multistage("cl", n_clusters = 3, n = 6, size = "rows") + expect_error(draw(bad, des, seed = 1), + "one size for each cluster, but cluster `k1` has 40 and 7", + fixed = TRUE) + expect_error(inclusion_prob(bad, des), "one size for each cluster") + bad$rows <- as.character(d$rows) + expect_error(inclusion_prob(bad, des), "must be numeric", fixed = TRUE) + expect_error(design_multistage("cl", n_clusters = 3, n = 7, size = "rows"), + "Use n = 6 or n = 9.", fixed = TRUE) + expect_error(design_multistage("cl", n_clusters = 3, n = 6, size = "rows", + allocation = "proportional"), + "`allocation` is \"proportional\"", fixed = TRUE) + expect_error(joint_prob(d, des, rows = 1:3), "simulate = TRUE", + fixed = TRUE) + + gap <- d + gap$rows[45] <- NA + expect_error(inclusion_prob(gap, des), + "1 row(s) have a missing size in `rows`", fixed = TRUE) + kept <- design_multistage("cl", n_clusters = 3, n = 6, size = "rows", + na_rm = TRUE) + p <- inclusion_prob(gap, kept) + expect_identical(p[45], 0) + expect_equal(sum(p), 6) +}) + +# ---- weights conditional on the clusters selected ---------------------------- + +test_that("a take that depends on the clusters selected is weighted on them", { + sizes <- c(6, 6, 9, 4, 6) + d <- data.frame(id = seq_len(sum(sizes)), + cl = rep(c("a", "b", "c", "d", "e"), sizes)) + d$y <- (d$id * 7) %% 13 + rep(c(5, 20, 9, 30, 14), sizes) + N_i <- rep(sizes, sizes) + designs <- list( + # A remainder, dealt in the order the clusters were selected when their + # sizes tie. + design_multistage("cl", n_clusters = 2, n = 7), + # Cluster d is smaller than the take of 5, and is taken whole. + design_multistage("cl", n_clusters = 3, n = 15), + design_multistage("cl", n_clusters = 3, n = 10, + allocation = "proportional", min_per_cluster = 1) + ) + for (des in designs) { + expect_error(inclusion_prob(d, des), "no closed-form") + a <- des$n_clusters + for (seed in 1:25) { + s <- draw(d, des, seed = seed, weights = TRUE) + expect_identical(s$id, draw(d, des, seed = seed)$id) + m <- as.vector(table(s$cl)[s$cl]) + expect_equal(s$.prob, a / 5 * m / N_i[s$.row]) + expect_setequal(attr(s, "drawn_selection"), + match(unique(s$cl), unique(d$cl))) + } + r <- ht_total(s, "y") + expect_equal(r$method, "analytic") + expect_equal(r$df, a - 1) + expect_equal(r$total, sum(s$y / s$.prob)) + } +}) + +test_that("conditional weights are unbiased, by enumeration", { + # Every ordered selection of 2 of 4 clusters, then every subset of the + # rows each selected cluster gives. Ties in the allocation are broken by + # the order of selection, so both orders are counted. + sizes <- c(5, 3, 2, 4) + d <- data.frame(cl = rep(1:4, sizes)) + d$y <- c(4, 9, 1, 7, 12, 30, 22, 26, 3, 5, 16, 18, 11, 20) + des <- design_multistage("cl", n_clusters = 2, n = 5, + allocation = "proportional", min_per_cluster = 1) + est <- numeric(0) + for (i in 1:4) for (j in setdiff(1:4, i)) { + p <- drawn:::conditional_inclusion(des, d, c(i, j)) + expect_true(all(is.na(p[!d$cl %in% c(i, j)]))) + # `.prob` is a / A times the chance of a row given the selection. + take <- round(p * 4 / 2 * sizes[d$cl]) + total <- 0 + for (k in c(i, j)) { + rows <- which(d$cl == k) + subsets <- utils::combn(rows, take[rows[1]], simplify = FALSE) + total <- total + mean(vapply(subsets, function(r) sum(d$y[r] / p[r]), + numeric(1))) + } + expect_equal(take[d$cl == i][1] + take[d$cl == j][1], 5) + est <- c(est, total) + } + expect_equal(mean(est), sum(d$y)) +}) + +test_that("conditionally weighted totals are unbiased over repeated draws", { + skip_on_cran() + sizes <- c(4, 9, 12, 5, 20, 7, 15, 6, 10, 8) + d <- data.frame(cl = rep(seq_along(sizes), sizes)) + d$y <- 3 * d$cl + seq_len(nrow(d)) %% 7 + rep(sizes, sizes) + des <- design_multistage("cl", n_clusters = 4, n = 15, + allocation = "proportional", min_per_cluster = 2) + totals <- vapply(1:1000, function(i) { + s <- draw(d, des, seed = i, weights = TRUE) + sum(s$y * s$.weight) + }, numeric(1)) + expect_lt(abs(mean(totals) - sum(d$y)), 3 * stats::sd(totals) / sqrt(1000)) +}) + +test_that("proportional weights need a row from every selected cluster", { + d <- data.frame(id = 1:31, cl = c("tiny", rep("big", 30)), y = 1:31) + des <- design_multistage("cl", n_clusters = 2, n = 10, + allocation = "proportional") + expect_error(draw(d, des, seed = 1, weights = TRUE), + "`min_per_cluster` is 0, so proportional allocation can give", + fixed = TRUE) + s <- draw(d, design_multistage("cl", n_clusters = 2, n = 10, + allocation = "proportional", + min_per_cluster = 1), seed = 1, + weights = TRUE) + expect_equal(as.vector(table(s$cl)[c("big", "tiny")]), c(9L, 1L)) + # Both clusters selected: no variance between them, and the one taken + # whole adds none within. + r <- ht_total(s, "y") + big <- s$y[s$cl == "big"] + expect_equal(r$variance, 30^2 * (1 - 9 / 30) * stats::var(big) / 9) +}) + +test_that("one row from a selected cluster of several falls back", { + sizes <- c(2, 20, 20, 20) + d <- data.frame(cl = rep(c("s", "x", "y", "z"), sizes)) + d$y <- seq_len(nrow(d)) %% 11 + des <- design_multistage("cl", n_clusters = 2, n = 8, + allocation = "proportional", min_per_cluster = 1) + seed <- which(vapply(1:40, function(i) { + "s" %in% draw(d, des, seed = i)$cl + }, logical(1)))[1] + s <- draw(d, des, seed = seed, weights = TRUE) + expect_equal(sum(s$cl == "s"), 1L) + r <- ht_total(s, "y") + expect_equal(r$method, "jackknife") + expect_match(r$note, "one row from a selected cluster of several") +}) + +test_that("a conditional sample keeps the clusters it was drawn from", { + sizes <- c(6, 6, 9, 4, 6) + d <- data.frame(id = seq_len(sum(sizes)), + cl = rep(c("a", "b", "c", "d", "e"), sizes)) + d$y <- d$id %% 5 + s <- draw(d, design_multistage("cl", n_clusters = 3, n = 13), seed = 2, + weights = TRUE) + expect_s3_class(ht_total(s, "y"), "drawn_ht") + expect_s3_class(ht_mean(s[rev(seq_len(nrow(s))), ], "y"), "drawn_mean") + expect_equal(sample_summary(s)$unreachable, 0L) + + lost <- s + attr(lost, "drawn_selection") <- NULL + expect_error(ht_total(lost, "y"), + "does not record which clusters were selected") + bad <- s + attr(bad, "drawn_selection") <- c(1L, 1L, 2L) + expect_error(ht_total(bad, "y"), "not 3 distinct clusters of the 5") + other <- s + sel <- attr(s, "drawn_selection") + attr(other, "drawn_selection") <- c(setdiff(1:5, sel)[1], sel[-1]) + expect_error(ht_total(other, "y"), "different inclusion probability") + edited <- s + edited$.prob[1] <- edited$.prob[1] / 2 + expect_error(ht_total(edited, "y"), "differ from the inclusion probabilities") +}) diff --git a/tests/testthat/test-design-reservoir.R b/tests/testthat/test-design-reservoir.R index 4a66d8b..9130c4d 100644 --- a/tests/testthat/test-design-reservoir.R +++ b/tests/testthat/test-design-reservoir.R @@ -41,7 +41,26 @@ test_that("max_items warns when it truncates", { expect_warning(draw(data.frame(x = 1:100), design_reservoir(n = 5, max_items = 20), seed = 1), - "below the 100 available rows") + "below the 100 available rows", class = "drawn_stream_truncated") +}) + +test_that("a simulation over a truncated frame warns once, with the count", { + d <- data.frame(x = 1:100) + des <- design_reservoir(n = 5, max_items = 20) + caught <- list() + p <- withCallingHandlers( + inclusion_prob(d, des, simulate = TRUE, R = 300, seed = 1), + warning = function(w) { + caught[[length(caught) + 1L]] <<- w + invokeRestart("muffleWarning") + }) + expect_length(caught, 1L) + expect_s3_class(caught[[1L]], "drawn_stream_truncated") + expect_match(conditionMessage(caught[[1L]]), + "only the first 20. This happened in 300 of the 300 simulated draws.", + fixed = TRUE) + expect_lt(max(abs(p[1:20] - 0.25)), 0.08) + expect_true(all(p[21:100] == 0)) }) test_that("max_items is validated", { @@ -55,7 +74,7 @@ test_that("an unsupported stream type is reported clearly", { }) test_that("the sample is uniform over the stream", { - set.seed(4) + local_seed(4) counts <- integer(20) for (i in 1:4000) { drawn <- unlist(draw(as.list(1:20), design_reservoir(n = 5))) @@ -87,3 +106,308 @@ test_that("a stream of exactly max_items is not reported as truncated", { expect_warning(draw(make_gen(9), design_reservoir(n = 3, max_items = 5), seed = 1), "may have held more") }) + +make_counter <- function(k) { + i <- 0L + function() { + i <<- i + 1L + if (i > k) NULL else i + } +} + +test_that("a NULL element of a list is an item, not the end of the stream", { + expect_identical(draw(list(1, NULL, 3, 4, 5), design_reservoir(n = 10), + seed = 1), + list(1, NULL, 3, 4, 5)) + + recs <- list(a = "a", b = NULL, c = "c", d = "d", e = "e", f = "f") + seen <- unlist(lapply(1:200, function(s) { + names(draw(recs, design_reservoir(n = 2), seed = s)) + })) + expect_true(all(table(factor(seen, letters[1:6])) > 40)) +}) + +test_that("a list is sampled by position, as a data frame is", { + expect_identical( + unlist(draw(as.list(1:50), design_reservoir(n = 5), seed = 9)), + draw(data.frame(x = 1:50), design_reservoir(n = 5), seed = 9)$x + ) +}) + +test_that("the stream counter is a double, which does not overflow at 2^31", { + local_seed(1) + out <- reservoir_stream(make_counter(10), n = 2, max_items = Inf) + expect_type(out$count, "double") + expect_equal(out$count, 10) +}) + +test_that("a stream's items come back in the order they arrived", { + for (s in 1:5) { + got <- unlist(draw(make_counter(500), design_reservoir(n = 20), seed = s)) + expect_length(got, 20) + expect_false(is.unsorted(got, strictly = TRUE)) + } +}) + +test_that("growing the reservoir keeps the items Algorithm L keeps", { + # The reservoir set aside all n slots at the start. Growing it as the stream + # fills it, and returning items in arrival order, must not change which + # items are kept for a seed. + algorithm_l <- function(items, n) { + res <- vector("list", n) + w <- exp(log(stats::runif(1)) / n) + nxt <- n + floor(log(stats::runif(1)) / log(1 - w)) + 1 + for (k in seq_along(items)) { + if (k <= n) { + res[[k]] <- items[[k]] + } else if (k == nxt) { + res[[sample.int(n, 1L)]] <- items[[k]] + w <- w * exp(log(stats::runif(1)) / n) + nxt <- nxt + floor(log(stats::runif(1)) / log(1 - w)) + 1 + } + } + unlist(res[seq_len(min(n, length(items)))]) + } + for (case in list(c(n = 3, N = 100), c(n = 1500, N = 4000), + c(n = 2000, N = 1800))) { + got <- unlist(draw(make_counter(case[["N"]]), + design_reservoir(n = case[["n"]]), seed = 2)) + ref <- with_seed(2, algorithm_l(seq_len(case[["N"]]), case[["n"]])) + expect_identical(got, sort(ref)) + } +}) + +test_that("a large n costs no memory for a short stream", { + skip_on_cran() + # All n slots were set aside before the first item was read, so n = 2e7 + # took 150 MB for a stream of five items. + # The last column of gc() is the peak in Mb. macOS sets a memory limit by + # default, which adds a column, so the peak is not always the sixth. + peak_mb <- function(g) g[2, ncol(g)] + before <- peak_mb(gc(reset = TRUE)) + got <- draw(make_counter(5), design_reservoir(n = 2e7), seed = 1) + expect_lt(peak_mb(gc()) - before, 50) + expect_identical(unlist(got), 1:5) +}) + +test_that("a header read off an open connection is left out of the sample", { + tf <- tempfile(fileext = ".csv") + on.exit(unlink(tf), add = TRUE) + pop <- data.frame(id = 1:5, v = letters[1:5]) + utils::write.csv(pop, tf, row.names = FALSE) + + # Every line is an item, the header included. + got <- unlist(draw(file(tf), design_reservoir(n = 10), seed = 1)) + expect_identical(got, readLines(tf)) + + con <- file(tf, "r") + on.exit(close(con), add = TRUE, after = FALSE) + header <- readLines(con, n = 1) + lines <- draw(con, design_reservoir(n = 10), seed = 1) + expect_length(lines, 5) + expect_identical(utils::read.csv(text = c(header, unlist(lines))), pop) +}) + +test_that("a connection read in blocks gives the line-by-line sample", { + tf <- tempfile() + on.exit(unlink(tf), add = TRUE) + writeLines(as.character(1:25000), tf) + line_by_line <- function(con) { + function() { + line <- readLines(con, n = 1L) + if (length(line) == 0L) NULL else line + } + } + # 25,000 lines span three blocks of 10,000. + for (n in c(3, 1500)) { + con <- file(tf, "r") + one <- draw(line_by_line(con), design_reservoir(n = n), seed = 4) + close(con) + expect_identical(draw(file(tf), design_reservoir(n = n), seed = 4), one) + } + + # Blocks of 7 lines put swaps at every position within a block, and a cap + # partway through one. + for (cap in c(Inf, 100)) { + con <- file(tf, "r") + got <- with_seed(8, reservoir_blocks(as_stream(con, block = 7L)$read, + n = 20, max_items = cap)) + close(con) + ref <- with_seed(8, reservoir_stream(make_counter(25000), n = 20, + max_items = cap)) + expect_identical(as.integer(unlist(got$items)), unlist(ref$items)) + expect_identical(got$truncated, is.finite(cap)) + } +}) + +test_that("the line read past max_items goes back onto an open connection", { + tf <- tempfile() + on.exit(unlink(tf), add = TRUE) + writeLines(as.character(1:20), tf) + + con <- file(tf, "r") + on.exit(close(con), add = TRUE, after = FALSE) + expect_warning(got <- draw(con, design_reservoir(n = 3, max_items = 5), + seed = 1), "may have held more") + expect_true(all(unlist(got) %in% as.character(1:5))) + # Line 6 was read to see that the stream held more, and pushed back. + expect_identical(readLines(con, n = 1), "6") + expect_silent(draw(con, design_reservoir(n = 3, max_items = 14), seed = 1)) + expect_identical(readLines(con), character(0)) + + # A connection in binary mode cannot take a line back, so it loses it. + bin <- file(tf, "rb") + on.exit(close(bin), add = TRUE, after = FALSE) + expect_warning(draw(bin, design_reservoir(n = 3, max_items = 5), seed = 1), + "may have held more") + expect_identical(readLines(bin, n = 1), "7") +}) + +test_that("a block ending exactly at max_items gives its next line back", { + tf <- tempfile() + on.exit(unlink(tf), add = TRUE) + writeLines(as.character(1:10005), tf) + + # The first block of 10,000 lines ends at the cap, so the line read past it + # is a block of its own, none of whose lines is within the cap. + con <- file(tf, "r") + on.exit(close(con), add = TRUE, after = FALSE) + expect_warning(draw(con, design_reservoir(n = 3, max_items = 10000), + seed = 1), "may have held more") + expect_identical(readLines(con, n = 1), "10001") + + tc <- textConnection(as.character(1:30)) + on.exit(close(tc), add = TRUE, after = FALSE) + stream <- as_stream(tc, block = 7L) + got <- with_seed(1, reservoir_blocks(stream$read, n = 3, max_items = 14, + give_back = stream$give_back)) + expect_true(got$truncated) + expect_identical(readLines(tc, n = 1), "15") +}) + +# A generator that returns its arguments one per call, then NULL. +calls <- function(...) { + out <- list(...) + i <- 0L + function() { + i <<- i + 1L + if (i > length(out)) NULL else out[[i]] + } +} + +batches_of <- function(pop, size) { + start <- 0L + function() { + if (start >= nrow(pop)) return(NULL) + rows <- start + seq_len(min(size, nrow(pop) - start)) + start <<- start + size + pop[rows, , drop = FALSE] + } +} + +test_that("batches = TRUE samples rows across a generator's data frames", { + pop <- data.frame(id = 1:103, g = rep(c("a", "b"), length.out = 103)) + des <- design_reservoir(n = 8, batches = TRUE) + got <- draw(batches_of(pop, 10), des, seed = 3) + expect_identical(got, reindex(pop, got$id)) + expect_equal(nrow(got), 8) + expect_false(is.unsorted(got$id, strictly = TRUE)) + + # The rows are the items, so the sample is the one a stream of the row + # numbers gives, however the rows are cut into batches. + expect_identical(got$id, unlist(draw(make_counter(103), + design_reservoir(n = 8), seed = 3))) + for (size in c(1, 7, 103, 500)) { + expect_identical(draw(batches_of(pop, size), des, seed = 3), got) + } + + # Without it, each data frame is one item. + whole <- draw(batches_of(pop, 10), design_reservoir(n = 3), seed = 3) + expect_type(whole, "list") + expect_true(all(vapply(whole, nrow, integer(1)) %in% c(10L, 3L))) +}) + +test_that("batches = TRUE gives every row the same chance", { + skip_on_cran() + pop <- data.frame(id = 1:30) + des <- design_reservoir(n = 5, batches = TRUE) + counts <- integer(30) + for (s in 1:1000) { + got <- draw(batches_of(pop, 7), des, seed = s)$id + counts[got] <- counts[got] + 1L + } + expect_equal(sum(counts), 5000) + expect_gt(stats::chisq.test(counts)$p.value, 0.001) +}) + +test_that("max_items counts rows under batches = TRUE", { + pop <- data.frame(id = 1:103) + expect_warning( + got <- draw(batches_of(pop, 10), + design_reservoir(n = 4, max_items = 25, batches = TRUE), + seed = 2), + "may have held more" + ) + ref <- suppressWarnings(draw(make_counter(103), + design_reservoir(n = 4, max_items = 25), + seed = 2)) + expect_identical(got$id, unlist(ref)) + expect_silent(draw(batches_of(pop, 10), + design_reservoir(n = 4, max_items = 103, batches = TRUE), + seed = 2)) +}) + +test_that("batches = TRUE keeps the batches' class and columns", { + pop <- data.frame(id = 1:40, f = factor(rep(c("x", "y"), 20))) + # Empty batches are skipped, and a stream of nothing else keeps the columns. + empty <- calls(pop[0, ], pop[0, ]) + expect_identical(draw(empty, design_reservoir(n = 3, batches = TRUE), + seed = 1), + pop[0, ]) + expect_identical(draw(function() NULL, + design_reservoir(n = 3, batches = TRUE), seed = 1), + data.frame()) + + skip_if_not_installed("tibble") + got <- draw(batches_of(tibble::as_tibble(pop), 6), + design_reservoir(n = 5, batches = TRUE), seed = 1) + expect_s3_class(got, "tbl_df") + expect_identical(levels(got$f), c("x", "y")) + + skip_if_not_installed("data.table") + env <- new.env(parent = globalenv()) + env$s <- draw(batches_of(data.table::as.data.table(pop), 6), + design_reservoir(n = 5, batches = TRUE), seed = 1) + expect_s3_class(env$s, "data.table") + expect_no_warning(evalq(s[, twice := id * 2L], env)) +}) + +test_that("batches = TRUE refuses what is not a batch of rows", { + local_seed(2) + expect_error(design_reservoir(n = 3, batches = NA), "`batches` must be") + des <- design_reservoir(n = 3, batches = TRUE) + expect_error(draw(list(data.frame(id = 1)), des), "`data` is a list") + + tf <- tempfile() + on.exit(unlink(tf), add = TRUE) + writeLines(as.character(1:5), tf) + con <- file(tf) + on.exit(close(con), add = TRUE, after = FALSE) + expect_error(draw(con, des), "`data` is a connection") + + pop <- data.frame(id = 1:3, v = 4:6) + expect_error(draw(calls(pop, as.matrix(pop)), des), + "returned a matrix on call 2") + expect_error(draw(calls(pop, 1:3), des), + "returned an integer on call 2", fixed = TRUE) + expect_error(draw(calls(pop, cbind(pop, z = 1)), des), + "Batch 2 from `data` adds `z`") + expect_error(draw(calls(pop, pop[2:1]), des), + "Batch 2 from `data` has the columns `v`, `id`") +}) + +test_that("a stream of the wrong kind is named with its article", { + expect_error(draw(1:10, design_reservoir(n = 2)), + "zero-argument function for a reservoir design, not an integer.", + fixed = TRUE) +}) diff --git a/tests/testthat/test-design-simple.R b/tests/testthat/test-design-simple.R index d4e0032..31049cc 100644 --- a/tests/testthat/test-design-simple.R +++ b/tests/testthat/test-design-simple.R @@ -36,3 +36,177 @@ test_that("a tibble comes back a tibble", { tb <- tibble::as_tibble(make_df()) expect_s3_class(draw(tb, design_simple(n = 3), seed = 1), "tbl_df") }) + +# ---- reserves ----------------------------------------------------------------- + +test_that("reserve is validated at construction time", { + expect_equal(design_simple(n = 5)$reserve, 0L) + expect_equal(design_simple(n = 5, reserve = 3)$reserve, 3L) + expect_error(design_simple(n = 5, reserve = -1), "must be non-negative") + expect_error(design_simple(n = 5, reserve = 1.5), "single whole number") + expect_error(design_simple(n = 5, replace = TRUE, reserve = 2), + "replace = FALSE with `reserve`") + expect_error(design_simple(n = 0, reserve = 3), + "`reserve` is 3 and `n` is 0, so there is no main sample") + expect_equal(design_simple(n = 0)$reserve, 0L) + expect_error(design_certainty("value", 1, rest = design_simple(5, reserve = 2)), + "Leave `reserve` out of `rest`") + df <- make_df() + expect_error(draw(df, design_simple(n = 95, reserve = 6)), + "`n` and `reserve` together \\(101\\) cannot exceed") + expect_error(inclusion_prob(df, design_simple(n = 95, reserve = 6)), + "`n` and `reserve` together") +}) + +test_that("a list holds the main sample, then reserves disjoint from it", { + df <- make_df() + des <- design_simple(n = 10, reserve = 4) + s <- draw(df, des, seed = 7) + expect_equal(names(s), c(".reserve", names(df))) + expect_identical(s$.reserve, c(integer(10), 1:4)) + expect_false(anyDuplicated(s$id) > 0) + # The main sample is the one the design without reserves draws. + expect_identical(s$id[1:10], draw(df, design_simple(n = 10), seed = 7)$id) + + w <- draw(df, des, seed = 7, weights = TRUE) + expect_equal(names(w)[1:5], c(".prob", ".weight", ".row", ".reserve", "id")) + expect_equal(w$.prob, rep(0.1, 14)) + expect_equal(inclusion_prob(df, des), rep(0.1, 100)) + expect_equal(attr(w, "drawn_rows"), w$.row) + + clash <- df + clash$.reserve <- 1 + expect_error(draw(clash, des, seed = 1), + "already has a column called `.reserve`") + expect_equal(nrow(draw(clash, design_simple(n = 3), seed = 1)), 3L) +}) + +test_that("estimates refuse a list until its reserves are resolved", { + df <- make_df() + s <- draw(df, design_simple(n = 10, reserve = 4), seed = 1, weights = TRUE) + expect_error(ht_total(s, "value"), "use_reserves\\(\\)") + expect_error(ht_mean(s, "value"), "not yet a sample to estimate from") + expect_error(sample_summary(s), "use_reserves\\(\\)") + skip_if_not_installed("survey") + expect_error(as_svydesign(s), "use_reserves\\(\\)") +}) + +test_that("use_reserves() takes the first available reserves, in order", { + df <- make_df() + s <- draw(df, design_simple(n = 10, reserve = 5), seed = 3, weights = TRUE) + # Units 2 and 6 of the main sample are out of reach, and so is reserve 1; + # reserves 2 and 3 replace them, and 4 and 5 are never visited. + gone <- s$id[c(2, 6, 11)] + found <- ifelse(s$.reserve <= 3, s$id %in% gone, NA) + u <- use_reserves(s, found) + expect_equal(nrow(u), 10L) + expect_equal(u$.reserve, c(integer(8), 2L, 3L)) + expect_equal(u$id, s$id[c(1, 3:5, 7:10, 12, 13)]) + expect_equal(u$.prob, rep(10 / 97, 10)) + expect_equal(u$.weight, 1 / u$.prob) + + des <- attr(u, "drawn_design") + expect_equal(des$reserve, 0L) + expect_equal(des$unavailable, sort(s$.row[c(2, 6, 11)])) + p <- inclusion_prob(df, des) + expect_equal(p[gone], c(0, 0, 0)) + expect_equal(sum(p), 10) + + # A simple random sample of 10 from the 97 rows left. + r <- ht_total(u, "value") + expect_equal(r$se, 97 * sqrt((1 - 10 / 97) * stats::var(u$value) / 10)) + expect_equal(r$unreachable, 3L) + expect_equal(r$unavailable, 3L) + expect_output(print(r), paste0("unreachable 3 frame rows at probability ", + "0, not covered by this estimate\n +\\(3 ", + "found unavailable; rows not visited are ", + "taken as available\\)")) + expect_equal(attr(ht_mean(u, "value", by = "site"), "unavailable"), 3L) + expect_null(ht_total(draw(df, design_simple(n = 10), seed = 1, + weights = TRUE), "value")$unavailable) + expect_equal(sample_summary(u)$N_reachable, 97L) + expect_equal(ht_mean(u, "value")$mean, mean(u$value)) + skip_if_not_installed("survey") + svd <- as_svydesign(u) + expect_equal(as.numeric(survey::SE(survey::svytotal(~value, svd))), r$se) +}) + +test_that("use_reserves() reads a column, keeps the frame copy compact", { + df <- make_df() + s <- draw(df, design_simple(n = 6, reserve = 3), seed = 2, weights = TRUE) + field <- data.frame(id = s$id, gone = c(TRUE, rep(FALSE, 6), NA, NA)) + s <- add_fieldwork(s, field, by = "id") + u <- use_reserves(s, "gone") + expect_equal(u$id, s$id[c(2:7)]) + small <- use_reserves(compact_sample(s), "gone") + expect_false(is.null(attr(small, "drawn_compact"))) + expect_equal(ht_total(small, "value")$se, ht_total(u, "value")$se) + + # A reordered list is matched through `.row`. + shuffled <- s[rev(seq_len(nrow(s))), ] + expect_equal(sort(use_reserves(shuffled, "gone")$id), sort(u$id)) +}) + +test_that("use_reserves() refuses findings it cannot place", { + df <- make_df() + s <- draw(df, design_simple(n = 6, reserve = 3), seed = 2, weights = TRUE) + expect_error(use_reserves(s, rep(NA, 9)), + "missing for 6 unit\\(s\\) of the main sample") + expect_error(use_reserves(s, c(TRUE, rep(FALSE, 5), NA, NA, NA)), + "missing for reserve 1, at frame row") + expect_error(use_reserves(s, 1:9), "must be a logical vector") + expect_error(use_reserves(s, logical(4)), "one value for each of the 9") + expect_error(use_reserves(s, "nope"), "no column `nope`") + expect_error(use_reserves(s, rep(TRUE, 9)), "Every unit `sample` lists") + expect_error(use_reserves(s[1:6, ], logical(6)), "6 of the 9 rows") + edited <- s + edited$.reserve <- rev(edited$.reserve) + expect_error(use_reserves(edited, logical(9)), "`.reserve` was changed") + plain <- draw(df, design_simple(n = 6), seed = 2, weights = TRUE) + expect_error(use_reserves(plain, logical(6)), "lists no reserves") +}) + +test_that("use_reserves() warns when the reserves run out", { + df <- make_df() + s <- draw(df, design_simple(n = 6, reserve = 2), seed = 2, weights = TRUE) + found <- c(TRUE, TRUE, TRUE, rep(FALSE, 3), TRUE, FALSE) + expect_warning(u <- use_reserves(s, found), class = "drawn_reserves_short") + expect_equal(nrow(u), 4L) + expect_equal(u$.prob, rep(4 / 96, 4)) +}) + +test_that("a list read back from a file is rebuilt whole", { + df <- make_df() + des <- design_simple(n = 6, reserve = 3) + s <- draw(df, des, seed = 5, weights = TRUE) + back <- as.data.frame(s) + attributes(back) <- attributes(back)[c("names", "row.names", "class")] + back <- back[c(9, 1:8), ] + rebuilt <- as_drawn(back, des, df) + expect_equal(attr(rebuilt, "drawn_rows"), s$.row) + # The reserve order comes from `.reserve`, not from the rows' order. + u <- use_reserves(rebuilt, rebuilt$id == s$id[1]) + expect_equal(u$id, s$id[c(2:6, 7)]) + expect_equal(ht_total(u, "value")$se, + ht_total(use_reserves(s, s$id == s$id[1]), "value")$se) + expect_error(as_drawn(back[1:6, ], des, df), "Rebuild the whole list") + back$.reserve <- NULL + expect_error(as_drawn(back, des, df), "no `.reserve` column") +}) + +test_that("the first n available units of a list are a simple random sample", { + # Rows 1 to 10 cannot be reached. Each of the other 30 is used with + # probability 8 / 30, whichever units were visited. + pop <- data.frame(id = 1:40) + hits <- integer(40) + for (i in 1:1000) { + s <- draw(pop, design_simple(n = 8, reserve = 12), seed = i, + weights = TRUE) + u <- use_reserves(s, s$id <= 10) + hits[u$.row] <- hits[u$.row] + 1L + } + p <- hits / 1000 + expect_equal(p[1:10], rep(0, 10)) + z <- (p[11:40] - 8 / 30) / sqrt(8 / 30 * 22 / 30 / 1000) + expect_lt(max(abs(z)), 4.5) +}) diff --git a/tests/testthat/test-design-spatial.R b/tests/testthat/test-design-spatial.R index b1496a6..a4a1058 100644 --- a/tests/testthat/test-design-spatial.R +++ b/tests/testthat/test-design-spatial.R @@ -6,10 +6,15 @@ test_that("samples rows inside the region", { expect_same_schema(res, df) }) -test_that("coords must name exactly two columns", { - expect_error(design_spatial("lon", region = NULL, n = 5), "exactly two columns") +test_that("coords must name two columns or one POINT geometry column", { expect_error(design_spatial(c("a", "b", "c"), region = NULL, n = 5), "exactly two columns") + # One name is a geometry column or nothing, which only the frame can say. + skip_if_not_installed("sf") + df <- make_df() + expect_error(draw(df, design_spatial("lon", wide_poly(), n = 5)), + "two coordinate columns, c(x, y) -- longitude then latitude -- or one POINT geometry column, not `lon`.", + fixed = TRUE) }) test_that("a region containing no rows is reported clearly", { @@ -25,7 +30,7 @@ test_that("a region containing no rows is reported clearly", { test_that("a list of geometries is unioned, whatever its length", { skip_if_not_installed("sf") - set.seed(7) + local_seed(7) df <- data.frame( id = 1:60, lon = c(stats::runif(20, 1, 9), stats::runif(20, 21, 29), @@ -79,3 +84,343 @@ test_that("over-drawing the region is refused", { seed = 1), "exceeds the") }) + +test_that("a sample is refused once sf_use_s2() differs from the draw", { + skip_if_not_installed("sf") + # Under spherical geometry the region's top edge, from -80 to 80 degrees of + # longitude at latitude 60, is a great circle that bows north past the rows + # at latitude 65 and 70. Under planar geometry those rows are outside. + bowing <- sf::st_sfc(sf::st_polygon(list(cbind(c(-80, 80, 80, -80, -80), + c(-60, -60, 60, 60, -60)))), + crs = 4326) + grid <- expand.grid(lon = seq(-70, 70, by = 10), + lat = c(-50, -20, 0, 20, 50, 65, 70)) + grid$y <- seq_len(nrow(grid)) %% 7 + grid$lat / 10 + des <- design_spatial(c("lon", "lat"), bowing, n = 20) + with_s2 <- function(value, code) { + old <- suppressMessages(sf::sf_use_s2(value)) + on.exit(suppressMessages(sf::sf_use_s2(old))) + suppressMessages(code) + } + + s <- with_s2(FALSE, draw(grid, des, seed = 1, weights = TRUE)) + expect_equal(unique(s$.prob), 20 / 75) + planar <- with_s2(FALSE, ht_total(s, "y")) + expect_error(with_s2(TRUE, ht_total(s, "y")), + "gives 105 of its 105 frame rows a different inclusion probability", + fixed = TRUE) + expect_error(with_s2(TRUE, ht_mean(s, "y")), + "sf::sf_use_s2() decides which rows of a spatial design fall", + fixed = TRUE) + expect_error(with_s2(TRUE, sample_summary(s)), "it is TRUE now", fixed = TRUE) + # Back under the setting it was drawn with, nothing has changed. + expect_equal(with_s2(FALSE, ht_total(s, "y"))$se, planar$se) + + # A sample saved by drawn 0.2.0 has no `.row` and no `drawn_pi`, but its + # `.prob` shows the same change. + old <- s + old$.row <- NULL + attr(old, "drawn_pi") <- NULL + expect_error(with_s2(TRUE, ht_total(old, "y")), + "gives 20 of its 20 rows a different inclusion probability", + fixed = TRUE) + expect_error(with_s2(TRUE, sample_summary(old)), + "in a session with the same version of sf", fixed = TRUE) + expect_equal(with_s2(FALSE, ht_total(old, "y"))$se, planar$se) + + skip_if_not_installed("survey") + expect_error(with_s2(TRUE, as_svydesign(s)), "sf_use_s2", fixed = TRUE) + expect_error(with_s2(TRUE, as_svydesign(old)), "sf_use_s2", fixed = TRUE) +}) + +test_that("a design that stops under another sf_use_s2() names the setting", { + skip_if_not_installed("sf") + # Under planar geometry this box spans longitudes -179 to 179. Under + # spherical geometry it is the 2-degree strip across the antimeridian, + # which holds 2 of the rows, fewer than `n`, so the design stops before + # any probability can be compared. + box <- sf::st_sfc(sf::st_polygon(list(cbind(c(-179, 179, 179, -179, -179), + c(-60, -60, 60, 60, -60)))), + crs = 4326) + grid <- expand.grid(lon = c(seq(-170, 170, by = 10), -179.5, 179.5), + lat = c(-40, 0, 40)) + grid <- grid[grid$lat == 0 | abs(grid$lon) < 179, ] + grid$y <- seq_len(nrow(grid)) %% 5 + grid$lat / 10 + des <- design_spatial(c("lon", "lat"), box, n = 20) + with_s2 <- function(value, code) { + old <- suppressMessages(sf::sf_use_s2(value)) + on.exit(suppressMessages(sf::sf_use_s2(old))) + suppressMessages(code) + } + expect_warning( + expect_error(with_s2(TRUE, inclusion_prob(grid, des)), + "`n` (20) exceeds the 2 row(s) inside `region`.", + fixed = TRUE), + class = "drawn_antimeridian") + + s <- with_s2(FALSE, draw(grid, des, seed = 1, weights = TRUE)) + old <- s + old$.row <- NULL + attr(old, "drawn_pi") <- NULL + planar <- with_s2(FALSE, ht_total(s, "y")) + for (x in list(s, old)) { + expect_error(with_s2(TRUE, ht_total(x, "y")), paste0( + "different inclusion probabilities in this session or this version of ", + "drawn than when the sample was drawn. Applied to the stored frame now, ", + "the design stops with the error \"`n` (20) exceeds the 2 row(s) ", + "inside `region`.\""), fixed = TRUE) + expect_error(with_s2(TRUE, ht_mean(x, "y")), "sf_use_s2", fixed = TRUE) + expect_error(with_s2(TRUE, sample_summary(x)), "it is TRUE now", + fixed = TRUE) + expect_equal(with_s2(FALSE, ht_total(x, "y"))$se, planar$se) + } + skip_if_not_installed("survey") + expect_error(with_s2(TRUE, as_svydesign(s)), "sf_use_s2", fixed = TRUE) + expect_error(with_s2(TRUE, as_svydesign(old)), "sf_use_s2", fixed = TRUE) +}) + +# ---- region checks, edges and coordinates ------------------------------------- + +lonlat_box <- function(lon, lat, crs = 4326) { + sf::st_sfc(sf::st_polygon(list(cbind(lon[c(1, 2, 2, 1, 1)], + lat[c(1, 1, 2, 2, 1)]))), crs = crs) +} + +test_that("a list region in mixed CRSs is reprojected member by member", { + skip_if_not_installed("sf") + # c() refuses geometries in different CRSs, which came back as "`region` + # must be an sf or sfc geometry, or a list of them, not list". + df <- data.frame(id = 1:40, lon = seq(1, 39, length.out = 40), lat = 5) + a <- lonlat_box(c(0, 10), c(0, 10)) + b <- lonlat_box(c(20, 30), c(0, 10)) + mixed <- design_spatial(c("lon", "lat"), list(a, sf::st_transform(b, 3857)), + n = 4) + same <- design_spatial(c("lon", "lat"), list(a, b), n = 4) + expect_equal(inclusion_prob(df, mixed), inclusion_prob(df, same)) + expect_equal(sum(inclusion_prob(df, mixed) > 0), 20L) + expect_error(design_spatial(c("lon", "lat"), + list(a, sf::st_set_crs(b, NA)), n = 4), + "`region[[2]]` has no CRS", fixed = TRUE) + expect_error(design_spatial(c("lon", "lat"), list(a, "b"), n = 4), + "`region[[2]]` must be an sf or sfc geometry, not character.", + fixed = TRUE) + expect_error(design_spatial(c("lon", "lat"), list(), n = 4), + "`region` is an empty list.", fixed = TRUE) +}) + +test_that("a region that encloses no area is refused", { + skip_if_not_installed("sf") + line <- sf::st_sfc(sf::st_linestring(rbind(c(0, 0), c(10, 10))), crs = 4326) + expect_error(design_spatial(c("lon", "lat"), line, n = 1), + "`region` must be POLYGON or MULTIPOLYGON geometry, not LINESTRING.", + fixed = TRUE) + expect_error(design_spatial(c("lon", "lat"), + sf::st_sfc(sf::st_point(c(0, 0)), crs = 4326), + n = 1), + "not POINT. A point or a line encloses no area", fixed = TRUE) + coll <- sf::st_sfc(sf::st_geometrycollection(list( + sf::st_polygon(list(cbind(c(0, 1, 1, 0, 0), c(0, 0, 1, 1, 0)))))), + crs = 4326) + expect_error(design_spatial(c("lon", "lat"), coll, n = 1), + "sf::st_collection_extract", fixed = TRUE) + expect_error(design_spatial(c("lon", "lat"), + list(lonlat_box(c(0, 1), c(0, 1)), line), n = 1), + "`region[[2]]` must be POLYGON or MULTIPOLYGON", fixed = TRUE) +}) + +test_that("coordinates outside longitude/latitude range are refused", { + skip_if_not_installed("sf") + box <- lonlat_box(c(-102, -99), c(39, 42)) + # Latitude and longitude the wrong way round + swapped <- data.frame(lat = c(40, 41), lon = c(-100, -101)) + des <- design_spatial(c("lat", "lon"), box, n = 1) + expect_error(draw(swapped, des, seed = 1), + "`lon` holds -101, outside -90 to 90, the range of a latitude", + fixed = TRUE) + expect_error(inclusion_prob(swapped, des), "(lat, lon) order, swap them", + fixed = TRUE) + expect_error(draw(data.frame(lon = c(10, 20), lat = c(95, 5)), + design_spatial(c("lon", "lat"), box, n = 1)), + "`lat` holds 95", fixed = TRUE) + # Projected coordinates under the default crs + expect_error(inclusion_prob(data.frame(lon = 512000, lat = 40), + design_spatial(c("lon", "lat"), box, n = 1)), + "`lon` holds 512,000, outside -180 to 360", fixed = TRUE) + # Longitudes from 0 to 360 are longitudes, and s2 wraps them + east <- data.frame(lon = c(259, 200), lat = c(40, 40)) + expect_equal(inclusion_prob(east, design_spatial(c("lon", "lat"), box, + n = 1)), + c(1, 0)) + # A projected crs is not range-checked + proj <- design_spatial(c("x", "y"), lonlat_box(c(0, 1e6), c(0, 1e6), 3857), + n = 1, crs = 3857) + expect_equal(inclusion_prob(data.frame(x = 5e5, y = 5e5), proj), 1) +}) + +test_that("an edge that bows far from its straight line warns on every path", { + skip_if_not_installed("sf") + # The top edge, at latitude 30 from -50 to 50, follows a great circle that + # reaches latitude 41.9 at longitude 0, so rows up to there are inside. + box <- lonlat_box(c(-50, 50), c(-30, 30)) + pts <- data.frame(id = 1:4, lon = 0, lat = c(29, 35, 41, 43)) + des <- design_spatial(c("lon", "lat"), box, n = 2) + expect_warning(p <- inclusion_prob(pts, des), + class = "drawn_geodesic_edges") + expect_equal(p, c(2 / 3, 2 / 3, 2 / 3, 0)) + expect_warning(inclusion_prob(pts, des), "passes 11.9 degrees", + fixed = TRUE) + expect_warning(joint_prob(pts, des), class = "drawn_geodesic_edges") + expect_warning(draw(pts, des, seed = 1), class = "drawn_geodesic_edges") + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + expect_warning(plot(des, pts, type = "probability"), + class = "drawn_geodesic_edges") + expect_warning(plot(des, pts, type = "map", seed = 1), + class = "drawn_geodesic_edges") + # Once per call, not once per simulated draw + caught <- 0L + withCallingHandlers( + inclusion_prob(pts, des, simulate = TRUE, R = 20, seed = 1), + drawn_geodesic_edges = function(w) { + caught <<- caught + 1L + invokeRestart("muffleWarning") + }) + expect_identical(caught, 1L) + + # The documented recipe: vertices every 0.1 degrees in degree space + flat <- sf::st_set_crs(sf::st_segmentize(sf::st_set_crs(box, NA), 0.1), 4326) + straight <- design_spatial(c("lon", "lat"), flat, n = 1) + expect_silent(p <- inclusion_prob(pts, straight)) + expect_equal(p, c(1, 0, 0, 0)) + + # Planar geometry draws the edges straight + old <- suppressMessages(sf::sf_use_s2(FALSE)) + on.exit(suppressMessages(sf::sf_use_s2(old)), add = TRUE) + expect_silent(p <- suppressMessages( + inclusion_prob(pts, design_spatial(c("lon", "lat"), box, n = 1)))) + expect_equal(p, c(1, 0, 0, 0)) +}) + +test_that("the antimeridian warning gives both readings of the edge", { + skip_if_not_installed("sf") + # A box meant to cross the antimeridian is what s2 draws, so the warning + # says which reading it took instead of calling the region too small. + dateline <- lonlat_box(c(179, -179), c(0, 2)) + d <- data.frame(lon = c(179.5, -179.5, 0), lat = 1) + des <- design_spatial(c("lon", "lat"), dateline, n = 2) + w <- tryCatch(inclusion_prob(d, des), warning = identity) + expect_s3_class(w, "drawn_antimeridian") + expect_match(conditionMessage(w), "joins longitudes 179 and -179", + fixed = TRUE) + expect_match(conditionMessage(w), "a span of 2 degrees", fixed = TRUE) + expect_match(conditionMessage(w), "span the 358 degrees of longitude", + fixed = TRUE) + expect_equal(suppressWarnings(inclusion_prob(d, des)), c(1, 1, 0)) + expect_warning(joint_prob(d, des), class = "drawn_antimeridian") +}) + +test_that("the antimeridian warning starts past 180 degrees", { + skip_if_not_installed("sf") + # The class of every warning a call gives, so the geodesic warning of a + # raw box cannot hide whether the antimeridian one came too. + classes <- function(code) { + out <- character(0) + withCallingHandlers(try(code, silent = TRUE), warning = function(w) { + out <<- c(out, class(w)[1]) + invokeRestart("muffleWarning") + }) + out + } + d <- data.frame(lon = c(0, 10, -10), lat = c(0, 5, -5)) + probs <- function(lon, lat = c(-10, 10)) { + inclusion_prob(d, design_spatial(c("lon", "lat"), lonlat_box(lon, lat), + n = 1)) + } + # Raw edges that bow, but that s2 takes the way they are drawn + expect_identical(classes(probs(c(-50, 50), c(-30, 30))), + "drawn_geodesic_edges") + expect_identical(classes(probs(c(-80, 80), c(-60, 60))), + "drawn_geodesic_edges") + expect_identical(classes(probs(c(-89.5, 89.5))), "drawn_geodesic_edges") + # One degree past half the globe, the edge goes the other way round + w <- tryCatch(probs(c(-90.5, 90.5)), drawn_antimeridian = identity) + expect_s3_class(w, "drawn_antimeridian") + expect_match(conditionMessage(w), "a span of 179 degrees", fixed = TRUE) +}) + +test_that("an edge from -180 to 180 warns, and one along a pole does not", { + skip_if_not_installed("sf") + # Both ends of such an edge lie on one meridian, so under s2 a band + # around the globe encloses nothing, alone or beside another part. + band <- lonlat_box(c(-180, 180), c(-60, 60)) + d <- data.frame(lon = c(0.5, 50, -100), lat = c(0.5, 10, -20)) + w <- tryCatch(inclusion_prob(d, design_spatial(c("lon", "lat"), band, + n = 1)), + warning = identity) + expect_s3_class(w, "drawn_antimeridian") + expect_match(conditionMessage(w), "joins longitudes -180 and 180", + fixed = TRUE) + expect_match(conditionMessage(w), "same meridian, so the edge spans 0 ", + fixed = TRUE) + expect_match(conditionMessage(w), "span the 360 degrees of longitude", + fixed = TRUE) + two <- design_spatial(c("lon", "lat"), + list(lonlat_box(c(0, 1), c(0, 1)), band), n = 1) + expect_warning(p <- inclusion_prob(d, two), class = "drawn_antimeridian") + expect_equal(p, c(1, 0, 0)) + + # A cap around the south pole, closed down the antimeridian and along the + # pole, is the region its coordinates describe. + cap <- sf::st_sfc(sf::st_polygon(list(cbind( + c(seq(180, -180, by = -1), -180, 180, 180), + c(rep(-70, 361), -90, -90, -70)))), crs = 4326) + south <- data.frame(lon = c(0, 100, 0), lat = c(-80, -85, 0)) + expect_silent(p <- inclusion_prob(south, design_spatial(c("lon", "lat"), + cap, n = 1))) + expect_equal(p, c(0.5, 0.5, 0)) +}) + +test_that("a region larger than a hemisphere works split into a list", { + skip_if_not_installed("sf") + # Unioned, the two halves came back as the rest of the globe under s2. + halves <- list(flat_box(c(-179, 0), c(-60, 60)), + flat_box(c(0, 179), c(-60, 60))) + d <- data.frame(lon = c(0, 100, -100, 179.5, 0), + lat = c(0, 10, -10, 0, 70)) + des <- design_spatial(c("lon", "lat"), halves, n = 1) + expect_silent(p <- inclusion_prob(d, des)) + expect_equal(p > 0, c(TRUE, TRUE, TRUE, FALSE, FALSE)) +}) + +test_that("a POINT geometry column can stand in for the coordinates", { + skip_if_not_installed("sf") + pts <- sf_points() + plain <- sf::st_drop_geometry(pts) + # No row lies on an edge, where planar and spherical tests can differ. + box <- flat_box(c(-49, 41), c(-24.5, 20.5)) + by_cols <- design_spatial(c("lon", "lat"), box, n = 8) + by_geom <- design_spatial("geometry", box, n = 8) + expect_equal(inclusion_prob(pts, by_geom), inclusion_prob(plain, by_cols)) + s <- draw(pts, by_geom, seed = 3, weights = TRUE) + expect_identical(s$id, draw(plain, by_cols, seed = 3)$id) + expect_equal(ht_total(s, "y")$se, + ht_total(draw(plain, by_cols, seed = 3, weights = TRUE), + "y")$se) + # The column's own CRS is used, and the region is reprojected to it + expect_equal(inclusion_prob(sf::st_transform(pts, 3857), by_geom), + inclusion_prob(pts, by_geom)) + # An empty point is a missing coordinate + gap <- pts + sf::st_geometry(gap)[10] <- sf::st_point() + expect_error(inclusion_prob(gap, by_geom), + "1 row(s) have missing coordinates in `geometry`", fixed = TRUE) + p <- inclusion_prob(gap, design_spatial("geometry", box, n = 8, + na_rm = TRUE)) + expect_equal(p[10], 0) + expect_equal(sum(p > 0), 44L) + lines <- sf::st_sf(id = 1:2, geometry = sf::st_sfc( + sf::st_linestring(rbind(c(0, 0), c(1, 1))), + sf::st_linestring(rbind(c(0, 1), c(1, 2))), crs = 4326)) + expect_error(draw(lines, design_spatial("geometry", box, n = 1)), + "holding LINESTRING geometry", fixed = TRUE) +}) diff --git a/tests/testthat/test-design-spread.R b/tests/testthat/test-design-spread.R index a0a9cf9..cec2f38 100644 --- a/tests/testthat/test-design-spread.R +++ b/tests/testthat/test-design-spread.R @@ -1,5 +1,5 @@ spread_pop <- function(N = 300) { - set.seed(11) + local_seed(11) d <- data.frame(id = seq_len(N), x = stats::runif(N), y = stats::runif(N)) d$smooth <- 100 + 80 * d$x + 60 * sin(4 * d$y) + stats::rnorm(N, 0, 10) d$size <- stats::rgamma(N, 3, 1) @@ -22,19 +22,35 @@ test_that("inclusion probabilities are exactly the ones asked for", { d <- spread_pop() eq <- design_spread(c("x", "y"), n = 30) expect_equal(inclusion_prob(d, eq), rep(0.1, 300)) - sim <- inclusion_prob(d, eq, simulate = TRUE, R = 4000, seed = 1) - z <- (sim - 0.1) / sqrt(0.1 * 0.9 / 4000) - expect_lt(max(abs(z)), 4.5) - expect_lt(abs(mean(z)), 0.2) - pps <- design_spread(c("x", "y"), n = 30, size = "size") expect_equal(inclusion_prob(d, pps), inclusion_prob(d, design_weighted("size", n = 30, method = "poisson"))) + + # The simulation runs 2,000 draws on 120 rows, where a draw costs less than + # half what it does on 300. A row's z depends on its probability and the + # number of draws, not on the size of the frame. + skip_on_cran() + d <- spread_pop(120) + eq <- design_spread(c("x", "y"), n = 12) + sim <- inclusion_prob(d, eq, simulate = TRUE, R = 2000, seed = 1) + z <- (sim - 0.1) / sqrt(0.1 * 0.9 / 2000) + expect_lt(max(abs(z)), 4.5) + # Every draw takes 12 rows, so z sums to 0 over the frame. Over each half of + # the space it does not have to: a walk that favoured one side of the plane + # would push that half's mean z away from 0. + for (half in list(d$x < 0.5, d$y < 0.5)) { + expect_lt(abs(mean(z[half])), 0.5) + } + + pps <- design_spread(c("x", "y"), n = 12, size = "size") ex <- inclusion_prob(d, pps) - sim <- inclusion_prob(d, pps, simulate = TRUE, R = 4000, seed = 2) - z <- (sim - ex) / sqrt(ex * (1 - ex) / 4000) + sim <- inclusion_prob(d, pps, simulate = TRUE, R = 2000, seed = 2) + z <- (sim - ex) / sqrt(ex * (1 - ex) / 2000) expect_lt(max(abs(z[ex < 1])), 4.5) + for (half in list(d$x < 0.5, d$y < 0.5)) { + expect_lt(abs(mean(z[half])), 0.5) + } }) test_that("spreading buys a large variance reduction on a smooth surface", { @@ -68,13 +84,76 @@ test_that("the local mean variance is conservative but in the right range", { r <- ht_total(draw(d, des, seed = i, weights = TRUE), "smooth") c(r$total, r$variance) }, numeric(2)) + # The ratio is 1.10 for these seeds, and 1.17 and 1.18 for two other runs + # of 400. The window stops at 1.4, so an estimator half again too large + # fails. ratio <- mean(out[2, ]) / stats::var(out[1, ]) - expect_gt(ratio, 0.85) - expect_lt(ratio, 1.9) + expect_gt(ratio, 0.9) + expect_lt(ratio, 1.4) r <- ht_total(draw(d, des, seed = 1, weights = TRUE), "smooth") expect_equal(r$method, "local mean") - expect_output(print(r), "local-mean approximation") + expect_output(print(r), "(local mean, an approximation)", fixed = TRUE) +}) + +test_that("a spread census reports an exact total", { + # Every row is in the sample, so there is no variance. The local mean + # estimator compared each row with its neighbours anyway and reported a + # standard error of about 5% of the total. + d <- spread_pop(20) + s <- draw(d, design_spread(c("x", "y"), n = 20), seed = 1, weights = TRUE) + r <- ht_total(s, "smooth") + expect_equal(r$total, sum(d$smooth)) + expect_equal(r$variance, 0) + expect_match(r$note, "exact rather than estimated") +}) + +dominant_spread <- function() { + d <- data.frame(x = (1:60 * 0.618) %% 1, y = (1:60 * 0.381) %% 1) + d$w <- c(500, 400, 300, 1 + (1:57 %% 7) * 0.5) + d$v <- 10 * d$w + 5 * sin(1:60) + d +} + +test_that("rows a size column puts past certainty add no local-mean variance", { + d <- dominant_spread() + des <- design_spread(c("x", "y"), n = 10, size = "w", scale = FALSE) + s <- draw(d, des, seed = 1, weights = TRUE) + expect_equal(sum(s$.prob == 1), 3L) + + # The estimator runs over the other rows only, as rows and as neighbours. + free <- s$.prob < 1 + want <- drawn:::local_mean_variance(as.matrix(s[free, c("x", "y")]), + s$v[free], s$.prob[free]) + r <- ht_total(s, "v") + expect_equal(r$method, "local mean") + expect_equal(r$variance, want$variance) + + y2 <- s$v * ifelse(free, 1, 4) + expect_equal(ht_total(s, y2)$variance, r$variance) + + # One row below certainty leaves nothing to compare it with + one <- draw(d, design_spread(c("x", "y"), n = 4, size = "w", scale = FALSE), + seed = 1, weights = TRUE) + expect_equal(sum(one$.prob < 1), 1L) + a <- ht_total(one, "v", variance = "analytic") + expect_true(is.na(a$variance)) + expect_match(a$note, "Only one sampled row") + expect_true(is.na(ht_total(one, "v")$variance)) +}) + +test_that("with certain rows the local mean variance stays near the truth", { + skip_on_cran() + # Counting the three dominant rows as random put this ratio above 5,000. + d <- dominant_spread() + des <- design_spread(c("x", "y"), n = 10, size = "w", scale = FALSE) + out <- vapply(1:300, function(i) { + r <- ht_total(draw(d, des, seed = i, weights = TRUE), "v") + c(r$total, r$variance) + }, numeric(2)) + ratio <- mean(out[2, ]) / stats::var(out[1, ]) + expect_gt(ratio, 0.6) + expect_lt(ratio, 1.6) }) test_that("joint probabilities have no closed form, but can be simulated", { @@ -86,14 +165,21 @@ test_that("joint probabilities have no closed form, but can be simulated", { }) test_that("scaling decides which column drives the distances", { - set.seed(4) + local_seed(4) d <- data.frame(big = stats::runif(200, 0, 1e6), small = stats::runif(200)) unscaled <- design_spread(c("big", "small"), n = 20, scale = FALSE) - s <- draw(d, unscaled, seed = 1) - # Unscaled, `small` barely moves the distance; scaled, it counts equally. - expect_true(is.data.frame(s)) - expect_equal(nrow(draw(d, design_spread(c("big", "small"), n = 20), seed = 1)), - 20L) + scaled <- design_spread(c("big", "small"), n = 20) + expect_equal(nrow(draw(d, scaled, seed = 1)), 20L) + # Unscaled, `small` barely moves the distance, so the sample spreads over + # `big` alone and its mean of `small` strays as a simple random sample's + # does. Scaled, `small` counts as much as `big`, and the sample is balanced + # on it too: about a quarter of the unscaled error over these 40 draws. + miss <- function(des) { + mean(vapply(1:40, function(i) { + abs(mean(draw(d, des, seed = i)$small) - mean(d$small)) + }, numeric(1))) + } + expect_lt(miss(scaled), 0.5 * miss(unscaled)) }) test_that("validates its inputs and honours na_rm", { @@ -115,17 +201,423 @@ test_that("validates its inputs and honours na_rm", { test_that("hands off to survey, and plots as a map", { d <- spread_pop() + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + expect_invisible(plot(design_spread(c("x", "y"), n = 30), d, type = "map", + seed = 1)) + expect_error(plot(design_simple(n = 5), d, type = "map"), "coords") + expect_invisible(plot(design_simple(n = 5), d, type = "map", + coords = c("x", "y"), seed = 1)) + s <- draw(d, design_spread(c("x", "y"), n = 30), seed = 1, weights = TRUE) skip_if_not_installed("survey") svd <- as_svydesign(s) expect_equal(as.numeric(survey::svytotal(~smooth, svd)), ht_total(s, "smooth")$total) +}) +test_that("an sf frame spreads across plain numeric columns", { + pts <- sf_points() + plain <- sf::st_drop_geometry(pts) + des <- design_spread(c("x", "yy"), n = 12) + s <- draw(pts, des, seed = 1, weights = TRUE) + expect_s3_class(s, "sf") + expect_identical(s$id, draw(plain, des, seed = 1)$id) + expect_equal(inclusion_prob(pts, des), rep(0.2, 60)) + expect_equal(ht_total(s, "y")$se, + ht_total(draw(plain, des, seed = 1, weights = TRUE), "y")$se) +}) + +test_that("a POINT geometry column spreads as its two coordinates", { + pts <- sf_points() + plain <- sf::st_drop_geometry(pts) + by_geom <- design_spread("geometry", n = 12) + by_cols <- design_spread(c("lon", "lat"), n = 12) + s <- draw(pts, by_geom, seed = 1, weights = TRUE) + expect_identical(s$id, draw(plain, by_cols, seed = 1)$id) + expect_equal(inclusion_prob(pts, by_geom), rep(0.2, 60)) + expect_equal(ht_total(s, "y")$se, + ht_total(draw(plain, by_cols, seed = 1, weights = TRUE), + "y")$se) + # With another column, the geometry still counts as two + mixed <- design_spread(c("geometry", "x"), n = 12) + expect_identical(draw(pts, mixed, seed = 2)$id, + draw(plain, design_spread(c("lon", "lat", "x"), n = 12), + seed = 2)$id) grDevices::pdf(NULL) on.exit(grDevices::dev.off(), add = TRUE) - expect_invisible(plot(design_spread(c("x", "y"), n = 30), d, type = "map", - seed = 1)) - expect_error(plot(design_simple(n = 5), d, type = "map"), "coords") - expect_invisible(plot(design_simple(n = 5), d, type = "map", - coords = c("x", "y"), seed = 1)) + expect_invisible(plot(by_geom, pts, type = "map", seed = 1)) + lines <- sf::st_sf(id = 1:2, geometry = sf::st_sfc( + sf::st_linestring(rbind(c(0, 0), c(1, 1))), + sf::st_linestring(rbind(c(0, 1), c(1, 2))))) + expect_error(draw(lines, design_spread("geometry", n = 1)), + "`across` names `geometry`, a geometry column holding LINESTRING", + fixed = TRUE) +}) + +test_that("Date and date-time columns spread as days and seconds", { + d <- spread_pop(40) + d$day <- as.Date("2024-03-01") + (d$id * 7) %% 40 + d$days <- as.numeric(d$day) + d$at <- as.POSIXct("2024-03-01", tz = "UTC") + d$days * 3600 + d$secs <- as.numeric(d$at) + same <- function(a, b) { + expect_identical(draw(d, design_spread(a, n = 6), seed = 3)$id, + draw(d, design_spread(b, n = 6), seed = 3)$id) + } + same(c("day", "x"), c("days", "x")) + same(c("at", "x"), c("secs", "x")) + expect_equal(inclusion_prob(d, design_spread("day", n = 6)), rep(0.15, 40)) + s <- draw(d, design_spread(c("day", "x"), n = 6), seed = 3, weights = TRUE) + expect_equal(ht_total(s, "smooth")$se, + ht_total(draw(d, design_spread(c("days", "x"), n = 6), seed = 3, + weights = TRUE), "smooth")$se) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + expect_invisible(plot(design_spread(c("day", "x"), n = 6), d, type = "map", + seed = 3)) + # A size has to be numeric, and anything else names the way out + expect_error(draw(d, design_spread("x", n = 6, size = "day")), + "`day` must be numeric to size by, not Date.", fixed = TRUE) + d$label <- format(d$x) + expect_error(draw(d, design_spread("label", n = 6)), + "for example with as.numeric()", fixed = TRUE) + d$day[4] <- NA + expect_error(draw(d, design_spread("day", n = 6)), "na_rm = TRUE") + expect_equal(inclusion_prob(d, design_spread("day", n = 6, + na_rm = TRUE))[4], 0) +}) + +# ---- strata ----------------------------------------------------------------- + +strata_pop <- function(N = 150, sizes = c(70, 50, 30)) { + i <- seq_len(N) + d <- data.frame(id = i, x = (i * 0.618034) %% 1, y = (i * 0.414214) %% 1, + g = rep(c("north", "south", "east"), sizes)) + d$v <- 100 + 80 * d$x + 60 * sin(4 * d$y) + 5 * sin(7 * i) + d$w <- 1 + (i %% 9) + d +} + +test_that("strata get their allocation, each spread on its own", { + d <- strata_pop() + des <- design_spread(c("x", "y"), n = 30, strata = "g") + expect_output(print(des), "strata +\"g\"") + for (i in 1:10) { + s <- draw(d, des, seed = i) + expect_equal(as.vector(table(factor(s$g, c("east", "north", "south")))), + c(6L, 14L, 10L)) + expect_identical(s$id, sort(s$id)) + } + eq <- draw(d, design_spread(c("x", "y"), n = 30, strata = "g", + allocation = "equal"), seed = 1) + expect_equal(as.vector(table(eq$g)), c(10L, 10L, 10L)) + + counts <- design_spread(c("x", "y"), strata = "g", + allocation = c(north = 4, south = 3, east = 2)) + expect_equal(counts$n, 9L) + expect_equal(as.vector(table(draw(d, counts, seed = 1)$g)), c(2L, 4L, 3L)) + + tab <- allocation_table(d, des) + expect_equal(tab$g, c("east", "north", "south")) + expect_equal(tab$n, c(6L, 14L, 10L)) + expect_equal(tab$prob, c(0.2, 0.2, 0.2)) + expect_equal(tab$status, rep("rule", 3)) + expect_equal(allocation_table(d, counts)$status, rep("count", 3)) + + # Each stratum is the design without strata on that stratum's rows alone. + north <- d[d$g == "north", ] + expect_equal(inclusion_prob(d, des)[d$g == "north"], + inclusion_prob(north, design_spread(c("x", "y"), n = 14))) +}) + +test_that("inclusion probabilities with strata and size are exact", { + d <- strata_pop() + d$w[c(5, 80)] <- 60 + des <- design_spread(c("x", "y"), n = 30, strata = "g", size = "w") + ex <- inclusion_prob(d, des) + expect_equal(as.vector(tapply(ex, d$g, sum)), c(6, 14, 10)) + north <- d$g == "north" + expect_equal(ex[north], + inclusion_prob(d[north, ], design_spread(c("x", "y"), n = 14, + size = "w"))) + expect_equal(as.vector(certainty_set(d, des)), c(5L, 80L)) + expect_true(is.na(attr(certainty_set(d, des), "threshold"))) + + skip_on_cran() + small <- strata_pop(90, c(40, 30, 20)) + small$w[c(5, 50)] <- 40 + des <- design_spread(c("x", "y"), n = 18, strata = "g", size = "w") + ex <- inclusion_prob(small, des) + sim <- inclusion_prob(small, des, simulate = TRUE, R = 1500, seed = 1) + z <- (sim - ex) / sqrt(ex * (1 - ex) / 1500) + expect_lt(max(abs(z[ex < 1])), 4.5) + expect_equal(sim[ex == 1], rep(1, sum(ex == 1))) +}) + +test_that("the variance sums the strata's local mean variances", { + d <- strata_pop() + d$w[c(5, 80)] <- 60 + for (size in list(NULL, "w")) { + des <- design_spread(c("x", "y"), n = 30, strata = "g", size = size) + s <- draw(d, des, seed = 3, weights = TRUE) + # Each stratum's own estimator, on that stratum alone as a frame. + parts <- vapply(c("east", "north", "south"), function(h) { + sub <- d[d$g == h, ] + own <- design_spread(c("x", "y"), n = sum(s$g == h), size = size) + in_h <- s$g == h + drawn:::ht_variance(own, sub, match(s$id[in_h], sub$id), s$v[in_h], + s$.prob[in_h])$variance + }, numeric(1)) + r <- ht_total(s, "v") + expect_equal(r$method, "local mean") + expect_equal(r$variance, sum(parts)) + expect_equal(r$df, sum(s$.prob < 1) - 3) + + by <- ht_total(s, "v", by = "g") + expect_equal(by$se^2, unname(parts)) + } + + jk <- ht_total(s, "v", variance = "jackknife") + expect_match(jk$note, "in 3 strata") +}) + +test_that("a stratum with one sampled row below certainty is refused", { + d <- strata_pop() + des <- design_spread(c("x", "y"), strata = "g", + allocation = c(north = 4, south = 1, east = 3)) + s <- draw(d, des, seed = 1, weights = TRUE) + a <- ht_total(s, "v", variance = "analytic") + expect_true(is.na(a$variance)) + expect_match(a$note, "The stratum `south` has a single sampled row") + expect_match(a$note, "a count of 2 or more for each in `allocation`") + expect_true(is.na(ht_total(s, "v")$variance)) + + # A domain with no unit in that stratum is measured without it. + by <- ht_total(s, "v", by = "g") + expect_true(all(is.finite(by$se[by$g != "south"]))) + expect_true(is.na(by$se[by$g == "south"])) +}) + +test_that("strata are refused or warned about as stratified designs are", { + expect_error(design_spread(c("x", "y"), n = 5, allocation = "equal"), + "`allocation` splits `n` over strata, and `strata` is NULL") + expect_error(design_spread(c("x", "y"), n = 5, strata = "g", + allocation = "neyman"), + "must be one of \"proportional\" or \"equal\"") + expect_error(design_spread(c("x", "y"), strata = "g"), "`n` is missing") + expect_error(design_spread(c("x", "y"), n = 7, strata = "g", + allocation = c(north = 2, south = 3)), + "is not the sum of the counts") + d <- strata_pop() + expect_error(draw(d, design_spread(c("x", "y"), strata = "g", + allocation = c(north = 2, south = 3))), + "no entry for 1 stratum of `data`: `east`") + expect_error(draw(d, design_spread(c("x", "y"), strata = "g", + allocation = c(north = 2, south = 3, + east = 31))), + "Stratum `east` has 30 row(s) but `allocation` asks for 31. ", + fixed = TRUE) + expect_error(inclusion_prob(d, design_spread(c("x", "y"), n = 151, + strata = "g")), + "cannot exceed the number of rows") + expect_warning(draw(d, design_spread(c("x", "y"), n = 2, strata = "g"), + seed = 1), + class = "drawn_empty_stratum") + + d$g[3] <- NA + des <- design_spread(c("x", "y"), n = 30, strata = "g") + expect_error(draw(d, des), "a missing value in `x`, `y`, `g`") + kept <- design_spread(c("x", "y"), n = 30, strata = "g", na_rm = TRUE) + p <- inclusion_prob(d, kept) + expect_equal(p[3], 0) + expect_equal(p[d$g %in% "north"], rep(14 / 69, 69)) + expect_equal(sample_summary(draw(d, kept, seed = 1, weights = TRUE))$N_reachable, + 149L) + + # A row dropped for a missing coordinate is in no stratum's count, so the + # sample and its variances are those of the frame without it. + d <- strata_pop() + d$x[10] <- NA + s1 <- draw(d, kept, seed = 1, weights = TRUE) + s2 <- draw(d[-10, ], kept, seed = 1, weights = TRUE) + expect_identical(s1$id, s2$id) + for (v in c("analytic", "jackknife")) { + expect_equal(ht_total(s1, "v", variance = v)$variance, + ht_total(s2, "v", variance = v)$variance) + } + + # A count for a stratum na_rm empties names that reason, on every path. + d <- strata_pop() + d$x[d$g == "east"] <- NA + counts <- design_spread(c("x", "y"), strata = "g", na_rm = TRUE, + allocation = c(north = 10, south = 5, east = 2)) + msg <- paste0("`allocation` gives a count for stratum `east`, but ", + "na_rm = TRUE drops every row of it for a missing value in ", + "`x`, `y`. Fill in those values, or leave the stratum out ", + "of `allocation`.") + expect_error(draw(d, counts, seed = 1), msg, fixed = TRUE) + expect_error(inclusion_prob(d, counts), msg, fixed = TRUE) + expect_error(allocation_table(d, counts), msg, fixed = TRUE) + # Without a count it is outside the frame the design draws from. + p <- inclusion_prob(d, design_spread(c("x", "y"), strata = "g", + na_rm = TRUE, + allocation = c(north = 10, south = 5))) + expect_equal(p[d$g == "east"], rep(0, 30)) + expect_equal(sum(p), 15) +}) + +test_that("sample_summary() and allocation_table() show the strata", { + d <- strata_pop() + s <- draw(d, design_spread(c("x", "y"), n = 30, strata = "g"), seed = 1, + weights = TRUE) + b <- sample_summary(s)$by_group + expect_equal(b$group, c("east", "north", "south")) + expect_equal(b$drawn, c(6L, 14L, 10L)) + expect_equal(b$in_frame, c(30L, 70L, 50L)) + + # Rows na_rm drops are in no stratum, as in allocation_table(). + gap <- strata_pop() + gap$x[1:2] <- NA + kept <- design_spread(c("x", "y"), n = 30, strata = "g", na_rm = TRUE) + b <- sample_summary(draw(gap, kept, seed = 1, weights = TRUE))$by_group + tab <- allocation_table(gap, kept) + expect_equal(b$in_frame, c(30L, 68L, 50L)) + expect_equal(b$in_frame, tab$N) + expect_equal(b$rate, round(tab$prob, 4)) + + d$w[c(5, 80)] <- 60 + sized <- design_spread(c("x", "y"), n = 30, strata = "g", size = "w") + expect_true(all(is.na(allocation_table(d, sized)$prob))) + expect_error(allocation_table(d, design_spread(c("x", "y"), n = 30)), + "which has no strata to allocate over") + + cert <- design_certainty("w", 60, rest = design_spread( + c("x", "y"), n = 20, strata = "g")) + tab <- allocation_table(d, cert) + expect_equal(tab$N, c(30L, 69L, 49L)) + expect_equal(sum(tab$n), 20L) +}) + +test_that("a spread sample with strata hands its strata to survey", { + skip_if_not_installed("survey") + d <- strata_pop() + s <- draw(d, design_spread(c("x", "y"), n = 30, strata = "g"), seed = 1, + weights = TRUE) + svd <- as_svydesign(s) + r <- ht_total(s, "v") + expect_equal(as.numeric(survey::svytotal(~v, svd)), r$total) + expect_equal(survey::degf(svd), r$df) + expect_equal(sort(unique(as.character(svd$strata[, 1]))), + c("east", "north", "south")) + + d$w[c(5, 80)] <- 60 + s <- draw(d, design_spread(c("x", "y"), n = 30, strata = "g", size = "w"), + seed = 2, weights = TRUE) + svd <- as_svydesign(s) + r <- ht_total(s, "v") + expect_equal(as.numeric(survey::svytotal(~v, svd)), r$total) + expect_equal(survey::degf(svd), r$df) + expect_equal(as.character(svd$strata[s$.prob == 1, 1]), + c("(certain)", "(certain)")) + + # A stratum of the frame named `(certain)` stays apart from the certain rows. + d$g[d$g == "east"] <- "(certain)" + s <- draw(d, design_spread(c("x", "y"), n = 30, strata = "g", size = "w"), + seed = 2, weights = TRUE) + svd <- as_svydesign(s) + expect_equal(length(unique(svd$strata[, 1])), 4L) + expect_equal(survey::degf(svd), ht_total(s, "v")$df) + + cert <- design_certainty("w", 60, rest = design_spread( + c("x", "y"), n = 20, strata = "g")) + s <- draw(d, cert, seed = 1, weights = TRUE) + expect_equal(survey::degf(as_svydesign(s)), ht_total(s, "v")$df) +}) + +test_that("a row with a tiny target probability still competes", { + # Targets below 1e-9 were set to 0 before the pivotal walk, so such a row + # could never be drawn although inclusion_prob() gave it a probability. + # The walk now snaps only rounding error, at a tolerance `eps`; a target + # far below it, here 0.01 against 0.05, is drawn at its own rate. + x <- matrix(c(0, 1), ncol = 1) + hits <- drawn:::with_seed(1, vapply(1:2000, function(i) { + 1L %in% drawn:::local_pivotal(c(0.01, 0.99), x, eps = 0.05) + }, logical(1))) + expect_gt(sum(hits), 5) + expect_lt(sum(hits), 40) + sizes <- drawn:::with_seed(2, vapply(1:200, function(i) { + length(drawn:::local_pivotal(c(1e-10, 1 - 1e-10), x)) + }, integer(1))) + expect_equal(sizes, rep(1L, 200)) + + d <- data.frame(x = 1:20, y = 0, w = c(2e-9, rep(1, 19))) + des <- design_spread(c("x", "y"), n = 5, size = "w") + expect_equal(inclusion_prob(d, des)[1], 5 * 2e-9 / sum(d$w)) + expect_equal(nrow(draw(d, des, seed = 1)), 5L) +}) + +test_that("reserve is refused with size or strata, and checked against N", { + expect_equal(design_spread(c("x", "y"), n = 5)$reserve, 0L) + expect_error(design_spread(c("x", "y"), n = 5, size = "size", reserve = 2), + "Leave out `size` or `reserve`") + expect_error(design_spread(c("x", "y"), n = 5, strata = "g", reserve = 2), + "Leave out `strata` or `reserve`") + expect_error(design_spread(c("x", "y"), n = 0, reserve = 3), + "`reserve` is 3 and `n` is 0") + expect_error(design_spread(c("x", "y"), n = 5, reserve = -1), + "must be non-negative") + d <- spread_pop(20) + expect_error(draw(d, design_spread(c("x", "y"), n = 15, reserve = 6)), + "`n` and `reserve` together \\(21\\) cannot exceed") +}) + +test_that("a spread list adds reserves disjoint from the main sample", { + d <- spread_pop() + des <- design_spread(c("x", "y"), n = 30, reserve = 10) + s <- draw(d, des, seed = 4) + expect_equal(names(s), c(".reserve", names(d))) + expect_identical(s$.reserve, c(integer(30), 1:10)) + expect_false(anyDuplicated(s$id) > 0) + main <- s$id[s$.reserve == 0] + expect_identical(main, draw(d, design_spread(c("x", "y"), n = 30), + seed = 4)$id) + expect_identical(main, sort(main)) + + w <- draw(d, des, seed = 4, weights = TRUE) + expect_equal(w$.prob, rep(0.1, 40)) + expect_equal(inclusion_prob(d, des), rep(0.1, 300)) + expect_error(ht_total(w, "smooth"), "use_reserves\\(\\)") +}) + +test_that("the reserves of a spread list are spread over the space", { + d <- spread_pop() + nn <- function(p) { + m <- as.matrix(stats::dist(p[, c("x", "y")])) + diag(m) <- Inf + mean(apply(m, 1, min)) + } + des <- design_spread(c("x", "y"), n = 30, scale = FALSE, reserve = 15) + gap <- vapply(1:20, function(i) { + s <- draw(d, des, seed = i) + c(reserve = nn(s[s$.reserve > 0, ]), + srs = nn(draw(d, design_simple(n = 15), seed = i))) + }, numeric(2)) + expect_gt(mean(gap[1, ]), 1.15 * mean(gap[2, ])) +}) + +test_that("use_reserves() on a spread list keeps the local mean variance", { + d <- spread_pop() + s <- draw(d, design_spread(c("x", "y"), n = 30, reserve = 10), seed = 2, + weights = TRUE) + gone <- s$id[c(1, 5, 9, 31)] + u <- use_reserves(s, ifelse(s$.reserve <= 4, s$id %in% gone, NA)) + expect_equal(nrow(u), 30L) + expect_equal(u$.reserve, c(integer(27), 2:4)) + expect_equal(u$.prob, rep(30 / 296, 30)) + expect_equal(inclusion_prob(d, attr(u, "drawn_design"))[gone], rep(0, 4)) + r <- ht_total(u, "smooth") + expect_equal(r$method, "local mean") + expect_equal(r$unreachable, 4L) + expect_true(is.finite(r$se) && r$se > 0) }) diff --git a/tests/testthat/test-design-stratified.R b/tests/testthat/test-design-stratified.R index 1bba573..51ec953 100644 --- a/tests/testthat/test-design-stratified.R +++ b/tests/testthat/test-design-stratified.R @@ -107,7 +107,7 @@ test_that("min_per_stratum still totals n exactly, at every feasible floor", { }) test_that("Neyman allocation puts rows where the values vary most", { - set.seed(2) + local_seed(2) d <- data.frame(id = 1:300, g = rep(c("a", "b", "c"), each = 100)) d$v <- c(stats::rnorm(100, 50, 1), stats::rnorm(100, 50, 10), stats::rnorm(100, 50, 30)) @@ -141,7 +141,7 @@ test_that("Neyman validates its auxiliary column", { }) test_that("Neyman inclusion probabilities are consistent with the draw", { - set.seed(4) + local_seed(4) d <- data.frame(id = 1:200, g = rep(c("a", "b"), each = 100)) d$v <- c(stats::rnorm(100, 0, 1), stats::rnorm(100, 0, 20)) des <- design_stratified("g", n = 40, allocation = "neyman", allocation_by = "v") @@ -154,3 +154,785 @@ test_that("Neyman inclusion probabilities are consistent with the draw", { } expect_equal(hits / 1500, p, tolerance = 0.05) }) + +test_that("a tie goes to the stratum with more room, then first in byte order", { + # Equal allocation of 8 over three strata leaves 2 rows after the whole + # parts, with equal remainders. "b" has the most room; "B" and "a" tie on + # room too, and "B" comes first in byte order in every locale. + d <- data.frame(id = 1:54, g = rep(c("a", "B", "b"), times = c(12, 12, 30))) + des <- design_stratified("g", n = 8, allocation = "equal") + want <- ifelse(d$g == "B", 3 / 12, ifelse(d$g == "a", 2 / 12, 3 / 30)) + expect_equal(inclusion_prob(d, des), want) + ids <- draw(d, des, seed = 1)$id + with_other_collation({ + expect_equal(inclusion_prob(d, des), want) + expect_identical(draw(d, des, seed = 1)$id, ids) + }) + + # A factor's level order decides instead. + d$g <- factor(d$g, levels = c("a", "B", "b")) + expect_equal(inclusion_prob(d, des), + ifelse(d$g == "a", 3 / 12, ifelse(d$g == "B", 2 / 12, 3 / 30))) +}) + +test_that("a sample drawn in one collation estimates the same in another", { + d <- data.frame(id = 1:54, g = rep(c("a", "B", "b"), times = c(12, 12, 30)), + y = 100 + 30 * rep(1:3, times = c(12, 12, 30)) + (1:54 %% 7)) + s <- draw(d, design_stratified("g", n = 8, allocation = "equal"), seed = 1, + weights = TRUE) + want <- ht_total(s, "y") + with_other_collation({ + got <- ht_total(s, "y") + expect_equal(got$se, want$se) + expect_equal(got$df, want$df) + }) +}) + +test_that("an sf frame draws the same strata as the plain frame", { + pts <- sf_points() + plain <- sf::st_drop_geometry(pts) + des <- design_stratified("site", n = 12) + s <- draw(pts, des, seed = 1, weights = TRUE) + expect_s3_class(s, "sf") + expect_identical(s$id, draw(plain, des, seed = 1)$id) + expect_equal(inclusion_prob(pts, des), inclusion_prob(plain, des)) + expect_equal(ht_total(s, "y")$se, + ht_total(draw(plain, des, seed = 1, weights = TRUE), "y")$se) +}) + +# ---- floors and caps ------------------------------------------------------- + +test_that("a floor holds the allocation rule among the strata it leaves free", { + # Raising a stratum to min_per_stratum took the rows back one at a time + # from the others, which broke the rule between them. Under Neyman + # allocation `a` and `b` got 19 and 101 rows where the rule gives 35.3 and + # 84.7, which cost 14% in variance. + bounded <- function(n, share, lower, upper) { + f <- function(l) sum(pmin(pmax(l * share, lower), upper)) - n + l <- stats::uniroot(f, c(0, max(upper / share)), tol = 1e-12)$root + pmin(pmax(l * share, lower), upper) + } + sizes <- c(a = 5000, b = 4000, + stats::setNames(rep(10, 20), paste0("s", 1:20))) + sp <- c(1, 3, rep(1, 20)) + got <- drawn:::allocate(200, sizes, "neyman", 4, spread = sp) + want <- bounded(200, sizes * sp, pmin(4, sizes), sizes) + expect_equal(sum(got), 200L) + expect_true(all(abs(got - want) < 1)) + expect_equal(unname(got), c(35L, 85L, rep(4L, 20))) + + got <- drawn:::allocate(200, sizes, "proportional", 4) + expect_true(all(abs(got - bounded(200, sizes, pmin(4, sizes), sizes)) < 1)) + expect_equal(unname(got[1:2]), c(67L, 53L)) + + # The same through a frame, on both the draw and the probabilities + d <- data.frame(g = rep(c("a", "b", paste0("s", 1:20)), + times = c(500, 400, rep(10, 20)))) + des <- design_stratified("g", n = 200, min_per_stratum = 4) + p <- inclusion_prob(d, des) + expect_equal(p[match(c("a", "b", "s1"), d$g)], c(67 / 500, 53 / 400, 0.4)) + expect_equal(c(table(draw(d, des, seed = 1)$g)[c("a", "b")]), + c(a = 67L, b = 53L)) +}) + +test_that("a floor larger than a stratum asks only for that stratum's rows", { + # Each of the three one-row strata is taken whole, so 7 rows cover a floor + # of 2. The check counted 2 for every stratum and refused anything under 8. + d <- data.frame(id = 1:103, g = c("a", "b", "c", rep("d", 100))) + got <- draw(d, design_stratified("g", n = 7, min_per_stratum = 2), seed = 1) + expect_equal(as.vector(table(got$g)), c(1L, 1L, 1L, 4L)) + expect_error( + draw(d, design_stratified("g", n = 4, min_per_stratum = 2), seed = 1), + paste0("`min_per_stratum` = 2 needs at least 5 rows across these 4 ", + "strata, with the 3 strata smaller than 2 taken whole, but `n` ", + "is 4."), fixed = TRUE) + # With replacement a one-row stratum can give the floor in repeats. + expect_error( + inclusion_prob(d, design_stratified("g", n = 7, min_per_stratum = 2, + replace = TRUE)), + "needs at least 8 rows", fixed = TRUE) + # One stratum is named as one. + expect_error( + draw(d[d$g == "d", ], design_stratified("g", n = 3, min_per_stratum = 5), + seed = 1), + "needs at least 5 rows in the one stratum, but `n` is 3.", fixed = TRUE) + expect_error( + draw(d[d$g == "d", ], design_stratified("g", n = 0, min_per_stratum = 1), + seed = 1), + "needs at least 1 row in the one stratum, but `n` is 0.", fixed = TRUE) +}) + +test_that("Neyman refuses an infinite allocation_by", { + # sd() of a stratum holding Inf is NaN, which was read as no spread: the + # stratum with the most extreme values was allocated nothing. + d <- data.frame(id = 1:60, g = rep(c("a", "b", "c"), each = 20), + v = c(1:20 * 50, (1:40 * 7) %% 13)) + d$v[3] <- Inf + des <- design_stratified("g", n = 15, allocation = "neyman", + allocation_by = "v") + expect_error(draw(d, des, seed = 1), "1 value(s) of `v` are missing or non-finite", + fixed = TRUE) + expect_error(inclusion_prob(d, des), "missing or non-finite") + + # Finite values whose standard deviation overflows split as the same + # values on a smaller scale do. + d$v[3] <- 150 + big <- d + big$v <- big$v * 1e305 + expect_equal(inclusion_prob(big, des), inclusion_prob(d, des)) +}) + +test_that("strata left with no spread after a cap are split by size", { + # The Neyman shares are 50, 0 and 0. `a` is taken whole, and the 25 rows + # left went to `b` and `c` equally, 12 and 13. A Neyman split over strata + # with no spread goes by size, 6 and 19, as it does when no stratum has any. + d <- data.frame(g = rep(c("a", "b", "c"), times = c(5, 100, 300)), + v = c(1:5 * 10, rep(3, 400))) + des <- design_stratified("g", n = 30, allocation = "neyman", + allocation_by = "v") + p <- inclusion_prob(d, des) + expect_equal(p[c(1, 6, 106)], c(1, 6 / 100, 19 / 300)) +}) + +test_that("the empty-stratum warning gives the cause it has", { + # A Neyman stratum with constant values gets rows only once every other + # stratum is taken whole, so "Raise `n`" pointed the wrong way. + z <- data.frame(id = 1:60, g = rep(c("a", "b", "c"), each = 20), + v = c(rep(5, 20), (1:40 * 7) %% 13)) + des <- design_stratified("g", n = 12, allocation = "neyman", + allocation_by = "v") + w <- tryCatch(draw(z, des, seed = 1), drawn_empty_stratum = function(w) w) + expect_s3_class(w, "drawn_warning") + expect_match(conditionMessage(w), paste0( + "`v` is constant within it, so Neyman allocation gives it no share ", + "until every other stratum is taken whole. Set min_per_stratum = 1"), + fixed = TRUE) + expect_no_match(conditionMessage(w), "Raise `n`", fixed = TRUE) + + # A stratum with spread but too small a share can still be reached by a + # larger `n`, and the message keeps that advice for it. + mixed <- data.frame(g = rep(c("a", "b", "c"), times = c(20, 2, 200)), + v = c(rep(5, 20), 1, 2, 1:200 %% 10)) + w <- tryCatch( + draw(mixed, design_stratified("g", n = 10, allocation = "neyman", + allocation_by = "v"), seed = 1), + drawn_empty_stratum = function(w) w) + expect_match(conditionMessage(w), "2 strata (`a`, `b`)", fixed = TRUE) + expect_match(conditionMessage(w), "`v` is constant within `a`, so", + fixed = TRUE) + expect_match(conditionMessage(w), "Raise `n`, or set min_per_stratum = 1", + fixed = TRUE) + + # n = 0 asks for no rows, and gets none without a warning per stratum, as + # design_simple(n = 0) does. + d <- data.frame(id = 1:10, g = rep(c("a", "b"), each = 5)) + expect_no_warning(got <- draw(d, design_stratified("g", n = 0), seed = 1)) + expect_equal(nrow(got), 0L) +}) + +# ---- counts per stratum ---------------------------------------------------- + +counts_frame <- function() { + data.frame(id = 1:100, + site = rep(c("north", "south", "east", "west"), + times = c(40, 30, 20, 10)), + y = (1:100 * 37) %% 23 + 1) +} + +test_that("counts given per stratum are drawn as given, on every path", { + d <- counts_frame() + counts <- c(north = 4, south = 6, east = 5, west = 5) + des <- design_stratified("site", allocation = counts) + expect_identical(des$n, 20L) + expect_identical(design_stratified("site", n = 20, allocation = counts)$n, + 20L) + expect_output(print(des), "c(north = 4, south = 6, east = 5, west = 5)", + fixed = TRUE) + + s <- draw(d, des, seed = 1, weights = TRUE) + expect_equal(c(table(s$site))[names(counts)], counts) + N_h <- c(table(d$site)) + want <- unname(counts[d$site] / N_h[d$site]) + expect_equal(inclusion_prob(d, des), want) + expect_equal(s$.prob, want[s$.row]) + expect_equal(joint_prob(d, des, rows = c(1, 2, 41)), + matrix(c(0.1, 0.1 * 3 / 39, 0.1 * 0.2, + 0.1 * 3 / 39, 0.1, 0.1 * 0.2, + 0.1 * 0.2, 0.1 * 0.2, 0.2), 3)) + + # The variance is the stratified form over the counts as given. + v <- sum(vapply(names(counts), function(h) { + yh <- s$y[s$site == h] + N_h[[h]]^2 * (1 - counts[[h]] / N_h[[h]]) * stats::var(yh) / counts[[h]] + }, numeric(1))) + expect_equal(ht_total(s, "y")$variance, v) + expect_equal(ht_total(s, "y", variance = "jackknife")$variance, v) + sm <- sample_summary(s)$by_group + expect_equal(sm$drawn[match(names(counts), sm$group)], unname(counts)) + + skip_if_not_installed("survey") + expect_equal( + unname(survey::SE(survey::svytotal(~y, as_svydesign(s)))[1]), + ht_total(s, "y")$se) +}) + +test_that("counts for several strata columns come as a data frame", { + d <- data.frame(id = 1:40, g = rep(c("a", "b"), 20), + h = rep(c(1.5, 2), each = 20)) + spec <- data.frame(h = c(1.5, 2, 1.5, 2), g = c("a", "a", "b", "b"), + n = c(2, 3, 4, 1)) + des <- design_stratified(c("g", "h"), allocation = spec) + expect_identical(des$n, 10L) + got <- draw(d, des, seed = 3) + expect_equal(c(table(paste(got$g, got$h))), + c("a 1.5" = 2L, "a 2" = 3L, "b 1.5" = 4L, "b 2" = 1L)) + expect_equal(inclusion_prob(d, des)[c(1, 2, 21, 22)], + c(2, 4, 3, 1) / 10) + + # A factor column is matched on its values, not its level order. + f <- counts_frame() + f$site <- factor(f$site, levels = c("west", "east", "south", "north")) + des <- design_stratified("site", + allocation = c(north = 4, south = 6, east = 5, + west = 5)) + expect_equal(c(table(draw(f, des, seed = 1)$site)), + c(west = 5L, east = 5L, south = 6L, north = 4L)) +}) + +test_that("counts that do not fit the frame are refused by name", { + d <- counts_frame() + expect_error( + draw(d, design_stratified("site", allocation = c(north = 4, south = 6, + east = 5)), seed = 1), + "`allocation` has no entry for 1 stratum of `data`: `west`.", + fixed = TRUE) + expect_error( + inclusion_prob(d, design_stratified( + "site", allocation = c(north = 4, south = 6, east = 5, west = 5, + nrth = 1))), + "`allocation` names 1 stratum that `data` does not have: `nrth`.", + fixed = TRUE) + over <- design_stratified("site", allocation = c(north = 4, south = 6, + east = 5, west = 11)) + expect_error(draw(d, over, seed = 1), + "Stratum `west` has 10 row(s) but `allocation` asks for 11.", + fixed = TRUE) + expect_error(inclusion_prob(d, over), "asks for 11", fixed = TRUE) + over$replace <- TRUE + expect_equal(nrow(draw(d, over, seed = 1)), 26L) + + # A count of 0 leaves the stratum unreachable, and says so. + expect_warning( + draw(d, design_stratified("site", allocation = c(north = 4, south = 0, + east = 5, west = 5)), + seed = 1), + "Give each stratum a count of at least 1 in `allocation`", + class = "drawn_empty_stratum") +}) + +test_that("counts are checked when the design is built", { + four <- c(north = 4, south = 6, east = 5, west = 5) + expect_error(design_stratified("site", n = 21, allocation = four), + "`n` (21) is not the sum of the counts in `allocation` (20)", + fixed = TRUE) + expect_error(design_stratified("site", allocation = four, + min_per_stratum = 2), + "count of at least 2", fixed = TRUE) + expect_error(design_stratified("site", allocation = c(a = 2.5, b = 4)), + "stratum `a` has 2.5", fixed = TRUE) + expect_error(design_stratified("site", allocation = c(a = -1, b = 4)), + "whole numbers of 0 or more") + expect_error(design_stratified("site", allocation = c(a = 1e10, b = 4)), + paste0("must be at most 2147483647, the largest integer R ", + "holds; stratum `a` has 1e+10"), fixed = TRUE) + expect_error(design_stratified("site", allocation = c(4, 6)), + "must be named by stratum") + expect_error(design_stratified("site", allocation = c(a = 1, a = 4)), + "gives stratum `a` more than once", fixed = TRUE) + expect_error(design_stratified(c("g", "h"), allocation = c(a = 1)), + "a data frame with columns `g`, `h` and `n`", fixed = TRUE) + expect_error(design_stratified("g", allocation = data.frame(g = "a", + count = 3)), + "missing column: `n`", fixed = TRUE) + expect_error(design_stratified("site"), "`n` is missing", fixed = TRUE) + # Counts passed as `n` are pointed to `allocation`. + expect_error(design_stratified("site", n = four), + "Give the count for each stratum as `allocation`", + fixed = TRUE) +}) + +# ---- standard deviations and costs per stratum ----------------------------- + +sd_frame <- function() { + data.frame(id = 1:120, g = rep(c("a", "b", "c"), times = c(60, 40, 20)), + v = c(1:60 %% 5, (1:40 * 7) %% 23, (1:20 * 11) %% 37), + y = (1:120 * 13) %% 29 + 1) +} + +test_that("Neyman from standard deviations per stratum matches a column", { + d <- sd_frame() + by_col <- design_stratified("g", n = 24, allocation = "neyman", + allocation_by = "v", min_per_stratum = 2) + sds <- vapply(split(d$v, d$g), stats::sd, numeric(1)) + by_vec <- design_stratified("g", n = 24, allocation = "neyman", + allocation_by = sds, min_per_stratum = 2) + by_df <- design_stratified( + "g", n = 24, allocation = "neyman", min_per_stratum = 2, + allocation_by = data.frame(g = c("c", "a", "b"), + sd = unname(sds[c("c", "a", "b")]))) + expect_output(print(by_vec), "allocation_by c(a = ", fixed = TRUE) + + # Given the standard deviations, the frame needs no `v` column, on any + # path. + bare <- d[c("id", "g", "y")] + p <- inclusion_prob(d, by_col) + expect_equal(inclusion_prob(bare, by_vec), p) + expect_equal(inclusion_prob(bare, by_df), p) + expect_identical(draw(bare, by_vec, seed = 1)$id, + draw(d, by_col, seed = 1)$id) + rows <- c(1, 2, 61, 101) + expect_equal(joint_prob(bare, by_vec, rows = rows), + joint_prob(d, by_col, rows = rows)) + s <- draw(bare, by_vec, seed = 1, weights = TRUE) + ref <- draw(d, by_col, seed = 1, weights = TRUE) + expect_equal(ht_total(s, "y")$se, ht_total(ref, "y")$se) + expect_equal(ht_total(s, "y", variance = "jackknife")$se, + ht_total(ref, "y", variance = "jackknife")$se) + + skip_if_not_installed("survey") + expect_equal( + unname(survey::SE(survey::svytotal(~y, as_svydesign(s)))[1]), + ht_total(s, "y")$se) +}) + +test_that("costs per stratum give the cost-optimal split", { + # Shares proportional to N_h * S_h / sqrt(c_h), rounded by largest + # remainder: 27.71, 25.98, 6.93 and 29.39 rows. + sizes <- c(a = 400, b = 300, c = 200, d = 100) + S <- c(2, 5, 3, 12) + cst <- c(1, 4, 9, 2) + share <- sizes * S / sqrt(cst) + want <- 90 * share / sum(share) + got <- drawn:::allocate(90, sizes, "neyman", 0, spread = S, cost = cst) + expect_equal(sum(got), 90L) + expect_true(all(abs(got - want) < 1)) + expect_equal(unname(got), c(28L, 26L, 7L, 29L)) + + # The same through a frame, with the values in one data frame + d <- data.frame(g = rep(names(sizes), times = sizes)) + pilot <- data.frame(g = names(sizes), sd = S, cost = cst) + des <- design_stratified("g", n = 90, allocation = "neyman", + allocation_by = pilot, cost = pilot) + expect_equal(inclusion_prob(d, des), + unname((got / sizes)[d$g])) + expect_equal(c(table(draw(d, des, seed = 1)$g)), got) + tab <- allocation_table(d, des) + expect_equal(tab$n, unname(got)) + expect_equal(tab$sd, S) + expect_equal(tab$cost, cst) + + # Costs with a column: the spread is the column's within each stratum. + f <- sd_frame() + sds <- vapply(split(f$v, f$g), stats::sd, numeric(1)) + costs <- c(a = 1, b = 4, c = 9) + by_col <- design_stratified("g", n = 24, allocation = "neyman", + allocation_by = "v", cost = costs) + expect_equal(allocation_table(f, by_col)$n, + unname(drawn:::allocate(24, c(60, 40, 20), "neyman", 0, + spread = sds, cost = costs))) + + # With no spread anywhere, the shares are those for equal spreads. + expect_equal(drawn:::allocate(30, c(100, 100), "neyman", 0, + spread = c(0, 0), cost = c(1, 4)), + c(20L, 10L)) +}) + +test_that("standard deviations and costs are checked at construction", { + ney <- function(...) { + design_stratified("g", n = 10, allocation = "neyman", ...) + } + expect_error(ney(allocation_by = c(a = 1, b = -2)), + paste0("The standard deviations in `allocation_by` must be ", + "finite numbers of 0 or more, and stratum `b` has -2."), + fixed = TRUE) + expect_error(ney(allocation_by = c(a = 1, b = Inf)), "stratum `b` has Inf", + fixed = TRUE) + expect_error(ney(allocation_by = c(a = 1, b = NA)), "stratum `b` has NA", + fixed = TRUE) + expect_error(ney(allocation_by = c(1, 2)), "must be named by stratum") + expect_error(ney(allocation_by = TRUE), + "`allocation_by` must be a column name, or the standard", + fixed = TRUE) + expect_error(ney(allocation_by = data.frame(g = c("a", "b"), + sd = c("1", "2"))), + "must be numbers, not character", fixed = TRUE) + expect_error(ney(allocation_by = data.frame(g = "a", s = 1)), + "missing column: `sd`", fixed = TRUE) + expect_error(ney(allocation_by = "v", cost = c(a = 1, b = 0)), + paste0("The costs in `cost` must be finite numbers above 0, ", + "and stratum `b` has 0."), fixed = TRUE) + expect_error(ney(allocation_by = "v", cost = c(a = 1, b = -3)), + "stratum `b` has -3", fixed = TRUE) + expect_error(design_stratified(c("g", "h"), n = 10, allocation = "neyman", + allocation_by = "v", cost = c(a = 1)), + "a data frame with columns `g`, `h` and `cost`", fixed = TRUE) + + # Costs shape a Neyman split and nothing else. + expect_error(design_stratified("g", n = 10, cost = c(a = 1, b = 2)), + paste0("`cost` applies only to allocation = \"neyman\", and ", + "`allocation` is \"proportional\"."), fixed = TRUE) + expect_error(design_stratified("g", allocation = c(a = 1, b = 2), + cost = c(a = 1, b = 2)), + "`allocation` gives the count for each stratum", fixed = TRUE) +}) + +test_that("standard deviations and costs that miss a stratum are refused", { + d <- sd_frame() + short <- design_stratified("g", n = 12, allocation = "neyman", + allocation_by = c(a = 1, b = 2)) + msg <- "`allocation_by` has no entry for 1 stratum of `data`: `c`." + expect_error(draw(d, short, seed = 1), msg, fixed = TRUE) + expect_error(inclusion_prob(d, short), msg, fixed = TRUE) + expect_error(allocation_table(d, short), msg, fixed = TRUE) + # A value for a stratum the frame does not have changes nothing. + three <- design_stratified("g", n = 12, allocation = "neyman", + allocation_by = c(a = 1, b = 2, c = 3), + cost = c(a = 1, b = 4, c = 1)) + four <- design_stratified("g", n = 12, allocation = "neyman", + allocation_by = c(a = 1, b = 2, c = 3, cc = 4), + cost = c(cc = 9, a = 1, b = 4, c = 1)) + expect_identical(inclusion_prob(d, four), inclusion_prob(d, three)) + expect_identical(allocation_table(d, four), allocation_table(d, three)) + expect_error( + draw(d, design_stratified("g", n = 12, allocation = "neyman", + allocation_by = "v", cost = c(a = 1, c = 2)), + seed = 1), + "`cost` has no entry for 1 stratum of `data`: `b`.", fixed = TRUE) + + # A standard deviation of 0 leaves a stratum without a share, and the + # warning says where that came from. + zero <- design_stratified("g", n = 12, allocation = "neyman", + allocation_by = c(a = 0, b = 2, c = 3)) + w <- tryCatch(draw(d, zero, seed = 1), drawn_empty_stratum = function(w) w) + expect_match(conditionMessage(w), paste0( + "`allocation_by` gives it a standard deviation of 0, so Neyman ", + "allocation gives it no share"), fixed = TRUE) +}) + +test_that("standard deviations serve the rest of a certainty design", { + # Every row of `a` is above the threshold, so `rest` sees no `a`. + d <- data.frame(id = 1:200, + g = rep(c("a", "b", "c", "d"), times = c(6, 64, 70, 60)), + value = c(rep(1000, 6), seq(1, 100, length.out = 194))) + des <- design_certainty("value", 500, design_stratified( + "g", n = 20, allocation = "neyman", + allocation_by = c(a = 5, b = 1, c = 2, d = 3))) + p <- inclusion_prob(d, des) + expect_equal(p[1:6], rep(1, 6)) + expect_equal(sum(p), 26) + s <- draw(d, des, seed = 1) + expect_identical(nrow(s), 26L) +}) + +test_that("Neyman shares far apart in size split as their ratios say", { + d <- data.frame(id = 1:90, g = rep(c("a", "b", "c"), each = 30)) + ney <- function(n, ...) { + design_stratified("g", n = n, allocation = "neyman", ...) + } + # Spreads near the largest double, and spreads over costs whose product + # overflows, split as the same ratios on a plain scale do. + plain <- allocation_table(d, ney(12, allocation_by = c(a = 1, b = 1, + c = 1e-307))) + near <- allocation_table(d, ney(12, allocation_by = c(a = 1e307, + b = 1e307, c = 1))) + expect_identical(near$n, plain$n) + expect_identical(near$n, c(6L, 6L, 0L)) + priced <- ney(12, allocation_by = c(a = 1e200, b = 1, c = 1), + cost = c(a = 1e-300, b = 1, c = 1)) + expect_identical(allocation_table(d, priced)$n, c(12L, 0L, 0L)) + # Spreads over costs whose product underflows split by their ratios too. + tiny <- ney(12, allocation_by = c(a = 1e-200, b = 2e-200, c = 1e-200), + cost = c(a = 1e300, b = 1e300, c = 1e300)) + expect_identical(allocation_table(d, tiny)$n, c(3L, 6L, 3L)) + + # Shares 1e20 apart: the largest takes what it can, then the next. + spread <- c(a = 1e20, b = 1, c = 1e-20) + drawn_from <- function(n) { + s <- suppressWarnings(draw(d, ney(n, allocation_by = spread), seed = 1)) + as.vector(table(factor(s$g, levels = c("a", "b", "c")))) + } + expect_equal(drawn_from(12), c(12, 0, 0)) + expect_equal(drawn_from(50), c(30, 20, 0)) + expect_equal(drawn_from(75), c(30, 30, 15)) + expect_identical( + allocation_table(d, ney(12, allocation_by = c(a = 1, b = 1, c = 1), + cost = c(a = 1e-40, b = 1, c = 1e40)))$n, + c(12L, 0L, 0L)) +}) + +test_that("a column scale that overflows keeps the small strata's spread", { + # sd() overflows in `a` and `b`, not in `c`, whose values vary. + d <- data.frame(id = 1:90, g = rep(c("a", "b", "c"), each = 30), + v = c(rep(c(0, 1e307), 30), rep(c(0, 1), 15))) + des <- design_stratified("g", n = 12, allocation = "neyman", + allocation_by = "v") + tab <- allocation_table(d, des) + expect_equal(tab$sd, stats::sd(rep(c(0, 1), 15)) * c(1e307, 1e307, 1)) + w <- tryCatch(draw(d, des, seed = 1), drawn_empty_stratum = function(w) w) + expect_match(conditionMessage(w), "1 stratum (`c`) is allocated no rows", + fixed = TRUE) + expect_no_match(conditionMessage(w), "constant", fixed = TRUE) +}) + +# ---- allocation_table() ---------------------------------------------------- + +status_frame <- function() { + data.frame(id = 1:262, + site = rep(c("a", "b", "c", "d", "e"), c(150, 80, 25, 5, 2)), + v = c(1:150 %% 7, (1:80 * 7) %% 19, rep(1:2, length.out = 25), + c(1, 90, 3, 70, 40), c(4, 4))) +} + +test_that("allocation_table() agrees with the draw and inclusion_prob()", { + d <- status_frame() + des <- design_stratified("site", n = 30, allocation = "neyman", + allocation_by = "v", min_per_stratum = 3) + tab <- allocation_table(d, des) + expect_identical(names(tab), + c("site", "N", "n", "prob", "sd", "cost", "status")) + expect_identical(tab$site, c("a", "b", "c", "d", "e")) + expect_equal(tab$N, c(150L, 80L, 25L, 5L, 2L)) + expect_equal(tab$n, as.vector(table(draw(d, des, seed = 1)$site))) + expect_equal(tab$prob, + as.vector(tapply(inclusion_prob(d, des), d$site, unique))) + expect_equal(tab$sd, as.vector(tapply(d$v, d$site, stats::sd))) + expect_true(all(is.na(tab$cost))) + # `d` is small and varies most, so the rule asks more of it than its 5 + # rows; `e` is smaller than the floor; `c` barely varies. + expect_identical(tab$status, c("rule", "rule", "floor", "capped", + "take-all")) + + # Without the floor, `c`'s share rounds to nothing and `e` has no spread. + bare <- allocation_table(d, design_stratified( + "site", n = 30, allocation = "neyman", allocation_by = "v")) + expect_identical(bare$status, c("rule", "rule", "empty", "capped", "empty")) + expect_equal(bare$prob[bare$status == "empty"], c(0, 0)) + + # With replacement no stratum is capped or taken whole. + rep_des <- design_stratified("site", n = 30, allocation = "neyman", + allocation_by = "v", min_per_stratum = 3, + replace = TRUE) + tab <- allocation_table(d, rep_des) + expect_identical(tab$status, c("rule", "rule", "floor", "rule", "floor")) + expect_equal(tab$prob, + as.vector(tapply(inclusion_prob(d, rep_des), d$site, unique))) + + # A census takes every stratum whole without capping any. + expect_identical( + allocation_table(d, design_stratified("site", n = 262))$status, + rep("take-all", 5)) + + # Counts as given + cnt <- allocation_table(d, design_stratified( + "site", allocation = c(a = 3, b = 0, c = 25, d = 2, e = 1))) + expect_identical(cnt$status, c("count", "empty", "take-all", "count", + "count")) + expect_true(all(is.na(cnt$sd))) + + # Values whose standard deviation overflows inside sd() are split on a + # smaller scale; the table reports the spread on the column's own scale. + big <- d + big$v <- big$v * 1e305 + expect_equal(allocation_table(big, des)$sd, + allocation_table(d, des)$sd * 1e305) +}) + +test_that("allocation_table() keeps the strata columns and their order", { + d <- data.frame(id = 1:40, g = factor(rep(c("b", "a"), 20), + levels = c("b", "a")), + h = rep(c(1.5, 2), each = 20)) + tab <- allocation_table(d, design_stratified(c("g", "h"), n = 8)) + expect_identical(tab$g, factor(c("b", "b", "a", "a"), levels = c("b", "a"))) + expect_identical(tab$h, c(1.5, 2, 1.5, 2)) + expect_equal(tab$n, rep(2L, 4)) +}) + +test_that("allocation_table() describes the rest of a certainty design", { + d <- status_frame() + d$w <- c(rep(1, 250), seq(100, 1200, by = 100)) + rest <- design_stratified("site", n = 20, min_per_stratum = 2) + des <- design_certainty("w", threshold = 100, rest = rest) + tab <- allocation_table(d, des) + below <- d$w < 100 + expect_equal(tab$N, as.vector(table(d$site[below]))) + expect_equal(tab$prob, as.vector(tapply(inclusion_prob(d, des)[below], + d$site[below], unique))) + expect_equal(tab, allocation_table(d[below, ], rest)) + + # With every row at or above the threshold, `rest` has no strata. + none <- allocation_table(d, design_certainty("w", threshold = 0, + rest = rest)) + expect_equal(nrow(none), 0L) + expect_identical(names(none), names(tab)) +}) + +test_that("allocation_table() refuses what it cannot describe", { + d <- status_frame() + expect_error(allocation_table(d, design_simple(n = 3)), + "which has no strata to allocate over", fixed = TRUE) + expect_error(allocation_table(d, list()), + "`design` must come from one of the design_*() constructors", + fixed = TRUE) + clash <- data.frame(n = rep(c("x", "y"), 5)) + expect_error(allocation_table(clash, design_stratified("n", n = 4)), + paste0("`strata` column `n` has the name of a column ", + "allocation_table() adds."), fixed = TRUE) +}) + +# ---- systematic sampling within strata --------------------------------------- + +walk_frame <- function() { + data.frame(id = 1:30, g = rep(c("b", "a"), c(17, 13)), + v = (1:30 * 7) %% 31, y = (1:30 * 13) %% 17 + 1:30) +} + +test_that("within takes a systematic design the allocation can size", { + within <- design_systematic(order_by = "v") + des <- design_stratified("g", n = 9, within = within) + expect_identical(des$within, within) + expect_null(design_stratified("g", n = 9)$within) + expect_output(print(des), 'within +design_systematic\\(order_by = "v"\\)') + expect_error(design_stratified("g", n = 9, within = design_simple(n = 2)), + "not design_simple(n = 2)", fixed = TRUE) + expect_error(design_stratified("g", n = 9, within = "systematic"), + "`within` must be NULL") + expect_error(design_stratified("g", n = 9, within = design_systematic(3)), + "and has `interval` (3)", fixed = TRUE) + expect_error(design_stratified("g", n = 9, within = design_systematic(n = 3)), + "and has `n` (3)", fixed = TRUE) + expect_error(design_stratified("g", n = 9, replace = TRUE, within = within), + "cannot be combined with replace = TRUE") +}) + +test_that("within draws n_h rows from each stratum at a step of N_h / n_h", { + d <- walk_frame() + des <- design_stratified("g", n = 9, within = design_systematic(order_by = "v")) + tab <- allocation_table(d, des) + expect_equal(tab$n, c(4L, 5L)) + for (seed in 1:15) { + s <- draw(d, des, seed = seed) + expect_identical(s$id, sort(s$id)) + for (h in c("a", "b")) { + in_h <- d[d$g == h, ] + # Positions along the stratum's walk, sorted on `v`. + pos <- sort(match(s$v[s$g == h], sort(in_h$v))) + expect_length(pos, tab$n[tab$g == h]) + step <- nrow(in_h) / length(pos) + expect_true(all(diff(pos) %in% c(floor(step), ceiling(step))), + info = paste("seed", seed, "stratum", h)) + } + } + # Without order_by each stratum is walked in frame order. + s <- draw(d, design_stratified("g", n = 9, within = design_systematic()), + seed = 1) + expect_true(all(diff(s$id[s$g == "b"]) %in% 3:4)) +}) + +test_that("within gives n_h / N_h to each row and exact joint probabilities", { + d <- walk_frame() + des <- design_stratified("g", n = 9, within = design_systematic(order_by = "v")) + pi <- inclusion_prob(d, des) + expect_equal(pi, ifelse(d$g == "a", 4 / 13, 5 / 17)) + jp <- joint_prob(d, des) + expect_equal(diag(jp), pi) + # Two strata are drawn independently. + expect_equal(jp[d$g == "a", d$g == "b"], tcrossprod(pi[d$g == "a"], + pi[d$g == "b"])) + # Within a stratum the size is fixed, so each row's pairs sum to n_h pi. + for (h in c("a", "b")) { + i <- which(d$g == h) + expect_equal(rowSums(jp[i, i]), sum(pi[i]) * pi[i]) + } + # Two rows of one stratum next to each other on its walk never co-occur. + b <- which(d$g == "b") + nb <- b[order(d$v[b])][1:2] + expect_equal(jp[nb[1], nb[2]], 0) + sim <- joint_prob(d, des, simulate = TRUE, R = 2000, seed = 1) + expect_lt(max(abs(jp - sim)), 0.04) +}) + +test_that("within adds up the strata's successive-difference variances", { + d <- walk_frame() + des <- design_stratified("g", n = 9, within = design_systematic(order_by = "v")) + s <- draw(d, des, seed = 4, weights = TRUE) + r <- ht_total(s, "y") + want <- 0 + for (h in c("a", "b")) { + sh <- s[s$g == h, ] + sh <- sh[order(sh$v), ] + n_h <- nrow(sh) + f <- n_h / sum(d$g == h) + want <- want + (1 - f) * n_h / (2 * (n_h - 1)) * + sum(diff(sh$y / sh$.prob)^2) + } + expect_equal(r$variance, want) + expect_identical(r$method, "successive difference") + expect_match(r$note, "within strata") + expect_equal(r$df, 9 - 2) + expect_match(ht_total(s, "y", variance = "jackknife")$note, + "Each stratum of a systematic sample within strata") + # Domains go through the same estimator. + by <- ht_total(s, "y", by = "g") + expect_equal(by$total, as.vector(tapply(s$y / s$.prob, s$g, sum))) + expect_true(all(by$method == "successive difference")) + # Each domain is a stratum here, so the two variances add up to the total's. + expect_equal(sum(by$se^2), r$variance) +}) + +test_that("within refuses a stratum with one sampled row", { + d <- walk_frame() + des <- design_stratified("g", allocation = c(a = 1, b = 3), + within = design_systematic(order_by = "v")) + s <- draw(d, des, seed = 1, weights = TRUE) + r <- ht_total(s, "y") + expect_true(is.na(r$se)) + expect_match(r$note, "The stratum `a` has a single sampled row") +}) + +test_that("within leaves out rows with a missing order_by only when told to", { + d <- walk_frame() + d$v[c(2, 20)] <- NA + strict <- design_stratified("g", n = 9, + within = design_systematic(order_by = "v")) + expect_error(draw(d, strict, seed = 1), "2 row(s) have a missing `v`", + fixed = TRUE) + expect_error(inclusion_prob(d, strict), "2 row(s) have a missing `v`", + fixed = TRUE) + des <- design_stratified("g", n = 9, + within = design_systematic(order_by = "v", + na_rm = TRUE)) + tab <- allocation_table(d, des) + expect_equal(tab$N, c(12L, 16L)) + pi <- inclusion_prob(d, des) + expect_equal(pi[c(2, 20)], c(0, 0)) + expect_equal(pi[-c(2, 20)], tab$prob[match(d$g[-c(2, 20)], tab$g)]) + s <- draw(d, des, seed = 1, weights = TRUE) + expect_false(any(c(2, 20) %in% s$.row)) + # sample_summary() counts the rows each stratum walks. + grp <- sample_summary(s)$by_group + expect_equal(grp$in_frame, c(12L, 16L)) + expect_equal(grp$rate, round(tab$prob, 4)) + # A stratum left with no row to walk is refused. + d$v[d$g == "a"] <- NA + expect_error(inclusion_prob(d, des), + "Stratum `a` has a missing `v` in every row", fixed = TRUE) + skip_if_not_installed("survey") + d <- walk_frame() + d$v[c(2, 20)] <- NA + s <- draw(d, des, seed = 1, weights = TRUE) + sv <- as_svydesign(s) + # `survey` gets the strata and the rows walked in each. + expect_equal(sort(unique(sv$fpc$popsize[, 1])), c(12, 16)) + expect_equal(survey::degf(sv), ht_total(s, "y")$df) + expect_equal(unname(coef(survey::svytotal(~y, sv))), ht_total(s, "y")$total) +}) diff --git a/tests/testthat/test-design-systematic.R b/tests/testthat/test-design-systematic.R index de4f346..82202d7 100644 --- a/tests/testthat/test-design-systematic.R +++ b/tests/testthat/test-design-systematic.R @@ -46,3 +46,470 @@ test_that("NA sort keys are reported rather than silently sorted last", { na_rm = TRUE)) expect_false(anyNA(res$v)) }) + +test_that("a text order_by is walked in byte order in every locale", { + d <- data.frame(id = 1:12, + key = c("a", "B", "c", "D", "e", "F", "g", "H", "i", "J", + "k", "L"), + y = 1:12) + des <- design_systematic(interval = 3, order_by = "key") + walk <- order(d$key, method = "radix") + pos <- integer(12) + pos[walk] <- 1:12 + expect_identical(drawn:::systematic_positions(des, d), pos) + ids <- draw(d, des, seed = 1)$id + expect_length(ids, 4L) + expect_length(unique((pos[ids] - 1L) %% 3L), 1L) + s <- draw(d, des, seed = 1, weights = TRUE) + want <- ht_total(s, "y")$se + pij <- joint_prob(d, des) + with_other_collation({ + expect_identical(drawn:::systematic_positions(des, d), pos) + expect_identical(draw(d, des, seed = 1)$id, ids) + expect_equal(ht_total(s, "y")$se, want) + expect_equal(joint_prob(d, des), pij) + }) +}) + +# One sample for each start: every start has probability 1 / interval, so +# averages over these are exact expectations. +every_start <- function(d, des) { + out <- list() + i <- 0L + while (length(out) < des$interval && i < 500L) { + i <- i + 1L + s <- suppressWarnings(draw(d, des, seed = i, weights = TRUE)) + out[[paste(s$.row, collapse = ",")]] <- s + } + unname(out) +} + +test_that("a random sample size adds its own variance", { + # 244 rows at interval 8 give samples of 30 or 31 rows. Successive + # differences cannot see that, so this near-constant `y` got 0.016 of its + # true variance, and a constant one a standard error of 0. + d <- data.frame(y = 1000 + (seq_len(244) * 37) %% 41 - 20, one = 1) + des <- design_systematic(interval = 8) + samples <- every_start(d, des) + expect_length(samples, 8L) + est <- vapply(samples, function(s) { + r <- ht_total(s, "y") + c(r$total, r$variance) + }, numeric(2)) + ratio <- mean(est[2, ]) / mean((est[1, ] - sum(d$y))^2) + expect_gt(ratio, 0.8) + expect_lt(ratio, 1.25) + + # For a constant `y` the term is exact: the total is 8 times the sample + # size, which is 30 or 31 with equal chance. + r <- ht_total(samples[[1]], "one") + expect_equal(r$se, 8 * 0.5) + expect_match(r$note, "random, 30 or 31 rows") + + # The mean over the known N carries the same term; the Hajek mean's + # residuals average 0 and do not. + m <- ht_mean(samples[[1]], "one", estimator = "ht") + expect_equal(m$se, 8 * 0.5 / 244) + expect_equal(ht_mean(samples[[1]], "y")$variance, + ht_mean(samples[[1]], "y", variance = "analytic")$variance) + h <- vapply(samples, function(s) { + u <- (s$y - mean(s$y)) / nrow(s) + k <- 8 + n <- nrow(s) + c(ht_mean(s, "y")$variance, + (1 - 1 / k) * n / (2 * (n - 1)) * sum(diff(u)^2)) + }, numeric(2)) + expect_equal(h[1, ], h[2, ]) +}) + +test_that("an interval that divides the frame adds nothing", { + d <- data.frame(y = 1000 + (seq_len(240) * 37) %% 41 - 20) + s <- draw(d, design_systematic(interval = 8), seed = 1, weights = TRUE) + r <- ht_total(s, "y") + n <- nrow(s) + expect_equal(r$variance, + (1 - 1 / 8) * n / (2 * (n - 1)) * sum(diff(8 * s$y)^2)) + expect_false(grepl("random", r$note)) +}) + +test_that("the rows an order_by drops do not count towards the remainder", { + # 246 rows, 2 with no sort key: 244 walked, 30 or 31 drawn. + d <- data.frame(key = c(NA, NA, seq_len(244)), one = 1) + s <- draw(d, design_systematic(interval = 8, order_by = "key", na_rm = TRUE), + seed = 1, weights = TRUE) + r <- ht_total(s, "one") + expect_equal(r$se, 4) + expect_match(r$note, "The 244 rows walked") +}) + +test_that("an order_by the frame lacks is refused on every path", { + # The probability paths gave every row 0 and every weight NA for a + # misspelt or missing column, where draw() refused it. + d <- data.frame(id = 1:24, v = (24:1) / 2, y = 1:24) + des <- design_systematic(interval = 4, order_by = "V") + want <- "`data` is missing column: `V`." + expect_error(draw(d, des, seed = 1), want, fixed = TRUE) + expect_error(inclusion_prob(d, des), want, fixed = TRUE) + expect_error(sampling_weight(d, des), want, fixed = TRUE) + expect_error(joint_prob(d, des, rows = 1:3), want, fixed = TRUE) + expect_error( + drawn:::ht_variance.drawn_design_systematic(des, d, 1:6, 1:6, rep(0.25, 6)), + want, fixed = TRUE) +}) + +test_that("deleting order_by from the frame after the draw leaves the sample", { + # The stored copy of the frame shared its names with the caller's, so + # deleting the column in place took it out of the copy too, and ht_total() + # refused the sample. + skip_if_not_installed("data.table") + d <- data.frame(id = 1:80, w = (80:1) / 4, y = sin(1:80) * 10 + 1:80) + s <- draw(d, design_systematic(interval = 8, order_by = "w"), seed = 1, + weights = TRUE) + want <- ht_total(s, "y") + data.table::set(d, j = "w", value = NULL) + expect_identical(names(attr(s, "drawn_population")), c("id", "w", "y")) + expect_equal(ht_total(s, "y"), want) +}) + +test_that("design_systematic() takes `interval` or `n`, and `start` with `interval`", { + expect_identical(design_systematic(7), design_systematic(interval = 7)) + # Without either it is built, for design_stratified(within =), and refused + # wherever it would have to draw on its own. + bare <- design_systematic(order_by = "id") + d <- data.frame(id = 1:10) + want <- "`design_systematic()` has no `interval` or `n`" + expect_error(draw(d, bare, seed = 1), want, fixed = TRUE) + expect_error(inclusion_prob(d, bare), want, fixed = TRUE) + expect_error(joint_prob(d, bare), want, fixed = TRUE) + expect_error(design_systematic(start = 2), "`start` needs `interval`") + expect_error(design_systematic(5, n = 3), "not both") + expect_error(design_systematic(n = 3, start = 1), + "`start` cannot be fixed with `n`") + expect_error(design_systematic(interval = 2.5), + "give the sample size as `n`") + expect_error(design_systematic(n = 2.5), "single whole number") + expect_error(design_systematic(n = -1), "non-negative") + des <- design_systematic(n = 7) + expect_output(print(des), "n +7") + expect_identical(drawn:::design_label(des), "design_systematic(n = 7)") +}) + +test_that("n draws exactly n rows at a step that need not be whole", { + d <- data.frame(id = 1:50, v = 50:1) + for (seed in 1:20) { + ids <- draw(d, design_systematic(n = 7), seed = seed)$id + expect_length(ids, 7L) + # A step of 50 / 7 rows leaves gaps of 7 or 8 along the walk. + expect_true(all(diff(ids) %in% 7:8), info = paste("seed", seed)) + # With order_by the gaps of 12 or 13 are counted along the sorted walk. + ids <- draw(d, design_systematic(n = 4, order_by = "v"), seed = seed)$id + expect_length(ids, 4L) + expect_true(all(diff(sort(d$v[ids])) %in% 12:13), + info = paste("seed", seed)) + } + expect_equal(nrow(draw(d, design_systematic(n = 0), seed = 1)), 0L) + expect_identical(draw(d, design_systematic(n = 50), seed = 1)$id, 1:50) +}) + +test_that("n gives every row n / N and every pair its overlap", { + d <- data.frame(id = 1:50) + des <- design_systematic(n = 7) + expect_equal(inclusion_prob(d, des), rep(7 / 50, 50)) + jp <- joint_prob(d, des) + expect_equal(diag(jp), rep(7 / 50, 50)) + # The size is fixed, so each row's pairs add up to n times its own pi. + expect_equal(rowSums(jp), rep(7 * 7 / 50, 50)) + expect_equal(jp[1, 2], 0) + sim <- joint_prob(d, des, simulate = TRUE, R = 2000, seed = 1) + expect_lt(max(abs(jp - sim)), 0.04) + # A step that divides N is the interval design. + d60 <- data.frame(id = 1:60) + expect_equal(joint_prob(d60, design_systematic(n = 10)), + joint_prob(d60, design_systematic(interval = 6))) +}) + +test_that("averaging over the start gives the joint probabilities and the total", { + # The rows taken change only where `u` crosses frac(j * n / N), so the + # expectation over `u` is a sum over the pieces between those points. + N <- 13L + n <- 5L + d <- data.frame(y = c(4, 9, 1, 7, 3, 12, 6, 2, 8, 5, 11, 10, 15)) + cuts <- sort(unique(c(0, 1, (seq_len(N) * n / N) %% 1))) + mid <- (cuts[-1] + cuts[-length(cuts)]) / 2 + len <- diff(cuts) + pairs <- matrix(0, N, N) + total <- 0 + for (i in seq_along(mid)) { + s <- drawn:::fractional_walk(mid[i], n, N) + expect_length(unique(s), n) + pairs[s, s] <- pairs[s, s] + len[i] + total <- total + len[i] * sum(d$y[s]) * N / n + } + expect_equal(joint_prob(d, design_systematic(n = n)), pairs) + expect_equal(total, sum(d$y)) +}) + +test_that("samples drawn with `interval` are the same for a seed as before", { + d <- data.frame(id = 1:100, value = (1:100) / 10) + des <- design_systematic(interval = 7) + expect_identical(draw(d, des, seed = 1)$id, seq(1L, 100L, by = 7L)) + expect_identical(draw(d, des, seed = 2)$id, seq(5L, 100L, by = 7L)) + expect_identical(draw(d, des, seed = 4)$id, seq(3L, 100L, by = 7L)) + expect_identical( + draw(d, design_systematic(interval = 6, order_by = "value"), seed = 9)$id, + seq(3L, 100L, by = 6L)) +}) + +test_that("a fixed-size sample has no term for a random size", { + d <- data.frame(y = 1000 + (seq_len(244) * 37) %% 41 - 20, one = 1) + s <- draw(d, design_systematic(n = 30), seed = 1, weights = TRUE) + expect_equal(nrow(s), 30L) + # Every sample gives the frame's row count exactly. + r <- ht_total(s, "one") + expect_equal(r$total, 244) + expect_equal(r$se, 0) + r <- ht_total(s, "y") + u <- s$y * 244 / 30 + expect_equal(r$variance, (1 - 30 / 244) * 30 / (2 * 29) * sum(diff(u)^2)) + expect_false(grepl("random", r$note)) + expect_match(r$note, "the step of 8.133 rows", fixed = TRUE) + expect_equal(r$df, 29) +}) + +test_that("an n above the rows walked is refused on every path", { + d <- data.frame(v = c(NA, 1:9)) + des <- design_systematic(n = 10, order_by = "v", na_rm = TRUE) + want <- "`n` (10) cannot exceed the number of rows walked (9)." + expect_error(draw(d, des, seed = 1), want, fixed = TRUE) + expect_error(inclusion_prob(d, des), want, fixed = TRUE) + expect_error(joint_prob(d, des), want, fixed = TRUE) + # The row with no sort key is never walked. + ok <- design_systematic(n = 4, order_by = "v", na_rm = TRUE) + expect_equal(inclusion_prob(d, ok), c(0, rep(4 / 9, 9))) + jp <- joint_prob(d, ok) + expect_equal(jp[1, ], rep(0, 10)) + expect_equal(rowSums(jp)[-1], rep(4 * 4 / 9, 9)) +}) + +test_that("a fixed-size systematic sample goes to survey with the rows walked", { + skip_if_not_installed("survey") + d <- data.frame(id = 1:50, v = c(NA, 49:1), y = sin(1:50) * 10 + 1:50) + s <- draw(d, design_systematic(n = 7, order_by = "v", na_rm = TRUE), + seed = 3, weights = TRUE) + sv <- as_svydesign(s) + r <- ht_total(s, "y") + expect_equal(unname(coef(survey::svytotal(~y, sv))), r$total) + expect_equal(survey::degf(sv), r$df) + expect_equal(unname(sv$fpc$popsize[, 1]), rep(49, 7)) +}) + +# ---- several random starts --------------------------------------------------- + +# Every set of `m` starts from 1:(m * k), each walked at a step of m * k: +# the rows each set takes, all equally likely. +every_start_set <- function(N, k, m) { + sets <- utils::combn(m * k, m) + lapply(seq_len(ncol(sets)), function(j) { + st <- sets[, j] + sort(unlist(lapply(st[st <= N], function(s) seq(s, N, by = m * k)))) + }) +} + +test_that("n_starts is checked when the design is built", { + des <- design_systematic(interval = 10, n_starts = 3) + expect_identical(des$n_starts, 3L) + expect_identical(design_systematic(10)$n_starts, 1L) + expect_output(print(des), "n_starts +3") + expect_identical(drawn:::design_label(des), + "design_systematic(interval = 10, n_starts = 3)") + expect_identical(drawn:::design_label(design_systematic(10)), + "design_systematic(interval = 10)") + expect_error(design_systematic(10, n_starts = 0), "at least 1") + expect_error(design_systematic(10, n_starts = 1.5), "single whole number") + expect_error(design_systematic(n = 4, n_starts = 2), + "Give `interval` in place of `n`") + expect_error(design_systematic(n_starts = 2), "needs `interval`") + expect_error(design_systematic(3, start = 1, n_starts = 2), + "`start` cannot be fixed with `n_starts` (2)", fixed = TRUE) + expect_error(design_systematic(1e9, n_starts = 3), "must be at most") +}) + +test_that("n_starts draws that many replicates, each at a step of n_starts * interval", { + d <- data.frame(id = 1:120) + for (seed in 1:10) { + ids <- draw(d, design_systematic(interval = 10, n_starts = 4), + seed = seed)$id + # 120 rows at a step of 40: three rows from each of four starts. + expect_length(ids, 12L) + expect_equal(as.vector(table((ids - 1L) %% 40L)), rep(3L, 4)) + } + # A seed draws the rows it drew before n_starts existed. + expect_identical(draw(d, design_systematic(7, n_starts = 1), seed = 2)$id, + seq(5L, 120L, by = 7L)) +}) + +test_that("several starts give every pair its exact joint probability", { + # 23 rows, interval 3 and 2 starts from 1:6: averaging over all 15 sets + # of starts gives the joint probabilities exactly. + d <- data.frame(y = c(4, 9, 1, 7, 3, 12, 6, 2, 8, 5, 11, 10, 15, 3, 9, 14, + 2, 6, 8, 1, 13, 7, 5)) + des <- design_systematic(interval = 3, n_starts = 2) + sets <- every_start_set(23L, 3L, 2L) + pairs <- matrix(0, 23, 23) + for (rows in sets) pairs[rows, rows] <- pairs[rows, rows] + 1 / length(sets) + jp <- joint_prob(d, des) + expect_equal(jp, pairs) + expect_equal(inclusion_prob(d, des), rep(1 / 3, 23)) + # Same residue class modulo 6, then two classes. + expect_equal(jp[1, 7], 1 / 3) + expect_equal(jp[1, 2], 2 * 1 / (6 * 5)) + sim <- joint_prob(d, des, simulate = TRUE, R = 2000, seed = 1) + expect_lt(max(abs(jp - sim)), 0.04) +}) + +test_that("the variance between replicates is unbiased over every set of starts", { + check <- function(y, k, m) { + N <- length(y) + des <- design_systematic(interval = k, n_starts = m) + est <- vapply(every_start_set(N, k, m), function(rows) { + c(k * sum(y[rows]), + drawn:::replicate_variance(des, seq_len(N), rows, y[rows], + rep(1 / k, length(rows)))$variance) + }, numeric(2)) + expect_equal(mean(est[1, ]), sum(y)) + expect_equal(mean(est[2, ]), mean((est[1, ] - sum(y))^2)) + } + # 23 rows at a step of 6, so the replicates differ in size. + check(c(4, 9, 1, 7, 3, 12, 6, 2, 8, 5, 11, 10, 15, 3, 9, 14, 2, 6, 8, 1, + 13, 7, 5), k = 3L, m = 2L) + # 10 rows at a step of 12: starts 11 and 12 draw nothing, and count with a + # total of 0. + check(c(5, 1, 8, 3, 9, 2, 7, 4, 6, 10), k = 4L, m = 3L) +}) + +test_that("ht_total() uses the replicates, on n_starts - 1 degrees of freedom", { + d <- data.frame(y = sin(1:24) * 10 + 1:24, one = 1) + des <- design_systematic(interval = 4, n_starts = 3) + s <- draw(d, des, seed = 5, weights = TRUE) + r <- ht_total(s, "y") + t_r <- vapply(split(s$y / s$.prob, (s$.row - 1L) %% 12L), sum, 0) * 3 + expect_equal(r$variance, (1 - 1 / 4) * var(t_r) / 3) + expect_identical(r$method, "analytic") + expect_equal(r$df, 2) + # With a fixed size, the Sen-Yates-Grundy sum over the exact joint + # probabilities gives the same figure. + pij <- joint_prob(d, des, rows = s$.row) + expect_equal(r$variance, + drawn:::syg_variance(s$y, s$.prob, pij)$variance) + # Every replicate holds two rows here, so the count is exact. + expect_equal(ht_total(s, "one")$se, 0) + expect_match(ht_total(s, "y", variance = "jackknife")$note, + "starts as its primary sampling units") +}) + +test_that("a Hajek mean over one replicate's rows has no standard error", { + # Its residuals sum to 0 inside the replicate, so every replicate total + # is 0 and the variance between them would be 0 too. + d <- data.frame(y = (1:60 * 7) %% 23) + s <- draw(d, design_systematic(interval = 6, n_starts = 2), seed = 1, + weights = TRUE) + s$dom <- ifelse((s$.row - 1L) %% 12L == (s$.row[1] - 1L) %% 12L, "x", "z") + r <- ht_mean(s, "y", by = "dom") + expect_true(all(is.na(r$se))) + expect_match(attr(r, "notes")[1], + "sampled rows in one replicate only", fixed = TRUE) + expect_true(is.finite(ht_mean(s, "y")$se)) +}) + +test_that("several starts go to survey as replicates with the same standard error", { + skip_if_not_installed("survey") + d <- data.frame(id = 1:50, v = c(NA, 49:1), y = sin(1:50) * 10 + 1:50, + g = rep(c("a", "b"), 25)) + des <- design_systematic(interval = 5, n_starts = 3, order_by = "v", + na_rm = TRUE) + s <- draw(d, des, seed = 3, weights = TRUE) + sv <- as_svydesign(s) + r <- ht_total(s, "y") + st <- survey::svytotal(~y, sv) + expect_equal(unname(coef(st)), r$total) + expect_equal(as.numeric(survey::SE(st)), r$se) + expect_equal(survey::degf(sv), r$df) + expect_equal(unname(sv$fpc$popsize[, 1]), rep(15, nrow(s))) + by <- ht_mean(s, "y", by = "g") + sb <- survey::svyby(~y, ~g, sv, survey::svymean) + expect_equal(by$se, unname(sb$se)) + + # A start past the last row drew nothing, and survey would count the + # replicates with rows only. + d2 <- data.frame(y = 1:10) + des2 <- design_systematic(interval = 4, n_starts = 3) + s2 <- draw(d2, des2, seed = 2, weights = TRUE) + expect_length(unique((s2$.row - 1L) %% 12L), 2L) + expect_error(as_svydesign(s2), "1 of its 3 starts fell past the last") + expect_true(is.finite(ht_total(s2, "y")$se)) + + # An interval of 1 takes every row, whatever the starts. + s3 <- draw(data.frame(y = c(3, 8)), design_systematic(1, n_starts = 3), + seed = 1, weights = TRUE) + r3 <- ht_total(s3, "y") + expect_equal(c(r3$total, r3$se), c(11, 0)) + expect_match(r3$note, "taken with certainty") + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, as_svydesign(s3)))), + 0) +}) + +test_that("a certainty design over several starts estimates, and goes to survey", { + d <- data.frame(y = c(1000, 2000, 1:48)) + des <- design_certainty("y", 500, design_systematic(interval = 4, + n_starts = 2)) + s <- draw(d, des, seed = 2, weights = TRUE) + r <- ht_total(s, "y") + rest <- s[s$.prob < 1, ] + t_r <- vapply(split(rest$y / rest$.prob, (rest$.row - 3L) %% 8L), sum, 0) * 2 + expect_equal(r$variance, (1 - 1 / 4) * var(t_r) / 2) + expect_equal(r$df, 1) + skip_if_not_installed("survey") + # The certainty rows are one more unit beside the replicates. + sv <- as_svydesign(s) + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, sv))), r$se, + tolerance = 1e-8) + expect_equal(survey::degf(sv), 1) +}) + +test_that("order_by takes one column, and a column of ranks walks by several", { + expect_error(design_systematic(3, order_by = c("region", "size")), + "order(order(data$region, data$size", fixed = TRUE) + d <- data.frame(region = rep(c("b", "a"), each = 6), size = c(6:1, 1:6)) + d$walk <- order(order(d$region, d$size, method = "radix")) + des <- design_systematic(interval = 4, order_by = "walk") + ids <- draw(d, des, seed = 1) + # The walk runs through region a, then b, each by size. + walk <- order(d$region, d$size, method = "radix") + pos <- match(seq_len(12), walk) + expect_length(unique((pos[match(ids$walk, d$walk)] - 1L) %% 4L), 1L) + expect_identical(drawn:::systematic_positions(des, d), pos) +}) + +test_that("start counts along the walk sorted by order_by", { + df <- data.frame(id = 1:10, value = c(5, 3, 9, 1, 7, 2, 8, 4, 10, 6)) + res <- draw(df, design_systematic(interval = 10, start = 3, + order_by = "value")) + # The third smallest value, not the frame's third row + expect_equal(res$id, 2L) +}) + +test_that("on a straight line the successive difference is 6k / (n(k + 1))", { + # ?ht_total quotes this limit: the random start is then the only source + # of variation, which differences between neighbours cannot see. + k <- 10L + n <- 10L + d <- data.frame(y = seq_len(n * k)) + totals <- vapply(seq_len(k), function(st) { + k * sum(draw(d, design_systematic(k, start = st))$y) + }, numeric(1)) + truth <- mean((totals - mean(totals))^2) + for (i in 1:3) { + s <- draw(d, design_systematic(k), seed = i, weights = TRUE) + expect_equal(ht_total(s, "y")$variance / truth, 6 * k / (n * (k + 1))) + } +}) diff --git a/tests/testthat/test-design-temporal.R b/tests/testthat/test-design-temporal.R index 7c92625..42c154b 100644 --- a/tests/testthat/test-design-temporal.R +++ b/tests/testthat/test-design-temporal.R @@ -109,13 +109,77 @@ test_that("unparseable timestamps follow the na_rm contract", { test_that("a backwards window is refused on every path, not just the draw", { d <- data.frame(ts = seq(as.POSIXct("2020-01-01", tz = "UTC"), by = "hour", length.out = 10)) - bad <- design_temporal("ts", from = "2020-01-02", to = "2020-01-01", + expect_error(design_temporal("ts", from = "2020-01-02", to = "2020-01-01", + interval = 1, per_interval = 1, unit = "hours"), + "`to` must be after `from`") + # A design built before the constructor checked its bounds + bad <- design_temporal("ts", from = "2020-01-01", to = "2020-01-02", interval = 1, per_interval = 1, unit = "hours") + bad$from <- "2020-01-02" + bad$to <- "2020-01-01" expect_error(draw(d, bad), "`to` must be after `from`") expect_error(inclusion_prob(d, bad), "`to` must be after `from`") expect_error(joint_prob(d, bad), "`to` must be after `from`") }) +test_that("an instant paired with a clock time is ordered in the data's zone", { + # 10:00 in New York is 15:00 UTC, after 12:00 read in UTC, and before + # 12:00 read in New York, the zone the window is laid out in. + zone <- "America/New_York" + d <- data.frame(ts = seq(as.POSIXct("2024-01-01 08:00", tz = zone), + by = "30 min", length.out = 16)) + from <- as.POSIXct("2024-01-01 10:00", tz = zone) + des <- design_temporal("ts", from = from, to = "2024-01-01 12:00", + interval = 1, per_interval = 1) + s <- draw(d, des, seed = 1) + expect_identical(nrow(s), 2L) + expect_true(all(s$ts >= from & s$ts < from + 7200)) + expect_equal(sum(inclusion_prob(d, des)), 2) + + # A pair that runs backwards in the data's zone is refused when used. + back <- design_temporal("ts", from = "2024-01-01 10:00", + to = as.POSIXct("2024-01-01 12:00", tz = "UTC"), + interval = 1, per_interval = 1) + expect_error(draw(d, back, seed = 1), "`to` must be after `from`") + expect_error(inclusion_prob(d, back), "`to` must be after `from`") + + # Bounds of one kind, or any pair under `tz`, are ordered when built. + expect_error(design_temporal("ts", from = from, to = from - 3600, + interval = 1, per_interval = 1), + "`to` must be after `from`") + expect_error(design_temporal("ts", from = from, to = "2024-01-01 12:00", + interval = 1, per_interval = 1, tz = "UTC"), + "`to` must be after `from`") + + # A mixed pair a day or more out of order is out of order in every zone, + # since no offset from UTC reaches a day, so it is refused when built. + # Under a day it can still be in order somewhere, and waits for the data. + utc <- function(x) as.POSIXct(x, tz = "UTC") + expect_error(design_temporal("ts", from = utc("2024-06-01"), + to = "2024-01-01", interval = 1, + per_interval = 1), + "`to` must be after `from`") + expect_error(design_temporal("ts", from = "2024-01-02 10:00", + to = utc("2024-01-01 10:00"), interval = 1, + per_interval = 1), + "`to` must be after `from`") + expect_error(design_temporal("ts", from = "2024-01-02", + to = "2024-01-01T00:00:00Z", interval = 1, + per_interval = 1), + "`to` must be after `from`") + # Read in UTC, 09:00 on 2 January comes 13 hours after `to`. In Kiritimati, + # 14 hours ahead of UTC, it is 19:00 UTC on 1 January, an hour before `to`, + # so the pair is kept until the zone is known. + east <- design_temporal("ts", from = "2024-01-02 09:00", + to = utc("2024-01-01 20:00"), interval = 1, + per_interval = 1) + kiri <- data.frame(ts = as.POSIXct("2024-01-02 09:30", + tz = "Pacific/Kiritimati")) + expect_equal(inclusion_prob(kiri, east), 1) + expect_error(inclusion_prob(data.frame(ts = utc("2024-01-01 19:30")), east), + "`to` must be after `from`") +}) + test_that("a column mixing dates with date-times keeps both", { # The date-only fallback fired only when nothing at all parsed, so a mixed # column silently lost every date-only row. @@ -131,3 +195,303 @@ test_that("a column mixing dates with date-times keeps both", { interval = 1, per_interval = 1, unit = "days") expect_equal(sum(inclusion_prob(d, des) > 0), 4) }) + +sparse_days <- function() { + # Nine days with three rows each, which per_interval = 3 takes whole, and + # one busy day of 30 rows from which three are drawn. + ts <- c(as.POSIXct("2024-01-01", tz = "UTC") + rep(0:8, each = 3) * 86400 + + rep(c(1, 2, 3) * 3600, 9), + as.POSIXct("2024-01-10", tz = "UTC") + (1:30) * 600) + data.frame(ts = ts, v = c(rep(1, 27), 50, 60, rep(1, 28)), + y = 100 + 20 * sin(1:57)) +} + +test_that("intervals taken whole carry no degrees of freedom", { + # Counting the 27 rows of the sparse days gave 20 degrees of freedom where + # the three random rows support 2. + d <- sparse_days() + des <- design_temporal("ts", from = "2024-01-01", to = "2024-01-11", + interval = 24, per_interval = 3, unit = "hours") + s <- draw(d, des, seed = 1, weights = TRUE) + expect_equal(sum(s$.prob == 1), 27L) + expect_equal(ht_total(s, "y")$df, 2) + + # The same holds under a certainty design over the temporal one + cert <- design_certainty("v", 50, des) + sc <- draw(d, cert, seed = 1, weights = TRUE) + expect_equal(sum(sc$v >= 50), 2L) + expect_equal(ht_total(sc, "y")$df, 2) + + skip_if_not_installed("survey") + expect_equal(survey::degf(as_svydesign(s)), 2) + expect_equal(survey::degf(as_svydesign(sc)), 2) + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, as_svydesign(sc)))), + ht_total(sc, "y")$se, tolerance = 1e-8) +}) + +day_frame <- function(from, days) { + data.frame(day = as.Date(from) + seq_len(days) - 1L, y = seq_len(days)) +} + +test_that("days and weeks start at local midnight across a clock change", { + # A fixed 86,400-second step drifted off midnight after the change, so two + # calendar days shared one interval and the last day was lost. + for (zone in c("America/New_York", "Europe/London")) { + for (start in c("2024-03-07", "2024-10-24", "2024-10-31")) { + d <- day_frame(start, 10) + des <- design_temporal("day", from = start, + to = as.Date(start) + 10, interval = 1, + per_interval = 1, unit = "days", tz = zone) + b <- drawn:::temporal_bucket(des, d) + expect_identical(as.integer(b), 1:10) + expect_identical(levels(b), + paste(format(as.Date(start) + 0:9), "00:00")) + expect_equal(inclusion_prob(d, des), rep(1, 10)) + expect_equal(nrow(draw(d, des, seed = 1)), 10L) + } + } + + # Hourly rows: every interval opens on a local midnight. + zone <- "America/New_York" + h <- data.frame(ts = seq(as.POSIXct("2024-03-08", tz = zone), + as.POSIXct("2024-03-13", tz = zone), by = "hour")) + des <- design_temporal("ts", from = "2024-03-08", to = "2024-03-13", + interval = 1, per_interval = 2, unit = "days") + b <- drawn:::temporal_bucket(des, h) + first <- h$ts[!duplicated(b) & !is.na(b)] + expect_equal(format(first, "%H:%M"), rep("00:00", 5)) + expect_equal(as.vector(table(b)), c(24, 24, 23, 24, 24)) + + # Weeks are seven calendar days each. + d <- day_frame("2024-03-04", 28) + des <- design_temporal("day", from = "2024-03-04", to = "2024-04-01", + interval = 1, per_interval = 7, unit = "weeks", + tz = "America/New_York") + expect_equal(as.vector(table(drawn:::temporal_bucket(des, d))), rep(7, 4)) +}) + +test_that("a Date on a day with no midnight is its first instant", { + # Santiago moved its clocks from 00:00 to 01:00 on 2022-09-11. The Date + # became 23:00 the day before, and the same day as a string did not parse. + zone <- "America/Santiago" + start <- drawn:::parse_time(as.Date("2022-09-11"), zone, "x") + expect_equal(format(start, "%Y-%m-%d %H:%M %z"), "2022-09-11 01:00 -0300") + expect_equal(drawn:::parse_time("2022-09-11", zone, "x"), start) + + d <- day_frame("2022-08-11", 61) + months <- design_temporal("day", from = "2022-08-11", to = "2022-10-11", + interval = 1, per_interval = 1, unit = "months", + tz = zone) + expect_equal(as.vector(table(drawn:::temporal_bucket(months, d))), + c(31, 30)) + expect_equal(inclusion_prob(d, months)[d$day == as.Date("2022-09-11")], + 1 / 30) + + # A Date `to` on that day ends the window at the end of the day before. + days <- design_temporal("day", from = as.Date("2022-09-08"), + to = as.Date("2022-09-11"), interval = 1, + per_interval = 1, unit = "days", tz = zone) + d <- day_frame("2022-09-08", 5) + expect_equal(inclusion_prob(d, days), c(1, 1, 1, 0, 0)) + + # Rows of strings on that day parse under na_rm = FALSE. + s <- data.frame(day = format(as.Date("2022-09-08") + 0:4), y = 1) + from_strings <- design_temporal("day", from = "2022-09-08", + to = "2022-09-13", interval = 1, + per_interval = 1, unit = "days", tz = zone) + expect_equal(inclusion_prob(s, from_strings), rep(1, 5)) +}) + +test_that("frame order does not move a Date on a repeated midnight", { + # The Azores repeated 00:00-01:00 on 2019-10-27, and which midnight a Date + # became depended on the rows beside it. + zone <- "Atlantic/Azores" + d <- day_frame("2019-10-24", 7) + des <- design_temporal("day", from = "2019-10-27", to = "2019-10-31", + interval = 1, per_interval = 1, unit = "days", + tz = zone) + p <- inclusion_prob(d, des) + expect_equal(p, c(0, 0, 0, 1, 1, 1, 1)) + expect_equal(rev(inclusion_prob(d[7:1, ], des)), p) + expect_equal( + format(drawn:::parse_time(as.Date(c("2019-10-28", "2019-10-27")), zone, + "x"), "%H:%M %z"), + c("00:00 -0100", "00:00 +0000")) +}) + +test_that("a day the zone skipped does not stop the draw", { + # Samoa went from 2011-12-29 to 2011-12-31. A Date column holding + # 2011-12-30 stopped every path, even with na_rm = TRUE. + d <- data.frame(day = seq(as.Date("2011-12-01"), as.Date("2012-01-31"), + by = "day"), y = 1) + des <- design_temporal("day", from = "2011-12-01", to = "2012-02-01", + interval = 1, per_interval = 3, unit = "months", + tz = "Pacific/Apia", na_rm = TRUE) + expect_equal(inclusion_prob(d, des), rep(3 / 31, 62)) + expect_equal(nrow(draw(d, des, seed = 1)), 6L) + expect_equal(dim(joint_prob(d, des, rows = 1:3)), c(3L, 3L)) + expect_equal(drawn:::parse_time(as.Date("2011-12-30"), "Pacific/Apia", "x"), + drawn:::parse_time(as.Date("2011-12-31"), "Pacific/Apia", "x")) +}) + +test_that("tz = NULL takes the zone of a POSIXct column", { + # The window was read in UTC, five hours off for New York data. + zone <- "America/New_York" + ny <- data.frame(id = 1:72, ts = seq(as.POSIXct("2023-12-31", tz = zone), + by = "hour", length.out = 72)) + des <- design_temporal("ts", from = "2024-01-01", to = "2024-01-02", + interval = 24, per_interval = 100, unit = "hours") + s <- draw(ny, des, seed = 1) + expect_equal(format(range(s$ts), "%Y-%m-%d %H:%M"), + c("2024-01-01 00:00", "2024-01-01 23:00")) + expect_equal(inclusion_prob(as.data.frame(list(ts = as.POSIXlt(ny$ts))), des), + inclusion_prob(ny, des)) + + # Naming UTC still reads the window in UTC. + utc <- draw(ny, design_temporal("ts", from = "2024-01-01", to = "2024-01-02", + interval = 24, per_interval = 100, + unit = "hours", tz = "UTC"), seed = 1) + expect_equal(format(min(utc$ts), "%H:%M"), "19:00") + + # A column with an empty zone, shown in the session's zone, gets UTC. + local <- ny + attr(local$ts, "tzone") <- "" + p <- inclusion_prob(local, des) + expect_equal(format(range(local$ts[p > 0]), "%H:%M", tz = "UTC"), + c("00:00", "23:00")) + + expect_output(print(des), "tz +from the time column, else UTC") + expect_output(print(design_temporal("ts", "2024-01-01", "2024-01-02", 1, 1, + tz = zone)), + "tz +\"America/New_York\"") +}) + +test_that("bad zones and bounds are refused when the design is built", { + expect_error(design_temporal("ts", "2024-01-01", "2024-01-02", 6, 2, + tz = "Mars/Olympus"), + "`tz` is \"Mars/Olympus\", which is not a time zone R knows") + expect_error(design_temporal("ts", "2024-01-01", "2024-01-02", 6, 2, + tz = c("UTC", "GMT")), + "`tz` must be a single time zone name") + expect_error(design_temporal("ts", c("2024-01-01", "2024-01-02"), + "2024-01-03", 6, 2), + "`from` must be a single date-time, not 2 values") + expect_error(design_temporal("ts", "yesterday", "2024-01-03", 6, 2), + "`from` is \"yesterday\", which does not read as a date-time") + expect_error(design_temporal("ts", "2024-01-01", NA, 6, 2), + "`to` is NA") + expect_error(design_temporal("ts", 5, "2024-01-03", 6, 2), + "`from` must hold date-times") + + d <- data.frame(ts = .POSIXct(1704067200 + 3600 * 0:3, tz = "Mars/Olympus")) + expect_error( + inclusion_prob(d, design_temporal("ts", "2024-01-01", "2024-01-02", 6, 2)), + "`ts` is in time zone \"Mars/Olympus\", which R does not know") +}) + +test_that("strings with hours and minutes but no seconds parse", { + d <- data.frame(ts = c("2024-01-01 05:00", "2024-01-01T07:30", + "2024-01-01 09", "2024-01-01 11:00:00", + "2024-01-01")) + des <- design_temporal("ts", from = "2024-01-01 00:00", to = "2024-01-02 00", + interval = 6, per_interval = 1) + expect_equal(inclusion_prob(d, des), c(1 / 2, 1 / 3, 1 / 3, 1 / 3, 1 / 2)) + + # A date written day or month first stays unread rather than guessed. + expect_true(is.na(drawn:::parse_time("01/02/2024", "UTC", "x"))) + expect_error( + inclusion_prob(data.frame(ts = c("01/02/2024", "2024-01-01")), des), + "strings must be year-month-day with an optional time") + + # A string with its own offset keeps its instant in another zone. + got <- drawn:::parse_time(c("2024-01-01T05:00:00Z", "2024-01-01 05:00"), + "America/New_York", "x") + expect_equal(format(got, "%H:%M"), c("00:00", "05:00")) +}) + +test_that("months and years count from the anchor", { + # seq() rolled 31 January on to 2 March, and 29 February on to 1 March. + utc <- function(x) as.POSIXct(x, tz = "UTC") + expect_equal( + drawn:::make_breaks(utc("2024-01-31"), utc("2024-07-01"), 1, "months"), + utc(c("2024-01-31", "2024-02-29", "2024-03-31", "2024-04-30", + "2024-05-31", "2024-06-30"))) + expect_equal( + drawn:::make_breaks(utc("2024-02-29"), utc("2028-03-01"), 1, "years"), + utc(c("2024-02-29", "2025-02-28", "2026-02-28", "2027-02-28", + "2028-02-29"))) + + d <- day_frame("2024-01-31", 182) + des <- design_temporal("day", from = "2024-01-31", to = "2024-07-31", + interval = 1, per_interval = 1, unit = "months") + expect_equal(as.vector(table(drawn:::temporal_bucket(des, d))), + c(29, 31, 30, 31, 30, 31)) +}) + +test_that("inclusion probabilities of a long hourly frame take one pass", { + skip_on_cran() + # One pass per interval took about 6 seconds here. + d <- data.frame(ts = seq(as.POSIXct("2024-01-01", tz = "UTC"), by = 150, + length.out = 2e5)) + des <- design_temporal("ts", from = "2024-01-01", to = "2024-12-01", + interval = 1, per_interval = 2, unit = "hours") + time <- system.time(p <- inclusion_prob(d, des))[["elapsed"]] + expect_lt(time, 2) + inw <- d$ts < as.POSIXct("2024-12-01", tz = "UTC") + expect_equal(p, ifelse(inw, 1 / 12, 0)) +}) + +test_that("intervals are named by their start, in time order", { + h <- data.frame(ts = seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "hour", + length.out = 12)) + des <- design_temporal("ts", from = "2024-01-01", to = "2024-01-01 12:00", + interval = 1, per_interval = 1, unit = "hours") + b <- drawn:::temporal_bucket(des, h) + expect_identical(as.integer(b), 1:12) + expect_identical(levels(b), sprintf("2024-01-01 %02d:00", 0:11)) + expect_identical(sort(levels(b), method = "radix"), levels(b)) + + # Seconds appear when an interval starts between minutes. + secs <- design_temporal("ts", from = "2024-01-01", to = "2024-01-01 00:02", + interval = 30, per_interval = 1, unit = "seconds") + expect_identical(levels(drawn:::temporal_bucket(secs, h)), + paste("2024-01-01", c("00:00:00", "00:00:30", "00:01:00", + "00:01:30"))) + + # New York repeats 01:00 when its clocks go back, and the two intervals + # starting then are told apart by the zone. + zone <- "America/New_York" + fall <- data.frame(ts = seq(as.POSIXct("2024-11-03 00:00", tz = zone), + by = "hour", length.out = 5)) + des <- design_temporal("ts", from = "2024-11-03 00:00", + to = "2024-11-03 04:00", interval = 1, + per_interval = 1, unit = "hours") + b <- drawn:::temporal_bucket(des, fall) + expect_identical(levels(b), c("2024-11-03 00:00", "2024-11-03 01:00 EDT", + "2024-11-03 01:00 EST", "2024-11-03 02:00", + "2024-11-03 03:00")) + expect_identical(as.integer(b), 1:5) +}) + +test_that("notes and survey's strata name intervals by their start", { + d <- data.frame(ts = rep(seq(as.POSIXct("2024-01-01", tz = "UTC"), + by = "day", length.out = 12), each = 4), + y = (1:48 * 7) %% 11) + des <- design_temporal("ts", from = "2024-01-01", to = "2024-01-13", + interval = 1, per_interval = 1, unit = "days") + s <- draw(d, des, seed = 1, weights = TRUE) + # In time order: the intervals were numbered and sorted as text, 1, 10, 11. + expect_match(ht_total(s, "y")$note, paste0( + "12 intervals `2024-01-01 00:00`, `2024-01-02 00:00`, ", + "`2024-01-03 00:00`, `2024-01-04 00:00`, `2024-01-05 00:00`, ... each"), + fixed = TRUE) + + skip_if_not_installed("survey") + two <- draw(d, design_temporal("ts", from = "2024-01-01", to = "2024-01-13", + interval = 1, per_interval = 2, + unit = "days"), + seed = 1, weights = TRUE) + sv <- as_svydesign(two) + expect_setequal(unique(sv$variables$.stratum), + paste(format(as.Date("2024-01-01") + 0:11), "00:00")) +}) diff --git a/tests/testthat/test-design-weighted.R b/tests/testthat/test-design-weighted.R index 5a7e169..db9f152 100644 --- a/tests/testthat/test-design-weighted.R +++ b/tests/testthat/test-design-weighted.R @@ -1,5 +1,5 @@ weighted_df <- function() { - set.seed(99) + local_seed(99) data.frame(id = 1:100, weight = stats::runif(100, 0.1, 10)) } @@ -64,3 +64,123 @@ test_that("over-drawing without replacement is refused", { expect_error(draw(d, design_weighted("w", n = 10), seed = 1), "cannot exceed the number of rows") }) + +test_that("weights draw() refuses are refused on every path, naming the column", { + # inclusion_prob() accepted logical weights and stopped inside base R on a + # factor; joint_prob(), draw(weights = TRUE) and plot() followed it. + pop <- data.frame(id = 1:20, size = 1:20, other = 1:20) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + bad <- list(logical = rep(TRUE, 20), factor = factor(rep(1:4, 5)), + character = as.character(1:20)) + for (type in names(bad)) { + pop$size <- bad[[type]] + want <- paste0("`size` must be numeric, not ", type, ".") + designs <- list( + design_weighted("size", n = 5), + design_weighted("size", n = 5, method = "systematic"), + design_weighted("size", n = 5, method = "poisson"), + design_certainty("other", 18, design_weighted("size", n = 5, + method = "poisson")) + ) + for (des in designs) { + info <- paste(type, drawn:::design_label(des)) + expect_error(draw(pop, des, seed = 1), want, fixed = TRUE, info = info) + expect_error(inclusion_prob(pop, des), want, fixed = TRUE, info = info) + expect_error(sampling_weight(pop, des), want, fixed = TRUE, info = info) + expect_error(joint_prob(pop, des, rows = 1:3), want, fixed = TRUE, + info = info) + expect_error(draw(pop, des, seed = 1, weights = TRUE), want, + fixed = TRUE, info = info) + expect_error(plot(des, pop, type = "probability"), want, fixed = TRUE, + info = info) + } + } +}) + +test_that("a weight of 0 is refused with the column and what to do", { + pop <- data.frame(w = c(0, 0, 0, 1:20)) + for (m in c("successive", "systematic", "poisson")) { + des <- design_weighted("w", n = 5, method = m) + expect_error(draw(pop, des, seed = 1), + "`w` must be positive, but 3 weight(s) are 0 or negative.", + fixed = TRUE) + expect_error(inclusion_prob(pop, des), "Drop those rows from `data`", + fixed = TRUE) + } + expect_error(inclusion_prob(pop, design_spread("w", n = 5, size = "w")), + "`w` must be positive", fixed = TRUE) +}) + +test_that("a design without strata draws the rows it drew before", { + d <- data.frame(id = 1:30, w = c(1:29, 90)) + for (m in c("systematic", "poisson")) { + des <- design_weighted("w", n = 6, method = m) + expect_null(des$strata) + expect_null(des$allocation) + pi <- pps_pi(d$w, 6) + old <- with_seed(4, if (m == "poisson") { + which(stats::runif(30) < pi) + } else { + systematic_pps(pi) + }) + expect_identical(draw(d, des, seed = 4)$id, old) + } + expect_false(any(grepl("strata|allocation", + utils::capture.output(print( + design_weighted("w", n = 6)))))) +}) + +test_that("strata and allocation print, and other designs are not stratified", { + des <- design_weighted("w", n = 6, method = "systematic", strata = "g", + allocation = "equal") + out <- utils::capture.output(print(des)) + expect_true(any(grepl("strata +\"g\"", out))) + expect_true(any(grepl("allocation +\"equal\"", out))) + expect_error(allocation_table(data.frame(w = 1:4, g = "a"), + design_weighted("w", n = 2, + method = "systematic")), + "design_weighted() with `strata`", fixed = TRUE) +}) + +test_that("strata of a weighted design are summarised from the frame", { + d <- data.frame(id = 1:40, g = rep(c("x", "y"), c(30, 10)), + w = rep(1:4, 10)) + s <- draw(d, design_weighted("w", n = 8, method = "systematic", + strata = "g"), seed = 1, weights = TRUE) + sm <- sample_summary(s) + expect_identical(sm$group_col, "g") + expect_identical(sm$by_group$drawn, c(6L, 2L)) + expect_identical(sm$by_group$in_frame, c(30L, 10L)) + s$g <- "renamed" + expect_identical(sample_summary(s)$by_group$drawn, c(6L, 2L)) + + # Rows dropped for a missing weight are in no stratum, as in + # allocation_table(). + d$w[1:4] <- NA + des <- design_weighted("w", n = 8, method = "systematic", strata = "g", + na_rm = TRUE) + b <- sample_summary(draw(d, des, seed = 1, weights = TRUE))$by_group + expect_identical(b$in_frame, c(26L, 10L)) + expect_identical(b$in_frame, allocation_table(d, des)$N) +}) + +test_that("counts for strata that na_rm empties name that reason", { + d <- data.frame(g = rep(c("a", "b", "c", "d"), each = 5), w = 1) + d$w[d$g %in% c("b", "d")] <- NA + des <- design_weighted("w", method = "poisson", strata = "g", na_rm = TRUE, + allocation = data.frame(g = c("a", "b", "c", "d"), + n = c(2, 1, 2, 1))) + expect_error(draw(d, des, seed = 1), + paste0("`allocation` gives counts for strata `b`, `d`, but ", + "na_rm = TRUE drops every row of them for a missing ", + "weight in `w`. Fill in those values, or leave those ", + "strata out of `allocation`."), fixed = TRUE) + expect_error(inclusion_prob(d, des), "drops every row of them", + fixed = TRUE) + # A stratum the frame does not have is still refused as one. + typo <- design_weighted("w", method = "poisson", strata = "g", + na_rm = TRUE, allocation = c(a = 2, c = 2, e = 1)) + expect_error(draw(d, typo, seed = 1), + "names 1 stratum that `data` does not have: `e`", fixed = TRUE) +}) diff --git a/tests/testthat/test-domains.R b/tests/testthat/test-domains.R index 54712e6..3851385 100644 --- a/tests/testthat/test-domains.R +++ b/tests/testthat/test-domains.R @@ -1,5 +1,5 @@ dom_pop <- function() { - set.seed(21) + local_seed(21) d <- data.frame( id = 1:400, site = rep(c("a", "b", "c", "d"), times = c(160, 120, 80, 40)), @@ -72,6 +72,21 @@ test_that("the HT domain mean divides by the domain's known size", { N_a <- sum(d$site == "a") expect_equal(r$mean[r$site == "a"], sum(s$y[s$site == "a"] * s$.weight[s$site == "a"]) / N_a) + + # A frame row with `site` missing could be in any domain, and leaving it + # out of the count overstated the mean. + gap <- d + gap$site[setdiff(seq_len(nrow(d)), s$id)[1:10]] <- NA + s2 <- as_drawn(s, attr(s, "drawn_design"), gap, by = "id") + expect_error(ht_mean(s2, "y", by = "site", estimator = "ht"), paste0( + "the `by` column `site` is missing in 10 of the frame's ", nrow(d), + " rows"), fixed = TRUE) + expect_true(all(is.finite(ht_mean(s2, "y", by = "site")$se))) + # With several `by` columns, one missing value is enough. + expect_error(ht_mean(s2, "y", by = c("site", "region"), estimator = "ht"), + paste0("the `by` columns `site` and `region` have a missing ", + "value in 10 of the frame's ", nrow(d), " rows"), + fixed = TRUE) }) test_that("by accepts several columns and validates them", { @@ -80,6 +95,885 @@ test_that("by accepts several columns and validates them", { two <- ht_total(s, "y", by = c("site", "region")) expect_true(all(c("site", "region") %in% names(two))) expect_equal(sum(two$total), ht_total(s, "y")$total) - expect_error(ht_total(s, "y", by = "nope"), "`by` must name") + expect_error(ht_total(s, "y", by = "nope"), + "`by` names `nope`, which `sample` does not have.", fixed = TRUE) + expect_error(ht_total(s, "y", by = 1), "`by` must name") expect_output(print(two), "by domain") }) + +test_that("a recoded stratum column does not change domain variances", { + d <- dom_pop() + s <- draw(d, design_stratified("site", n = 80, min_per_stratum = 2), seed = 4, + weights = TRUE) + recoded <- s + recoded$site <- "z" + for (v in c("analytic", "jackknife")) { + want <- ht_total(s, "y", by = "region", variance = v) + got <- ht_total(recoded, "y", by = "region", variance = v) + expect_equal(got$se, want$se, label = v) + expect_equal(attr(got, "df"), attr(want, "df"), label = v) + } +}) + +test_that("domains come out in key order, not sorted as text", { + d <- dom_pop() + d$month <- rep(1:12, length.out = 400) + d$mfac <- factor(month.abb[d$month], levels = month.abb) + d$case <- c("a", "B", "b")[(d$id %/% 12) %% 3 + 1] + s <- draw(d, design_simple(n = 120), seed = 1, weights = TRUE) + expect_equal(ht_total(s, "y", by = "month")$month, 1:12) + expect_equal(as.character(ht_total(s, "y", by = "mfac")$mfac), month.abb) + expect_equal(ht_total(s, "y", by = "case")$case, c("B", "a", "b")) + with_other_collation( + expect_equal(ht_total(s, "y", by = "case")$case, c("B", "a", "b")) + ) + # Several columns: the first varies slowest. + two <- ht_total(s, "y", by = c("mfac", "case")) + expect_gt(nrow(two), 12) + expect_identical(order(as.integer(two$mfac), match(two$case, c("B", "a", "b"))), + seq_len(nrow(two))) +}) + +test_that("domains and summaries of an sf sample carry no geometry", { + pts <- sf_points() + plain <- sf::st_drop_geometry(pts) + des <- design_cluster("cl", n_clusters = 5) + s <- draw(pts, des, seed = 1, weights = TRUE) + by_site <- ht_total(s, "y", by = "site") + expect_false(inherits(by_site, "sf")) + expect_false("geometry" %in% names(by_site)) + want <- ht_total(draw(plain, des, seed = 1, weights = TRUE), "y", + by = "site") + expect_equal(as.data.frame(by_site), as.data.frame(want)) + expect_equal(sample_summary(s)$by_group, + sample_summary(draw(plain, des, seed = 1, + weights = TRUE))$by_group) + st <- draw(pts, design_stratified("site", n = 12), seed = 1, weights = TRUE) + expect_equal(sample_summary(st)$by_group$in_frame, c(30L, 20L, 10L)) +}) + +# ---- domains with too little to measure -------------------------------------- + +test_that("a Hajek domain mean inside one sampling unit has no se", { + # Its linearised residuals sum to zero inside the one unit, so every + # estimator gave a standard error of 0 and a zero-width "analytic" interval. + d <- dom_pop() + d$rare <- ifelse(d$id %% 40 == 0, "rare", "common") + des <- design_simple(n = 40) + hits <- vapply(1:100, function(i) { + sum(draw(d, des, seed = i)$rare == "rare") + }, integer(1)) + s <- draw(d, des, seed = which(hits == 1L)[1], weights = TRUE) + expect_equal(sum(s$rare == "rare"), 1L) + m <- ht_mean(s, "y", by = "rare") + expect_true(is.na(m$se[m$rare == "rare"])) + expect_equal(m$method[m$rare == "rare"], "none") + expect_true(is.finite(m$se[m$rare == "common"])) + expect_match(attr(m, "notes"), "The domain `rare` has one sampled row", + fixed = TRUE, all = FALSE) + # A domain total from one row is still estimated. + expect_true(all(is.finite(ht_total(s, "y", by = "rare")$se))) + + # Ten rows of one cluster are still one unit. + d$part <- ifelse(d$cl == "c3" & d$id %% 2 == 0, "part", "rest") + cs <- draw(d, design_cluster("cl", n_clusters = 8), seed = 1, weights = TRUE) + if (!"c3" %in% cs$cl) { + seeds <- vapply(1:200, function(i) { + "c3" %in% draw(d, design_cluster("cl", n_clusters = 8), seed = i)$cl + }, logical(1)) + cs <- draw(d, design_cluster("cl", n_clusters = 8), + seed = which(seeds)[1], weights = TRUE) + } + cm <- ht_mean(cs, "y", by = "part") + expect_equal(cm$n[cm$part == "part"], 5) + expect_true(is.na(cm$se[cm$part == "part"])) + expect_match(attr(cm, "notes"), "in one cluster only", all = FALSE) + expect_true(is.finite(cm$se[cm$part == "rest"])) + for (v in c("analytic", "jackknife")) { + expect_true(is.na(ht_mean(cs, "y", by = "part", variance = v)$se[1])) + } +}) + +test_that("a Hajek domain mean of certain rows only has no se unless exact", { + # Every estimator holds rows taken with certainty fixed, so a domain whose + # sampled rows were all certain got a standard error of 0 and a zero-width + # interval, however many rows it had, though the design could have drawn + # its other rows and the mean would then have moved. + pop <- data.frame(id = 1:100, w = c(rep(1, 98), 400, 450)) + pop$y <- 40 + (pop$id * 37) %% 23 + pop$x <- ifelse(pop$id %in% c(1:6, 99, 100), "d", "other") + pop$big <- ifelse(pop$id %in% 99:100, "big", "small") + s <- draw(pop, design_weighted("w", n = 20, method = "systematic"), + seed = 7, weights = TRUE) + expect_equal(sort(s$id[s$x == "d"]), 99:100) + expect_true(all(s$.prob[s$x == "d"] == 1)) + for (v in c("auto", "analytic", "jackknife")) { + m <- ht_mean(s, "y", by = "x", variance = v) + expect_true(is.na(m$se[m$x == "d"]), label = v) + expect_equal(m$method[m$x == "d"], "none", label = v) + expect_true(is.finite(m$se[m$x == "other"]), label = v) + } + expect_match(attr(m, "notes"), paste0( + "The domain `d` has sampled rows taken with certainty only, and the ", + "design could have drawn other rows of it"), fixed = TRUE, all = FALSE) + # The contrast that weighs it has no standard error either. + ct <- ht_mean(s, "y", by = "x", contrast = c(d = 1, other = -1)) + expect_true(is.na(ct$se)) + # A domain of the two rows the design always takes is exact. + b <- ht_mean(s, "y", by = "big") + expect_identical(b$se[b$big == "big"], 0) + expect_equal(b$ci_lower[b$big == "big"], mean(pop$y[99:100])) + # The domain total keeps the 0 its unbiased estimator gives, with a note + # that says why the interval has no width. + tot <- ht_total(s, "y", by = "x") + expect_true(all(is.finite(tot$se))) + expect_match(attr(tot, "notes"), paste0( + "The domain `d` has sampled rows taken with certainty only, and the ", + "design could have drawn other rows of it"), fixed = TRUE, all = FALSE) + ht <- ht_mean(s, "y", by = "x", estimator = "ht") + expect_match(attr(ht, "notes"), "Measuring that variation needs", + fixed = TRUE, all = FALSE) + # A domain of the rows the design always takes gets no such note. + expect_false(any(grepl("taken with certainty only", + attr(ht_total(s, "y", by = "big"), "notes")))) + + # Under a certainty design, two rows above the threshold are one unit too. + pop2 <- data.frame(id = 1:60, w = c(rep(10, 55), 200, 300, 150, 400, 500)) + pop2$y <- 10 + (pop2$id * 13) %% 17 + pop2$x <- ifelse(pop2$id %in% c(1:3, 56:57), "d", "other") + des <- design_certainty("w", 100, design_simple(n = 10)) + cs <- draw(pop2, des, seed = 2, weights = TRUE) + expect_equal(sort(cs$id[cs$x == "d"]), 56:57) + expect_true(is.na(ht_mean(cs, "y", by = "x")$se[1])) + expect_true(is.finite(ht_mean(cs, "y", by = "x")$se[2])) + + # A whole Poisson sample of certain rows is declined the same way. + pop3 <- data.frame(id = 1:30, w = c(rep(1, 28), 500, 600), + y = c(1:28, 40, 70)) + des3 <- design_weighted("w", n = 3, method = "poisson") + seeds <- vapply(1:100, function(i) { + all(draw(pop3, des3, seed = i)$id %in% 29:30) + }, logical(1)) + ps <- draw(pop3, des3, seed = which(seeds)[1], weights = TRUE) + pm <- ht_mean(ps, "y") + expect_true(is.na(pm$se)) + expect_match(pm$note, "Every sampled row was taken with certainty, and", + fixed = TRUE) + # A census stays exact. + cen <- draw(pop3, design_simple(n = 30), seed = 1, weights = TRUE) + expect_identical(ht_mean(cen, "y")$se, 0) +}) + +test_that("certain rows of a sample saved by drawn 0.2.0 stay exact", { + # Such a sample records no probabilities, and every mean of certain rows + # only, a census included, was declined as if the frame could not say + # whether other rows could have been drawn. The design says. + as_legacy <- function(s) { + s$.row <- NULL + attr(s, "drawn_pi") <- NULL + s + } + d <- data.frame(id = 1:30, st = rep(c("a", "b", "c"), each = 10), + y = (1:30 * 7) %% 11 + 1) + cen <- as_legacy(draw(d, design_simple(n = 30), seed = 1, weights = TRUE)) + m <- ht_mean(cen, "y") + expect_identical(m$se, 0) + expect_equal(m$ci, rep(mean(d$y), 2)) + mb <- ht_mean(cen, "y", by = "st") + expect_identical(mb$se, c(0, 0, 0)) + expect_identical(ht_quantile(cen, "y")$se, 0) + expect_identical(ht_ratio(cen, "y", "id")$se, 0) + + # A stratum taken whole is exact, and the others are estimated. + d2 <- data.frame(id = 1:50, st = rep(c("a", "b", "c"), times = c(20, 20, 10)), + y = (1:50 * 7) %% 13 + 1) + s <- draw(d2, design_stratified("st", allocation = c(a = 5, b = 5, c = 10)), + seed = 2, weights = TRUE) + old <- ht_mean(as_legacy(s), "y", by = "st") + expect_identical(old$se, ht_mean(s, "y", by = "st")$se) + expect_identical(old$se[old$st == "c"], 0) + expect_equal(old$method, rep("analytic", 3)) +}) + +lonely_pop <- function() { + # Neyman allocation gives stratum `b`, nearly constant in `aux`, one row of + # 40 and takes all three rows of `c`. + p <- data.frame(st = rep(c("a", "b", "c"), c(40, 40, 3)), + aux = c(seq(-1, 1, length.out = 40), + seq(-0.05, 0.05, length.out = 40), c(-100, 0, 100)), + y = 50 + (seq_len(83) * 37) %% 23) + p$half <- p$st == "c" | seq_len(83) %% 2 == 0 + p +} + +test_that("a domain clear of a lonely stratum is estimated, one across not", { + p <- lonely_pop() + des <- design_stratified("st", n = 20, allocation = "neyman", + allocation_by = "aux") + s <- draw(p, des, seed = 1, weights = TRUE) + expect_equal(as.vector(table(s$st)), c(16L, 1L, 3L)) + expect_true(all(s$.prob[s$st == "c"] == 1)) + + for (v in c("auto", "analytic", "jackknife")) { + r <- ht_total(s, "y", by = "st", variance = v) + # Stratum `c` was taken whole, so its total is exact. + expect_equal(r$se[r$st == "c"], 0, label = v) + expect_equal(r$ci_lower[r$st == "c"], sum(p$y[p$st == "c"]), label = v) + expect_equal(r$ci_upper[r$st == "c"], sum(p$y[p$st == "c"]), label = v) + # Stratum `a` is unaffected by `b`, and `b` itself cannot be measured. + expect_true(is.finite(r$se[r$st == "a"]), label = v) + expect_true(is.na(r$se[r$st == "b"]), label = v) + } + # The analytic and jackknife figures for `a` agree. + expect_equal(ht_total(s, "y", by = "st", variance = "jackknife")$se[1], + ht_total(s, "y", by = "st", variance = "analytic")$se[1]) + + # `half` cuts across `b`: its one sampled row is outside the TRUE domain, + # but other rows of `b` are in it, so neither domain can be measured. + expect_false(s$half[s$st == "b"]) + h <- ht_total(s, "y", by = "half") + expect_true(all(is.na(h$se))) + expect_match(attr(h, "notes"), "would understate", all = FALSE) + + # A `by` column the frame does not hold cannot be checked, so it is refused + # and the note says the frame cannot tell. + s$late <- s$st == "c" + u <- ht_total(s, "y", by = "late") + expect_true(all(is.na(u$se))) + expect_match(attr(u, "notes"), "cannot be told from the frame", + all = FALSE) +}) + +test_that("a frame row with no by value may be in any domain", { + # The frame's `grp` is missing for every row of the lonely stratum `b` + # but the one sampled. Those rows may belong to `A`, so its variance is + # refused as well, where it was estimated with `b` left out. + p <- lonely_pop() + des <- design_stratified("st", n = 20, allocation = "neyman", + allocation_by = "aux") + s0 <- draw(p, des, seed = 1, weights = TRUE) + p$grp <- ifelse(p$st == "a", "A", "other") + p$grp[p$st == "b" & seq_len(nrow(p)) != s0$.row[s0$st == "b"]] <- NA + s <- draw(p, des, seed = 1, weights = TRUE) + for (v in c("auto", "analytic", "jackknife")) { + r <- ht_total(s, "y", by = "grp", variance = v) + expect_true(all(is.na(r$se)), label = v) + expect_match(attr(r, "notes"), "which cannot be told from the frame", + all = FALSE, label = v) + expect_true(is.na(ht_mean(s, "y", by = "grp", variance = v)$se[1]), + label = v) + } + # Missing values outside the lonely stratum leave the domains it does not + # hold as they were: `a` is estimated and `c`, taken whole, is exact. + q <- lonely_pop() + q$g <- q$st + unsampled <- setdiff(which(q$st == "a"), s0$.row) + q$g[unsampled[1:3]] <- NA + t <- draw(q, des, seed = 1, weights = TRUE) + expect_false(anyNA(t$g)) + r <- ht_total(t, "y", by = "g") + expect_equal(r$se[r$g == "a"], ht_total(s0, "y", by = "st")$se[1]) + expect_equal(r$se[r$g == "c"], 0) + expect_true(is.na(r$se[r$g == "b"])) +}) + +test_that("a domain of intervals taken whole is exact at 0 df", { + # One row a day on days 1 to 5, taken whole at per_interval = 1, and five + # rows a day on days 6 to 10, of which one is drawn. + day <- c(1:5, rep(6:10, each = 5)) + p <- data.frame(ts = as.POSIXct("2024-01-01", tz = "UTC") + + (day - 1) * 86400 + 3600 * c(rep(0, 5), rep(0:4, 5)), + y = 10 * day + (seq_along(day) * 7) %% 5) + p$early <- day <= 5 + des <- design_temporal("ts", from = "2024-01-01", to = "2024-01-11", + interval = 1, per_interval = 1, unit = "days") + s <- draw(p, des, seed = 1, weights = TRUE) + r <- ht_total(s, "y", by = "early") + expect_equal(attr(r, "df"), 0) + expect_equal(r$se[r$early], 0) + expect_equal(r$ci_lower[r$early], sum(p$y[p$early])) + expect_equal(r$ci_upper[r$early], sum(p$y[p$early])) + expect_true(is.na(r$se[!r$early])) + m <- ht_mean(s, "y", by = "early") + expect_equal(m$ci_lower[m$early], mean(p$y[p$early])) +}) + +test_that("domain means decide a proportion from the frame, as ht_mean() does", { + pop <- data.frame(id = 1:100, site = rep(c("a", "b"), 50), + kids = c(rep(0, 60), rep(1, 36), rep(3, 4))) + s <- draw(pop, design_simple(n = 10), seed = 1, weights = TRUE) + expect_true(all(s$kids %in% 0:1)) + expect_equal(attr(ht_mean(s, "kids", by = "site"), "ci_scale"), "linear") + r <- ht_mean(s, "kids", by = "site", proportion = TRUE) + expect_equal(attr(r, "ci_scale"), "logit") + expect_output(print(r), "95% CI, logit, ") +}) + +test_that("a domain proportion's interval is the logit interval, in numbers", { + d <- dom_pop() + d$big <- d$y > 300 + s <- draw(d, design_stratified("site", n = 80), seed = 3, weights = TRUE) + r <- ht_mean(s, "big", by = "region") + df <- attr(r, "df") + expect_equal(df, 76) + p <- r$mean + expect_true(all(p > 0 & p < 1)) + # The delta-method interval on the logit scale, mapped back. + half <- stats::qt(0.975, df) * r$se / (p * (1 - p)) + expect_equal(r$ci_lower, stats::plogis(stats::qlogis(p) - half)) + expect_equal(r$ci_upper, stats::plogis(stats::qlogis(p) + half)) + # Both proportions are below a half, where the logit interval sits above + # the symmetric one. + expect_true(all(r$ci_lower > p - stats::qt(0.975, df) * r$se)) + + skip_if_not_installed("survey") + sv <- as_svydesign(s) + theirs <- survey::svyby(~big, ~region, sv, survey::svyciprop, + method = "xlogit", vartype = "ci", + df = survey::degf(sv)) + expect_equal(r$ci_lower, unname(theirs$ci_l), tolerance = 1e-8) + expect_equal(r$ci_upper, unname(theirs$ci_u), tolerance = 1e-8) +}) + +test_that("a domain proportion of 0 gets a beta interval and a note", { + pop <- data.frame(id = 1:300, site = rep(c("a", "b", "c"), each = 100)) + pop$late <- pop$site == "c" & pop$id %% 4 == 0 + s <- draw(pop, design_stratified("site", n = 60), seed = 1, weights = TRUE) + r <- ht_mean(s, "late", by = "site") + # Twenty sampled rows in each domain, against the design's 57 degrees of + # freedom. Scaling by those degrees of freedom took the effective size to + # 21.9 and the upper bound to 0.155, under Clopper-Pearson's 0.168 for 0 + # of 20. The size is capped at the domain's rows. + expect_equal(attr(r, "df"), 57) + expect_equal(r$ci_lower[1:2], c(0, 0)) + expect_equal(r$ci_upper[1:2], rep(1 - 0.025^(1 / 20), 2)) + expect_true(r$ci_lower[3] > 0 && r$ci_upper[3] < 1) + expect_match(attr(r, "notes"), "The domains `a`, `b` have a proportion of 0", + all = FALSE) + expect_output(print(r), "The domains `a`, `b` have a proportion of 0") +}) + +test_that("a y constant over a domain gives its mean a variance of exactly 0", { + pop <- data.frame(id = 1:200, site = rep(c("a", "b"), 100), + w = 1 + (1:200 * 7) %% 13) + pop$y <- ifelse(pop$site == "a", 0.3, (1:200 * 11) %% 17) + s <- draw(pop, design_weighted("w", n = 40, method = "poisson"), seed = 17, + weights = TRUE) + r <- ht_mean(s, "y", by = "site") + expect_identical(r$mean[1], 0.3) + expect_identical(r$se[1], 0) + expect_true(r$se[2] > 0) + expect_match(attr(r, "notes"), "every sampled row of the domain `a`", + all = FALSE) +}) + +test_that("domain tables carry one-sided bounds and the unreachable count", { + skew <- data.frame(id = 1:1000, g = rep(c("big", "rare"), c(990, 10)), + region = rep(c("east", "west"), 500), + y = 1 + (1:1000 * 7) %% 31) + expect_warning( + s <- draw(skew, design_stratified("g", n = 40), seed = 1, weights = TRUE), + class = "drawn_empty_stratum") + r <- ht_total(s, "y", by = "region", alternative = "less") + two <- ht_total(s, "y", by = "region", level = 0.90) + expect_equal(r$ci_upper, two$ci_upper) + expect_equal(r$ci_lower, c(-Inf, -Inf)) + expect_equal(attr(r, "alternative"), "less") + expect_equal(attr(r, "unreachable"), 10) + expect_output(print(r), "95% upper bound, t, 39 df") + expect_output(print(r), "unreachable 10 frame rows at probability 0") + g <- ht_mean(s, "y", by = "region", alternative = "greater") + expect_equal(g$ci_upper, c(Inf, Inf)) +}) + +# ---- all domains at once, and contrasts -------------------------------------- + +contrast_pop <- function() { + id <- 1:400 + d <- data.frame( + id = id, + site = rep(c("a", "b", "c", "d"), times = c(160, 120, 80, 40)), + region = rep(c("east", "west"), 200), + cl = rep(paste0("c", 1:40), each = 10), + w = 1 + (id * 7) %% 19, + ts = as.POSIXct("2024-01-01", tz = "UTC") + ((id - 1) %% 10) * 86400 + + id * 60 + ) + d$y <- 10 + (id * 37) %% 491 + d$hit <- (id * 13) %% 7 < 3 + d +} + +# Each domain's variance from its own run of the estimator, with nothing +# shared between domains: the way `by` worked before every domain was +# estimated against one context. +domain_loop <- function(s, y, by, what = "total", estimator = "hajek", + variance = "auto") { + parts <- drawn:::ht_prepare(s, y, 0.95) + key <- s[[by]] + vapply(sort(unique(key)), function(d) { + ind <- as.numeric(key == d) + z <- if (what == "total") { + ind * parts$y + } else if (estimator == "ht") { + ind * parts$y / sum(parts$pop[[by]] == d) + } else { + n_hat <- sum(ind / parts$pi) + ind * (parts$y - sum(ind * parts$y / parts$pi) / n_hat) / n_hat + } + drawn:::ht_variance_dispatch(parts$design, parts$units, parts$pop, + parts$rows, z, parts$pi, variance, + parts$pop[[by]] == d)$variance + }, numeric(1), USE.NAMES = FALSE) +} + +test_that("domain variances worked out together equal one run per domain", { + d <- contrast_pop() + designs <- list( + simple = design_simple(n = 60), + reservoir = design_reservoir(n = 60), + stratified = design_stratified("site", n = 60), + temporal = design_temporal("ts", from = "2024-01-01", to = "2024-01-11", + interval = 1, per_interval = 6, unit = "days"), + certainty = design_certainty("w", 18, design_stratified("site", n = 40)), + cluster = design_cluster("cl", n_clusters = 8), + multistage = design_multistage("cl", n_clusters = 8, n = 40), + systematic = design_systematic(interval = 7), + pps = design_weighted("w", n = 40, method = "systematic"), + spread = design_spread("w", n = 40) + ) + for (nm in names(designs)) { + s <- draw(d, designs[[nm]], seed = 3, weights = TRUE) + for (v in c("auto", "jackknife")) { + lab <- paste(nm, v) + tot <- ht_total(s, "y", by = "region", variance = v) + expect_equal(tot$se^2, domain_loop(s, "y", "region", variance = v), + tolerance = 1e-10, label = lab) + hajek <- ht_mean(s, "y", by = "region", variance = v) + expect_equal(hajek$se^2, + domain_loop(s, "y", "region", "mean", variance = v), + tolerance = 1e-10, label = lab) + ht <- ht_mean(s, "y", by = "site", estimator = "ht", variance = v) + expect_equal(ht$se^2, + domain_loop(s, "y", "site", "mean", "ht", variance = v), + tolerance = 1e-10, label = lab) + } + } +}) + +test_that("domains with units in a lonely stratum fall back one by one", { + p <- lonely_pop() + p$third <- c("u", "v", "w")[seq_len(83) %% 3 + 1] + des <- design_stratified("st", n = 20, allocation = "neyman", + allocation_by = "aux") + s <- draw(p, des, seed = 1, weights = TRUE) + s$late <- s$st == "c" + for (by in c("st", "half", "third", "late")) { + for (v in c("auto", "analytic")) { + r <- ht_total(s, "y", by = by, variance = v) + want <- domain_loop(s, "y", by, variance = v) + expect_equal(is.na(r$se), is.na(want), label = paste(by, v)) + expect_equal(r$se^2, want, tolerance = 1e-10, label = paste(by, v)) + } + } +}) + +test_that("200 domains of 2,000 sampled rows take well under 2 seconds", { + skip_on_cran() + N <- 40000 + pop <- data.frame(id = seq_len(N), st = sprintf("s%d", seq_len(N) %% 5), + dom = sprintf("d%03d", (seq_len(N) * 7919) %% 200)) + pop$y <- 100 + (pop$id * 37) %% 101 + s <- draw(pop, design_stratified("st", n = 2000), seed = 1, weights = TRUE) + tot <- NULL + mean_by <- NULL + expect_lt(system.time(tot <- ht_total(s, "y", by = "dom"))[["elapsed"]], 2) + expect_lt(system.time(mean_by <- ht_mean(s, "y", by = "dom"))[["elapsed"]], + 2) + expect_equal(nrow(tot), 200L) + expect_equal(tot$se^2, domain_loop(s, "y", "dom"), tolerance = 1e-10) + expect_equal(mean_by$se^2, domain_loop(s, "y", "dom", "mean"), + tolerance = 1e-10) +}) + +test_that("by works out a stratified allocation as often as one estimate does", { + # Every domain worked the allocation out again over the frame, so 50 + # domains took 51 allocations where the whole sample took 2. + N <- 5000 + pop <- data.frame(id = seq_len(N), st = sprintf("s%d", seq_len(N) %% 5), + dom = sprintf("d%02d", (seq_len(N) * 7919) %% 50)) + pop$y <- 100 + (pop$id * 37) %% 101 + s <- draw(pop, design_stratified("st", n = 500), seed = 1, weights = TRUE) + calls <- 0L + allocate <- stratum_allocation + local_mocked_bindings(stratum_allocation = function(...) { + calls <<- calls + 1L + allocate(...) + }) + count <- function(expr) { + calls <<- 0L + force(expr) + calls + } + whole <- count(ht_total(s, "y")) + expect_gt(whole, 0L) + expect_equal(count(ht_total(s, "y", by = "dom")), whole) + expect_equal(count(ht_mean(s, "y", by = "dom")), whole) + expect_equal(count(ht_total(s, "y", by = "dom", variance = "jackknife")), + count(ht_total(s, "y", variance = "jackknife"))) +}) + +test_that("a jackknife by table places the frame's rows in strata once", { + # Every domain matched the frame's rows to the jackknife's strata again + # and counted them, so 50 domains made 50 passes over the frame. + N <- 5000 + pop <- data.frame(id = seq_len(N), st = sprintf("s%d", seq_len(N) %% 5), + dom = sprintf("d%02d", (seq_len(N) * 7919) %% 50)) + pop$y <- 100 + (pop$id * 37) %% 101 + s <- draw(pop, design_stratified("st", n = 500), seed = 1, weights = TRUE) + calls <- 0L + strata <- jackknife_frame + local_mocked_bindings(jackknife_frame = function(...) { + calls <<- calls + 1L + strata(...) + }) + tot <- ht_total(s, "y", by = "dom", variance = "jackknife") + expect_equal(calls, 1L) + expect_equal(nrow(tot), 50L) + expect_equal(tot$se^2, domain_loop(s, "y", "dom", variance = "jackknife"), + tolerance = 1e-10) +}) + +test_that("a contrast of domain totals is the total of the weighted variable", { + d <- contrast_pop() + w <- c(a = 1, b = -1, d = 0.5) + for (des in list(design_stratified("site", n = 60), + design_cluster("cl", n_clusters = 8), + design_systematic(interval = 7))) { + s <- draw(d, des, seed = 2, weights = TRUE) + r <- ht_total(s, "y", by = "site", contrast = w) + weighted <- ht_total(s, s$y * unname(c(w, c = 0)[s$site])) + expect_s3_class(r, "drawn_contrast") + expect_equal(r$contrast, weighted$total) + expect_equal(r$se, weighted$se) + expect_equal(r$ci, weighted$ci) + expect_equal(r$method, weighted$method) + by_site <- ht_total(s, "y", by = "site") + expect_equal(r$estimates, stats::setNames(by_site$total[c(1, 2, 4)], + c("a", "b", "d"))) + expect_equal(r$weights, w) + expect_equal(r$df, attr(by_site, "df")) + } + + # A Horvitz-Thompson mean divides each domain's total by its frame size. + s <- draw(d, design_stratified("site", n = 60), seed = 2, weights = TRUE) + m <- ht_mean(s, "y", by = "site", estimator = "ht", + contrast = c(a = 1, b = -1)) + z <- s$y * ((s$site == "a") / 160 - (s$site == "b") / 120) + expect_equal(m$contrast, ht_total(s, z)$total) + expect_equal(m$se, ht_total(s, z)$se) +}) + +test_that("contrast standard errors match survey::svycontrast", { + skip_if_not_installed("survey") + d <- contrast_pop() + for (des in list(design_stratified("site", n = 80), + design_cluster("cl", n_clusters = 8))) { + s <- draw(d, des, seed = 2, weights = TRUE) + svd <- as_svydesign(s) + + w <- c(east = 1, west = -1) + ours <- ht_total(s, "y", by = "region", contrast = w) + theirs <- survey::svycontrast( + survey::svyby(~y, ~region, svd, survey::svytotal, covmat = TRUE), w) + expect_equal(ours$contrast, as.numeric(stats::coef(theirs))) + expect_equal(ours$se, as.numeric(survey::SE(theirs)), tolerance = 1e-8) + + w <- c(a = 1, b = -0.5, c = -0.5) + ours <- ht_mean(s, "y", by = "site", contrast = w) + theirs <- survey::svycontrast( + survey::svyby(~y, ~site, svd, survey::svymean, covmat = TRUE), w) + expect_equal(ours$contrast, as.numeric(stats::coef(theirs))) + expect_equal(ours$se, as.numeric(survey::SE(theirs)), tolerance = 1e-8) + } +}) + +test_that("a contrast of proportions has a symmetric interval", { + d <- contrast_pop() + s <- draw(d, design_stratified("site", n = 80), seed = 2, weights = TRUE) + r <- ht_mean(s, "hit", by = "region", contrast = c(east = 1, west = -1)) + expect_equal(r$ci_scale, "linear") + q <- stats::qt(0.975, r$df) + expect_equal(r$ci, r$contrast + c(-1, 1) * q * r$se) + up <- ht_mean(s, "hit", by = "region", contrast = c(east = 1, west = -1), + alternative = "less") + expect_equal(up$ci, c(-Inf, r$contrast + stats::qt(0.95, r$df) * r$se)) +}) + +test_that("a contrast weighing a mean over one sampling unit has no se", { + d <- contrast_pop() + d$rare <- ifelse(d$id %% 40 == 0, "rare", "common") + des <- design_simple(n = 40) + hits <- vapply(1:100, function(i) { + sum(draw(d, des, seed = i)$rare == "rare") + }, integer(1)) + s <- draw(d, des, seed = which(hits == 1L)[1], weights = TRUE) + r <- ht_mean(s, "y", by = "rare", contrast = c(rare = 1, common = -1)) + expect_true(is.na(r$se)) + expect_equal(r$method, "none") + expect_match(r$note, "The domain `rare` has one sampled row", fixed = TRUE) + expect_match(r$note, "so it has no standard error either", fixed = TRUE) + # A contrast of totals is still estimated. + expect_true(is.finite(ht_total(s, "y", by = "rare", + contrast = c(rare = 1, common = -1))$se)) +}) + +test_that("contrasts name domains as by does, and odd weights are refused", { + d <- contrast_pop() + d$empty <- ifelse(d$id == 400, "never", d$site) + s <- draw(d, design_stratified("site", n = 60), seed = 2, weights = TRUE) + expect_false("never" %in% s$empty) + two <- ht_total(s, "y", by = c("site", "region"), + contrast = c("a . east" = 1, "a . west" = -1)) + expect_equal(names(two$weights), c("a . east", "a . west")) + + expect_error(ht_total(s, "y", contrast = c(a = 1, b = -1)), + "`contrast` weighs the domains of `by`, and `by` is NULL", + fixed = TRUE) + expect_error(ht_total(s, "y", by = "site", contrast = c(1, -1)), + "`contrast` must be a named numeric vector") + expect_error(ht_total(s, "y", by = "site", contrast = c(a = "1")), + "`contrast` must be a named numeric vector") + expect_error(ht_total(s, "y", by = "site", + contrast = stats::setNames(c(1, -1), c("a", NA))), + "`contrast` has a weight with no name") + expect_error(ht_total(s, "y", by = "site", contrast = c(a = 1, a = -1)), + "`contrast` names `a` more than once", fixed = TRUE) + expect_error(ht_total(s, "y", by = "site", contrast = c(a = 1, b = NA)), + "`contrast` gives `b` a weight of NA", fixed = TRUE) + expect_error(ht_total(s, "y", by = "site", contrast = c(a = 1, z = -1)), + paste("`contrast` names `z`, which is not a domain of `by`.", + "Name the weights after the domains, which are `a`,", + "`b`, `c`, `d`."), fixed = TRUE) + # Past five domains the list ends with a count of the rest. It ended with + # "..." and then the full stop, four dots in all. + cl <- sort(unique(s$cl), method = "radix") + msg <- tryCatch(ht_total(s, "y", by = "cl", contrast = c(z = 1)), + error = conditionMessage) + expect_match(msg, paste0("which are ", paste0("`", cl[1:5], "`", + collapse = ", "), + " and ", length(cl) - 5L, " more.$")) + expect_no_match(msg, "..", fixed = TRUE) + expect_error(ht_total(s, "y", by = "empty", contrast = c(a = 1, never = -1)), + "`contrast` names `never`, which has no sampled row", + fixed = TRUE) + expect_error(ht_total(s, "y", by = "site", contrast = c(a = 0, b = 0)), + "`contrast` gives every domain a weight of 0", fixed = TRUE) +}) + +test_that("a contrast prints its weights, domains and interval", { + d <- contrast_pop() + s <- draw(d, design_stratified("site", n = 60), seed = 2, weights = TRUE) + r <- ht_mean(s, "y", by = "site", contrast = c(a = 0.5, b = 0.5, c = -1)) + expect_output(print(r), "Contrast of Hajek means (stratified design, n = 60)", + fixed = TRUE) + expect_output(print(r), "contrast 0.5 `a` + 0.5 `b` - `c`", fixed = TRUE) + expect_output(print(r), "domains `a` ", fixed = TRUE) + expect_output(print(r), "95% CI", fixed = TRUE) + t2 <- ht_total(s, "y", by = "site", contrast = c(b = -1, a = 1)) + expect_output(print(t2), "Contrast of Horvitz-Thompson totals") + expect_output(print(t2), "contrast `a` - `b`", fixed = TRUE) + expect_output(print(ht_mean(s, "y", by = "site", estimator = "ht", + contrast = c(a = -1, b = 1))), + "contrast -`a` + `b`", fixed = TRUE) +}) + +# ---- the by table as numbers ------------------------------------------------ + +table_pop <- function() { + id <- 1:300 + data.frame(id = id, site = rep(c("a", "b", "c"), times = c(150, 100, 50)), + half = rep(c("east", "west"), 150), + y = 20 + (id * 37) %% 101, + flag = id <= 150 & id %% 3 == 0) +} + +test_that("a by table holds each domain's variance and an integer count", { + s <- draw(table_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + b <- ht_total(s, "y", by = "site") + expect_type(b$n, "integer") + expect_equal(b$variance, b$se^2) + expect_equal(names(b), c("site", "n", "total", "variance", "se", + "ci_lower", "ci_upper", "method")) + expect_equal(attr(b, "variable"), "y") + out <- capture.output(print(b)) + expect_false(any(grepl("variance", out))) + expect_error(deff(b), "no design effect") +}) + +test_that("a by column named like a column of the table is refused", { + # The count overwrote a `by` column called `n`, which then held the counts. + d <- data.frame(id = 1:100, n = rep(c("x", "y"), 50), y = 1:100) + s <- draw(d, design_simple(n = 20), seed = 1, weights = TRUE) + expect_error(ht_total(s, "y", by = "n"), "`by` names `n`, which the table") + s$variance <- s$n + expect_error(ht_mean(s, "y", by = c("variance", "n")), + paste0("`variance`, `n`, which the table of domain estimates ", + "uses for its own columns"), fixed = TRUE) + # A contrast builds no table, so the name does not matter there. + expect_s3_class(ht_total(s, "y", by = "n", contrast = c(x = 1, y = -1)), + "drawn_contrast") +}) + +test_that("a by table gives coef(), vcov(), confint() and tidy() by domain", { + s <- draw(table_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + b <- ht_mean(s, "y", by = "site") + expect_equal(coef(b), c(a = b$mean[1], b = b$mean[2], c = b$mean[3])) + v <- vcov(b) + expect_equal(diag(v), c(a = b$variance[1], b = b$variance[2], + c = b$variance[3])) + expect_equal(v[upper.tri(v)], c(0, 0, 0)) + expect_equal(unname(confint(b)), cbind(b$ci_lower, b$ci_upper)) + b8 <- ht_mean(s, "y", by = "site", level = 0.8) + expect_equal(unname(confint(b, level = 0.8)), + cbind(b8$ci_lower, b8$ci_upper)) + + # A proportion keeps its logit interval, and the domains at 0 their beta + # interval, at another level. + p <- ht_mean(s, "flag", by = "site") + p8 <- ht_mean(s, "flag", by = "site", level = 0.8) + expect_equal(unname(confint(p, level = 0.8)), + cbind(p8$ci_lower, p8$ci_upper)) + q <- ht_mean(s, "flag", by = "site", ci_method = "beta", + alternative = "less") + q8 <- ht_mean(s, "flag", by = "site", ci_method = "beta", + alternative = "less", level = 0.8) + expect_equal(unname(confint(q, level = 0.8)), + cbind(q8$ci_lower, q8$ci_upper)) + + # Domains of several columns are named as `contrast` names them. + two <- ht_total(s, "y", by = c("site", "half")) + expect_equal(names(coef(two))[1:2], c("a . east", "a . west")) + + skip_if_not_installed("survey") + expect_equal(unname(survey::SE(b)), b$se) + skip_if_not_installed("generics") + t <- generics::tidy(b, conf.int = TRUE) + expect_equal(names(t), c("site", "term", "estimate", "std.error", + "conf.low", "conf.high")) + expect_equal(t$term, rep("y", 3)) + expect_equal(t$conf.high, b$ci_upper) +}) + +test_that("selecting rows of a by table keeps its methods; columns drop them", { + s <- draw(table_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + b <- ht_total(s, "y", by = "site") + r <- b[c(3, 1), ] + expect_equal(coef(r), coef(b)[c(3, 1)]) + expect_equal(confint(r, level = 0.8), confint(b, level = 0.8)[c(3, 1), ]) + expect_output(print(r), "by domain") + + # Selecting columns keeps the class but not the attributes the heading + # reads, and print() stopped with "argument is of length zero". + cols <- b[, c("site", "total")] + out <- capture.output(print(cols)) + expect_false(any(grepl("by domain", out))) + expect_true(any(grepl("site", out)) && any(grepl("total", out))) + expect_output(print(subset(b, total > 0, select = c(site, se))), "se") + expect_error(coef(cols), "attributes of a `by` table") + expect_error(confint(cols), "attributes of a `by` table") + + plain <- as.data.frame(b) + expect_identical(class(plain), "data.frame") + expect_null(attr(plain, "what")) + expect_equal(plain$total, b$total) +}) + +test_that("a contrast gives the same methods, named by its weights", { + s <- draw(table_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + k <- ht_total(s, "y", by = "site", contrast = c(a = 1, b = -1)) + expect_equal(coef(k), c("a - b" = k$contrast)) + expect_equal(vcov(k)[1, 1], k$variance) + k8 <- ht_total(s, "y", by = "site", contrast = c(a = 1, b = -1), + level = 0.8) + expect_equal(unname(confint(k, level = 0.8)[1, ]), k8$ci) + df <- as.data.frame(k) + expect_equal(df$domains, "a - b") + expect_equal(df$contrast, k$contrast) + expect_true(is.na(deff(k))) +}) + +test_that("several y by domain hold the covariances within each domain", { + s <- draw(table_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + s$v <- s$y %% 7 + b <- ht_total(s, c("y", "v"), by = "half") + expect_equal(names(b)[1:3], c("variable", "half", "n")) + one <- ht_total(s, "v", by = "half") + expect_equal(b$total[b$variable == "v"], one$total) + expect_equal(b$se[b$variable == "v"], one$se) + V <- vcov(b) + expect_equal(rownames(V), c("y . east", "y . west", "v . east", + "v . west")) + expect_equal(unname(diag(V)), b$variance) + # The halves cross the strata, and their covariance is not estimated. + expect_true(is.na(V["y . east", "v . west"])) + expect_true(is.na(vcov(one)["east", "west"])) + # Domains in strata of their own are sampled independently. + by_site <- vcov(ht_total(s, c("y", "v"), by = "site")) + expect_equal(by_site["y . a", "v . b"], 0) + expect_equal(by_site["y . a", "y . c"], 0) + # Selecting rows keeps the matching part of the matrix. + expect_equal(vcov(b[c(4, 1), ]), V[c(4, 1), c(4, 1)]) + expect_output(print(b), "by variable and domain") + s$variable <- s$half + expect_error(ht_total(s, c("y", "v"), by = "variable"), + "`by` names `variable`") + + skip_if_not_installed("survey") + svd <- as_svydesign(s) + sb <- survey::svyby(~y + v, ~half, svd, survey::svytotal, covmat = TRUE) + expect_equal(V["y . east", "v . east"], vcov(sb)["east:y", "east:v"]) + expect_equal(V["y . west", "v . west"], vcov(sb)["west:y", "west:v"]) + m <- ht_mean(s, c("y", "v"), by = "half") + sm <- survey::svyby(~y + v, ~half, svd, survey::svymean, covmat = TRUE) + expect_equal(vcov(m)["y . west", "v . west"], + vcov(sm)["west:y", "west:v"]) + ss <- survey::svyby(~y + v, ~site, svd, survey::svytotal, covmat = TRUE) + expect_equal(vcov(ss)["a:y", "b:v"], by_site["y . a", "v . b"]) +}) + +test_that("domain ratios match survey::svyby(svyratio)", { + d <- dom_pop() + d$x <- 1 + d$id %% 9 + s <- draw(d, design_stratified("site", n = 80), seed = 2, weights = TRUE) + b <- ht_ratio(s, "y", "x", by = "region") + expect_equal(names(b), c("region", "n", "ratio", "variance", "se", + "ci_lower", "ci_upper", "method")) + for (r in c("east", "west")) { + i <- s$region == r + expect_equal(b$ratio[b$region == r], + sum(s$y[i] * s$.weight[i]) / sum(s$x[i] * s$.weight[i])) + } + expect_output(print(b), "Ratio `y` / `x` by domain", fixed = TRUE) + s$x0 <- ifelse(s$region == "east", 0, s$x) + expect_error(ht_ratio(s, "y", "x0", by = "region"), + "The estimated total of `x0` is 0 in the domain `east`") + skip_if_not_installed("generics") + expect_equal(generics::tidy(b)$term, c("y/x", "y/x")) + + skip_if_not_installed("survey") + for (des in list(design_stratified("site", n = 80), + design_cluster("cl", n_clusters = 8))) { + s <- draw(d, des, seed = 2, weights = TRUE) + ours <- ht_ratio(s, "y", "x", by = "region") + theirs <- survey::svyby(~y, ~region, as_svydesign(s), survey::svyratio, + denominator = ~x) + expect_equal(ours$ratio, unname(coef(theirs))) + expect_equal(ours$se, unname(survey::SE(theirs))) + } +}) diff --git a/tests/testthat/test-draw.R b/tests/testthat/test-draw.R index b32de1d..047aa70 100644 --- a/tests/testthat/test-draw.R +++ b/tests/testthat/test-draw.R @@ -45,7 +45,7 @@ test_that("every design returns the input's class and column order", { test_that("seeding is local to the draw", { df <- make_df() - set.seed(42) + local_seed(42) expected <- stats::runif(3) designs <- list( @@ -60,7 +60,7 @@ test_that("seeding is local to the draw", { interval = 6, per_interval = 1, unit = "hours") ) for (d in designs) { - set.seed(42) + local_seed(42) invisible(draw(df, d, seed = 7)) expect_equal(stats::runif(3), expected, info = class(d)[1]) } @@ -68,7 +68,7 @@ test_that("seeding is local to the draw", { test_that("an unseeded draw still advances the RNG normally", { df <- make_df() - set.seed(1) + local_seed(1) a <- draw(df, design_simple(n = 3))$id b <- draw(df, design_simple(n = 3))$id expect_false(identical(a, b)) @@ -85,3 +85,397 @@ test_that("an empty or non-data-frame input is reported clearly", { "has no rows") expect_error(draw(1:10, design_simple(n = 1)), "must be a data frame") }) + +test_that("weights = TRUE stores a copy of the frame and its probabilities", { + df <- make_df() + des <- design_stratified("site", n = 8) + s <- draw(df, des, seed = 1, weights = TRUE) + expect_identical(attr(s, "drawn_population"), df) + expect_equal(attr(s, "drawn_pi"), inclusion_prob(df, des)) + expect_identical(attr(s, "drawn_rows"), s$.row) + expect_type(s$.row, "integer") + expect_equal(s$.prob, attr(s, "drawn_pi")[s$.row]) +}) + +test_that("the frame copy keeps a tibble's and an sf frame's class", { + skip_if_not_installed("tibble") + tb <- tibble::as_tibble(make_df()) + s <- draw(tb, design_simple(n = 5), seed = 1, weights = TRUE) + expect_identical(attr(s, "drawn_population"), tb) + + skip_if_not_installed("sf") + pts <- sf::st_as_sf(make_df(), coords = c("lon", "lat"), crs = 4326, + remove = FALSE) + s <- draw(pts, design_simple(n = 5), seed = 1, weights = TRUE) + expect_s3_class(s, "sf") + expect_identical(attr(s, "drawn_population"), pts) +}) + +test_that("an in-place edit of a data.table frame does not reach the sample", { + skip_if_not_installed("data.table") + dt <- data.table::as.data.table(make_df()) + data.table::setkeyv(dt, "site") + s <- draw(dt, design_simple(n = 5), seed = 1, weights = TRUE) + pop <- attr(s, "drawn_population") + expect_s3_class(pop, "data.table") + expect_identical(data.table::key(pop), "site") + # `+ 0` makes new vectors. set() overwrites the column vector in place, so + # a plain reference to it would change along with the frame. + before <- pop$value + 0 + ids <- pop$id + 0L + data.table::set(dt, j = "value", value = 0) + data.table::setorderv(dt, "id", order = -1L) + expect_identical(attr(s, "drawn_population")$value, before) + expect_identical(attr(s, "drawn_population")$value, make_df()$value) + expect_identical(attr(s, "drawn_population")$id, ids) +}) + +test_that("the frame copy keeps S4 vector columns as they were", { + # lubridate's Period, Duration and Interval columns are S4 vectors. A copy + # that lost the S4 bit printed as bare numbers and could not be ordered by + # its methods, so the variance of a design ordered by one went wrong. + df <- make_df(40L) + df$per <- lubridate::hours((seq_len(40L) * 17L) %% 41L) + df$dur <- lubridate::duration(seq_len(40L), "hours") + s <- draw(df, design_stratified("site", n = 5), seed = 1, weights = TRUE) + expect_identical(attr(s, "drawn_population"), df) + expect_true(isS4(attr(s, "drawn_population")$per)) + + df$sec <- lubridate::period_to_seconds(df$per) + by_per <- draw(df, design_systematic(interval = 4, order_by = "per"), + seed = 1, weights = TRUE) + by_sec <- draw(df, design_systematic(interval = 4, order_by = "sec"), + seed = 1, weights = TRUE) + expect_identical(by_per$id, by_sec$id) + expect_equal(ht_total(by_per, "value")$se, ht_total(by_sec, "value")$se) +}) + +test_that("renaming, reordering or deleting frame columns does not reach the sample", { + # The copy of the frame shared its names vector with the caller's, which + # setnames(), setcolorder() and deleting a column rewrite in place. + skip_if_not_installed("data.table") + for (as_table in c(FALSE, TRUE)) { + d <- make_df() + if (as_table) d <- data.table::as.data.table(d) + s <- draw(d, design_stratified("site", n = 8), seed = 1, weights = TRUE) + want <- ht_total(s, "value") + cols <- names(make_df()) + data.table::setnames(d, "site", "SITE") + data.table::setcolorder(d, rev(names(d))) + data.table::set(d, j = "lon", value = NULL) + pop <- attr(s, "drawn_population") + expect_identical(names(pop), cols) + expect_identical(pop$site, make_df()$site) + expect_equal(ht_total(s, "value"), want) + } +}) + +test_that("a sample drawn from a data.table takes := without a warning", { + skip_if_not_installed("data.table") + dt <- data.table::as.data.table(make_df()) + for (w in c(FALSE, TRUE)) { + # `:=` works only where data.table is attached or imported, which the + # global environment counts as. + env <- new.env(parent = globalenv()) + env$s <- draw(dt, design_stratified("site", n = 8), seed = 1, weights = w) + expect_s3_class(env$s, "data.table") + expect_no_warning(evalq(s[, obs := value * 2], env)) + expect_equal(env$s$obs, env$s$value * 2) + if (w) expect_false(is.null(attr(env$s, "drawn_design"))) + } +}) + +test_that("a value outside an argument's choices is refused by name", { + # match.arg() said "'arg' should be one of", which names no argument. + msg <- function(expr) tryCatch(expr, error = conditionMessage) + expect_equal( + msg(design_stratified("g", n = 30, allocation = "neymann")), + paste0("`allocation` must be one of \"proportional\", \"equal\" or ", + "\"neyman\", not \"neymann\".") + ) + expect_match(msg(design_stratified("g", n = 30, allocation = character(0))), + "not a length-0 character.", fixed = TRUE) + expect_match(msg(design_multistage("g", n_clusters = 2, n = 4, + allocation = "even")), + "^`allocation` must be one of \"equal\" or \"proportional\"") + expect_match(msg(design_weighted("w", n = 5, method = "pps")), + "^`method` must be one of") + expect_match(msg(design_bootstrap(5, method = "wild")), + "^`method` must be one of") + expect_match(msg(design_temporal("t", "2020-01-01", "2020-01-02", 1, 1, + unit = "fortnights")), + "^`unit` must be one of") + expect_match(msg(plan_size(0.1, sd = 1, target = "median")), + "^`target` must be one of") + expect_match(msg(plot(design_simple(n = 2), data.frame(x = 1:5), + type = "pie")), + "^`type` must be one of") + s <- draw(data.frame(y = 1:10), design_simple(n = 5), seed = 1, + weights = TRUE) + expect_match(msg(ht_total(s, "y", variance = "boot")), + "^`variance` must be one of") + expect_match(msg(ht_mean(s, "y", estimator = "median")), + "^`estimator` must be one of") + expect_match(msg(ht_mean(s, "y", variance = NA)), "not NA\\.$") + + # The default and a unique abbreviation work as they did with match.arg(). + expect_equal(design_stratified("g", n = 30)$allocation, "proportional") + expect_equal(design_stratified("g", n = 30, allocation = "ney", + allocation_by = "w")$allocation, "neyman") + expect_equal(ht_total(s, "y", variance = "jack")$method, "jackknife") + # NULL gives the default, as match.arg() gave it, for code that passes on + # an argument it was not given. + expect_equal(design_stratified("g", n = 30, allocation = NULL)$allocation, + "proportional") + expect_equal(design_multistage("g", n_clusters = 2, n = 4, + allocation = NULL)$allocation, "equal") + expect_equal(design_weighted("w", n = 5, method = NULL)$method, + "successive") + expect_equal(ht_total(s, "y", variance = NULL)$method, "analytic") + expect_equal(ht_mean(s, "y", estimator = NULL)$estimator, "hajek") + expect_equal(plan_size(0.1, sd = 1, target = NULL)$target, "mean") +}) + +test_that("a printed design says what a NULL default means", { + out <- capture.output(print(design_bootstrap(20, method = "block"))) + expect_true(any(grepl("^ n +nrow\\(data\\)$", out))) + expect_true(any(grepl("^ block_length +nrow\\(data\\)\\^\\(1/3\\), rounded down$", + out))) + out <- capture.output(print(design_bootstrap(20))) + expect_false(any(grepl("block_length", out))) + out <- capture.output(print(design_systematic(interval = 5))) + expect_true(any(grepl("^ start +random$", out))) + out <- capture.output(print(design_systematic(interval = 5, start = 2))) + expect_true(any(grepl("^ start +2$", out))) +}) + +test_that("messages give a class its article", { + expect_error(draw(data.frame(id = 1:5), 1L), + "constructors, not an integer.", fixed = TRUE) + expect_error(draw(1:5, design_simple(n = 2), weights = TRUE), + "needs a data frame, not an integer.", fixed = TRUE) + expect_error(design_certainty("w", 1, list()), + "not a list.", fixed = TRUE) +}) + +test_that("a value with no single value to show is named by its class", { + # A function warned from is.na(), and a data frame stopped with "the + # condition has length > 1". + expect_no_warning( + expect_error(design_simple(n = mean), + "`n` must be a single whole number, not a function.", + fixed = TRUE) + ) + expect_error(design_simple(n = data.frame(n = 1:3)), + "`n` must be a single whole number, not a data.frame.", + fixed = TRUE) + expect_error(design_simple(n = new.env()), + "`n` must be a single whole number, not an environment.", + fixed = TRUE) +}) + +# ---- seeds, generators and the record of a draw ----------------------------- + +# Run `code` under another generator, then put back the caller's random number +# state, or its absence, and generator. +under_kind <- function(kind, code) { + had <- exists(".Random.seed", envir = globalenv(), inherits = FALSE) + old <- if (had) get(".Random.seed", envir = globalenv()) + old_kind <- RNGkind() + on.exit({ + if (had) { + assign(".Random.seed", old, envir = globalenv()) + } else { + do.call(RNGkind, as.list(old_kind)) + suppressWarnings(rm(".Random.seed", envir = globalenv())) + } + }) + do.call(RNGkind, as.list(kind)) + code +} + +test_that("a seed draws the same sample under any generator", { + df <- make_df() + des <- design_stratified("site", n = 8) + ref <- draw(df, des, seed = 11) + for (kind in list("L'Ecuyer-CMRG", "Knuth-TAOCP-2002", + list("Mersenne-Twister", "Box-Muller", "Rounding"))) { + got <- suppressWarnings(under_kind(kind, { + before <- RNGkind() + out <- draw(df, des, seed = 11) + # The caller's generator is back in place afterwards. + expect_identical(RNGkind(), before) + out + })) + expect_identical(got, ref) + } + expect_equal(inclusion_prob(df, design_simple(n = 8), simulate = TRUE, + R = 50, seed = 3), + under_kind("L'Ecuyer-CMRG", + inclusion_prob(df, design_simple(n = 8), + simulate = TRUE, R = 50, seed = 3))) +}) + +test_that("a seeded draw leaves the caller's generator and stream alone", { + df <- make_df() + under_kind("L'Ecuyer-CMRG", { + before <- get(".Random.seed", envir = globalenv()) + draw(df, design_simple(n = 3), seed = 1) + expect_identical(get(".Random.seed", envir = globalenv()), before) + expect_identical(RNGkind()[[1L]], "L'Ecuyer-CMRG") + }) + # With no stream started, none is left behind, and the generator is the + # caller's. + under_kind("L'Ecuyer-CMRG", { + rm(".Random.seed", envir = globalenv()) + draw(df, design_simple(n = 3), seed = 1) + expect_false(exists(".Random.seed", envir = globalenv(), + inherits = FALSE)) + expect_identical(RNGkind()[[1L]], "L'Ecuyer-CMRG") + }) + # Putting back the "Rounding" sampler gave R's warning about it from a + # seeded draw. The warning muffled here is the one for choosing it. + suppressWarnings( + under_kind(list("Mersenne-Twister", "Inversion", "Rounding"), { + rm(".Random.seed", envir = globalenv()) + expect_no_warning(draw(df, design_simple(n = 3), seed = 1)) + expect_false(exists(".Random.seed", envir = globalenv(), + inherits = FALSE)) + expect_identical(RNGkind()[[3L]], "Rounding") + }) + ) +}) + +test_that("a seed outside the integer range or given as text is refused", { + df <- make_df() + des <- design_simple(n = 3) + for (s in list(2^31, -2^31, 1e15)) { + expect_error(draw(df, des, seed = s), "must lie between -2147483647 and") + } + expect_no_error(draw(df, des, seed = .Machine$integer.max)) + expect_error(draw(df, des, seed = "1"), 'not the string "1"', fixed = TRUE) + # The probability functions check it whether or not they simulate. + expect_error(inclusion_prob(df, des, seed = "abc"), 'the string "abc"', + fixed = TRUE) + expect_error(joint_prob(df, des, rows = 1:2, seed = 2^31), "must lie") +}) + +test_that("a weighted sample records how it was drawn", { + df <- make_df() + des <- design_stratified("site", n = 8) + s <- draw(df, des, seed = 5, weights = TRUE) + meta <- attr(s, "drawn_meta") + expect_identical(meta$seed, 5) + expect_identical(meta$rng_kind, + c("Mersenne-Twister", "Inversion", "Rejection")) + expect_identical(meta$version, as.character(utils::packageVersion("drawn"))) + expect_s3_class(meta$time, "POSIXct") + expect_identical(meta$frame_rows, 100L) + expect_identical(meta$made_by, "draw()") + expect_identical(sample_summary(s)$drawn, meta) + expect_match(capture.output(sample_summary(s)), + "with seed 5, by drawn [0-9.]+ on [0-9-]+$", all = FALSE) + + # Without a seed, the session's generator is recorded. + u <- under_kind("L'Ecuyer-CMRG", draw(df, des, weights = TRUE)) + expect_null(attr(u, "drawn_meta")$seed) + expect_identical(attr(u, "drawn_meta")$rng_kind[[1L]], "L'Ecuyer-CMRG") + expect_match(capture.output(sample_summary(u)), + "without a seed (L'Ecuyer-CMRG", fixed = TRUE, all = FALSE) + + # A sample rebuilt from a file does not know its seed. + back <- as_drawn(as.data.frame(s)[, c(".row", names(df))], des, df) + expect_identical(attr(back, "drawn_meta")$made_by, "as_drawn()") + expect_null(attr(back, "drawn_meta")$seed) + expect_match(capture.output(sample_summary(back)), "rebuilt", + all = FALSE) +}) + +test_that("use_reserves() keeps the record of the draw", { + df <- make_df() + l <- draw(df, design_simple(n = 4, reserve = 2), seed = 9, weights = TRUE) + s <- use_reserves(l, c(TRUE, FALSE, FALSE, FALSE, FALSE, NA)) + expect_identical(attr(s, "drawn_meta"), attr(l, "drawn_meta")) +}) + +# ---- row names -------------------------------------------------------------- + +test_that("row names of the frame's own stay with their rows", { + cars <- mtcars[, c("mpg", "cyl", "wt")] + cars$id <- seq_len(nrow(cars)) + s <- draw(cars, design_simple(n = 5), seed = 1) + expect_identical(rownames(s), rownames(cars)[s$id]) + w <- draw(cars, design_stratified("cyl", n = 6), seed = 1, weights = TRUE) + expect_identical(rownames(w), rownames(cars)[w$.row]) + # A frame left with integer row names by an earlier subset keeps them. + sub <- cars[cars$cyl != 6, ] + w <- draw(sub, design_simple(n = 4), seed = 2, weights = TRUE) + expect_identical(rownames(w), rownames(sub)[w$.row]) + + # A row drawn twice gets a name made unique, as `[` gives it. + r <- draw(cars, design_simple(n = 40, replace = TRUE), seed = 1) + expect_false(anyDuplicated(rownames(r)) > 0) + expect_identical(rownames(r), make.unique(rownames(cars)[r$id])) + b <- draw(cars, design_bootstrap(n_replicates = 2, n = 5), seed = 1) + expect_false(anyDuplicated(rownames(b)) > 0) +}) + +test_that("automatic row names are numbered afresh, also after rows drop", { + df <- make_df() + df$o <- df$id + df$o[c(3, 50)] <- NA + df$w <- df$id + df$w[7] <- NA + df$cl <- rep(1:10, each = 10) + df$cl[c(1, 95)] <- NA + df$big <- df$id + df$big[4] <- NA + designs <- list( + design_systematic(interval = 7, order_by = "o", na_rm = TRUE), + design_weighted("w", n = 6, na_rm = TRUE), + design_cluster("cl", n_clusters = 2, na_rm = TRUE), + design_certainty("big", 95, rest = design_simple(n = 3), na_rm = TRUE) + ) + for (d in designs) { + s <- draw(df, d, seed = 4) + expect_identical(attr(s, "row.names"), seq_len(nrow(s)), + info = class(d)[1]) + } +}) + +# ---- arguments -------------------------------------------------------------- + +test_that("a design and data given the wrong way round are named as swapped", { + df <- make_df() + des <- design_simple(n = 3) + expect_error(draw(des, df), "look swapped. Call draw(data, design)", + fixed = TRUE) + expect_error(des |> draw(df), "look swapped") + expect_error(inclusion_prob(des, df), "Call inclusion_prob(data, design)", + fixed = TRUE) + expect_error(joint_prob(des, df), "Call joint_prob(data, design)", + fixed = TRUE) +}) + +test_that("a design class of the user's own draws through draw_design()", { + df <- data.frame(id = 1:10) + first <- structure(list(n = 3), class = c("drawn_test_first", "drawn_design")) + .S3method("draw_design", "drawn_test_first", function(design, data) { + data[seq_len(design$n), , drop = FALSE] + }) + expect_identical(draw(df, first)$id, 1:3) + expect_equal(inclusion_prob(df, first, simulate = TRUE, R = 5, seed = 1), + rep(c(1, 0), c(3, 7))) + expect_error(draw(df, first, weights = TRUE), + "simulate = TRUE) estimates the probabilities", fixed = TRUE) + expect_error(joint_prob(df, first, rows = 1:2), + "joint_prob(data, design, simulate = TRUE)", fixed = TRUE) + # A method that drops columns is caught rather than counted as drawing + # nothing. + thin <- structure(list(), class = c("drawn_test_thin", "drawn_design")) + .S3method("draw_design", "drawn_test_thin", function(design, data) { + data.frame(id = data$id[1:2]) + }) + expect_error(inclusion_prob(df, thin, simulate = TRUE, R = 2, seed = 1), + "returned rows without the `.drawn_row_id` column") +}) diff --git a/tests/testthat/test-estimate.R b/tests/testthat/test-estimate.R index 250283c..fc56347 100644 --- a/tests/testthat/test-estimate.R +++ b/tests/testthat/test-estimate.R @@ -1,5 +1,5 @@ est_pop <- function() { - set.seed(404) + local_seed(404) N <- 300 d <- data.frame( id = 1:N, @@ -20,10 +20,10 @@ test_that("ht_mean recovers the population mean under a range of designs", { design_stratified("site", n = 80), design_weighted("w", n = 80, method = "poisson") )) { - est <- replicate(400, { - s <- draw(d, des, weights = TRUE) + est <- vapply(1:400, function(i) { + s <- draw(d, des, seed = i, weights = TRUE) ht_mean(s, "y", variance = "none")$mean - }) + }, numeric(1)) se <- stats::sd(est) / sqrt(length(est)) expect_lt(abs(mean(est) - truth), 4 * se) } @@ -45,6 +45,21 @@ test_that("the two estimators differ, and Hajek is the steadier one", { expect_lt(stats::sd(pair["hajek", ]), stats::sd(pair["ht", ])) }) +test_that("equal probabilities over the rows reached part Hajek from HT", { + # A reservoir capped at max_items is a simple random sample of the rows it + # reaches, so its weights sum to 100, not 200, and the HT mean, which + # divides by all 200, is half the Hajek mean. + d <- data.frame(y = 1:200) + expect_warning( + s <- draw(d, design_reservoir(n = 20, max_items = 100), seed = 1, + weights = TRUE), + "max_items" + ) + expect_equal(sum(s$.weight), 100) + hajek <- ht_mean(s, "y", variance = "none")$mean + expect_equal(ht_mean(s, "y", "ht", variance = "none")$mean, hajek / 2) +}) + test_that("the Hajek variance tracks the actual sampling variance", { d <- est_pop() des <- design_stratified("site", n = 90) @@ -93,7 +108,8 @@ test_that("ht_mean refuses samples it cannot estimate from", { s <- draw(d, design_simple(n = 20), seed = 1, weights = TRUE) expect_error(ht_mean(s, "nope"), "no column") - expect_error(ht_mean(s, "site"), "numeric") + s$when <- as.Date("2024-01-01") + seq_len(nrow(s)) + expect_error(ht_mean(s, "when"), "numeric") expect_error(ht_mean(s, "y", level = 1), "between 0 and 1") na_y <- s @@ -102,7 +118,7 @@ test_that("ht_mean refuses samples it cannot estimate from", { }) test_that("deff falls below 1 when stratification helps and rises when it hurts", { - set.seed(88) + local_seed(88) N <- 400 d <- data.frame( id = 1:N, @@ -127,7 +143,12 @@ test_that("deff is available from both estimators and NA without a variance", { expect_true(is.finite(deff(ht_total(s, "y")))) expect_true(is.finite(deff(ht_mean(s, "y")))) expect_true(is.na(deff(ht_mean(s, "y", variance = "none")))) - expect_error(deff(1:10), "ht_total") + # Anything else goes to survey's deff(), which has no design effect for it. + skip_if_not_installed("survey") + expect_warning(expect_null(deff(1:10)), "no design effect") + # The warning's call names the object rather than printing it. + w <- tryCatch(deff(c(a = 1.5, b = 2)), warning = function(w) w) + expect_identical(conditionCall(w)[[2]], quote(object)) }) test_that("the jackknife deletes clusters, not rows", { @@ -176,7 +197,7 @@ test_that("deff is exactly 1 for a simple random sample", { # The reference variance divided an n-term sum by N - 1, leaving it short by # n(N-1)/(N(n-1)) -- so deff came out at 1 + 1/n and a plain SRS of 10 # printed as "worse than simple random sampling". - set.seed(31) + local_seed(31) pop <- data.frame(y = stats::rnorm(5000, 100, 20)) for (n in c(10, 20, 50, 200)) { got <- vapply(1:200, function(i) { @@ -189,7 +210,7 @@ test_that("deff is exactly 1 for a simple random sample", { }) test_that("deff is NA rather than negative when there is no variance", { - set.seed(5) + local_seed(5) pop <- data.frame(y = stats::rnorm(60, 10, 3), cl = rep(1:6, each = 10)) r <- ht_total(draw(pop, design_cluster("cl", n_clusters = 1), seed = 1, weights = TRUE), "y") @@ -198,12 +219,1251 @@ test_that("deff is NA rather than negative when there is no variance", { "total"))) }) -test_that("an empty sample is refused with a reason, not a crash", { - # A start past the end of a short frame selects nothing +test_that("an empty sample gives a total of 0 and no Hajek mean, not a crash", { + # A start past the end of a short frame selects nothing. The total of that + # draw is 0, which keeps the estimator unbiased; the Hajek mean is 0 / 0. d <- data.frame(y = 1:10) s <- suppressWarnings(draw(d, design_systematic(interval = 20), seed = 2, weights = TRUE)) expect_equal(nrow(s), 0L) expect_error(ht_mean(s, "y"), "no rows") - expect_error(ht_total(s, "y"), "no rows") + r <- ht_total(s, "y") + expect_equal(r$total, 0) + expect_true(is.na(r$se)) + expect_match(r$note, "The sample is empty") +}) + +# ---- a sample's rows are matched to the frame through `.row` ---------------- + +reorder_designs <- function() { + list( + stratified = design_stratified("site", n = 30), + systematic = design_systematic(interval = 10), + certainty = design_certainty("w", 440, design_stratified("site", n = 20)) + ) +} + +estimate_summary <- function(s) { + t <- ht_total(s, "y") + m <- ht_mean(s, "y") + b <- ht_total(s, "y", by = "site") + list(total = t$total, se = t$se, df = t$df, deff = t$deff, method = t$method, + mean_se = m$se, by_se = b$se[order(b$site)]) +} + +test_that("reordering a weighted sample leaves every estimate unchanged", { + # The design's rows were recovered by position, so sorting a sample moved + # each row onto another row's stratum, cluster or systematic position: + # a stratified standard error fell from 3014 to 1332 on a sort by `y`. + d <- est_pop() + for (des in reorder_designs()) { + s <- draw(d, des, seed = 3, weights = TRUE) + want <- estimate_summary(s) + expect_equal(estimate_summary(s[order(s$y), ]), want) + expect_equal(estimate_summary(s[rev(seq_len(nrow(s))), ]), want) + } +}) + +test_that("an in-place data.table sort of a sample changes nothing", { + skip_if_not_installed("data.table") + d <- est_pop() + for (des in reorder_designs()) { + for (s in list(draw(d, des, seed = 3, weights = TRUE), + draw(data.table::as.data.table(d), des, seed = 3, + weights = TRUE))) { + want <- estimate_summary(s) + drawn_order <- attr(s, "drawn_rows") + data.table::setorderv(s, "y") + expect_false(is.unsorted(s$y)) + expect_identical(attr(s, "drawn_rows"), drawn_order) + expect_equal(estimate_summary(s), want) + } + } +}) + +test_that("an in-place data.table edit of the frame does not reach the sample", { + # The sample held the caller's frame by reference: setkey() on it after + # drawing doubled a cluster design's standard error. + skip_if_not_installed("data.table") + dt <- data.table::as.data.table(est_pop()) + for (des in list(design_cluster("cl", n_clusters = 6), + design_certainty("w", 440, design_simple(n = 20)))) { + s <- draw(dt, des, seed = 3, weights = TRUE) + want <- estimate_summary(s) + data.table::setkeyv(dt, "w") + data.table::set(dt, j = "site", value = "z") + expect_equal(estimate_summary(s), want) + data.table::setorderv(dt, "id") + } +}) + +test_that("a subset, a bound or a merged sample is refused, not misread", { + d <- est_pop() + s <- draw(d, design_stratified("site", n = 30), seed = 3, weights = TRUE) + expect_error(ht_total(head(s), "y"), "`sample` has 6 of the 30 rows", + fixed = TRUE) + expect_error(ht_total(s[s$site == "a", ], "y"), "use `by` for groups", + fixed = TRUE) + expect_error(ht_mean(rbind(s, s), "y"), "more than once") + other <- draw(d, design_stratified("site", n = 30), seed = 4, weights = TRUE) + other <- other[!other$.row %in% s$.row, ] + expect_error(ht_total(rbind(s, other), "y"), "that were not in the sample") + + merged <- merge(s, data.frame(id = s$id, resp = 1), by = "id") + expect_error(ht_total(merged, "y"), "does not carry its design") + expect_error(ht_total(merged, "y"), "merge()", fixed = TRUE) + expect_error(ht_total(s[, c("y", "site")], "y"), "column selection") +}) + +test_that("a damaged `.row` column is refused", { + d <- est_pop() + s <- draw(d, design_simple(n = 20), seed = 3, weights = TRUE) + gone <- s + gone$.row <- NULL + expect_error(ht_total(gone, "y"), "has no `.row` column", fixed = TRUE) + far <- s + far$.row[1] <- 1000L + expect_error(ht_total(far, "y"), "not rows of the 300-row frame") + gap <- s + gap$.row[2] <- NA + expect_error(ht_total(gap, "y"), "frame it was drawn from: NA.", + fixed = TRUE) + gap$.row[5] <- 1000L + expect_error(ht_mean(gap, "y"), "frame it was drawn from: 1000, NA.", + fixed = TRUE) + half <- s + half$.row <- half$.row + 0.5 + expect_error(ht_total(half, "y"), "not rows of the 300-row frame") + chr <- s + chr$.row <- as.character(chr$.row) + expect_error(ht_total(chr, "y"), "character `.row` column", fixed = TRUE) +}) + +test_that("a sample saved by drawn 0.2.0 still estimates, by position", { + d <- est_pop() + s <- draw(d, design_stratified("site", n = 30), seed = 3, weights = TRUE) + old <- s + old$.row <- NULL + attr(old, "drawn_pi") <- NULL + expect_equal(ht_total(old, "y")$se, ht_total(s, "y")$se) + expect_error(ht_total(old[1:10, ], "y"), "has 10 rows but was drawn with 30") +}) + +test_that("a sample saved by drawn 0.2.0 and put in another order is refused", { + # Such a sample is matched to its frame rows by position. Every row of a + # proportional stratified or systematic sample has the same `.prob`, so a + # sort leaves `.prob` as the design gives it and moves `y` onto other rows' + # strata or places in the walk. + d <- est_pop() + as_legacy <- function(s) { + s$.row <- NULL + attr(s, "drawn_pi") <- NULL + s + } + sorted <- list() + for (des in list(design_stratified("site", n = 30), + design_systematic(interval = 10))) { + s <- draw(d, des, seed = 3, weights = TRUE) + old <- as_legacy(s) + r <- old[order(old$y), ] + expect_error(ht_total(r, "y"), paste0( + "`sample` has its rows in another order than draw() returned them: ", + "its `id` column"), fixed = TRUE) + expect_error(ht_mean(r, "y"), "by = \"id\")", fixed = TRUE) + expect_error(sample_summary(r), "matched to its frame rows by position", + fixed = TRUE) + back <- as_drawn(r, attr(r, "drawn_design"), attr(r, "drawn_population"), + by = "id") + expect_equal(ht_total(back, "y")$se, ht_total(s, "y")$se) + sorted <- c(sorted, list(r)) + } + + # A frame column changed after the draw is not taken for a reorder. + s <- draw(d, design_stratified("site", n = 30), seed = 3, weights = TRUE) + edited <- as_legacy(s) + edited$y <- edited$y * 2 + edited$site <- toupper(edited$site) + expect_equal(ht_total(edited, "y")$se, 2 * ht_total(s, "y")$se) + + # Nor is a correction that swaps two values between rows, while `id` still + # matches the drawn rows in order. + i <- c(match("a", s$site), match("c", s$site)) + swapped <- as_legacy(s) + swapped$site[i] <- swapped$site[rev(i)] + swapped$y[i] <- swapped$y[rev(i)] + fixed <- s + fixed$y[i] <- fixed$y[rev(i)] + expect_equal(ht_total(swapped, "y")$se, ht_total(fixed, "y")$se) + expect_false(isTRUE(all.equal(ht_total(fixed, "y")$se, + ht_total(s, "y")$se))) + + skip_if_not_installed("survey") + for (r in sorted) { + expect_error(as_svydesign(r), "in another order", fixed = TRUE) + } +}) + +test_that("a design saved by drawn 0.2.0 draws as it did", { + # A systematic design then had no `n` field, and `design$n` matched its + # `na_rm` by partial name, so the design drew no rows. + d <- est_pop() + des <- design_systematic(interval = 10, order_by = "w") + old <- structure(unclass(des)[c("interval", "start", "order_by", "na_rm")], + class = class(des)) + expect_identical(draw(d, old, seed = 2), draw(d, des, seed = 2)) + local_seed(2) + direct <- draw_design(old, d) + local_seed(2) + expect_identical(direct, draw_design(des, d)) + expect_identical(draw(d, old, seed = 2, weights = TRUE)$.row, + draw(d, des, seed = 2, weights = TRUE)$.row) + expect_equal(inclusion_prob(d, old), rep(0.1, nrow(d))) + expect_equal(joint_prob(d, old, rows = 1:3), joint_prob(d, des, rows = 1:3)) + cert <- design_certainty("w", 450, old) + expect_identical(draw(d, cert, seed = 2), + draw(d, design_certainty("w", 450, des), seed = 2)) + s <- draw(d, des, seed = 2, weights = TRUE) + back <- as_drawn(s[, c("id", "y")], old, d, by = "id") + expect_equal(ht_total(back, "y")$se, ht_total(s, "y")$se) +}) + +test_that("a sample saved by drawn 0.2.0 has its design brought up to date", { + # A systematic design saved then has no `n` field, and `design$n` matched + # its `na_rm` by partial name, so the design read as `n = FALSE`. + d <- est_pop() + s <- draw(d, design_systematic(interval = 10, order_by = "w"), seed = 2, + weights = TRUE) + old <- s + old$.row <- NULL + attr(old, "drawn_pi") <- NULL + des <- attr(s, "drawn_design") + attr(old, "drawn_design") <- structure( + unclass(des)[c("interval", "start", "order_by", "na_rm")], + class = class(des)) + want <- ht_total(s, "y") + got <- ht_total(old, "y") + expect_equal(got$se, want$se) + expect_equal(got$df, want$df) + expect_equal(sample_summary(old)$N_reachable, nrow(d)) +}) + +test_that("a `.prob` changed or removed after the draw is refused", { + d <- est_pop() + s <- draw(d, design_simple(n = 20), seed = 3, weights = TRUE) + + gone <- s + gone$.prob <- NULL + expect_error(ht_total(gone, "y"), "has no `.prob` column", fixed = TRUE) + missing_p <- s + missing_p$.prob[1] <- NA + expect_error(ht_total(missing_p, "y"), + "not probabilities in (0, 1] in 1 row(s): NA", fixed = TRUE) + zero <- s + zero$.prob[2] <- 0 + expect_error(ht_mean(zero, "y"), "in 1 row(s): 0.", fixed = TRUE) + many <- s + many$.prob[1:7] <- -(1:7) + expect_error(ht_total(many, "y"), + "in 7 row(s): -1, -2, -3, -4, -5 and 2 more. `.prob` was", + fixed = TRUE) + chr <- s + chr$.prob <- as.character(chr$.prob) + expect_error(ht_total(chr, "y"), "character `.prob` column", fixed = TRUE) + + # Within (0, 1], but not what was drawn: the total would move while the + # variance still followed the design. + edited <- s + edited$.prob[1:3] <- edited$.prob[1:3] * 1.1 + expect_error(ht_total(edited, "y"), "in 3 row(s) that differ", fixed = TRUE) + expect_error(ht_mean(edited, "y"), "estimate from them with as_svydesign()", + fixed = TRUE) + expect_error(sample_summary(edited), "`.prob` was changed after draw()", + fixed = TRUE) + + # A sample saved by drawn 0.2.0 records no probabilities for the frame, so + # its `.prob` must be a probability and the one the design gives its row. + old <- s + old$.row <- NULL + attr(old, "drawn_pi") <- NULL + old$.prob[1] <- NA + expect_error(ht_total(old, "y"), "in 1 row(s): NA", fixed = TRUE) + expect_error(sample_summary(old), "in 1 row(s): NA", fixed = TRUE) + old$.prob <- NULL + expect_error(sample_summary(old), "has no `.prob` column", fixed = TRUE) + old <- edited + old$.row <- NULL + attr(old, "drawn_pi") <- NULL + expect_error(ht_total(old, "y"), paste0( + "gives 3 of its 20 rows a different inclusion probability in this ", + "session or this version of drawn than its `.prob` column records"), + fixed = TRUE) + expect_error(ht_mean(old, "y"), "`.prob` changed after draw()", + fixed = TRUE) + expect_error(sample_summary(old), "matched to its frame rows by position", + fixed = TRUE) + skip_if_not_installed("survey") + expect_error(as_svydesign(old), "than its `.prob` column records", + fixed = TRUE) +}) + +test_that("a `y` that is not finite is refused with a count", { + d <- est_pop() + s <- draw(d, design_simple(n = 20), seed = 3, weights = TRUE) + s$y[c(2, 5)] <- c(Inf, NaN) + expect_error(ht_total(s, "y"), + "`y` is Inf or NaN in 2 row(s) of `sample`: 2, 5.", fixed = TRUE) + expect_error(ht_mean(s, "y", by = "site"), "finite `y`") + s$y[c(2, 5)] <- c(-Inf, 1) + expect_error(ht_mean(s, "y"), "`y` is -Inf in 1 row(s)", fixed = TRUE) +}) + +test_that("an edited `.weight` warns, and the estimate keeps to `.prob`", { + d <- est_pop() + s <- draw(d, design_stratified("site", n = 30), seed = 1, weights = TRUE) + want <- ht_total(s, "y") + w <- s + w$.weight <- w$.weight * 1.1 + expect_warning(got <- ht_total(w, "y"), class = "drawn_weight_edited") + expect_equal(got$total, want$total) + expect_equal(got$se, want$se) + expect_warning(ht_mean(w, "y"), "differ from 1 / `.prob` in 30 row(s)", + fixed = TRUE) + expect_warning(ht_total(w, "y", by = "site"), class = "drawn_weight_edited") + expect_warning(ht_total(w, "y"), class = "drawn_warning") + expect_no_warning(ht_total(s, "y")) +}) + +test_that("a design that gives the frame other probabilities now is refused", { + # Editing the stored probabilities of rows that were not drawn stands in for + # a sample drawn by another version of drawn, or in a session whose settings + # change what the design computes. + d <- est_pop() + s <- draw(d, design_simple(n = 20), seed = 3, weights = TRUE) + p <- attr(s, "drawn_pi") + p[setdiff(seq_len(nrow(d)), s$.row)[1:2]] <- 0.5 + attr(s, "drawn_pi") <- p + expect_error(ht_total(s, "y"), paste0( + "gives 2 of its 300 frame rows a different inclusion probability in this ", + "session or this version of drawn"), fixed = TRUE) + expect_error(ht_mean(s, "y"), "draw the sample again") +}) + +test_that("dplyr groups are reported, not silently ignored", { + d <- est_pop() + s <- draw(d, design_stratified("site", n = 30), seed = 1, weights = TRUE) + # The class and `groups` attribute dplyr::group_by() gives, without dplyr. + g <- s + groups <- data.frame(site = c("a", "b", "c")) + groups$.rows <- unname(split(seq_len(nrow(s)), s$site)) + attr(g, "groups") <- groups + class(g) <- c("grouped_df", "data.frame") + expect_warning(m <- ht_mean(g, "y"), "Use `by = \"site\"`", fixed = TRUE) + expect_equal(m$mean, ht_mean(s, "y")$mean) + expect_warning(ht_total(g, "y"), class = "drawn_grouped_df") + expect_no_warning(ht_total(g, "y", by = "site")) +}) + +# ---- proportions, one-sided bounds, design effects and reachable rows ------- + +test_that("whether y is a proportion is read from the frame, not the sample", { + # The frame's column holds 3s as well, so this is the mean of a count. A + # logit interval, which cannot pass 1, would never cover a mean above 1. + pop <- data.frame(id = 1:100, kids = c(rep(0, 60), rep(1, 36), rep(3, 4))) + pop$any <- as.numeric(pop$kids > 0) + s <- draw(pop, design_simple(n = 10), seed = 1, weights = TRUE) + expect_true(all(s$kids %in% 0:1)) + expect_equal(ht_mean(s, "kids")$ci_scale, "linear") + expect_equal(ht_mean(s, "kids", proportion = TRUE)$ci_scale, "logit") + + # A frame column of 0s and 1s, and a logical vector, are proportions + expect_equal(ht_mean(s, "any")$ci_scale, "logit") + expect_equal(ht_mean(s, s$kids > 0)$ci_scale, "logit") + expect_equal(ht_mean(s, "any", proportion = FALSE)$ci_scale, "linear") + + # A 0/1 column added after the draw, or a numeric vector, has no frame + # column to read, so its sampled values decide and the note says so + s$found <- as.numeric(s$kids > 0) + expect_equal(ht_mean(s, "found")$ci_scale, "logit") + expect_equal(ht_mean(s, s$found)$ci_scale, "logit") + expect_equal(ht_mean(s, "found")$ci, ht_mean(s, "any")$ci) + expect_equal(ht_mean(s, "found", proportion = TRUE)$ci, + ht_mean(s, "any")$ci) + expect_equal(ht_mean(s, "found", proportion = FALSE)$ci_scale, "linear") + # A single number stands for a constant, not a proportion + expect_equal(ht_mean(s, 1)$ci_scale, "linear") + + expect_error(ht_mean(s, "kids", proportion = NA), + "`proportion` must be NULL, TRUE or FALSE, not NA.", + fixed = TRUE) + s$kids[1] <- 3 + expect_error(ht_mean(s, "kids", proportion = TRUE), + "needs `y` to be 0 or 1 in every sampled row") + expect_error(ht_mean(s, "kids", ci_method = "beta"), + "Pass `proportion = TRUE`") + expect_error(ht_mean(s, "any", ci_method = "exact"), + "`ci_method` must be one of \"logit\" or \"beta\"") +}) + +test_that("a 0/1 column recorded in fieldwork keeps its logit interval", { + # Deviations found in 2 of 60 sampled rows, recorded after the draw. With + # no frame column to read, the sampled values decide, as they always did, + # and the note says so. The symmetric interval ran below 0 and put the + # upper bound at 0.078 against 0.120. + pop <- data.frame(id = 1:600) + s <- draw(pop, design_simple(n = 60), seed = 1, weights = TRUE) + s$dev <- as.numeric(seq_len(60) %in% c(5, 40)) + r <- ht_mean(s, "dev") + expect_equal(r$ci_scale, "logit") + half <- stats::qt(0.975, 59) * r$se / (r$mean * (1 - r$mean)) + expect_equal(r$ci, stats::plogis(stats::qlogis(r$mean) + c(-1, 1) * half)) + expect_equal(round(r$ci, 4), c(0.0086, 0.1202)) + expect_match(r$note, "`dev` is not a column of the frame, so it was taken", + fixed = TRUE) + expect_output(print(r), "taken for a proportion") + expect_match(ht_mean(s, s$dev)$note, "`y` is not a column of the frame", + fixed = TRUE) + s$half <- rep(c("a", "b"), 30) + by_half <- ht_mean(s, "dev", by = "half") + expect_equal(attr(by_half, "ci_scale"), "logit") + expect_match(attr(by_half, "notes"), "`dev` is not a column of the frame", + fixed = TRUE, all = FALSE) + + # proportion = FALSE gives the symmetric interval, with no note + lin <- ht_mean(s, "dev", proportion = FALSE) + expect_equal(lin$ci_scale, "linear") + expect_lt(lin$ci[1], 0) + expect_null(lin$note) + # proportion = TRUE settles it, so there is nothing to note + expect_null(ht_mean(s, "dev", proportion = TRUE)$note) + + # A fieldwork column of zeros gets the beta interval + s$none <- 0 + z <- ht_mean(s, "none") + expect_equal(z$ci, c(0, 1 - 0.025^(1 / 60))) + expect_match(z$note, "not a column of the frame") +}) + +test_that("a proportion of 0 or 1 gets a beta interval and a note", { + # No deviations in 60 sampled invoices: the variance is 0, and a logit + # interval would be [0, 0]. Clopper-Pearson over 60 rows gives the bounds. + pop <- data.frame(id = 1:240, deviation = FALSE) + s <- draw(pop, design_simple(n = 60), seed = 1, weights = TRUE) + r <- ht_mean(s, "deviation") + expect_equal(r$mean, 0) + expect_equal(r$ci_scale, "beta") + expect_equal(r$ci, c(0, 1 - 0.025^(1 / 60))) + expect_match(r$note, "beta interval, with the 60 sampled rows") + expect_output(print(r), "beta, t, 59 df") + expect_output(print(r), "would have no width") + + up <- ht_mean(s, "deviation", alternative = "less") + expect_equal(up$ci, c(0, 1 - 0.05^(1 / 60))) + expect_equal(round(up$ci[2], 4), 0.0487) + expect_output(print(up), "95% upper bound 0.0487") + + s$deviation <- TRUE + expect_equal(ht_mean(s, "deviation")$ci, c(0.025^(1 / 60), 1)) + + # Rows taken with certainty carry no sampling error and are not counted + pop$w <- c(rep(1000, 10), rep(1, 230)) + cs <- draw(pop, design_certainty("w", 1000, design_simple(n = 20)), + seed = 1, weights = TRUE) + rc <- ht_mean(cs, "deviation") + expect_equal(rc$ci, c(0, 1 - 0.025^(1 / 20))) + expect_match(rc$note, "20 sampled rows below certainty") + + # A census of zeros is exact + cen <- draw(pop[1:20, ], design_simple(n = 20), seed = 1, weights = TRUE) + expect_equal(ht_mean(cen, "deviation")$ci, c(0, 0)) +}) + +test_that("a proportion of 0 at 0 degrees of freedom gets Clopper-Pearson", { + # A Poisson sample of one row leaves 0 degrees of freedom. The beta + # interval at an estimate of 0 needs no variance, but it was dropped, and + # the note said both that there was no interval and that it was a beta one. + pop <- data.frame(id = 1:50, w = 1:50, flag = FALSE) + s <- draw(pop, design_weighted("w", n = 1, method = "poisson"), seed = 2, + weights = TRUE) + expect_equal(nrow(s), 1L) + r <- ht_mean(s, "flag", estimator = "ht") + expect_equal(r$df, 0) + expect_equal(r$ci_scale, "beta") + expect_equal(r$ci, c(0, 0.975)) + expect_match(r$note, "beta interval, with the 1 sampled row") + expect_false(grepl("no t interval", r$note)) +}) + +test_that("one-sided bounds are the ends of a two-sided interval", { + pop <- data.frame(id = 1:200, site = rep(c("a", "b"), each = 100), + y = 20 + (1:200 * 37) %% 101) + pop$flag <- pop$y > 60 + s <- draw(pop, design_stratified("site", n = 40), seed = 1, weights = TRUE) + two <- ht_total(s, "y", level = 0.90) + up <- ht_total(s, "y", alternative = "less") + lo <- ht_total(s, "y", alternative = "greater") + expect_equal(up$ci, c(-Inf, two$ci[2])) + expect_equal(lo$ci, c(two$ci[1], Inf)) + expect_equal(up$alternative, "less") + expect_output(print(up), "95% upper bound ") + expect_output(print(lo), "95% lower bound ") + + # A proportion's bound has 0 or 1 at its open end, on either scale + m2 <- ht_mean(s, "flag", level = 0.90) + expect_equal(ht_mean(s, "flag", alternative = "less")$ci, c(0, m2$ci[2])) + b2 <- ht_mean(s, "flag", level = 0.90, ci_method = "beta") + expect_equal(ht_mean(s, "flag", alternative = "greater", + ci_method = "beta")$ci, c(b2$ci[1], 1)) + + expect_error(ht_total(s, "y", alternative = "up"), + "`alternative` must be one of") + expect_error(ht_mean(s, "y", alternative = 1), + "`alternative` must be one of") +}) + +test_that("a constant y has a variance of exactly 0 and no design effect", { + # Unequal weights left the residuals a rounding error from 0, which gave a + # standard error near 1e-16 and design effects from noise. + pop <- data.frame(id = 1:240, w = 1 + (1:240 * 7) %% 19) + s <- draw(pop, design_weighted("w", n = 30, method = "poisson"), seed = 8, + weights = TRUE) + s$k <- 5 + m <- ht_mean(s, "k") + expect_identical(m$mean, 5) + expect_identical(m$variance, 0) + expect_equal(m$ci, c(5, 5)) + expect_true(is.na(m$deff)) + expect_match(m$note, "`y` is 5 in every sampled row") + expect_output(print(m), "5 in every sampled row") + tot <- ht_total(s, "k") + expect_true(tot$se > 0) + expect_true(is.na(tot$deff)) + + # Data with a large offset is not constant, and keeps its design effect + s$big <- 1e6 + (seq_len(nrow(s)) %% 3) / 2 + expect_true(is.finite(ht_mean(s, "big")$deff)) + expect_true(is.finite(ht_total(s, "big")$deff)) +}) + +test_that("deff is measured against the rows the design can reach", { + # An equal-probability sample of 20 from the first 100 of 400 rows. Against + # all 400 rows the total's design effect came out 0.05. + pop <- data.frame(y = 50 + (1:400 * 37) %% 23) + expect_warning( + s <- draw(pop, design_reservoir(n = 20, max_items = 100), seed = 1, + weights = TRUE), + "max_items") + expect_equal(deff(ht_total(s, "y")), 1) + expect_equal(deff(ht_mean(s, "y")), 1) + # The Horvitz-Thompson mean is the total over all 400 rows + expect_equal(deff(ht_mean(s, "y", estimator = "ht")), + deff(ht_total(s, "y"))) +}) + +test_that("an estimate says how many frame rows it cannot cover", { + skew <- data.frame(id = 1:1000, g = rep(c("big", "rare"), c(990, 10)), + y = rep(c(1, 1000), c(990, 10))) + expect_warning( + s <- draw(skew, design_stratified("g", n = 20), seed = 1, weights = TRUE), + class = "drawn_empty_stratum") + r <- ht_total(s, "y") + expect_equal(r$unreachable, 10) + expect_output(print(r), "unreachable 10 frame rows at probability 0") + expect_output(print(ht_total(s, "y", variance = "none")), "unreachable 10") + expect_equal(ht_mean(s, "y")$unreachable, 10) + + all_rows <- draw(skew, design_simple(n = 20), seed = 1, weights = TRUE) + expect_equal(ht_total(all_rows, "y")$unreachable, 0) + out <- capture.output(print(ht_total(all_rows, "y"))) + expect_false(any(grepl("unreachable", out))) +}) + +# ---- the estimate as numbers ------------------------------------------------ + +methods_pop <- function() { + id <- 1:300 + w <- 1 + (id * 13) %% 50 + w[c(5, 160, 260)] <- 500 + data.frame(id = id, site = rep(c("a", "b", "c"), times = c(150, 100, 50)), + y = 20 + (id * 37) %% 101, hit = (id * 7) %% 5 == 0, + none = FALSE, w = w) +} + +test_that("an estimate gives coef(), vcov(), confint() and a data frame", { + s <- draw(methods_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + r <- ht_total(s, "y") + expect_equal(r$variable, "y") + expect_equal(coef(r), c(y = r$total)) + expect_equal(vcov(r), matrix(r$variance, 1, 1, dimnames = list("y", "y"))) + ci <- confint(r) + expect_equal(unname(ci[1, ]), r$ci) + expect_equal(colnames(ci), c("2.5 %", "97.5 %")) + expect_equal(confint(r, "y"), ci) + expect_equal(confint(r, 1), ci) + expect_error(confint(r, level = 95), "strictly between 0 and 1") + + df <- as.data.frame(r) + expect_equal(names(df), c("variable", "n", "total", "variance", "se", + "ci_lower", "ci_upper", "level", "df", "deff", + "method")) + expect_equal(unlist(df[c("total", "se", "ci_lower", "ci_upper", "df")]), + c(total = r$total, se = r$se, ci_lower = r$ci[1], + ci_upper = r$ci[2], df = r$df)) + + # A vector `y` has no name, and the row says so. + m <- ht_mean(s, s$y) + expect_true("variable" %in% names(m)) + expect_null(m$variable) + expect_equal(names(coef(m)), "mean") + both <- rbind(as.data.frame(ht_mean(s, "y")), as.data.frame(m)) + expect_equal(both$variable, c("y", NA)) + expect_equal(both$mean, c(m$mean, m$mean)) +}) + +test_that("confint() at another level is the estimate made at that level", { + pop <- methods_pop() + s <- draw(pop, design_stratified("site", n = 60), seed = 1, weights = TRUE) + same <- function(fit) { + expect_equal(unname(confint(fit(0.95), level = 0.8)[1, ]), fit(0.8)$ci) + } + same(function(l) ht_total(s, "y", level = l)) + same(function(l) ht_total(s, "y", level = l, alternative = "less")) + same(function(l) ht_mean(s, "y", level = l, estimator = "ht")) + # Proportions keep their scale: logit, beta, and beta at an estimate of 0. + same(function(l) ht_mean(s, "hit", level = l)) + same(function(l) ht_mean(s, "hit", level = l, ci_method = "beta")) + same(function(l) ht_mean(s, "none", level = l, alternative = "less")) + expect_equal(colnames(confint(ht_total(s, "y", alternative = "less"), + level = 0.9)), c("0 %", "90 %")) + + # The beta interval's sample size leaves out the rows taken with certainty. + cs <- draw(pop, design_certainty("w", 500, design_simple(n = 40)), seed = 2, + weights = TRUE) + b <- ht_mean(cs, "hit", ci_method = "beta") + expect_equal(b$n_random, 40L) + expect_equal(b$n, 43L) + same(function(l) ht_mean(cs, "hit", level = l, ci_method = "beta")) +}) + +test_that("survey's SE() and cv() read an estimate", { + skip_if_not_installed("survey") + s <- draw(methods_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + r <- ht_total(s, "y") + expect_equal(survey::SE(r), c(y = r$se)) + expect_equal(survey::cv(r), c(y = r$se / r$total)) + m <- ht_mean(s, "y") + expect_equal(survey::SE(m), c(y = m$se)) +}) + +test_that("tidy() gives an estimate in broom's columns", { + skip_if_not_installed("generics") + s <- draw(methods_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + r <- ht_total(s, "y") + t <- generics::tidy(r) + expect_equal(t, data.frame(term = "y", estimate = r$total, + std.error = r$se)) + t <- generics::tidy(r, conf.int = TRUE) + expect_equal(c(t$conf.low, t$conf.high), r$ci) + t <- generics::tidy(ht_mean(s, "hit"), conf.int = TRUE, conf.level = 0.8) + expect_equal(c(t$conf.low, t$conf.high), ht_mean(s, "hit", level = 0.8)$ci) +}) + +test_that("deff() answers for survey's objects, and survey's deff() for these", { + skip_if_not_installed("survey") + s <- draw(methods_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + des <- as_svydesign(s) + # drawn attached after survey: this package's deff() is found first and + # hands survey's objects to survey. + m <- survey::svymean(~y, des, deff = TRUE) + expect_equal(deff(m), survey::deff(m)) + by_site <- survey::svyby(~y, ~site, des, survey::svytotal, deff = TRUE) + expect_equal(deff(by_site), survey::deff(by_site)) + expect_equal(deff(m, quietly = TRUE), survey::deff(m, quietly = TRUE)) + # survey attached after drawn: survey's deff() is found first and finds the + # methods for the estimates made here. + r <- ht_total(s, "y") + expect_equal(survey::deff(r), r$deff) + expect_equal(survey::deff(ht_mean(s, "y")), ht_mean(s, "y")$deff) + expect_true(is.na(survey::deff(ht_total(s, "y", by = "site", + contrast = c(a = 1, b = -1))))) + expect_error(survey::deff(ht_total(s, "y", by = "site")), + "no design effect") +}) + +test_that("a printed estimate and a by table name the method alike", { + d <- data.frame(id = 1:200, g = rep(c("a", "b"), 100), + y = 20 + (1:200 * 37) %% 101) + s <- draw(d, design_systematic(interval = 8), seed = 1, weights = TRUE) + r <- ht_total(s, "y") + b <- ht_total(s, "y", by = "g") + expect_equal(r$method, "successive difference") + expect_equal(unique(b$method), r$method) + expect_output(print(r), "(successive difference, an approximation)", + fixed = TRUE) + expect_output(print(b), "successive difference") + srs <- draw(d, design_simple(n = 20), seed = 1, weights = TRUE) + expect_output(print(ht_total(srs, "y")), "(analytic)", fixed = TRUE) +}) + +test_that("ht_total() refuses a missing y and says why a respondent total is low", { + d <- est_pop() + s <- draw(d, design_stratified("site", n = 40), seed = 1, weights = TRUE) + s$y[c(2, 7, 25)] <- NA + msg <- tryCatch(ht_total(s, "y"), error = conditionMessage) + expect_match(msg, "`y` is missing in 3 of the 40 sampled rows", fixed = TRUE) + share <- sum(s$.weight[is.na(s$y)]) / sum(s$.weight) + expect_match(msg, paste0(format(signif(100 * share, 2)), "% here"), + fixed = TRUE) + expect_match(msg, "ht_mean(na_rm = TRUE)", fixed = TRUE) + expect_match(msg, "as_svydesign()", fixed = TRUE) + expect_error(ht_mean(s, "y"), "Set `na_rm = TRUE`") + expect_error(ht_mean(s, "y", na_rm = NA), "`na_rm` must be TRUE or FALSE") +}) + +test_that("ht_mean(na_rm = TRUE) is the mean over the rows with y present", { + d <- est_pop() + for (des in list(design_stratified("site", n = 40), + design_cluster("cl", n_clusters = 6))) { + s <- draw(d, des, seed = 1, weights = TRUE) + s$y[c(2, 7, 25)] <- NA + m <- ht_mean(s, "y", na_rm = TRUE) + r <- !is.na(s$y) + expect_equal(m$mean, sum(s$y[r] * s$.weight[r]) / sum(s$.weight[r])) + expect_identical(m$n, sum(r)) + expect_identical(m$n_missing, 3L) + expect_true(is.na(m$deff)) + expect_match(m$note, "missing completely at random") + expect_output(print(m), "3 sampled rows left out") + # The same as the domain of the rows with y present + s0 <- s + s0$y0 <- ifelse(r, s$y, 0) + s0$r <- r + dom <- ht_mean(s0, "y0", by = "r") + expect_equal(m$se, dom$se[dom$r]) + skip_if_not_installed("survey") + sv <- survey::svymean(~y, as_svydesign(s), na.rm = TRUE) + expect_equal(m$mean, unname(coef(sv))) + expect_equal(m$se, as.numeric(survey::SE(sv))) + by <- ht_mean(s, "y", by = "site", na_rm = TRUE) + sb <- survey::svyby(~y, ~site, as_svydesign(s), survey::svymean, + na.rm = TRUE) + expect_equal(by$se, unname(sb$se)) + expect_identical(by$n, as.integer(tapply(r, s$site, sum))) + } +}) + +test_that("ht_mean(na_rm = TRUE) changes nothing when no y is missing", { + d <- est_pop() + s <- draw(d, design_stratified("site", n = 40), seed = 1, weights = TRUE) + expect_identical(ht_mean(s, "y", na_rm = TRUE), ht_mean(s, "y")) + expect_identical(ht_mean(s, "y", by = "site", na_rm = TRUE), + ht_mean(s, "y", by = "site")) + expect_identical(ht_mean(s, "y")$n_missing, 0L) +}) + +test_that("ht_mean(na_rm = TRUE) refuses what it cannot estimate", { + d <- est_pop() + s <- draw(d, design_simple(n = 20), seed = 1, weights = TRUE) + s$y[1] <- NA + expect_error(ht_mean(s, "y", estimator = "ht", na_rm = TRUE), + "number of frame rows the mean is over is unknown") + s$y[] <- NA + expect_error(ht_mean(s, "y", na_rm = TRUE), "missing in every one of the 20") + # One row with y present has no standard error + s$y[1] <- 5 + one <- ht_mean(s, "y", na_rm = TRUE) + expect_true(is.na(one$se)) + expect_match(one$note, "The domain of rows with `y` present has one") +}) + +test_that("ht_mean(na_rm = TRUE) says which domains have y missing throughout", { + s <- draw(est_pop(), design_stratified("site", n = 40), seed = 1, + weights = TRUE) + s$spend <- s$y + s$spend[s$site == "c"] <- NA + s$spend[1] <- NA + m <- ht_mean(s, "spend", by = "site", na_rm = TRUE) + expect_false("c" %in% m$site) + expect_match(attr(m, "notes"), + "Every sampled row of the domain `c` has `spend` missing", + all = FALSE) + expect_match(attr(m, "notes"), "rows with `spend` present", all = FALSE) + expect_error(ht_mean(s, "spend", by = "site", na_rm = TRUE, + contrast = c(a = 1, c = -1)), + "`c`, whose sampled rows all have `spend` missing") + expect_error(ht_mean(s, "spend", by = "site", na_rm = TRUE, + contrast = c(a = 1, d = -1)), + "`d`, which is not a domain") +}) + +# ---- ratios ----------------------------------------------------------------- + +ratio_pop <- function() { + id <- 1:300 + book <- 20 + (id * 37) %% 400 + data.frame(id = id, site = rep(c("a", "b", "c"), times = c(150, 100, 50)), + cl = rep(paste0("c", 1:30), each = 10), book = book, + audited = book * (0.9 + ((id * 7) %% 11) / 50)) +} + +test_that("a ratio and a ratio total match survey::svyratio()", { + skip_if_not_installed("survey") + d <- ratio_pop() + for (des in list(design_stratified("site", n = 45), + design_cluster("cl", n_clusters = 6))) { + s <- draw(d, des, seed = 3, weights = TRUE) + sv <- survey::svyratio(~audited, ~book, as_svydesign(s)) + r <- ht_ratio(s, "audited", "book") + expect_s3_class(r, "drawn_ratio") + expect_equal(r$ratio, unname(coef(sv))) + expect_equal(r$se, unname(survey::SE(sv))) + expect_equal(r$ratio, r$total_y / r$total_x) + expect_equal(r$df, ht_total(s, "audited")$df) + + t <- ht_total(s, "audited", ratio = "book") + p <- predict(sv, total = sum(d$book)) + expect_s3_class(t, "drawn_ht") + expect_equal(t$total, as.numeric(p$total)) + expect_equal(t$se, as.numeric(p$se)) + expect_equal(t$ratio, r$ratio) + expect_equal(t$frame_total, sum(d$book)) + } + # The design effect is measured as svyratio(deff = TRUE) measures it. + s <- draw(d, design_stratified("site", n = 45), seed = 3, weights = TRUE) + sv <- survey::svyratio(~audited, ~book, as_svydesign(s), deff = TRUE) + expect_equal(ht_ratio(s, "audited", "book")$deff, + as.numeric(attr(sv, "deff"))) +}) + +test_that("the ratio total uses the frame total over the rows reached", { + d <- ratio_pop() + d$book[d$site == "c"] <- NA + # Site c is outside the design, so its missing `book` plays no part. + expect_warning( + s <- draw(d, design_stratified("site", n = 40, + allocation = c(a = 25, b = 15, c = 0)), + seed = 3, weights = TRUE), + class = "drawn_empty_stratum") + t <- ht_total(s, "audited", ratio = "book") + expect_equal(t$frame_total, sum(d$book[d$site != "c"])) + expect_equal(t$frame_total, unname(frame_totals(s, ~book)["book"])) + # Close to proportional to `book`, so far more precise than the HT total. + expect_lt(t$se, ht_total(s, "audited")$se / 3) + expect_output(print(t), "Ratio estimate of the total") + expect_output(print(t), "`book` over the frame", fixed = TRUE) +}) + +test_that("ht_ratio() and ht_total(ratio =) refuse what they cannot estimate", { + d <- ratio_pop() + s <- draw(d, design_stratified("site", n = 45), seed = 3, weights = TRUE) + s$gap <- s$book + s$gap[3] <- NA + expect_error(ht_ratio(s, "audited", "gap"), "`x` is missing in 1 of the 45") + s$zero <- 0 + expect_error(ht_ratio(s, "audited", "zero"), + "The estimated total of `zero`, `sum(x / pi)` over the sampled", + fixed = TRUE) + expect_error(ht_ratio(s, "audited", "site"), + "`x` names `site`, a character column") + expect_error(ht_ratio(s, "audited", c("book", "id")), + "`x` must be one column name or a numeric vector") + expect_error(ht_total(s, "audited", ratio = "zero"), + "`ratio` names `zero`, which is not a column of the frame") + expect_error(ht_total(s, "audited", ratio = "site"), + "a character column of the frame") + expect_error(ht_total(s, "audited", ratio = c("book", "id")), + "`ratio` must be the name of one column") + expect_error(ht_total(s, "audited", ratio = "book", by = "site"), + "`ratio` gives one ratio estimator of the total") + + d$part <- d$book + d$part[7] <- NA + s <- draw(d, design_stratified("site", n = 45), seed = 3, weights = TRUE) + expect_error(ht_total(s, "audited", ratio = "part"), + "`part` is missing in 1 of the 300 frame rows") + small <- compact_sample(s) + expect_error(ht_total(small, "audited", ratio = "book"), + "compact_sample() dropped", fixed = TRUE) +}) + +test_that("a ratio over one sampling unit has no se, an exact one a note", { + d <- ratio_pop() + s <- draw(d, design_cluster("cl", n_clusters = 1), seed = 1, + weights = TRUE) + r <- ht_ratio(s, "audited", "book") + expect_true(is.na(r$se)) + expect_match(r$note, "A ratio's linearised residuals sum to zero") + expect_true(is.na(ht_total(s, "audited", ratio = "book")$se)) + + # `y` proportional to `x`: residuals of exactly 0 rather than rounding + # error, and no design effect. + s <- draw(d, design_simple(n = 30), seed = 1, weights = TRUE) + s$part <- 0.3 * s$book + r <- ht_ratio(s, "part", "book") + expect_identical(r$variance, 0) + expect_true(is.na(r$deff)) + expect_match(r$note, "`y / x` is 0.3 in every sampled row", fixed = TRUE) +}) + +test_that("a ratio has coef(), vcov(), confint(), as.data.frame() and tidy()", { + s <- draw(ratio_pop(), design_stratified("site", n = 45), seed = 3, + weights = TRUE) + r <- ht_ratio(s, "audited", "book") + expect_equal(coef(r), c("audited/book" = r$ratio)) + expect_equal(vcov(r), matrix(r$variance, 1, 1, + dimnames = list("audited/book", + "audited/book"))) + expect_equal(unname(confint(r)[1, ]), r$ci) + expect_equal(unname(confint(r, level = 0.8)[1, ]), + ht_ratio(s, "audited", "book", level = 0.8)$ci) + df <- as.data.frame(r) + expect_equal(df$x, "book") + expect_equal(df$ratio, r$ratio) + expect_equal(df$se, r$se) + expect_equal(deff(r), r$deff) + expect_output(print(r), "Ratio of Horvitz-Thompson totals") + expect_output(print(r), "`audited` / `book`", fixed = TRUE) + + # Vectors have no names. + v <- ht_ratio(s, s$audited, s$book) + expect_equal(names(coef(v)), "y/x") + expect_equal(v$se, r$se) + expect_null(v$x) + + skip_if_not_installed("generics") + expect_equal(generics::tidy(r)$term, "audited/book") + skip_if_not_installed("survey") + expect_equal(survey::deff(r), r$deff) +}) + +# ---- several variables ------------------------------------------------------ + +test_that("several y give a table whose rows are their own estimates", { + s <- draw(est_pop(), design_stratified("site", n = 40), seed = 1, + weights = TRUE) + s$hit <- s$y > 200 + b <- ht_total(s, c("y", "w")) + expect_s3_class(b, "drawn_by") + expect_equal(names(b), c("variable", "n", "total", "variance", "se", + "ci_lower", "ci_upper", "method")) + expect_equal(b$variable, c("y", "w")) + m <- ht_mean(s, c("y", "hit")) + for (i in 1:2) { + one <- ht_total(s, b$variable[i]) + expect_equal(b$total[i], one$total) + expect_equal(b$se[i], one$se) + expect_equal(c(b$ci_lower[i], b$ci_upper[i]), one$ci) + one <- ht_mean(s, m$variable[i]) + expect_equal(m$mean[i], one$mean) + expect_equal(c(m$ci_lower[i], m$ci_upper[i]), one$ci) + } + expect_equal(coef(b), c(y = b$total[1], w = b$total[2])) + V <- vcov(b) + expect_equal(dimnames(V), list(c("y", "w"), c("y", "w"))) + expect_equal(unname(diag(V)), b$variance) + expect_equal(V[1, 2], V[2, 1]) + # The proportion keeps its logit interval at another level. + expect_equal(unname(confint(m, level = 0.8)[2, ]), + ht_mean(s, "hit", level = 0.8)$ci) + expect_output(print(m), "Hajek mean by variable") + expect_output(print(m), "logit for proportions") + expect_error(deff(b), "several variables") + skip_if_not_installed("generics") + expect_equal(generics::tidy(b)$term, c("y", "w")) +}) + +test_that("the covariances of several estimates are survey's", { + skip_if_not_installed("survey") + d <- est_pop() + d$z <- (d$id * 17) %% 23 + for (des in list(design_stratified("site", n = 40), + design_cluster("cl", n_clusters = 6))) { + s <- draw(d, des, seed = 1, weights = TRUE) + svd <- as_svydesign(s) + b <- ht_total(s, c("y", "z")) + expect_equal(unname(vcov(b)), + unname(matrix(vcov(survey::svytotal(~y + z, svd)), 2))) + m <- ht_mean(s, c("y", "z")) + expect_equal(unname(vcov(m)), + unname(matrix(vcov(survey::svymean(~y + z, svd)), 2))) + } +}) + +test_that("several means with y missing are each over their own rows", { + s <- draw(est_pop(), design_stratified("site", n = 40), seed = 1, + weights = TRUE) + s$y[c(2, 7)] <- NA + m <- ht_mean(s, c("y", "w"), na_rm = TRUE) + expect_equal(m$mean, c(ht_mean(s, "y", na_rm = TRUE)$mean, + ht_mean(s, "w")$mean)) + expect_equal(m$se, c(ht_mean(s, "y", na_rm = TRUE)$se, ht_mean(s, "w")$se)) + expect_identical(m$n, c(38L, 40L)) + expect_match(attr(m, "notes"), "^`y`: 2 of the 40 sampled rows", + all = FALSE) + expect_error(ht_total(s, c("w", "y")), + "`y`, named in `y`, is missing in 2 of the 40", fixed = TRUE) + + # Each covariance is that of the two means' linearised residuals. + skip_if_not_installed("survey") + r <- !is.na(s$y) + s$za <- 0 + s$za[r] <- (s$y[r] - m$mean[1]) / sum(s$.weight[r]) + s$zb <- (s$w - m$mean[2]) / sum(s$.weight) + V <- vcov(survey::svytotal(~za + zb, as_svydesign(s))) + expect_equal(vcov(m)[1, 2], V[1, 2]) +}) + +test_that("a y that is not a column name or a numeric vector says so", { + s <- draw(est_pop(), design_simple(n = 20), seed = 1, weights = TRUE) + forms <- paste0("`y` must be one column name, several column names, or a ", + "numeric vector or factor as long as `sample`.") + expect_error(ht_total(s, letters[1:20]), forms, fixed = TRUE) + expect_error(ht_total(s, letters[1:20]), "none of them a column") + expect_error(ht_mean(s, c("y", NA)), "some of them missing or empty") + expect_error(ht_total(s, 1:3), + "an integer vector of length 3, and `sample` has 20 rows") + expect_error(ht_total(s, list(1)), forms, fixed = TRUE) + # A factor is one of the forms, so one of the wrong length says so. + expect_error(ht_mean(s, factor(c("a", "b"))), forms, fixed = TRUE) + expect_error(ht_mean(s, factor(c("a", "b"))), + "a factor vector of length 2, and `sample` has 20 rows") + expect_error(ht_mean(s, c("y", "site")), + "`y` names `site`, a character column, among several") + expect_error(ht_total(s, c("y", "y")), "`y` names `y` more than once") + expect_error(ht_total(s, c("y", "nope")), "`sample` has no column `nope`") + expect_error(ht_total(s, c("y", "w"), by = "site", + contrast = c(a = 1, b = -1)), + "`contrast` weighs the domains of one variable") +}) + +test_that("a factor y gives the share or count of each level, as survey's", { + pop <- est_pop() + pop$band <- factor(ifelse(pop$y < 150, "low", + ifelse(pop$y < 300, "mid", "high")), + levels = c("low", "mid", "high", "none")) + pop$band_chr <- as.character(pop$band) + s <- draw(pop, design_stratified("site", n = 40), seed = 1, weights = TRUE) + m <- ht_mean(s, "band") + expect_s3_class(m, "drawn_by") + expect_equal(names(m), c("level", "n", "mean", "variance", "se", + "ci_lower", "ci_upper", "method")) + expect_equal(levels(m$level), levels(pop$band)) + expect_equal(as.character(m$level), levels(pop$band)) + expect_equal(sum(m$mean), 1) + expect_equal(attr(m, "ci_scale"), "logit") + # Each row is the mean of the level's indicator. + one <- ht_mean(s, s$band == "mid") + expect_equal(m$mean[2], one$mean) + expect_equal(c(m$ci_lower[2], m$ci_upper[2]), one$ci) + # A level no sampled row has is a share of 0, with a beta interval. + expect_equal(m$mean[4], 0) + expect_gt(m$ci_upper[4], 0) + expect_equal(ht_mean(s, s$band)$mean, m$mean) + # A character column's levels are its values, sorted. + t <- ht_total(s, "band_chr") + expect_equal(t$level, c("high", "low", "mid")) + expect_equal(sum(t$total), sum(1 / s$.prob)) + expect_output(print(m), "Hajek mean of `band` by level") + expect_output(print(ht_total(s, "band", by = "site")), + "total of `band` by level and domain") + expect_error(deff(m), "levels of `y`") + expect_error(ht_mean(s, "band", by = "site", contrast = c(a = 1, b = -1)), + "Pass the indicator of one level as `y`") + s$level <- s$site + expect_error(ht_mean(s, "band", by = "level"), "uses for its own column") + + skip_if_not_installed("survey") + svd <- as_svydesign(s) + sm <- survey::svymean(~band, svd) + expect_equal(unname(coef(m)), unname(coef(sm))) + expect_equal(unname(vcov(m)), unname(matrix(vcov(sm), 4))) + st <- survey::svytotal(~band_chr, svd) + expect_equal(unname(coef(t)), unname(coef(st))) + expect_equal(unname(vcov(t)), unname(matrix(vcov(st), 3))) + # By domain, each level's share in each site. + b <- ht_mean(s, "band", by = "site") + sb <- survey::svyby(~band, ~site, svd, survey::svymean) + at <- paste0(b$site, ":band", b$level) + expect_equal(b$mean, unname(coef(sb)[at])) + # survey's standard errors come a column per level, a row per site. + expect_equal(b$se, c(as.matrix(survey::SE(sb)))) +}) + +test_that("a single number as y stands for that value in every row", { + s <- draw(est_pop(), design_weighted("w", n = 40, method = "poisson"), + seed = 1, weights = TRUE) + ones <- rep(1, nrow(s)) + n_hat <- ht_total(s, 1) + expect_equal(n_hat$total, sum(1 / s$.prob)) + expect_equal(n_hat$se, ht_total(s, ones)$se) + expect_equal(ht_total(s, 1, by = "site")$total, + ht_total(s, ones, by = "site")$total) + expect_equal(ht_ratio(s, "y", 1)$ratio, ht_mean(s, "y")$mean) + # A single string is still a column name. + expect_error(ht_total(s, "nope"), "`sample` has no column `nope`") + expect_error(ht_total(s, letters[seq_len(nrow(s))]), "pass it as a factor") +}) + +test_that("ht_quantile() gives survey's quantiles and Woodruff intervals", { + skip_if_not_installed("survey") + pop <- est_pop() + probs <- c(0.25, 0.5, 0.75) + for (des in list(design_stratified("site", n = 40), + design_cluster("cl", n_clusters = 6), + design_multistage("cl", n_clusters = 8, n = 40))) { + s <- draw(pop, des, seed = 2, weights = TRUE) + q <- ht_quantile(s, "y", probs = probs) + sq <- survey::svyquantile(~y, as_svydesign(s), probs, ci = TRUE, + interval.type = "mean")$y + expect_equal(q$quantile, unname(sq[, 1])) + expect_equal(cbind(q$ci_lower, q$ci_upper), unname(sq[, 2:3])) + expect_equal(q$se, unname(sq[, 4])) + expect_equal(attr(q, "df"), survey::degf(as_svydesign(s))) + med <- ht_quantile(s, "y") + expect_equal(c(med$quantile, med$ci, med$se), + unname(c(sq[2, 1], sq[2, 2:3], sq[2, 4]))) + } + # By domain, with the normal interval survey also gives each domain. + s <- draw(pop, design_stratified("site", n = 60), seed = 2, weights = TRUE) + b <- ht_quantile(s, "y", probs = c(0.5, 0.75), by = "site", df = Inf) + sb <- survey::svyby(~y, ~site, as_svydesign(s), survey::svyquantile, + quantiles = c(0.5, 0.75), ci = TRUE, df = Inf) + expect_equal(b$quantile, c(t(as.matrix(sb[c("y.0.5", "y.0.75")]))), + ignore_attr = TRUE) + expect_equal(b$se, c(t(as.matrix(sb[c("se.y.0.5", "se.y.0.75")]))), + ignore_attr = TRUE) +}) + +test_that("ht_quantile() follows the quantile rule and the indicator's mean", { + pop <- est_pop() + # With equal weights the rule is quantile(type = 1). + sr <- draw(pop, design_simple(n = 30), seed = 3, weights = TRUE) + p <- c(0, 0.1, 1 / 3, 0.5, 0.9, 1) + q <- ht_quantile(sr, "y", p, variance = "none") + expect_equal(q$quantile, unname(stats::quantile(sr$y, p, type = 1))) + # A p a rounding error above a share of the weight gives the value at + # that share, where quantile(type = 1) gives the next. + p70 <- seq(0, 1, 0.01)[71] + expect_gt(p70, 0.7) + sorted <- sort(sr$y) + expect_equal(ht_quantile(sr, "y", p70, variance = "none")$quantile, + sorted[21]) + expect_equal(unname(stats::quantile(sr$y, p70, type = 1)), sorted[22]) + # F(q) and its standard error are the Hajek mean of y <= q, for a design + # survey has no estimator for. + sy <- draw(pop, design_systematic(interval = 7), seed = 1, weights = TRUE) + med <- ht_quantile(sy, "y") + ind <- ht_mean(sy, sy$y <= med$quantile, proportion = FALSE) + expect_equal(med$cdf, ind$mean) + expect_equal(med$cdf_se, ind$se) + expect_equal(med$method, "successive difference") + expect_gte(med$cdf, 0.5) + expect_lte(med$ci[1], med$quantile) + expect_gte(med$ci[2], med$quantile) +}) + +test_that("a quantile has coef(), vcov(), confint(), a frame and tidy()", { + s <- draw(est_pop(), design_stratified("site", n = 60), seed = 1, + weights = TRUE) + q <- ht_quantile(s, "y") + expect_s3_class(q, "drawn_quantile") + expect_equal(coef(q), c(y = q$quantile)) + expect_equal(vcov(q), matrix(q$se^2, 1, 1, dimnames = list("y", "y"))) + expect_equal(unname(confint(q)[1, ]), q$ci) + expect_equal(unname(confint(q, level = 0.8)[1, ]), + ht_quantile(s, "y", level = 0.8)$ci) + expect_equal(names(as.data.frame(q)), + c("variable", "prob", "n", "quantile", "variance", "se", + "ci_lower", "ci_upper", "level", "df", "deff", "method")) + expect_true(is.na(deff(q))) + expect_output(print(q), "Quantile of `y`") + expect_output(print(q), "Woodruff, t, 57 df", fixed = TRUE) + + b <- ht_quantile(s, "y", c(0.25, 0.5), by = "site") + expect_equal(names(b), c("site", "prob", "n", "quantile", "variance", "se", + "ci_lower", "ci_upper", "method")) + expect_equal(names(coef(b))[1:2], c("a . 0.25", "a . 0.5")) + at <- ht_quantile(s, "y", c(0.25, 0.5), by = "site", level = 0.8) + expect_equal(unname(confint(b, level = 0.8)), + cbind(at$ci_lower, at$ci_upper)) + # Selected rows keep their own intervals at another level. + expect_equal(unname(confint(b[3:4, ], level = 0.8)), + cbind(at$ci_lower, at$ci_upper)[3:4, ]) + expect_equal(unname(diag(vcov(b))), b$variance) + # The covariances between quantiles are not estimated. + off <- vcov(b)[row(vcov(b)) != col(vcov(b))] + expect_true(all(is.na(off))) + several <- vcov(ht_quantile(s, "y", c(0.25, 0.5, 0.75))) + expect_equal(is.na(several), row(several) != col(several), + ignore_attr = TRUE) + expect_output(print(b), "Quantiles of `y` by domain") + expect_output(print(ht_quantile(s, "y", c(0.25, 0.75))), + "Quantiles of `y` (stratified", fixed = TRUE) + expect_error(deff(b), "table of quantiles") + skip_if_not_installed("generics") + expect_equal(generics::tidy(q, conf.int = TRUE)$conf.low, q$ci[1]) + expect_equal(names(generics::tidy(b)), + c("site", "prob", "term", "estimate", "std.error")) +}) + +test_that("ht_quantile() declines what it cannot measure", { + pop <- est_pop() + s <- draw(pop, design_stratified("site", n = 40), seed = 1, weights = TRUE) + # At the largest value F(q) is 1, with a variance of 0 whatever y does. + top <- ht_quantile(s, "y", 0.99) + expect_equal(top$quantile, max(s$y)) + expect_true(is.na(top$se)) + expect_equal(top$method, "none") + expect_match(top$note, "largest sampled value") + b <- ht_quantile(s, "y", c(0.5, 0.99), by = "site") + expect_equal(is.na(b$se), rep(c(FALSE, TRUE), 3)) + expect_match(attr(b, "notes"), "`a . 0.99`, `b . 0.99`", all = FALSE) + # A census is exact there. + cen <- draw(pop, design_simple(n = 300), seed = 1, weights = TRUE) + ex <- ht_quantile(cen, "y", 1) + expect_equal(ex$se, 0) + expect_equal(ex$ci, rep(max(pop$y), 2)) + # An interval for F(q) below 0 bounds the quantile from above only. + low <- ht_quantile(s, "y", 0.01) + expect_true(is.na(low$ci[1])) + expect_false(is.na(low$ci[2])) + expect_true(is.na(low$se)) + expect_match(low$note, "bounds the quantile on one side only") + # One sampled row in a domain. + s$one <- c("x", rep("y", nrow(s) - 1L)) + expect_match(attr(ht_quantile(s, "y", by = "one"), "notes"), + "A quantile's linearised residuals sum to zero", + all = FALSE) +}) + +test_that("ht_quantile() refuses what it cannot read", { + s <- draw(est_pop(), design_stratified("site", n = 40), seed = 1, + weights = TRUE) + s$gap <- s$y + s$gap[3] <- NA + expect_error(ht_quantile(s, "gap"), "`y` is missing in 1 of the 40") + expect_error(ht_quantile(s, "site"), + "a character column of `sample`. Name a numeric column.", + fixed = TRUE) + s$big <- s$y > stats::median(s$y) + expect_error(ht_quantile(s, "big"), + "`y` names `big`, a logical column, and the quantiles") + expect_error(ht_quantile(s, s$big), "`y` is logical.*Use ht_mean\\(\\)") + s$none <- NA + expect_error(ht_quantile(s, "none"), "`y` is missing in 40 of the 40") + expect_error(ht_quantile(s, rep(NA, nrow(s))), + "`y` is missing in 40 of the 40") + expect_error(ht_quantile(s, c("y", "w")), "one column name or a numeric") + expect_error(ht_quantile(s, "y", probs = 1.5), + "`probs` must be one or more numbers from 0 to 1") + expect_error(ht_quantile(s, "y", probs = c(0.5, 0.5)), "more than once") + s$prob <- 1 + expect_error(ht_quantile(s, "y", by = "prob"), "uses for its own column") + d <- data.frame(y = 1:10) + e <- suppressWarnings(draw(d, design_systematic(interval = 20), seed = 2, + weights = TRUE)) + expect_error(ht_quantile(e, "y"), "no rows, so there is no quantile") }) diff --git a/tests/testthat/test-grid.R b/tests/testthat/test-grid.R new file mode 100644 index 0000000..2c00a2c --- /dev/null +++ b/tests/testthat/test-grid.R @@ -0,0 +1,302 @@ +# Every design in design_rows() down every path a sample takes: draw() with +# and without weights, inclusion_prob() exact and simulated, +# sampling_weight(), joint_prob(), ht_total() under each variance, ht_mean(), +# domains, degrees of freedom, as_svydesign(), sample_summary(), plot() and +# deff(). A path an entry refuses on purpose is checked for its message, as +# any other result is; every other path has to run and agree with the +# others. The bugs a path once had are pinned in the tests for its area. +# This file checks that the paths agree for every design, including the ones +# those tests leave out, and a new design added to design_rows() is checked +# the same way. + +rows <- design_rows() + +# Runs `code` for `row`, muffling the warning the design gives on every draw. +quietly <- function(row, code) { + withCallingHandlers(code, warning = function(w) { + if (!is.null(row$warns) && inherits(w, row$warns)) { + invokeRestart("muffleWarning") + } + }) +} + +# The value of `code`, or, for a path `row` refuses, NULL after checking that +# `code` stops with the message the entry gives. +cell <- function(row, path, code, label) { + why <- row$refuse[[path]] + if (is.null(why)) return(quietly(row, code)) + expect_error(quietly(row, code), why, fixed = TRUE, label = label) + NULL +} + +# The weighted sample of `row`, or NULL for a design that refuses one. +grid_sample <- function(row) { + if (!is.null(row$refuse$weights)) return(NULL) + quietly(row, draw(row$frame, row$design, seed = 1, weights = TRUE)) +} + +# Sampling units below certainty less the strata that hold them, worked out +# from the entry's own description of its units and strata. +reference_df <- function(row, s) { + free <- s$.prob < 1 - 1e-9 + if (!any(free)) return(Inf) + units <- row$frame[s$.row[free], , drop = FALSE] + psu <- if (is.null(row$psu)) seq_len(nrow(units)) else units[[row$psu]] + stratum <- if (is.null(row$strata)) { + rep(1, nrow(units)) + } else if (is.function(row$strata)) { + row$strata(units) + } else { + do.call(paste, c(unname(as.list(units[row$strata])), sep = "\r")) + } + length(unique(psu)) - length(unique(stratum)) +} + +test_that("every design draws the same rows for a seed, with the frame's columns", { + for (nm in names(rows)) { + row <- rows[[nm]] + if (is.null(row$warns)) { + a <- draw(row$frame, row$design, seed = 1) + } else { + expect_warning(a <- draw(row$frame, row$design, seed = 1), + class = row$warns) + } + expect_identical(quietly(row, draw(row$frame, row$design, seed = 1)), a, + label = nm) + if (is.data.frame(a)) { + expect_identical(setdiff(names(a), ".replicate"), names(row$frame), + label = nm) + size <- nrow(a) + } else { + size <- length(a) + } + if (row$fixed) expect_equal(size, row$n, label = nm) + } +}) + +test_that("a weighted sample holds the rows drawn and their probabilities", { + for (nm in names(rows)) { + row <- rows[[nm]] + s <- cell(row, "weights", + draw(row$frame, row$design, seed = 1, weights = TRUE), nm) + if (is.null(s)) next + plain <- quietly(row, draw(row$frame, row$design, seed = 1)) + expect_identical(names(s), c(".prob", ".weight", ".row", + names(row$frame)), label = nm) + expect_identical(s$id, plain$id, label = nm) + expect_identical(s$id, row$frame$id[s$.row], label = nm) + expect_equal(s$.weight, 1 / s$.prob, label = nm) + if (is.null(row$refuse$inclusion)) { + p <- quietly(row, inclusion_prob(row$frame, row$design)) + expect_equal(s$.prob, p[s$.row], label = nm) + } else { + # Weighted on the clusters selected, which no frame-wide probability + # gives. + expect_true(all(s$.prob > 0 & s$.prob <= 1), label = nm) + } + } +}) + +test_that("inclusion probabilities sum to the expected size and give the weights", { + for (nm in names(rows)) { + row <- rows[[nm]] + p <- cell(row, "inclusion", inclusion_prob(row$frame, row$design), nm) + w <- cell(row, "inclusion", sampling_weight(row$frame, row$design), nm) + if (is.null(p)) next + expect_length(p, nrow(row$frame)) + expect_true(all(p >= 0 & p <= 1), label = nm) + expect_equal(sum(p), row$expected, label = nm) + expect_equal(w, ifelse(p > 0, 1 / p, NA_real_), label = nm) + } +}) + +test_that("simulated inclusion agrees with the exact probabilities", { + skip_on_cran() + R <- 100 + for (nm in names(rows)) { + row <- rows[[nm]] + if (!is.null(row$refuse$inclusion)) next + p <- quietly(row, inclusion_prob(row$frame, row$design)) + sim <- quietly(row, inclusion_prob(row$frame, row$design, simulate = TRUE, + R = R, seed = 1)) + # Each row's count of draws is binomial, exactly, so its smaller tail + # probability is a test of that row whatever its probability. A row at 0 + # or 1 fails on a single draw against it. + hits <- round(sim * R) + tail <- pmin(stats::pbinom(hits, R, p), + stats::pbinom(hits - 1, R, p, lower.tail = FALSE)) + expect_gt(min(tail), 1e-7, label = nm) + } +}) + +test_that("joint probabilities agree with the inclusion probabilities", { + for (nm in names(rows)) { + row <- rows[[nm]] + m <- cell(row, "joint", joint_prob(row$frame, row$design), nm) + if (is.null(m)) next + m <- unname(m) + p <- quietly(row, inclusion_prob(row$frame, row$design)) + expect_equal(diag(m), p, label = nm) + expect_equal(m, t(m), label = nm) + expect_true(all(m >= 0 & m <= outer(p, p, pmin) + 1e-12), label = nm) + if (row$fixed) { + # A row's joint probabilities with every row, itself included, add up + # to n times its own when every draw has n rows. + expect_equal(rowSums(m), row$n * p, label = nm) + } else { + # Rows of a design of random size are taken independently. + want <- outer(p, p) + diag(want) <- p + expect_equal(m, want, label = nm) + } + } +}) + +test_that("ht_total() gives the Horvitz-Thompson total under every variance", { + for (nm in names(rows)) { + row <- rows[[nm]] + s <- grid_sample(row) + if (is.null(s)) next + auto <- ht_total(s, "y") + expect_equal(auto$total, sum(s$y * s$.weight), label = nm) + expect_equal(auto$method, row$method, label = nm) + expect_true(is.finite(auto$se) && auto$se > 0, label = nm) + expect_equal(ht_total(s, "y", variance = "analytic")$se, auto$se, + label = nm) + expect_true(is.na(ht_total(s, "y", variance = "none")$se), label = nm) + + jk <- ht_total(s, "y", variance = "jackknife") + if (identical(row$jackknife, "same")) { + expect_equal(jk$se, auto$se, label = nm) + } else if (identical(row$jackknife, "own")) { + expect_equal(jk$method, "jackknife", label = nm) + expect_gt(jk$se / auto$se, 2 / 3, label = nm) + expect_lt(jk$se / auto$se, 3 / 2, label = nm) + } else { + expect_true(is.na(jk$se), label = nm) + expect_equal(jk$method, "none", label = nm) + expect_match(jk$note, row$jackknife, fixed = TRUE, label = nm) + } + } +}) + +test_that("ht_mean() is the Hajek mean, with a logit interval for a 0/1 variable", { + for (nm in names(rows)) { + row <- rows[[nm]] + s <- grid_sample(row) + if (is.null(s)) next + m <- ht_mean(s, "y") + expect_equal(m$mean, sum(s$y * s$.weight) / sum(s$.weight), label = nm) + expect_true(is.finite(m$se) && m$se > 0, label = nm) + + b <- ht_mean(s, "flag") + expect_equal(b$ci_scale, "logit", label = nm) + half <- stats::qt(0.975, b$df) * b$se / (b$mean * (1 - b$mean)) + expect_equal(b$ci, stats::plogis(stats::qlogis(b$mean) + c(-1, 1) * half), + label = nm) + } +}) + +test_that("domain totals add up to the whole sample's", { + for (nm in names(rows)) { + row <- rows[[nm]] + s <- grid_sample(row) + if (is.null(s)) next + by <- ht_total(s, "y", by = "site") + expect_equal(sum(by$total), ht_total(s, "y")$total, label = nm) + expect_equal(sum(by$n), nrow(s), label = nm) + expect_true(all(is.finite(by$se) & by$se > 0), label = nm) + } +}) + +test_that("degrees of freedom are the units below certainty less their strata", { + for (nm in names(rows)) { + row <- rows[[nm]] + s <- grid_sample(row) + if (is.null(s)) next + want <- reference_df(row, s) + expect_equal(ht_total(s, "y")$df, want, label = nm) + expect_equal(ht_mean(s, "y")$df, want, label = nm) + expect_equal(attr(ht_total(s, "y", by = "site"), "df"), want, label = nm) + } +}) + +test_that("survey gets the total, the degrees of freedom and the same estimator", { + skip_if_not_installed("survey") + for (nm in names(rows)) { + row <- rows[[nm]] + s <- grid_sample(row) + if (is.null(s)) next + ours <- ht_total(s, "y") + sv <- as_svydesign(s) + theirs <- survey::svytotal(~y, sv) + expect_equal(as.numeric(theirs), ours$total, label = nm) + expect_equal(survey::degf(sv), ours$df, label = nm) + se <- as.numeric(survey::SE(theirs)) + if (row$survey == "same") { + expect_equal(se, ours$se, tolerance = 1e-6, label = nm) + } else if (row$survey == "close") { + # Brewer's approximation in survey, Deville's here. + expect_equal(se, ours$se, tolerance = 0.01, label = nm) + } else { + # Successive differences and the local mean have no survey estimator; + # survey treats these samples as simple random ones. + expect_true(is.finite(se) && se > 0, label = nm) + } + } +}) + +test_that("sample_summary() counts the sample and the rows the design reaches", { + for (nm in names(rows)) { + row <- rows[[nm]] + s <- grid_sample(row) + if (is.null(s)) next + x <- sample_summary(s) + expect_equal(x$n, nrow(s), label = nm) + expect_equal(x$N, nrow(row$frame), label = nm) + expect_equal(x$n_certain, sum(s$.prob >= 1 - 1e-9), label = nm) + if (row$conditional) { + # Every row of a cluster left out could have been drawn, at a + # probability the clusters selected do not give. + expect_equal(x$N_reachable, nrow(row$frame), label = nm) + expect_true(is.na(x$expected_n), label = nm) + expect_equal(x$conditional, length(unique(s$cl)), label = nm) + } else { + p <- quietly(row, inclusion_prob(row$frame, row$design)) + expect_equal(x$N_reachable, sum(p > 0), label = nm) + expect_equal(x$expected_n, row$expected, label = nm) + expect_true(is.na(x$conditional), label = nm) + } + } +}) + +test_that("every view of every design plots, or says why it cannot", { + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + for (nm in names(rows)) { + row <- rows[[nm]] + for (type in c("selection", "probability", "map")) { + path <- if (!is.null(row$refuse$plot)) "plot" else type + out <- cell(row, path, + plot(row$design, row$frame, type = type, seed = 1, + coords = c("x", "yy")), + paste(nm, type)) + if (!is.null(out)) expect_identical(out, row$design, label = nm) + } + } +}) + +test_that("deff() reads the design effect under drawn's generic and survey's", { + survey <- requireNamespace("survey", quietly = TRUE) + for (nm in names(rows)) { + row <- rows[[nm]] + s <- grid_sample(row) + if (is.null(s)) next + r <- ht_total(s, "y") + m <- ht_mean(s, "y") + expect_gt(r$deff, 0, label = nm) + expect_equal(deff(r), r$deff, label = nm) + expect_equal(deff(m), m$deff, label = nm) + if (survey) expect_equal(survey::deff(r), r$deff, label = nm) + } +}) diff --git a/tests/testthat/test-inclusion.R b/tests/testthat/test-inclusion.R index 6b16760..97125f8 100644 --- a/tests/testthat/test-inclusion.R +++ b/tests/testthat/test-inclusion.R @@ -30,6 +30,28 @@ test_that("a fixed systematic start is refused as a probability sample", { ) }) +test_that("systematic inclusion is n / N with `n`, at any N", { + for (N in c(20, 23, 29)) { + p <- inclusion_prob(data.frame(id = seq_len(N)), design_systematic(n = 7)) + expect_equal(p, rep(7 / N, N), info = paste("N =", N)) + } +}) + +test_that("a fixed systematic start is refused by every weighting path alike", { + d <- data.frame(id = 1:20) + des <- design_systematic(interval = 5, start = 2) + want <- paste0("A systematic design with a fixed `start` is not a ", + "probability sample: each row is selected with probability ", + "0 or 1. Leave `start` as NULL for a random start.") + expect_error(inclusion_prob(d, des), want, fixed = TRUE) + expect_error(sampling_weight(d, des), want, fixed = TRUE) + expect_error(joint_prob(d, des, rows = 1:3), want, fixed = TRUE) + expect_error(draw(d, des, weights = TRUE), want, fixed = TRUE) + # The design is deterministic, and the simulation reports its 0s and 1s. + expect_identical(inclusion_prob(d, des, simulate = TRUE, R = 20, seed = 1), + as.numeric(d$id %in% c(2, 7, 12, 17))) +}) + test_that("sampling_weight is the reciprocal, and 0 becomes NA not Inf", { d <- data.frame(id = 1:10) expect_equal(sampling_weight(d, design_simple(n = 5)), rep(2, 10)) @@ -60,9 +82,11 @@ test_that("designs with no closed form refuse rather than invent one", { expect_error(inclusion_prob(df, design_weighted("w", n = 3)), "no closed-form inclusion probability") - expect_error( + # Balanced clusters have one: with clusters of equal size every selected + # cluster is taken whole. + expect_equal( inclusion_prob(df, design_cluster("cl", n_clusters = 2, balanced = TRUE)), - "no closed-form inclusion probability" + rep(0.5, 20) ) expect_error( inclusion_prob(df, design_multistage("cl", n_clusters = 2, n = 4, @@ -202,3 +226,406 @@ test_that("Neyman allocation reports probabilities for a design it can draw", { expect_equal(p[11:12], c(0, 0)) expect_equal(nrow(draw(d, des, seed = 1, weights = TRUE)), 4) }) + +test_that("joint_prob refuses a matrix past about 1 GB and says how to avoid it", { + # 8 bytes a pair: every row of a 12,000-row frame is 1.2 GB, and a frame + # some times larger could end the session. + pop <- data.frame(id = seq_len(12000)) + d <- design_simple(n = 10) + expect_error(joint_prob(pop, d), + "12,000 x 12,000 matrix for every row of `data`, which needs about 1.2 GB", + fixed = TRUE) + expect_error(joint_prob(pop, d), "rows = s$.row", fixed = TRUE) + expect_error(joint_prob(pop, d, rows = seq_len(12000)), + "for the 12,000 `rows` given, which needs about 1.2 GB of memory. Pass fewer `rows`.", + fixed = TRUE) + expect_error(joint_prob(pop, d, simulate = TRUE, R = 2), "1.2 GB", + fixed = TRUE) + expect_equal(dim(joint_prob(pop, d, rows = c(5, 9000))), c(2L, 2L)) +}) + +test_that("joints filled block by block equal the pairwise forms", { + # Same group: a simple random sample of n from N. Different groups: + # independent. A row in no group co-occurs with nothing. Built here pair by + # pair. + pairwise <- function(group, n_g, size_g, pi_i) { + k <- length(group) + out <- outer(pi_i, pi_i) + for (i in seq_len(k)) for (j in seq_len(k)) { + if (is.na(group[i]) || is.na(group[j])) { + out[i, j] <- 0 + } else if (group[i] == group[j]) { + n <- n_g[group[i]] + N <- size_g[group[i]] + out[i, j] <- if (N > 1) n * (n - 1) / (N * (N - 1)) else 0 + } + } + diag(out) <- pi_i + out + } + group <- c(2L, 1L, NA, 3L, 2L, 1L, 2L, 4L, 1L) + n_g <- c(2, 3, 1, 1) + size_g <- c(5, 3, 4, 1) + pi_i <- ifelse(is.na(group), 0, (n_g / size_g)[group]) + expect_equal(drawn:::joint_from_groups(group, n_g, size_g, pi_i), + pairwise(group, n_g, size_g, pi_i)) + + # Cluster: the same cluster a / A, different clusters a(a-1) / (A(A-1)). + pop <- data.frame(cl = c("a", "a", "b", NA, "c", "b", "c", "c", "d")) + d <- design_cluster("cl", n_clusters = 2, na_rm = TRUE) + same <- outer(pop$cl, pop$cl, "==") + want <- ifelse(same, 2 / 4, 2 * 1 / (4 * 3)) + want[is.na(pop$cl), ] <- 0 + want[, is.na(pop$cl)] <- 0 + diag(want) <- inclusion_prob(pop, d) + expect_equal(joint_prob(pop, d), want) + + # Multistage, a = 2 of A = 4 clusters and m = 2 rows from each: the stages + # multiplied. + pop <- data.frame(cl = c(rep(c("a", "b", "c", "d"), times = c(3, 4, 5, 4)), + NA)) + d <- design_multistage("cl", n_clusters = 2, n = 4, na_rm = TRUE) + N_i <- as.numeric(table(pop$cl)[pop$cl]) + same <- outer(pop$cl, pop$cl, "==") + want <- ifelse(same, (2 / 4) * 2 / (N_i * (N_i - 1)), + 2 / (4 * 3) * outer(2 / N_i, 2 / N_i)) + want[is.na(pop$cl), ] <- 0 + want[, is.na(pop$cl)] <- 0 + diag(want) <- inclusion_prob(pop, d) + expect_equal(joint_prob(pop, d), want) +}) + +test_that("the probability paths refuse what draw() refuses, with its message", { + # They answered instead: 1.25 for every row of a simple random sample of 30 + # from 24, a census of 1s for a stratified one, 0 for every row when no + # interval fits the window. + d <- data.frame(id = 1:24, site = rep(c("a", "b", "c"), c(12, 8, 4)), + cl = rep(sprintf("c%02d", 1:6), each = 4), w = c(1:23, 100), + ts = seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "hour", + length.out = 24), + stringsAsFactors = FALSE) + none <- d + none$site <- NA_character_ + none$cl <- NA_character_ + none$w <- NA_real_ + none$ts[] <- NA + cases <- list( + list(d, design_simple(n = 30), "cannot exceed the number of rows (24)"), + list(d, design_stratified("site", n = 30), + "cannot exceed the number of rows (24)"), + list(none, design_stratified("site", n = 3, na_rm = TRUE), + "Every row has a missing stratum key."), + list(d, design_cluster("cl", n_clusters = 7), + "`n_clusters` (7) exceeds the 6 cluster(s) available."), + list(none, design_cluster("cl", n_clusters = 1, na_rm = TRUE), + "Every row has a missing cluster label."), + list(d, design_multistage("cl", n_clusters = 7, n = 14), + "`n_clusters` (7) exceeds the 6 cluster(s) available."), + list(d, design_multistage("cl", n_clusters = 2, n = 10), + "`n` (10) exceeds the 8 row(s) available across the 2 selected"), + list(d, design_weighted("w", n = 30, method = "systematic"), + "`n` (30) cannot exceed the number of rows (24) for method"), + list(d, design_weighted("w", n = 30, method = "poisson"), + "`n` (30) cannot exceed the number of rows (24) for method"), + list(none, design_weighted("w", n = 3, method = "poisson", na_rm = TRUE), + "Every row has a missing weight in `w`."), + list(d, design_certainty("w", 20, design_simple(n = 30)), + "applied to the 19 rows with `w` below 20: `n` (30) cannot exceed"), + list(d, design_certainty("w", 20, design_weighted("w", n = 30, + method = "poisson")), + "applied to the 19 rows with `w` below 20: `n` (30) cannot exceed"), + list(d, design_temporal("ts", "2024-01-01", "2024-01-01 02:00:00", + interval = 3, per_interval = 1), + "shorter than one interval"), + list(none, design_temporal("ts", "2024-01-01", "2024-01-02", interval = 3, + per_interval = 1, na_rm = TRUE), + "Every row has a missing or unparseable timestamp in `ts`."), + list(d, design_systematic(interval = 3, order_by = "W"), + "`data` is missing column: `W`."), + list(none, design_systematic(interval = 3, order_by = "w", na_rm = TRUE), + "Every row has a missing `w`.") + ) + if (requireNamespace("sf", quietly = TRUE)) { + d$lon <- seq(-10, 10, length.out = 24) + d$lat <- seq(-5, 5, length.out = 24) + none$lon <- NA_real_ + none$lat <- d$lat + gap <- d + gap$lat[3] <- NA + box <- function(lo, hi) { + sf::st_sfc(sf::st_polygon(list(cbind(c(lo, hi, hi, lo, lo), + c(lo, lo, hi, hi, lo)))), + crs = 4326) + } + cases <- c(cases, list( + list(d, design_spatial(c("lon", "lat"), box(-2, 2), n = 10), + "`n` (10) exceeds the 4 row(s) inside `region`."), + list(d, design_spatial(c("lon", "lat"), box(50, 60), n = 1), + "No rows fall inside `region`."), + list(none, design_spatial(c("lon", "lat"), box(-2, 2), n = 1, + na_rm = TRUE), + "Every row has missing coordinates in `lon` or `lat`."), + list(gap, design_spatial(c("lon", "lat"), box(-2, 2), n = 1), + "1 row(s) have missing coordinates in `lon` or `lat`") + )) + } + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + # The 10-degree box at latitude 50 to 60 bows past the edge warning's + # limit; only the errors are compared here. + message_of <- function(code) { + tryCatch({ + withCallingHandlers(force(code), drawn_geodesic_edges = function(w) { + invokeRestart("muffleWarning") + }) + NA_character_ + }, error = conditionMessage) + } + for (case in cases) { + pop <- case[[1]] + des <- case[[2]] + info <- drawn:::design_label(des) + want <- message_of(draw(pop, des, seed = 1)) + expect_true(grepl(case[[3]], want, fixed = TRUE), info = info) + expect_identical(message_of(inclusion_prob(pop, des)), want, info = info) + expect_identical(message_of(sampling_weight(pop, des)), want, info = info) + expect_identical(message_of(joint_prob(pop, des, rows = 1:2)), want, + info = info) + expect_identical(message_of(draw(pop, des, seed = 1, weights = TRUE)), + want, info = info) + expect_true(grepl(want, message_of(plot(des, pop, type = "probability")), + fixed = TRUE), info = info) + } +}) + +test_that("joint_prob pairs a repeated row with itself at its own probability", { + # A row given twice was two units: the pair it made with itself got + # n(n-1)/(N(N-1)), and simulate = TRUE gave it 0. + d <- data.frame(id = 1:20, g = rep(c("a", "b"), each = 10)) + for (des in list(design_simple(n = 5), design_stratified("g", n = 6))) { + p <- inclusion_prob(d, des) + m <- joint_prob(d, des, rows = c(3, 3, 12)) + expect_equal(dim(m), c(3L, 3L)) + expect_equal(m[1, 2], p[3]) + expect_equal(m[1:2, 1:2], matrix(p[3], 2, 2)) + expect_equal(m[c(1, 3), c(1, 3)], joint_prob(d, des, rows = c(3, 12))) + expect_equal(m[2, 3], m[1, 3]) + sim <- joint_prob(d, des, rows = c(3, 3, 12), simulate = TRUE, R = 200, + seed = 1) + expect_equal(sim[1, 2], sim[1, 1]) + expect_equal(sim[2, 2], sim[1, 1]) + expect_gt(sim[1, 1], 0) + } +}) + +test_that("joint_prob refuses rows that are not whole numbers", { + d <- data.frame(id = 1:20) + expect_error(joint_prob(d, design_simple(n = 5), rows = c(1, 1.5)), + "`rows` must be whole row numbers, not 1.5.", fixed = TRUE) + expect_error(joint_prob(d, design_simple(n = 5), rows = 1.7, + simulate = TRUE, R = 10), + "not 1.7", fixed = TRUE) + # Past five values the list counts the rest, so it ends in one full stop. + expect_error(joint_prob(d, design_simple(n = 5), rows = 1:8 + 0.5), + "not 1.5, 2.5, 3.5, 4.5, 5.5 and 3 more. Pass", fixed = TRUE) +}) + +# ---- where a refusal points --------------------------------------------------- + +test_that("a refusal names the function that simulates", { + df <- data.frame(id = 1:20, cl = rep(letters[1:4], each = 5), w = 1:20) + succ <- design_weighted("w", n = 3) + # draw() and plot() take no `simulate`, so the pointer names the function + # that does. + for (call in list(quote(inclusion_prob(df, succ)), + quote(draw(df, succ, seed = 1, weights = TRUE)))) { + err <- tryCatch(eval(call), error = conditionMessage) + expect_match(err, "inclusion_prob(data, design, simulate = TRUE)", + fixed = TRUE) + expect_no_match(err, "Or pass simulate", fixed = TRUE) + } + # Joint refusals point to a simulation where one works ... + for (des in list(succ, + design_cluster("cl", n_clusters = 2, balanced = TRUE), + design_multistage("cl", n_clusters = 2, n = 4, + allocation = "proportional"), + design_simple(n = 3, replace = TRUE))) { + expect_error(joint_prob(df, des, rows = 1:3), + "joint_prob(data, design, simulate = TRUE)", fixed = TRUE) + } + # ... and not for a bootstrap, where it is refused. + err <- tryCatch(joint_prob(df, design_bootstrap(n_replicates = 2), + rows = 1:3), error = conditionMessage) + expect_no_match(err, "simulate = TRUE", fixed = TRUE) +}) + +# ---- warnings and time in a simulation -------------------------------------- + +test_that("a warning each draw raises is given once, with the count", { + short <- data.frame(y = 1:5) + caught <- list() + p <- withCallingHandlers( + inclusion_prob(short, design_systematic(interval = 8), simulate = TRUE, + R = 400, seed = 1), + warning = function(w) { + caught[[length(caught) + 1L]] <<- w + invokeRestart("muffleWarning") + }) + expect_length(caught, 1L) + expect_s3_class(caught[[1L]], "drawn_empty_start") + expect_match(conditionMessage(caught[[1L]]), + "^The random start \\([678]\\) is past the last row \\(5\\)") + # The start shown is the first draw's, and the count covers every draw + # with a start past the last row, whichever it was. Each other draw takes + # one row, so the empty draws are the 400 less the rows drawn. + empty <- 400L - as.integer(round(sum(p) * 400)) + expect_match(conditionMessage(caught[[1L]]), + paste0("This is the first of these warnings. ", empty, + " of the 400 simulated draws gave one like it, with ", + "details that differ from draw to draw."), + fixed = TRUE) + expect_no_match(conditionMessage(caught[[1L]]), "This happened in", + fixed = TRUE) + expect_lt(max(abs(p - 1 / 8)), 0.05) + + # A message that is the same in every draw is given with its count. + expect_warning( + inclusion_prob(short, design_systematic(interval = 8, start = 7), + simulate = TRUE, R = 30, seed = 1), + paste("`start` (7) is past the last row (5); returning no rows.", + "This happened in 30 of the 30 simulated draws."), + fixed = TRUE, class = "drawn_empty_start") + + # simulate_joint() counts them the same way. + caught <- list() + withCallingHandlers( + joint_prob(short, design_systematic(interval = 8), simulate = TRUE, + R = 50, seed = 1), + warning = function(w) { + caught[[length(caught) + 1L]] <<- w + invokeRestart("muffleWarning") + }) + expect_length(caught, 1L) + expect_s3_class(caught[[1L]], "drawn_empty_start") + + # A fixed start keeps its wording. + expect_warning(draw(short, design_systematic(interval = 8, start = 7)), + "`start` (7) is past the last row (5); returning no rows.", + fixed = TRUE, class = "drawn_empty_start") + expect_warning(draw(short[1, , drop = FALSE], + design_systematic(interval = 50, n_starts = 2), + seed = 1), + "Every random start", class = "drawn_empty_start") +}) + +test_that("messages that differ only inside a draw are not called varied", { + given <- function(R, one) { + caught <- character(0) + withCallingHandlers(simulate_draws(R, seed = 1, one), + drawn_empty_stratum = function(w) { + caught <<- c(caught, conditionMessage(w)) + invokeRestart("muffleWarning") + }) + caught + } + # Every draw gives the same two messages, so none differ from draw to draw. + same_pair <- function() { + warn_drawn("Stratum `a` is empty.", "drawn_empty_stratum") + warn_drawn("Stratum `b` is empty.", "drawn_empty_stratum") + } + expect_identical(given(5, same_pair), + paste("Stratum `a` is empty. This happened in 5 of the 5", + "simulated draws. Each of them gave the same 2", + "warnings like it, and this is the first.")) + expect_identical(given(1, same_pair), + paste("Stratum `a` is empty. This happened in 1 of the 1", + "simulated draws. That draw gave 2 warnings like it,", + "and this is the first.")) + # A repeat of one message in a draw is still one message. + twice <- function() { + warn_drawn("Stratum `a` is empty.", "drawn_empty_stratum") + warn_drawn("Stratum `a` is empty.", "drawn_empty_stratum") + } + expect_identical(given(4, twice), + paste("Stratum `a` is empty. This happened in 4 of the 4", + "simulated draws.")) + # The pair in the first draw and one message after it differ by draw. + k <- 0L + first_pair <- function() { + k <<- k + 1L + warn_drawn("Stratum `a` is empty.", "drawn_empty_stratum") + if (k == 1L) warn_drawn("Stratum `b` is empty.", "drawn_empty_stratum") + } + expect_match(given(3, first_pair), + "3 of the 3 simulated draws gave one like it, with details that differ from draw to draw.", + fixed = TRUE) +}) + +test_that("a long simulation says how long it will take", { + df <- data.frame(id = 1:20) + des <- design_simple(n = 3) + # Each reading of the clock is 10 seconds after the last, so every timed + # draw takes 10 seconds and 40 draws project 400. + clock <- 0 + local_mocked_bindings(elapsed_time = function() { + clock <<- clock + 10 + clock + }) + expect_message(p <- inclusion_prob(df, des, simulate = TRUE, R = 40, + seed = 1), + "Simulating 40 draws will take about 6.7 minutes, at 10 seconds a draw.", + fixed = TRUE) + # Timing and messages leave the draws as they were. + expect_identical(p, suppressMessages( + inclusion_prob(df, des, simulate = TRUE, R = 40, seed = 1))) + expect_message(joint_prob(df, des, rows = 1:3, simulate = TRUE, R = 40, + seed = 1), "Simulating 40 draws") + + # An interactive session also gets a progress bar. + local_mocked_bindings(is_interactive = function() TRUE) + shown <- capture.output(suppressMessages( + inclusion_prob(df, des, simulate = TRUE, R = 40, seed = 1))) + expect_match(paste(shown, collapse = ""), "100%", fixed = TRUE) +}) + +test_that("the time of a run leaves out the first two draws", { + # The clock moves only when a draw runs, by the cost given for that draw. + clock <- 0 + local_mocked_bindings(elapsed_time = function() clock) + run <- function(cost, R) { + i <- 0L + simulate_draws(R, seed = 1, function() { + i <<- i + 1L + clock <<- clock + cost[min(i, length(cost))] + }) + } + + # Two slow draws, as when a package loads and code compiles, then fast + # ones: 100 draws take under 2 seconds in all. + expect_silent(run(c(1, 1, 0.001), R = 100)) + + # Later draws set the rate, not the slow first ones. + expect_message(run(c(5, 5, 1), R = 100), + "Simulating 100 draws will take about 1.7 minutes, at 1 second a draw.", + fixed = TRUE) + + # Draws faster than the clock's millisecond steps are timed over enough of + # them to measure. + expect_message(run(c(0.5, 0.2, 0.001), R = 50000), + "will take about 50 seconds, at 0.001 seconds a draw.", + fixed = TRUE) +}) + +test_that("a short simulation is quiet", { + df <- data.frame(id = 1:20) + local_mocked_bindings(is_interactive = function() TRUE) + expect_silent(inclusion_prob(df, design_simple(n = 3), simulate = TRUE, + R = 200, seed = 1)) +}) + +test_that("durations read in the unit that suits them", { + expect_identical(format_duration(0.0123), "0.012 seconds") + expect_identical(format_duration(1), "1 second") + expect_identical(format_duration(400), "6.7 minutes") + expect_identical(format_duration(3600 * 3.3), "3.3 hours") +}) diff --git a/tests/testthat/test-invariants.R b/tests/testthat/test-invariants.R index 9638b53..3bf52bb 100644 --- a/tests/testthat/test-invariants.R +++ b/tests/testthat/test-invariants.R @@ -4,15 +4,6 @@ # Each pins a specific case where a plausible implementation gives a wrong # answer silently, rather than erroring. -test_that("a single numeric cluster id is not reinterpreted as a range", { - # sample(5, 1) samples from 1:5, so the only real cluster was never selected. - d <- data.frame(x = 1:10, cl = rep(5, 10)) - expect_equal(nrow(draw(d, design_cluster("cl", n_clusters = 1), seed = 1)), 10) - expect_equal( - nrow(draw(d, design_multistage("cl", n_clusters = 1, n = 2), seed = 1)), 2 - ) -}) - test_that("capping a result keeps every stratum represented", { # max_rows was head() of a stratum-sorted frame, so a cap of 10 returned # group "a" and nothing else. The argument is gone: n IS the cap, and it is @@ -48,30 +39,20 @@ test_that("multistage allocation totals the request, up or down", { allocation = "proportional"), seed = 1)), 20 ) - # And 20 for a request of 5, because max(1, ...) floored every cluster. - many <- data.frame(x = 1:1000, cl = as.character(rep(1:100, each = 10))) - expect_equal( - nrow(draw(many, design_multistage("cl", n_clusters = 20, n = 5, - allocation = "proportional"), seed = 1)), - 5 + # And more than requested, because max(1, ...) floored every cluster. A + # proportional share below one row stays at none; it is not raised to one. + many <- data.frame(x = 1:1090, cl = c(rep("big", 1000), + rep(sprintf("s%02d", 1:90), each = 1))) + expect_warning( + res <- draw(many, design_multistage("cl", n_clusters = 91, n = 91, + allocation = "proportional"), seed = 1), + class = "drawn_empty_cluster" ) -}) - -test_that("the caller's weights come back untouched", { - d <- data.frame(id = 1:10, w = 1:10) - out <- draw(d, design_weighted("w", n = 5), seed = 1) - expect_equal(out$w, d$w[match(out$id, d$id)]) - expect_type(out$w, "integer") -}) - -test_that("the lightest row stays selectable", { - # min-max and z-score both subtracted the minimum and added double.eps, - # leaving the lightest row at ~2.2e-16. Rescaling is gone entirely: prob= - # normalises by sum, so it never bought anything. - d <- data.frame(id = 1:5, w = c(1, 2, 3, 4, 5)) - drawn <- vapply(1:600, function(i) draw(d, design_weighted("w", n = 1), - seed = i)$id, numeric(1)) - expect_true(1 %in% drawn) + expect_equal(nrow(res), 91) + # Fewer rows than clusters left selected clusters empty without a word. + expect_error(design_multistage("cl", n_clusters = 20, n = 5, + allocation = "proportional"), + "smaller than `n_clusters`") }) test_that("balanced clustering works with unused factor levels", { @@ -82,52 +63,6 @@ test_that("balanced clustering works with unused factor levels", { expect_equal(nrow(res), 20) }) -test_that("block replicates are stitched from blocks across the frame", { - d <- data.frame(id = 1:1000) - res <- draw(d, design_bootstrap(n_replicates = 20, n = 50, method = "block", - block_length = 5), seed = 1) - reps <- split(res, res$.replicate) - spans <- vapply(reps, function(z) diff(range(z$id)), numeric(1)) - expect_true(all(spans > 200)) -}) - -test_that("bootstrap returns exactly n_replicates of equal size (invariant)", { - # A8 was the max_rows branch rbinding, de-duplicating and re-splitting the - # replicates. That branch is gone, so this passes against the original code - # too. Kept as an invariant, not as a regression guard. - df <- make_df() - res <- draw(df, design_bootstrap(n_replicates = 5, n = 10), seed = 1) - expect_equal(length(unique(res$.replicate)), 5) - expect_equal(unique(as.vector(table(res$.replicate))), 10L) -}) - -test_that("POSIXct and Date columns are used as-is", { - expect_silent( - res <- draw(make_ts(), design_temporal("ts", "2020-01-01", "2020-01-02", - interval = 6, per_interval = 2, - unit = "hours"), seed = 1) - ) - expect_equal(nrow(res), 8) - - dates <- data.frame(id = 1:10, - d = seq(as.Date("2020-01-01"), by = "day", length.out = 10)) - expect_equal( - nrow(draw(dates, design_temporal("d", "2020-01-01", "2020-01-06", - interval = 1, per_interval = 1, - unit = "days"), seed = 1)), - 5 - ) -}) - -test_that("a region list of three or more geometries is unioned", { - skip_if_not_installed("sf") - d <- data.frame(id = 1:3, lon = c(5, 25, 45), lat = c(5, 25, 45)) - expect_equal( - nrow(draw(d, design_spatial(c("lon", "lat"), three_boxes(), n = 3), seed = 1)), - 3 - ) -}) - test_that("count arguments reject negative, non-numeric and length-2 values", { # max_rows accepted all three: head(x, -3) trimmed from the end, "5" was # ignored, and c(3, 2) silently dropped columns. @@ -155,43 +90,6 @@ test_that("single-column frames survive intact", { expect_equal(res_sys$v, c(3, 1, 2)) }) -test_that("a short stream is trimmed, not padded with NULLs", { - res <- draw(as.list(1:5), design_reservoir(n = 10), seed = 1) - expect_equal(length(res), 5) - expect_false(any(vapply(res, is.null, logical(1)))) -}) - -test_that("empty results keep the input's columns", { - df <- make_df() - empty <- draw(df, design_temporal("time", "2021-01-01", "2021-01-02", - interval = 6, per_interval = 2, - unit = "hours"), seed = 1) - expect_equal(ncol(empty), ncol(df)) - expect_identical(names(empty), names(df)) -}) - -test_that("NA cluster labels never fabricate rows", { - d <- data.frame(x = 1:30, cl = c(rep("a", 10), rep("b", 10), rep(NA, 10))) - - # `==` against an NA label yields NA, and indexing with NA manufactures - # all-NA rows that were never in the data. - expect_error(draw(d, design_multistage("cl", n_clusters = 1, n = 5), seed = 1), - "missing cluster label") - - res <- draw(d, design_multistage("cl", n_clusters = 1, n = 5, na_rm = TRUE), - seed = 1) - expect_false(anyNA(res$x)) - expect_equal(nrow(res), 5) - - # A guard reading the NA-inflated count would let this through, returning 15 - # rows from a 10-row cluster with replace = FALSE. - expect_error( - draw(d, design_multistage("cl", n_clusters = 1, n = 15, na_rm = TRUE), - seed = 1), - "exceeds the 10 row\\(s\\) available" - ) -}) - test_that("an antimeridian-spanning region warns instead of failing mutely", { skip_if_not_installed("sf") df <- make_df() @@ -213,61 +111,6 @@ test_that("the warning does not fire on legitimate multi-part regions", { seed = 1)) }) -test_that("allocation hits the total and does not floor rare strata", { - uneven <- data.frame( - x = 1:143, - g = rep(letters[1:7], times = c(31, 29, 23, 19, 17, 13, 11)) - ) - expect_equal(nrow(draw(uneven, design_stratified("g", n = 50), seed = 1)), 50) - - skewed <- data.frame(x = 1:1000, g = c(rep("big", 999), "rare")) - expect_warning(res <- draw(skewed, design_stratified("g", n = 10), seed = 1), - "allocated no rows") - expect_equal(nrow(res), 10) -}) - -test_that("month buckets follow the calendar, not 30.44-day durations", { - df <- data.frame( - id = 1:365, - ts = seq(as.POSIXct("2020-01-01", tz = "UTC"), by = "day", length.out = 365) - ) - res <- draw(df, design_temporal("ts", "2020-01-01", "2020-04-01", interval = 1, - per_interval = 1, unit = "months"), seed = 1) - expect_equal(sort(as.integer(format(res$ts, "%m"))), 1:3) -}) - -test_that("count arguments are validated rather than passed to sample()", { - expect_error(design_simple(n = 2.7), "single whole number") - expect_error(design_systematic(interval = 0), "at least 1") - expect_error(design_systematic(interval = 2.5), "single whole number") -}) - -test_that("drawing leaves the caller's RNG stream alone", { - df <- make_df() - set.seed(42) - expected <- stats::runif(3) - set.seed(42) - invisible(draw(df, design_simple(n = 2), seed = 99)) - expect_equal(stats::runif(3), expected) -}) - -test_that("column order is preserved by every design", { - df <- make_df() - designs <- list( - design_simple(n = 4), - design_stratified("site", n = 4), - design_systematic(interval = 10), - design_cluster("site", n_clusters = 2), - design_multistage("site", n_clusters = 2, n = 4), - design_reservoir(n = 4), - design_temporal("time", "2020-01-01 00:00:00", "2020-01-01 12:00:00", - interval = 6, per_interval = 1, unit = "hours") - ) - for (d in designs) { - expect_identical(names(draw(df, d, seed = 1)), names(df), info = class(d)[1]) - } -}) - test_that("removed arguments stay removed", { # max_rows caused both halves of A2 and all of A8. normalization caused A5. # Reintroducing either should be a deliberate act, not an accident, so pin @@ -300,7 +143,7 @@ test_that("weights = TRUE keeps the input's class, not just its columns", { expect_s3_class(out, "tbl_df") } wt <- draw(tb, design_simple(n = 10), seed = 1, weights = TRUE) - expect_identical(names(wt), c(".prob", ".weight", "id", "site")) + expect_identical(names(wt), c(".prob", ".weight", ".row", "id", "site")) }) test_that("simulation refuses the bootstrap instead of returning all ones", { @@ -366,6 +209,7 @@ test_that("a negative seed is a seed", { }) test_that("proportional allocation survives a frame big enough to overflow", { + skip_on_cran() # `n * sizes` was evaluated in 32-bit integer arithmetic, so 3,000 rows out # of 2.4 million produced NAs and an unrelated error. big <- data.frame(g = rep(c("a", "b", "c"), diff --git a/tests/testthat/test-key-columns.R b/tests/testthat/test-key-columns.R index d077174..145028b 100644 --- a/tests/testthat/test-key-columns.R +++ b/tests/testthat/test-key-columns.R @@ -65,3 +65,213 @@ test_that("factors and ordinary vectors are still accepted", { expect_equal(nrow(draw(d, design_systematic(interval = 2, order_by = "nu"), seed = 1)), 10) }) + +# A blank field read from a file arrives as "". It is a key value like any +# other, so a frame whose blank is relabelled "_", which sorts to the same +# place, must give the same probabilities and the same draw. +blank_frame <- function(blank = "") { + data.frame( + id = 1:30, + g = rep(c(blank, "a", "b"), each = 10), + v = c(seq(-20, 20, length.out = 10), seq(-1, 1, length.out = 10), + seq(-1, 1, length.out = 10)), + w = c(1000, rep(1:29)), + y = 1:30 + ) +} + +test_that("an empty-string stratum is a stratum like any other", { + d <- blank_frame() + ref <- blank_frame("_") + for (des in list( + design_stratified("g", n = 9), + design_stratified("g", n = 9, allocation = "neyman", allocation_by = "v", + min_per_stratum = 1), + design_certainty("w", threshold = 500, + rest = design_stratified("g", n = 6, min_per_stratum = 2)) + )) { + expect_equal(inclusion_prob(d, des), inclusion_prob(ref, des)) + expect_equal(joint_prob(d, des, rows = c(2, 3, 12)), + joint_prob(ref, des, rows = c(2, 3, 12))) + s <- draw(d, des, seed = 1, weights = TRUE) + expect_identical(s$id, draw(ref, des, seed = 1, weights = TRUE)$id) + expect_false(anyNA(s$.prob)) + expect_equal(ht_total(s, "y")$se, ht_total(draw(ref, des, seed = 1, + weights = TRUE), "y")$se) + } + # Neyman reads the blank stratum's spread, the largest of the three. + ney <- design_stratified("g", n = 9, allocation = "neyman", + allocation_by = "v", min_per_stratum = 1) + p <- inclusion_prob(d, ney) + expect_gt(p[1], p[11]) + expect_equal(sum(p), 9) +}) + +test_that("an empty-string cluster is a cluster like any other", { + d <- data.frame(id = 1:40, cl = rep(c("", "a", "b", "c"), each = 10), + y = 41:80) + ref <- d + ref$cl[ref$cl == ""] <- "_" + des <- design_multistage("cl", n_clusters = 2, n = 6) + expect_equal(inclusion_prob(d, des), rep(0.15, 40)) + expect_equal(joint_prob(d, des, rows = c(1, 2, 11)), + joint_prob(ref, des, rows = c(1, 2, 11))) + s <- draw(d, des, seed = 1, weights = TRUE) + expect_false(anyNA(s$.prob)) + expect_true(is.finite(ht_total(s, "y")$total)) + + cs <- draw(d, design_cluster("cl", n_clusters = 4), seed = 1, + weights = TRUE) + sm <- sample_summary(cs) + expect_equal(sm$by_group$group, c("(blank)", "a", "b", "c")) + expect_equal(sm$by_group$in_frame, rep(10L, 4)) + + cd <- design_cluster("cl", n_clusters = 2) + expect_equal(joint_prob(d, cd, rows = c(1, 2, 11)), + joint_prob(ref, cd, rows = c(1, 2, 11))) + for (seed in 1:3) { + s <- draw(d, cd, seed = seed, weights = TRUE) + r <- ht_total(s, "y") + expect_equal(r$method, "analytic") + expect_equal(r$se, ht_total(draw(ref, cd, seed = seed, weights = TRUE), + "y")$se) + } +}) + +test_that("a carriage return inside a key value cannot merge two strata", { + # Joined with a carriage return, ("x\ry", "z") and ("x", "y\rz") read the + # same. Keyed on codes, they stay two strata of ten. + d <- data.frame(id = 1:20, a = rep(c("x\ry", "x"), each = 10), + b = rep(c("z", "y\rz"), each = 10)) + des <- design_stratified(c("a", "b"), n = 4, allocation = "equal") + expect_equal(inclusion_prob(d, des), rep(0.2, 20)) + s <- draw(d, des, seed = 1) + expect_equal(as.vector(table(s$a)), c(2L, 2L)) +}) + +test_that("blank values are shown as (blank) and columns joined with ' . '", { + d <- data.frame(a = c("", "x", "x"), b = c("p", "", "q")) + expect_equal(drawn:::group_label(levels(drawn:::group_key(d, c("a", "b")))), + c("(blank) . p", "x . (blank)", "x . q")) +}) + +test_that("keys follow factor levels and byte order, not the locale", { + d <- data.frame(ch = c("b", "a", "B", "_"), + f = factor(c("lo", "hi", "lo", "mid"), + levels = c("lo", "mid", "hi")), + n = c(10, 2, 1, 2)) + expect_equal(levels(drawn:::group_key(d, "ch")), c("B", "_", "a", "b")) + expect_equal(levels(drawn:::group_key(d, "f")), c("lo", "mid", "hi")) + expect_equal(levels(drawn:::group_key(d, "n")), c("1", "2", "10")) + with_other_collation( + expect_equal(levels(drawn:::group_key(d, "ch")), c("B", "_", "a", "b")) + ) +}) + +test_that("many nested strata are keyed in time linear in the rows", { + skip_on_cran() + # 2,000 counties by 20,000 tracts is 40 million combinations, of which + # 20,000 occur. Crossing every level ran out of memory. + tract <- rep(seq_len(20000), each = 2) + d <- data.frame(county = sprintf("C%04d", tract %% 2000), + tract = sprintf("T%05d", tract)) + des <- design_stratified(c("county", "tract"), n = 20000, + min_per_stratum = 1) + took <- system.time({ + key <- drawn:::group_key(d, c("county", "tract")) + p <- inclusion_prob(d, des) + })[["elapsed"]] + expect_equal(nlevels(key), 20000L) + expect_equal(p, rep(0.5, 40000)) + expect_lt(took, 20) +}) + +test_that("an unmarked and a UTF-8 cluster label with the same bytes are one", { + # In the C locale match() told them apart, so selection counted one + # cluster as two while sample_summary() keyed them as one stratum. + plain <- "Z\xc3\xbcrich" + marked <- plain + Encoding(marked) <- "UTF-8" + d <- data.frame(id = 1:27, cl = rep(c(plain, marked, "Bern", "Basel"), + times = c(4, 5, 9, 9))) + run <- function() { + list(codes = drawn:::cluster_codes(d$cl), + pi = inclusion_prob(d, design_cluster("cl", n_clusters = 2))) + } + for (utf8 in c(FALSE, TRUE)) { + out <- with_ctype(run(), utf8 = utf8) + expect_identical(out$codes, rep(1:3, each = 9)) + expect_equal(out$pi, rep(2 / 3, 27)) + } +}) + +test_that("text of unknown encoding is keyed by its bytes", { + # read.csv() and readLines() leave text unmarked unless told the file's + # encoding. A radix sort refuses unmarked non-ASCII text, which stopped + # every grouped or ordered path. ASCII stand-ins that sort the same way + # give the same rows. + site <- c("Z\xc3\xbcrich", "Bern", "Gen\xc3\xa8ve", "Basel") + Encoding(site) <- "unknown" + plain <- c("Zurich", "Bern", "Geneve", "Basel") + sizes <- c(7, 11, 9, 13) + d <- data.frame(id = 1:40, site = rep(site, times = sizes), + y = (1:40 * 7) %% 23) + a <- d + a$site <- rep(plain, times = sizes) + keyed <- site[c(4, 2, 3, 1)] + strat <- design_stratified("site", n = 10) + walk <- design_systematic(interval = 4, order_by = "site") + run <- function(data) { + s <- draw(data, strat, seed = 1, weights = TRUE) + cs <- draw(data, design_cluster("site", n_clusters = 2), seed = 1, + weights = TRUE) + list(levels = levels(drawn:::group_key(data, "site")), + strat = s$id, + pi = inclusion_prob(data, strat), + walk = draw(data, walk, seed = 2)$id, + by = ht_total(s, "y", by = "site")$site, + by_se = ht_total(s, "y", by = "site")$se, + level = ht_mean(s, "site")$level, + groups = sample_summary(cs)$by_group$group, + se = ht_total(s, "y")$se) + } + out <- run(d) + expect_identical(out$levels, keyed) + expect_identical(out$by, keyed) + expect_identical(out$level, keyed) + ref <- run(a) + expect_identical(out$groups, keyed[match(ref$groups, plain[c(4, 2, 3, 1)])]) + for (part in c("strat", "pi", "walk", "by_se", "se")) { + expect_identical(out[[part]], ref[[part]], label = part) + } + expect_identical(with_other_collation(run(d)), out) + + skip_if_not_installed("survey") + s <- draw(d, strat, seed = 1, weights = TRUE) + expect_equal(survey::SE(survey::svytotal(~y, as_svydesign(s)))[[1]], + out$se) + + # read.csv() of a Windows-1252 file in a UTF-8 session gives Latin-1 + # bytes, which are not valid UTF-8. Labels are made from them by byte. + latin <- c("Z\xfcrich", "Bern", "Gen\xe8ve", "Basel") + l <- d + l$site <- rep(latin, times = sizes) + keyed <- latin[c(4, 2, 3, 1)] + with_ctype({ + s <- draw(l, strat, seed = 1, weights = TRUE) + expect_identical(s$id, out$strat) + tot <- ht_total(s, "y", by = "site") + expect_identical(tot$site, keyed) + expect_identical(tot$se, out$by_se) + expect_identical(ht_mean(s, "site")$level, keyed) + expect_output(print(ht_mean(s, "y", by = "site")), "Basel", + useBytes = TRUE) + cs <- draw(l, design_cluster("site", n_clusters = 2), seed = 1, + weights = TRUE) + expect_output(print(sample_summary(cs)), "in frame", useBytes = TRUE) + svy <- as_svydesign(s) + expect_equal(survey::SE(survey::svytotal(~y, svy))[[1]], out$se) + by_svy <- survey::svyby(~y, ~site, svy, survey::svytotal) + expect_equal(unname(by_svy$se[match(keyed, by_svy$site)]), tot$se) + }) +}) diff --git a/tests/testthat/test-plan.R b/tests/testthat/test-plan.R index 604b54d..f46a41d 100644 --- a/tests/testthat/test-plan.R +++ b/tests/testthat/test-plan.R @@ -1,5 +1,5 @@ test_that("plan_size delivers the margin it promises, for a mean", { - set.seed(3030) + local_seed(3030) N <- 20000 pop <- data.frame(id = 1:N, y = stats::rnorm(N, 100, 40)) truth <- mean(pop$y) @@ -14,7 +14,7 @@ test_that("plan_size delivers the margin it promises, for a mean", { }) test_that("plan_size delivers the margin it promises, for a proportion", { - set.seed(4040) + local_seed(4040) N <- 20000 pop <- data.frame(id = 1:N, y = stats::rbinom(N, 1, 0.45)) truth <- mean(pop$y) @@ -104,6 +104,605 @@ test_that("printing a plan states the number and the assumptions behind it", { expect_true(any(grepl("deff 2.5", out, fixed = TRUE))) }) +test_that("plan_size gives the smallest size that meets the margin", { + z <- stats::qnorm(0.975) + # The smallest n whose variance meets (margin / z)^2, found by trying every + # size the frame allows, and never below two rows. + smallest <- function(N, ratio) { + n <- seq_len(N) + ok <- ratio(n) <= 1 + 1e-12 + n <- if (any(ok)) min(n[ok]) else N + if (N >= 2) max(n, 2) else n + } + for (N in c(3, 7, 10, 25, 60)) { + for (m in c(5, 8.4, 12.5, 20, 40)) { + mean_n <- smallest(N, function(n) (1 / n - 1 / N) * 40^2 / (m / z)^2) + expect_equal(plan_size(margin = m, sd = 40, N = N)$n, mean_n, + info = paste("mean", N, m)) + total_n <- smallest(N, function(n) { + N^2 * (1 / n - 1 / N) * 2 * 40^2 / (m * N / z)^2 + }) + expect_equal(plan_size(margin = m * N, sd = 40, N = N, deff = 2, + target = "total")$n, total_n, + info = paste("total", N, m)) + } + for (m in c(0.05, 0.1, 0.2, 0.4)) { + for (p in c(0.1, 0.5)) { + prop_n <- smallest(N, function(n) { + p * (1 - p) / n * (N - n) / (N - 1) / (m / z)^2 + }) + expect_equal(plan_size(margin = m, p = p, N = N, + target = "proportion")$n, prop_n, + info = paste("proportion", N, m, p)) + } + } + } +}) + +test_that("a margin that fewer rows than the frame meet is not a census", { + # With sd = 40, nine of ten rows meet a margin of 8.4. + z <- stats::qnorm(0.975) + expect_lte((1 / 9 - 1 / 10) * 40^2, (8.4 / z)^2) + p <- plan_size(margin = 8.4, sd = 40, N = 10) + expect_equal(p$n, 9) + expect_false(p$capped) + + # Nine rows do not meet a margin of 2, so only a census does. + expect_gt((1 / 9 - 1 / 10) * 40^2, (2 / z)^2) + cen <- plan_size(margin = 2, sd = 40, N = 10) + expect_equal(cen$n, 10) + expect_true(cen$capped) + expect_output(print(cen), "No sample smaller than the frame meets") +}) + +test_that("a census plan is capped and not short", { + cen <- plan_size(margin = 0.2, sd = 40, N = 300, response = 0.5) + expect_true(cen$capped) + expect_false(cen$short) + expect_equal(cen$n, 300) + expect_equal(cen$n_effective, 150) +}) + +test_that("non-response does not add a row through rounding", { + # 21 / 0.7 is 30.000000000000004 in floating point. + p <- plan_size(margin = 17.11, sd = 40, response = 0.7) + expect_equal(p$n_effective, 21) + expect_equal(p$n, 30) + + # Thirty rows at 70% response bring back the 21 needed, so the frame is + # not short. + q <- plan_size(margin = 10, sd = 40, N = 30, response = 0.7) + expect_equal(q$n, 30) + expect_equal(q$n_effective, 21) + expect_false(q$short) + expect_false(q$capped) + expect_false(any(grepl("more rows than the frame holds", + utils::capture.output(print(q)), fixed = TRUE))) +}) + +test_that("a fractional N gives a whole n that draw() accepts", { + p <- plan_size(margin = 0.01, sd = 40, N = 240.5) + expect_equal(p$n, 240) + expect_true(p$capped) + s <- draw(data.frame(id = 1:240), design_simple(n = p$n), seed = 1) + expect_equal(nrow(s), 240) + expect_output(print(p), "N 240.5", fixed = TRUE) + + # An estimated N plans a total as a whole one would, below the cap. + expect_equal(plan_size(margin = 5000, sd = 40, N = 2400.4, + target = "total")$n, + ceiling(2400.4 / (1 + 2400.4 / + (stats::qnorm(0.975) * 40 * 2400.4 / + 5000)^2))) + + expect_error(plan_size(margin = 1000, sd = 40, N = 0.5), + "`N` is 0.5, and a frame holds at least one row") + expect_error(plan_size(margin = 5, sd = 40, N = 1e-9), "at least one row") + expect_equal(plan_size(margin = 5, sd = 40, N = 1)$n, 1) +}) + +test_that("a size too large for a number gives a census or a clear error", { + p <- plan_size(margin = 1e-300, sd = 40, N = 240) + expect_equal(p$n, 240) + expect_true(p$capped) + # The margin prints in scientific notation rather than as 300 digits. + expect_output(print(p), "+/- 1e-300 at 95% confidence", fixed = TRUE) + expect_equal(plan_size(margin = 5, sd = 40, N = 240, deff = 1e308)$n, 240) + expect_equal(plan_size(margin = 5, sd = 1e300, N = 240)$n, 240) + expect_equal(plan_size(margin = 5, sd = 40, N = 240, level = 1 - 1e-16)$n, + 240) + expect_equal(plan_size(margin = 0.03, N = 240, level = 1 - 1e-16, + target = "proportion")$n, 240) + # Where R has no extended precision, as on Apple silicon, the literal + # 1e-300 parses as 9.99999999999999e-301, and the message shows that. + expect_error(plan_size(margin = 1e-300, sd = 40), + "`margin` = (1e-300|9\\.9+e-301) with a spread of 40") + expect_error(plan_size(margin = 1e-300, sd = 40), "finite `N`") + expect_error(plan_size(margin = 5, sd = 40, level = 1 - 1e-16), + "lower `level`") +}) + +test_that("a plan has two rows at least, the fewest that give a variance", { + p <- plan_size(margin = 80, sd = 40) + expect_equal(p$n, 2) + expect_equal(p$n_effective, 2) + expect_true(p$raised) + expect_output(print(p), "interval need\\s+two") + expect_false(plan_size(margin = 5, sd = 40)$raised) + + # A proportion margin close to 1 would have asked for one row. + expect_equal(plan_size(margin = 0.99, target = "proportion")$n, 2) + + two <- plan_size(margin = 80, sd = 40, N = 2) + expect_equal(two$n, 2) + expect_false(two$capped) + expect_equal(plan_size(margin = 80, sd = 40, N = 1)$n, 1) + expect_equal(plan_size(margin = 80, sd = 40, response = 0.5)$n, 4) +}) + +test_that("an argument the target does not use is ignored with a warning", { + expect_warning( + a <- plan_size(margin = 0.05, sd = 0.1, target = "proportion"), + class = "drawn_irrelevant_argument") + expect_equal(a$n, plan_size(margin = 0.05, target = "proportion")$n) + expect_warning(plan_size(margin = 0.05, sd = 0.1, target = "proportion"), + "`sd` is not used") + + expect_warning(b <- plan_size(margin = 5, sd = 40, p = 7), + class = "drawn_irrelevant_argument") + expect_equal(b$n, plan_size(margin = 5, sd = 40)$n) + expect_warning(plan_size(margin = 5e4, sd = 40, p = 0.2, N = 2e4, + target = "total"), + "`p` is not used for target = \"total\"") + + expect_error(plan_size(margin = 0.03, p = 0.2), + "use target = \"proportion\"", fixed = TRUE) + expect_error(plan_size(margin = 5), + "plausible range divided by four.$") + + expect_silent(plan_size(margin = 0.03, p = 0.2, target = "proportion")) + expect_silent(plan_size(margin = 5, sd = 40)) +}) + +test_that("a proportion margin of 1 or more is refused", { + expect_error(plan_size(margin = 5, N = 20000, target = "proportion"), + "such as 0.05 for 5 percentage points", fixed = TRUE) + expect_error(plan_size(margin = 1, target = "proportion"), + "0.01 for 1 percentage point.", fixed = TRUE) + expect_equal(plan_size(margin = 0.03, target = "proportion")$n, + plan_size(margin = 0.03, p = 0.5, target = "proportion")$n) +}) + +test_that("a proportion plan prints and returns p", { + p <- plan_size(margin = 0.03, p = 0.1, N = 20000, target = "proportion") + expect_equal(p$p, 0.1) + expect_output(print(p), "assuming p 0.1, N 20,000", fixed = TRUE) + m <- plan_size(margin = 5, sd = 40, N = 20000) + expect_true(is.na(m$p)) + expect_output(print(m), "assuming sd 40, N 20,000", fixed = TRUE) +}) + +test_that("deff takes the estimate it came from, of the kind target plans", { + pop <- data.frame(id = 1:400, cl = rep(paste0("c", 1:40), each = 10)) + pop$y <- rep(seq(10, 49), each = 10) + rep(c(-2, 2), 200) + pilot <- draw(pop, design_cluster("cl", n_clusters = 6), seed = 1, + weights = TRUE) + m <- ht_mean(pilot, "y") + tot <- ht_total(pilot, "y") + expect_true(is.finite(deff(m))) + expect_true(is.finite(deff(tot))) + + expect_equal(plan_size(margin = 3, sd = 10, N = 400, deff = m), + plan_size(margin = 3, sd = 10, N = 400, deff = deff(m))) + expect_equal(plan_size(margin = 3, sd = 10, N = 400, deff = m)$deff, + deff(m)) + expect_equal(plan_size(margin = 1200, sd = 10, N = 400, deff = tot, + target = "total")$deff, deff(tot)) + expect_equal(plan_size(margin = 0.1, N = 400, deff = m, + target = "proportion")$deff, deff(m)) + + expect_error(plan_size(margin = 1200, sd = 10, N = 400, deff = m, + target = "total"), + "Pass ht_total() on the same pilot", fixed = TRUE) + expect_error(plan_size(margin = 3, sd = 10, N = 400, deff = tot), + "Pass ht_mean() on the same pilot", fixed = TRUE) + expect_error(plan_size(margin = 0.1, N = 400, deff = tot, + target = "proportion"), + "`target` is \"proportion\"", fixed = TRUE) + + none <- ht_mean(pilot, "y", variance = "none") + expect_error(plan_size(margin = 3, sd = 10, N = 400, deff = none), + "design effect of NA") + expect_error(plan_size(margin = 3, sd = 10, deff = NA), + "`deff` is NA, which deff() gives", fixed = TRUE) + expect_error(plan_size(margin = 3, sd = 10, deff = NA_real_), + "`deff` is NA", fixed = TRUE) + expect_error(plan_size(margin = 3, sd = 10, + deff = ht_mean(pilot, "y", by = "cl")), + "without `by`", fixed = TRUE) + + # A mean over the rows with `y` has a standard error but no design effect. + pilot$ym <- pilot$y + pilot$ym[c(2, 5)] <- NA + part <- ht_mean(pilot, "ym", na_rm = TRUE) + expect_true(is.finite(part$se)) + expect_true(is.na(deff(part))) + expect_error(plan_size(margin = 3, sd = 10, N = 400, deff = part), + "which ht_mean(na_rm = TRUE) gives when `y` is missing", + fixed = TRUE) + expect_error(plan_size(margin = 3, sd = 10, N = 400, deff = deff(part)), + "for a mean from ht_mean(na_rm = TRUE)", fixed = TRUE) + + # A number with a class, such as a survey estimate, is refused. + fake <- structure(c(y = 30), class = "svystat", deff = 2) + expect_error(plan_size(margin = 3, sd = 10, N = 400, deff = fake), + "`deff` is a `svystat`, whose value is the survey estimate", + fixed = TRUE) + expect_error(plan_size(margin = 3, sd = 10, N = 400, deff = fake), + "survey::deff() reads the design effect", fixed = TRUE) + expect_error(plan_size(margin = 3, sd = 10, N = 400, + deff = structure(2, class = "other")), + "`deff` is an `other`. Give a design effect", fixed = TRUE) + # I() marks a plain number. + expect_equal(plan_size(margin = 3, sd = 10, N = 400, deff = I(2)), + plan_size(margin = 3, sd = 10, N = 400, deff = 2)) + expect_equal(plan_size(margin = 3, sd = 10, N = 400, deff = I(c(1, 2)))$n, + plan_size(margin = 3, sd = 10, N = 400, deff = c(1, 2))$n) + skip_if_not_installed("survey") + sm <- survey::svymean(~y, as_svydesign(pilot), deff = TRUE) + expect_error(plan_size(margin = 3, sd = 10, N = 400, deff = sm), + "`deff` is a `svystat`") + expect_equal(plan_size(margin = 3, sd = 10, N = 400, + deff = unname(survey::deff(sm)))$deff, + unname(survey::deff(sm))) +}) + +test_that("plan_size meets the margin at a small N, where the correction bites", { + skip_on_cran() + N <- 60 + pop <- data.frame(id = seq_len(N), + y = 100 + 40 * stats::qnorm(stats::ppoints(N))) + truth <- mean(pop$y) + p <- plan_size(margin = 8, sd = stats::sd(pop$y), N = N) + # Without the correction the plan would be more than the frame. + expect_gt(plan_size(margin = 8, sd = stats::sd(pop$y))$n, N) + expect_lt(p$n, N) + hit <- vapply(seq_len(500), function(i) { + s <- draw(pop, design_simple(n = p$n), seed = i, weights = TRUE) + abs(ht_mean(s, "y", variance = "none")$mean - truth) <= 8 + }, logical(1)) + expect_gt(mean(hit), 0.92) + expect_lt(mean(hit), 0.99) +}) + +test_that("plan_size meets a margin on a total", { + skip_on_cran() + N <- 400 + pop <- data.frame(id = seq_len(N), + y = exp(3 + 0.5 * stats::qnorm(stats::ppoints(N)))) + truth <- sum(pop$y) + M <- 0.04 * truth + p <- plan_size(margin = M, sd = stats::sd(pop$y), N = N, target = "total") + expect_lt(p$n, N) + hit <- vapply(seq_len(500), function(i) { + s <- draw(pop, design_simple(n = p$n), seed = 1000 + i, weights = TRUE) + abs(ht_total(s, "y", variance = "none")$total - truth) <= M + }, logical(1)) + expect_gt(mean(hit), 0.92) + expect_lt(mean(hit), 0.99) +}) + +# ---- stratified plans, cluster design effects, several plans -------------- + +test_that("a stratified Neyman plan matches the closed form", { + st <- data.frame(site = c("a", "b"), N = c(120, 120), sd = c(30, 40)) + p <- plan_size(margin = 5, strata = st, allocation = "neyman") + z <- stats::qnorm(0.975) + W <- st$N / sum(st$N) + # Cochran (1977), 5.25 with the finite population correction. + closed <- ceiling(sum(W * st$sd)^2 / + ((5 / z)^2 + sum(W * st$sd^2) / sum(st$N))) + expect_equal(closed, 105) + expect_equal(p$n, 105) + # Neyman shares of 30 : 40 split 105 into 45 and 60 exactly. + expect_equal(p$allocation, data.frame(site = c("a", "b"), n = c(45L, 60L))) + v <- function(n_h) sum(W^2 * (1 / n_h - 1 / st$N) * st$sd^2) + expect_lte(v(c(45, 60)), (5 / z)^2) + # Neither split of 104 rows meets the margin. + expect_gt(v(c(45, 59)), (5 / z)^2) + expect_gt(v(c(44, 60)), (5 / z)^2) + expect_equal(p$rule, "neyman") + expect_equal(p$min_per_stratum, 2L) + expect_false(p$raised) + expect_true(is.na(p$spread)) + expect_equal(p$N, 240) +}) + +test_that("a stratified plan takes the smallest n whose split meets the margin", { + # Largest-remainder splits of n over strata of 15, 5 and 18 rows: + # 26 -> 10.26, 3.42, 12.32 -> 10, 4, 12 + # 27 -> 10.66, 3.55, 12.79 -> 11, 3, 13 + # One more row takes a row from the stratum that varies most, so 26 rows + # meet a margin of 1.3 and 27 do not. + st <- data.frame(g = c("a", "b", "c"), N = c(15, 5, 18), sd = c(6, 9, 5)) + z <- stats::qnorm(0.975) + W <- st$N / 38 + v <- function(n_h) sum(W^2 * (1 / n_h - 1 / st$N) * st$sd^2) + expect_lte(v(c(10, 4, 12)), (1.3 / z)^2) + expect_gt(v(c(11, 3, 13)), (1.3 / z)^2) + p <- plan_size(margin = 1.3, strata = st) + expect_equal(p$n, 26) + expect_equal(p$allocation$n, c(10L, 4L, 12L)) + # No smaller total meets it. + smaller <- vapply(6:25, function(n) { + v(drawn:::allocate(n, st$N, "proportional", 2L)) + }, numeric(1)) + expect_true(all(smaller > (1.3 / z)^2)) +}) + +test_that("a plan with one stratum is the plan without strata", { + for (N in c(7, 25, 60, 240)) { + one <- function(...) data.frame(g = "all", N = N, ...) + for (m in c(5, 8.4, 12.5, 20, 40)) { + expect_equal(plan_size(margin = m, strata = one(sd = 40))$n, + plan_size(margin = m, sd = 40, N = N)$n, + info = paste("mean", N, m)) + expect_equal(plan_size(margin = m * N, strata = one(sd = 40), + deff = 2, response = 0.7, target = "total")$n, + plan_size(margin = m * N, sd = 40, N = N, deff = 2, + response = 0.7, target = "total")$n, + info = paste("total", N, m)) + } + for (m in c(0.05, 0.1, 0.2)) { + expect_equal(plan_size(margin = m, strata = one(p = 0.3), + target = "proportion")$n, + plan_size(margin = m, p = 0.3, N = N, + target = "proportion")$n, + info = paste("proportion", N, m)) + } + } +}) + +test_that("a stratified plan draws as planned", { + bands <- data.frame(band = c("small", "medium", "large"), + N = c(120, 60, 20), sd = c(5, 12, 40)) + p <- plan_size(margin = 2, strata = bands, allocation = "neyman", + response = 0.8) + expect_equal(p$n, ceiling(p$n_needed / 0.8 - 1e-9)) + expect_equal(sum(p$allocation$n), p$n) + frame <- data.frame(id = 1:200, band = rep(bands$band, times = bands$N)) + s <- draw(frame, design_stratified("band", allocation = p$allocation), + seed = 1, weights = TRUE) + expect_equal(nrow(s), p$n) + expect_equal(as.vector(table(factor(s$band, bands$band))), p$allocation$n) + + # The design splits the plan's n the same way under the same rule. + again <- design_stratified("band", n = p, allocation = "neyman", + allocation_by = c(small = 5, medium = 12, + large = 40), + min_per_stratum = 2) + tab <- allocation_table(frame, again) + expect_equal(tab$n[match(bands$band, tab$band)], p$allocation$n) +}) + +test_that("a stratified plan prints its strata", { + st <- data.frame(site = c("a", "b"), N = c(120, 120), sd = c(30, 40)) + p <- plan_size(margin = 5, strata = st, allocation = "neyman", deff = 1.5) + out <- utils::capture.output(print(p)) + expect_equal(out[1], "Sample size for a mean, over 2 strata") + expect_true(any(grepl(paste0("assuming Neyman allocation, at least ", + "2 rows per stratum, deff 1.5, N 240"), + out, fixed = TRUE))) + expect_true(any(grepl("site N sd n", out, fixed = TRUE))) + many <- data.frame(g = sprintf("g%02d", 1:12), N = 50, sd = 10) + expect_output(print(plan_size(margin = 1, strata = many)), + "and 2 more strata, all in `$allocation`", fixed = TRUE) +}) + +test_that("plan_size checks the strata it is given", { + st <- data.frame(site = c("a", "b"), N = c(120, 120), sd = c(30, 40)) + expect_error(plan_size(margin = 5, strata = list(1)), + "`strata` must be a data frame") + expect_error(plan_size(margin = 5, strata = st[c("site", "N")]), + "`strata` needs a column `sd`") + expect_error(plan_size(margin = 0.05, strata = st, target = "proportion"), + "`strata` needs a column `p`") + expect_error(plan_size(margin = 5, strata = transform(st, n = 1)), + "`strata` has a column `n`") + expect_error(plan_size(margin = 5, strata = st[c("N", "sd")]), + "no column naming the strata") + expect_error(plan_size(margin = 5, strata = transform(st, N = c(0, 5))), + "stratum `a` has 0") + expect_error(plan_size(margin = 5, strata = transform(st, N = c(10.5, 5))), + "whole numbers of 1 or more") + expect_error(plan_size(margin = 5, strata = transform(st, sd = c(-1, 5))), + "standard deviations in `strata`") + expect_error(plan_size(margin = 0.05, target = "proportion", + strata = data.frame(g = 1:2, N = 10, p = c(0.2, 2))), + "stratum `2` has 2") + expect_error(plan_size(margin = 5, strata = transform(st, cost = 1)), + "applies only to allocation = \"neyman\"") + expect_error(plan_size(margin = 5, strata = rbind(st, st)), + "more than once") + expect_error(plan_size(margin = 5, strata = st, allocation = "optimal"), + "`allocation` must be one of") + expect_error(plan_size(margin = 5, strata = st, min_per_stratum = -1), + "`min_per_stratum` must be non-negative") + + expect_warning(plan_size(margin = 5, strata = st, sd = 40), + "`sd` is not used with `strata`") + expect_warning(plan_size(margin = 5, strata = st, N = 240), + class = "drawn_irrelevant_argument") + expect_warning(plan_size(margin = 5, strata = st, sd = 40, p = 0.3, + N = 240), + "`sd`, `p` and `N` are not used with `strata`", fixed = TRUE) + expect_warning(plan_size(margin = 5, strata = transform(st, p = 0.5)), + "has a `p` column, which target = \"mean\" does not use") + expect_warning(plan_size(margin = 5, sd = 40, allocation = "neyman"), + "`allocation` is not used without `strata`") + + # Costs enter a Neyman split as N_h * S_h / sqrt(c_h): 3600 and 1200, so + # the first stratum gets three rows for each one the second gets. + costly <- plan_size(margin = 5, allocation = "neyman", + strata = transform(st, cost = c(1, 16))) + expect_equal(costly$strata$cost, c(1, 16)) + expect_lte(abs(costly$allocation$n[1] - 3 * costly$allocation$n[2]), 3) + expect_gt(costly$n, plan_size(margin = 5, allocation = "neyman", + strata = st)$n) + + # A spread too large to square takes its stratum whole. + huge <- plan_size(margin = 5, allocation = "neyman", + strata = data.frame(g = 1:2, N = 10, sd = c(1e300, 1))) + expect_equal(huge$allocation$n, c(10L, 2L)) + # A floor of one row gives the one-row stratum its row at once, and the + # variance is 0 at any split that reaches every stratum. + bare <- plan_size(margin = 5, min_per_stratum = 1, + strata = data.frame(g = 1:2, N = c(1, 10), sd = c(3, 0))) + expect_equal(bare$allocation$n, c(1L, 1L)) + expect_output(print(bare), paste0("assuming proportional allocation, ", + "at least 1 row per stratum, N 11"), + fixed = TRUE) +}) + +test_that("a stratified plan needs a floor of one row a stratum", { + # Without a floor, proportional allocation gives the one-row stratum its + # first row only at about half the frame, so the plan would be that size. + st <- data.frame(g = c("a", "b"), N = c(1, 2e5), sd = c(10, 10)) + expect_error(plan_size(margin = 2, strata = st, min_per_stratum = 0), + "`min_per_stratum` is 0, which lets the split give a small") + expect_error(plan_size(margin = 2, strata = st, min_per_stratum = 0), + "Use 1 or more", fixed = TRUE) + one <- plan_size(margin = 2, strata = st, min_per_stratum = 1) + expect_equal(one$allocation$n, c(1L, one$n - 1L)) + expect_lte(abs(one$n - plan_size(margin = 2, sd = 10, N = 2e5 + 1)$n), 2) + # Neyman allocation gives a stratum with no spread its floor. + flat <- plan_size(margin = 1, allocation = "neyman", min_per_stratum = 1, + strata = data.frame(g = c("a", "b"), N = c(100, 2e5), + sd = c(0, 10))) + expect_equal(flat$allocation$n[1], 1L) + expect_lt(flat$n, 1000) +}) + +test_that("a frame in strata given as vectors points to `strata`", { + expect_error(plan_size(margin = 5, sd = c(a = 30, b = 40), + N = c(a = 120, b = 120)), + "give each stratum's `N` and `sd` in `strata`") +}) + +test_that("deff_cluster gives Kish's design effect", { + expect_equal(deff_cluster(10, 0.05), 1.45) + expect_equal(deff_cluster(1, 0.9), 1) + expect_equal(deff_cluster(c(5, 10, 20), 0.05), c(1.2, 1.45, 1.95)) + expect_equal(deff_cluster(11, -0.1), 0) + expect_equal(plan_size(margin = 5, sd = 40, N = 20000, + deff = deff_cluster(10, 0.05)), + plan_size(margin = 5, sd = 40, N = 20000, deff = 1.45)) + expect_error(deff_cluster(0.5, 0.1), "`m` must be the rows taken") + expect_error(deff_cluster(NA, 0.1), "`m` must be") + expect_error(deff_cluster(10, 1.5), "between -1 / \\(m - 1\\) and 1") + expect_error(deff_cluster(10, -0.2), "below -0.111") + expect_error(deff_cluster(10, "0.1"), "`icc` must be a finite number") + expect_error(deff_cluster(c(5, 10), c(0.1, 0.2, 0.3)), + "`m` has 2 values and `icc` has 3") +}) + +test_that("every design takes a plan as `n`", { + p <- plan_size(margin = 5, sd = 40, N = 240) + expect_equal(p$n, 122) + expect_equal(design_simple(n = p)$n, 122L) + expect_equal(design_simple(p)$n, 122L) + expect_equal(design_stratified("g", n = p)$n, 122L) + expect_equal(design_systematic(n = p)$n, 122L) + expect_equal(design_multistage("cl", n_clusters = 2, n = p)$n, 122L) + expect_equal(design_weighted("w", n = p)$n, 122L) + expect_equal(design_weighted("w", n = p, method = "systematic", + strata = "g")$n, 122L) + expect_equal(design_spread("x", n = p)$n, 122L) + expect_equal(design_spread("x", n = p, strata = "g")$n, 122L) + expect_equal(design_reservoir(n = p)$n, 122L) + expect_equal(design_bootstrap(10, n = p)$n, 122L) + s <- draw(data.frame(id = 1:240), design_simple(n = p), seed = 1) + expect_equal(nrow(s), 122) + # Only `n` takes a plan. + expect_error(design_multistage("cl", n_clusters = p, n = 10), + "`n_clusters` must be a single whole number") + expect_error(design_simple(n = plan_size(margin = c(3, 5), sd = 40)), + "`n` must be a single whole number") +}) + +test_that("a design inside a region takes a plan as `n`", { + skip_if_not_installed("sf") + p <- plan_size(margin = 5, sd = 40, N = 240) + expect_equal(design_spatial(c("lon", "lat"), wide_poly(), n = p)$n, 122L) +}) + +test_that("plan_size plans several margins at once", { + out <- plan_size(margin = c(3, 5, 10), sd = 40, N = 240) + expect_s3_class(out, "data.frame") + expect_equal(nrow(out), 3) + each <- lapply(c(3, 5, 10), function(m) plan_size(margin = m, sd = 40, + N = 240)) + expect_equal(out$n, vapply(each, `[[`, numeric(1), "n")) + expect_equal(out, do.call(rbind, lapply(each, as.data.frame))) + + # One value is used for every plan; several are paired by position. + two <- plan_size(margin = 5, sd = c(30, 40), deff = c(1, 2), N = 240) + expect_equal(two$n, c(plan_size(margin = 5, sd = 30, N = 240)$n, + plan_size(margin = 5, sd = 40, N = 240, deff = 2)$n)) + props <- plan_size(margin = 0.05, p = c(0.1, 0.5), response = c(1, 0.5), + target = "proportion") + expect_equal(props$n, + c(plan_size(margin = 0.05, p = 0.1, target = "proportion")$n, + plan_size(margin = 0.05, p = 0.5, response = 0.5, + target = "proportion")$n)) + expect_equal(props$p, c(0.1, 0.5)) + + expect_error(plan_size(margin = c(3, 5, 10), sd = c(30, 40), N = 240), + "`margin` has 3 values and `sd` has 2") + expect_error(plan_size(margin = c(3, -5), sd = 40), + "`margin` must be a positive number, or a vector of them") + expect_error(plan_size(margin = c(0.03, 3), target = "proportion"), + "`margin` is 3, and a proportion") + expect_error(plan_size(margin = 3, sd = 40, deff = c(1, NA)), + "`deff` holds an NA") + + # An argument the target does not use is warned about once. + seen <- 0L + withCallingHandlers( + plan_size(margin = c(0.03, 0.05), sd = 1, target = "proportion"), + drawn_irrelevant_argument = function(w) { + seen <<- seen + 1L + invokeRestart("muffleWarning") + }) + expect_equal(seen, 1L) + + st <- data.frame(site = c("a", "b"), N = c(120, 120), sd = c(30, 40)) + sp <- plan_size(margin = c(5, 10), strata = st) + expect_equal(sp$n, c(plan_size(margin = 5, strata = st)$n, + plan_size(margin = 10, strata = st)$n)) + expect_equal(sp$strata, c(2L, 2L)) + expect_equal(sp$rule, c("proportional", "proportional")) +}) + +test_that("a plan turns into a data frame of one row", { + p <- plan_size(margin = 5, sd = 40, N = 240, response = 0.7) + df <- as.data.frame(p) + expect_equal(names(df), c("n", "n_effective", "margin", "level", "N", + "deff", "response", "target", "spread", "p", + "capped", "short", "raised", "n_needed")) + expect_equal(nrow(df), 1) + expect_equal(df$n, p$n) + expect_equal(df$target, "mean") + expect_equal(row.names(as.data.frame(p, row.names = "plan")), "plan") + + st <- data.frame(site = c("a", "b"), N = c(120, 120), sd = c(30, 40)) + sdf <- as.data.frame(plan_size(margin = 5, strata = st, + allocation = "neyman")) + expect_equal(sdf$strata, 2L) + expect_equal(sdf$rule, "neyman") + expect_equal(sdf$min_per_stratum, 2L) +}) + # ---- sample_summary -------------------------------------------------------- test_that("sample_summary counts what was drawn against what was there", { @@ -146,6 +745,21 @@ test_that("rows the design can never reach are counted", { expect_output(print(sample_summary(s)), "unreachable rows") }) +test_that("the sampling fraction is over the rows the design can reach", { + pop <- data.frame( + id = 1:200, + ts = seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "hour", + length.out = 200) + ) + des <- design_temporal("ts", from = "2024-01-01", to = "2024-01-07", + interval = 1, per_interval = 2, unit = "days") + x <- sample_summary(draw(pop, des, seed = 1, weights = TRUE)) + expect_equal(x$N, 200) + expect_equal(x$N_reachable, 144) + expect_output(print(x), "sampling fraction 0.0833 (of the 144 reachable", + fixed = TRUE) +}) + test_that("a design with no grouping reports no group table", { pop <- data.frame(id = 1:100) s <- draw(pop, design_simple(n = 20), seed = 1, weights = TRUE) @@ -163,6 +777,21 @@ test_that("sample_summary reports on a cluster design by cluster", { expect_true(all(x$by_group$rate == 1)) }) +test_that("sample_summary counts groups from the frame, not the sample", { + pop <- data.frame(id = 1:200, cl = rep(paste0("c", 1:20), each = 10), + site = rep(c("a", "b"), times = c(150, 50))) + s <- draw(pop, design_cluster("cl", n_clusters = 4), seed = 1, weights = TRUE) + want <- sample_summary(s)$by_group + gone <- s + gone$cl <- NULL + expect_equal(sample_summary(gone)$by_group, want) + st <- draw(pop, design_stratified("site", n = 40), seed = 1, weights = TRUE) + recoded <- st + recoded$site <- "z" + expect_equal(sample_summary(recoded)$by_group, + sample_summary(st)$by_group) +}) + test_that("sample_summary needs a sample carrying its design", { pop <- data.frame(id = 1:100) expect_error(sample_summary(draw(pop, design_simple(n = 10), seed = 1)), @@ -210,3 +839,179 @@ test_that("the frame caps the analysable size, not just the draw", { expect_false(q$capped) expect_equal(q$n, ceiling(q$n_effective / 0.5)) }) + +test_that("sample_summary refuses a subset and explains a lost design", { + pop <- data.frame(id = 1:400, + site = rep(c("a", "b", "c", "d"), times = c(200, 100, 60, 40))) + s <- draw(pop, design_stratified("site", n = 40), seed = 1, weights = TRUE) + expect_equal(sample_summary(s[order(-s$id), ]), sample_summary(s)) + expect_error(sample_summary(s[s$site == "a", ]), "rows that were drawn") + merged <- merge(s, data.frame(id = s$id, resp = 1), by = "id") + expect_error(sample_summary(merged), "does not carry its design") + expect_error(sample_summary(merged), "transform()", fixed = TRUE) +}) + +test_that("a plan prints a round margin in full", { + out <- utils::capture.output(print(plan_size(margin = 1e5, sd = 40, + N = 20000, target = "total"))) + expect_true(any(grepl("+/- 100,000 at 95% confidence", out, fixed = TRUE))) + expect_false(any(grepl("e+", out, fixed = TRUE))) +}) + +test_that("sample_summary lists a stratum allocated no rows", { + inv <- data.frame(id = 1:600, site = rep(c("north", "south", "east", "west"), + times = c(300, 180, 90, 30))) + expect_warning( + s <- draw(inv, design_stratified("site", n = 12), seed = 1, + weights = TRUE), + class = "drawn_empty_stratum") + x <- sample_summary(s) + expect_equal(x$by_group$group, c("east", "north", "south", "west")) + expect_equal(x$by_group$drawn, c(2, 6, 4, 0)) + expect_equal(x$by_group$in_frame, c(90, 300, 180, 30)) + out <- capture.output(print(x)) + # Every rate has three decimals, so the column lines up. + expect_true(any(grepl("east +2 +90 0.022$", out))) + expect_true(any(grepl("north +6 +300 0.020$", out))) + expect_true(any(grepl("west +0 +30 0.000$", out))) +}) + +test_that("sample_summary gives a certainty design the strata of its rest", { + pop <- data.frame(id = 1:200, site = rep(c("a", "b"), times = c(120, 80)), + w = c(rep(500, 3), rep(1, 197))) + s <- draw(pop, design_certainty("w", 100, + design_stratified("site", n = 20)), + seed = 1, weights = TRUE) + x <- sample_summary(s) + expect_equal(x$group_col, "site") + expect_equal(x$by_group$group, c("(certain)", "a", "b")) + expect_equal(x$by_group$drawn, c(3, 12, 8)) + expect_equal(x$by_group$in_frame, c(3, 117, 80)) + expect_equal(x$n_certain, 3L) + expect_equal(x$certain_by, c(threshold = 3L, size = 0L, whole = 0L)) + out <- capture.output(print(x)) + expect_true(any(grepl("certain rows 3 (3 above the threshold)", out, + fixed = TRUE))) + expect_true(any(grepl("(certain)", out, fixed = TRUE))) +}) + +test_that("sample_summary says why rows were taken with certainty", { + big <- data.frame(id = 1:100, w = c(rep(1, 95), rep(1000, 5))) + s <- draw(big, design_weighted("w", n = 20, method = "systematic"), seed = 1, + weights = TRUE) + x <- sample_summary(s) + expect_equal(x$n_certain, 5L) + expect_equal(x$certain_by, c(threshold = 0L, size = 5L, whole = 0L)) + expect_output(print(x), "certain rows 5 (5 by size)", fixed = TRUE) + + # A stratum taken whole is certain too, and neither of the above. + st <- data.frame(id = 1:53, site = rep(c("big", "small"), c(50, 3))) + s <- draw(st, design_stratified("site", allocation = c(big = 10, small = 3)), + seed = 1, weights = TRUE) + x <- sample_summary(s) + expect_equal(x$certain_by, c(threshold = 0L, size = 0L, whole = 3L)) + + srs <- draw(st, design_simple(n = 10), seed = 1, weights = TRUE) + x <- sample_summary(srs) + expect_equal(x$n_certain, 0L) + expect_false(any(grepl("certain rows", capture.output(print(x))))) +}) + +test_that("sample_summary counts a group a size design took whole as whole", { + d <- data.frame(id = 1:30, w = c(50, 1 + (2:30) %% 7), + site = rep(c("a", "b", "c"), each = 10), + cl = rep(1:6, each = 5), cs = rep(c(40, 2:6), each = 5)) + # Stratum c is allocated all 10 of its rows; the row of weight 50 in a is + # certain by size. + s <- draw(d, design_weighted("w", n = 15, method = "systematic", + strata = "site", + allocation = c(a = 3, b = 2, c = 10)), + seed = 1, weights = TRUE) + expect_equal(sample_summary(s)$certain_by, + c(threshold = 0L, size = 1L, whole = 10L)) + # A census of the rows a size design could reach, two of them dropped + d$w[c(25, 26)] <- NA + s <- draw(d, design_weighted("w", n = 28, method = "systematic", + na_rm = TRUE), seed = 1, weights = TRUE) + expect_equal(sample_summary(s)$certain_by, + c(threshold = 0L, size = 0L, whole = 28L)) + # Every cluster selected and taken whole, against a cluster put at 1 by + # size and then taken whole + s <- draw(d, design_multistage("cl", n_clusters = 6, n = 30, size = "cs"), + seed = 1, weights = TRUE) + expect_equal(sample_summary(s)$certain_by, + c(threshold = 0L, size = 0L, whole = 30L)) + s <- draw(d, design_multistage("cl", n_clusters = 2, n = 10, size = "cs"), + seed = 1, weights = TRUE) + expect_equal(sample_summary(s)$certain_by, + c(threshold = 0L, size = 5L, whole = 0L)) +}) + +test_that("sample_summary files certain rows by the design, not the draw", { + # Eight rows are certain by size. Seed 3 draws all 12 rows by chance and + # seed 1 draws 11; the four rows below 1 keep the frame from being whole. + d <- data.frame(id = 1:12, w = c(100, 90, 5:14)) + des <- design_weighted("w", n = 11, method = "poisson") + full <- draw(d, des, seed = 3, weights = TRUE) + part <- draw(d, des, seed = 1, weights = TRUE) + expect_equal(nrow(full), 12L) + expect_equal(nrow(part), 11L) + for (s in list(full, part)) { + expect_equal(sample_summary(s)$certain_by, + c(threshold = 0L, size = 8L, whole = 0L)) + } + # Stratum b is allocated all its rows; seed 9 draws every row of a too. + d$w <- c(100, 90, 5:8, 1:6) + d$site <- rep(c("a", "b"), each = 6) + des <- design_weighted("w", n = 10, method = "poisson", strata = "site", + allocation = c(a = 4, b = 6)) + full <- draw(d, des, seed = 9, weights = TRUE) + expect_equal(sum(full$site == "a"), 6L) + for (s in list(full, draw(d, des, seed = 1, weights = TRUE))) { + expect_equal(sample_summary(s)$certain_by, + c(threshold = 0L, size = 2L, whole = 6L)) + } +}) + +test_that("sample_summary gives the expected size of a sample of random size", { + pop <- data.frame(id = 1:240) + s <- draw(pop, design_systematic(interval = 7), seed = 1, weights = TRUE) + x <- sample_summary(s) + expect_equal(x$expected_n, 240 / 7) + expect_output(print(x), "expected n 34.29", fixed = TRUE) + + fixed <- sample_summary(draw(pop, design_simple(n = 30), seed = 1, + weights = TRUE)) + expect_equal(fixed$expected_n, 30) + expect_false(any(grepl("expected n", capture.output(print(fixed))))) +}) + +test_that("sample_summary reports Kish's effective sample size", { + pop <- data.frame(id = 1:300, w = 1 + (1:300 * 13) %% 40) + s <- draw(pop, design_weighted("w", n = 40, method = "systematic"), seed = 1, + weights = TRUE) + x <- sample_summary(s) + expect_equal(x$n_kish, sum(s$.weight)^2 / sum(s$.weight^2)) + expect_lt(x$n_kish, nrow(s)) + expect_output(print(x), "effective n") + srs <- sample_summary(draw(pop, design_simple(n = 30), seed = 1, + weights = TRUE)) + expect_equal(srs$n_kish, 30) +}) + +test_that("sample_summary groups a temporal sample by interval", { + pop <- data.frame( + id = 1:300, + ts = seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "hour", + length.out = 300) + ) + des <- design_temporal("ts", from = "2024-01-01", to = "2024-01-13", + interval = 1, per_interval = 2, unit = "days") + x <- sample_summary(draw(pop, des, seed = 1, weights = TRUE)) + expect_equal(x$group_col, "ts") + # Twelve intervals named by their start, in time order. + expect_equal(x$by_group$group, + paste(format(as.Date("2024-01-01") + 0:11), "00:00")) + expect_equal(x$by_group$drawn, rep(2, 12)) + expect_equal(x$by_group$in_frame, rep(24, 12)) +}) diff --git a/tests/testthat/test-plot.R b/tests/testthat/test-plot.R index e37772d..de56884 100644 --- a/tests/testthat/test-plot.R +++ b/tests/testthat/test-plot.R @@ -52,6 +52,7 @@ test_that("the default title describes the design", { }) test_that("plot leaves graphical parameters as it found them", { + local_seed(54) pop <- data.frame(id = 1:200, site = rep(c("a", "b"), each = 100), w = stats::runif(200, 1, 5)) f <- tempfile(fileext = ".png") @@ -76,7 +77,608 @@ test_that("plot reports the real reason it cannot draw probabilities", { expect_error(plot(design_systematic(interval = 7, start = 3), pop, type = "probability"), "fixed `start`") - expect_error(plot(design_weighted("site", n = 10), pop, + pop$w <- 1:50 + expect_error(plot(design_weighted("w", n = 10), pop, type = "probability"), "no closed-form") + # Weights draw() refuses are refused first, for the same reason. + expect_error(plot(design_weighted("site", n = 10), pop, + type = "probability"), + "`site` must be numeric, not character", fixed = TRUE) +}) + +test_that("a spatial map draws the region's outline as the design reads it", { + skip_if_not_installed("sf") + skip_if_not(sf::sf_use_s2(), "spherical geometry is switched off") + box <- sf::st_sfc(sf::st_polygon(list(cbind(c(-50, 50, 50, -50, -50), + c(-30, -30, 30, 30, -30)))), + crs = 4326) + d <- data.frame(id = 1:200, lon = (1:200 * 37) %% 120 - 60, + lat = (1:200 * 53) %% 90 - 45) + des <- design_spatial(c("lon", "lat"), box, n = 20) + + # Under s2 the top edge follows its great circle up to latitude 41.9. + outline <- drawn:::region_outline(des, d) + expect_gt(max(outline$y, na.rm = TRUE), 41.9) + expect_lt(max(outline$y, na.rm = TRUE), 42) + planar <- function() { + old <- suppressMessages(sf::sf_use_s2(FALSE)) + on.exit(suppressMessages(sf::sf_use_s2(old))) + drawn:::region_outline(des, d) + } + flat <- planar() + expect_equal(max(flat$y), 30) + expect_length(flat$x, 5) + + drawn_calls <- function(code) { + grDevices::pdf(NULL) + on.exit(grDevices::dev.off()) + grDevices::dev.control("enable") + code + vapply(grDevices::recordPlot()[[1]], function(e) { + f <- e[[2]][[1]] + if (is.list(f)) f$name else as.character(f)[1] + }, character(1)) + } + calls <- drawn_calls(expect_warning(plot(des, d, type = "map", seed = 1), + class = "drawn_geodesic_edges")) + expect_true("C_polygon" %in% calls) + calls <- drawn_calls(plot(design_simple(n = 20), d, type = "map", + coords = c("lon", "lat"), seed = 1)) + expect_false("C_polygon" %in% calls) +}) + +test_that("a map outline follows the sphere's great circles without lwgeom", { + skip_if_not_installed("sf") + skip_if_not(sf::sf_use_s2(), "spherical geometry is switched off") + # sf::st_segmentize() needs lwgeom, which sf only suggests, for + # longitude/latitude geometry. Here it fails as it does without lwgeom. + local_mocked_bindings( + st_segmentize = function(x, ...) { + stop("package lwgeom required, please install it first") + }, + .package = "sf") + box <- sf::st_sfc(sf::st_polygon(list(cbind(c(-50, 50, 50, -50, -50), + c(-30, -30, 30, 30, -30)))), + crs = 4326) + d <- data.frame(id = 1:200, lon = (1:200 * 37) %% 120 - 60, + lat = (1:200 * 53) %% 90 - 45) + des <- design_spatial(c("lon", "lat"), box, n = 20) + outline <- drawn:::region_outline(des, d) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + expect_warning(plot(des, d, type = "map", seed = 1), + class = "drawn_geodesic_edges") + + # The corners are kept, and every vertex of the top edge lies on the great + # circle through its corners, at most 50 km from the next. + expect_equal(outline$x[1], -50) + expect_equal(outline$y[1], -30) + expect_true(all(c(50, -50) %in% outline$x[outline$y == 30])) + u <- drawn:::unit_vector(outline$x, outline$y) + a <- drawn:::unit_vector(50, 30) + b <- drawn:::unit_vector(-50, 30) + normal <- c(a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], + a[1] * b[2] - a[2] * b[1]) + top <- outline$y >= 30 + expect_gt(sum(top), 100) + expect_lt(max(abs(u[top, ] %*% normal)), 1e-12) + apart <- acos(pmin(1, rowSums(u[-1, ] * u[-nrow(u), ]))) * 6371 + expect_lte(max(apart), 50) + + # Longitudes from 0 to 360 stay in that range across 180. + east <- drawn:::great_circle_path(c(170, 200), c(10, 10), km = 500) + expect_true(all(east$x >= 170 & east$x <= 200)) + expect_true(all(diff(east$x) > 0)) +}) + +test_that("a design with reserves is plotted by its main sample", { + pop <- data.frame(id = 1:100, x = (1:100) %% 10, y = (1:100) %/% 10) + f <- tempfile(fileext = ".png") + grDevices::png(f); on.exit({grDevices::dev.off(); unlink(f)}, add = TRUE) + shown <- NULL + local_mocked_bindings(draw_titles = function(main, sub, pal) { + shown <<- c(main, sub) + }) + + des <- design_simple(n = 10, reserve = 5) + expect_identical(plot(des, pop, seed = 1), des) + expect_equal(shown, c("design_simple(n = 10, reserve = 5)", + "10 of 100 rows selected")) + spread <- design_spread(c("x", "y"), n = 10, reserve = 5) + expect_identical(plot(spread, pop, type = "map", seed = 1), spread) + expect_match(shown[2], "^10 of 100") +}) + +# The calls a plot records, with their arguments, on a null device. +recorded_calls <- function(code) { + grDevices::pdf(NULL) + on.exit(grDevices::dev.off()) + grDevices::dev.control("enable") + code + calls <- grDevices::recordPlot()[[1]] + names(calls) <- vapply(calls, function(e) { + f <- e[[2]][[1]] + if (is.list(f)) f$name else as.character(f)[1] + }, character(1)) + lapply(calls, function(e) e[[2]][-1]) +} + +test_that("the probability view counts and draws every row of a large frame", { + n <- 10000 + pop <- data.frame(id = seq_len(n), + site = rep(c("a", "b", "c"), length.out = n), + w = rep(1:50, length.out = n)) + pop$site[c(2, 5000)] <- NA + pop$w[c(3, 9999)] <- 5000 + des <- design_certainty("w", 1000, + design_stratified("site", n = 500, na_rm = TRUE)) + p <- inclusion_prob(pop, des) + + view <- drawn:::probability_view(p, max_dots = 4000) + expect_equal(view$size, 3) + expect_equal(c(view$n_zero, view$n_certain), c(2L, 2L)) + expect_equal(c(view$low, view$top, view$mean), c(0, 1, mean(p))) + # Rows 2 and 5000 fall in different runs, so each gets its own mark, at + # its frame row. + expect_equal(view$zero, c(2, 5000)) + expect_equal(range(view$y), c(0, 1)) + expect_equal(range(view$x), c(0.5, n + 0.5)) + + shown <- NULL + local_mocked_bindings(draw_titles = function(main, sub, pal) shown <<- sub) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + plot(des, pop, type = "probability") + expect_equal(shown, paste("2 rows unreachable", "2 rows taken with certainty", + "range 0 to 1", sep = " | ")) +}) + +test_that("a run of rows keeps the order of its lowest and highest values", { + p <- seq(1, 0.01, length.out = 1000) + view <- drawn:::probability_view(p, max_dots = 100) + expect_equal(view$size, 10) + # A falling frame draws a falling step, with no saw teeth. + expect_true(all(diff(view$y) <= 0)) + expect_true(all(diff(view$x) >= 0)) +}) + +test_that("the probability view gives every row a plateau of its own", { + view <- drawn:::probability_view(c(1, 1, 1, 3) / 3, max_dots = 4000) + expect_equal(view$x, c(0.5, 1.5, 1.5, 2.5, 2.5, 3.5, 3.5, 4.5)) + # The last row, taken whole, is as wide as the others. + expect_equal(view$y[7:8], c(1, 1)) + + expect_equal(drawn:::row_ticks(1), 1) + expect_equal(drawn:::row_ticks(2), 1:2) + expect_equal(drawn:::row_ticks(3), 1:3) + expect_equal(drawn:::row_ticks(4), 1:4) + expect_equal(drawn:::row_ticks(10000), seq(2000, 10000, by = 2000)) + + # A one-row frame draws its step and its fill. + calls <- recorded_calls(plot(design_simple(n = 1), data.frame(id = 1), + type = "probability")) + expect_true("C_polygon" %in% names(calls)) + expect_equal(sum(names(calls) == "C_plotXY"), 2) + calls <- recorded_calls(plot(design_simple(n = 1), data.frame(id = 1:2), + type = "probability")) + axes <- calls[names(calls) == "C_axis"] + side_1 <- axes[vapply(axes, function(a) a[[1]] == 1, logical(1))][[1]] + expect_equal(side_1[[2]], 1:2) + expect_equal(side_1[[3]], c("1", "2")) + # The mean is labelled right-aligned above the end of its line, inside the + # panel. + label <- calls[["C_text"]] + expect_equal(label[[1]]$x, 2.5) + expect_equal(label[[3]], c(1, -0.4)) + expect_null(label[[4]]) +}) + +test_that("the selection view counts every selected row of a large frame", { + pop <- data.frame(id = 1:4000) + shown <- NULL + local_mocked_bindings(draw_titles = function(main, sub, pal) shown <<- sub) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + + # An evenly spaced subset of 1,500 rows fell in step with every fourth row, + # so some starts showed no selected row at all. + filled <- integer(4) + for (start in 1:4) { + des <- design_systematic(interval = 4, start = start) + plot(des, pop, max_dots = 1500) + expect_equal(shown, "1,000 of 4,000 rows selected") + counts <- tabulate(draw(pop, des)$id, 4000) + view <- drawn:::selection_view(counts, 1500) + expect_equal(view$size, 3) + expect_match(view$key, "each dot is 3 rows") + filled[start] <- sum(view$filled) + } + # Three of every four runs of three rows hold a selected row, whatever the + # start. + expect_true(all(abs(filled - 1334 * 3 / 4) <= 1)) +}) + +test_that("a with-replacement selection counts draws and rings repeats", { + pop <- data.frame(id = 1:240, x = (1:240) %% 16, y = (1:240) %/% 16) + des <- design_simple(n = 60, replace = TRUE) + ids <- draw(pop, des, seed = 3)$id + counts <- tabulate(ids, 240) + + shown <- NULL + local_mocked_bindings(draw_titles = function(main, sub, pal) shown <<- sub) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + plot(des, pop, seed = 3) + expect_equal(shown, paste0("60 draws, ", sum(counts > 0), + " distinct rows of 240")) + view <- drawn:::selection_view(counts, 4000) + expect_equal(which(view$ringed), which(counts > 1)) + expect_equal(view$key, "a ring marks a row drawn more than once") + + plot(des, pop, type = "map", coords = c("x", "y"), seed = 3) + expect_equal(shown, paste0("60 draws, ", sum(counts > 0), + " distinct rows of 240 | ringed rows were ", + "drawn more than once")) +}) + +test_that("a bootstrap is plotted by its first replicate", { + pop <- data.frame(id = 1:240) + des <- design_bootstrap(n_replicates = 50, n = 30) + reps <- draw(pop, des, seed = 1) + first <- reps$id[reps$.replicate == 1] + + shown <- NULL + local_mocked_bindings(draw_titles = function(main, sub, pal) shown <<- sub) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + expect_identical(plot(des, pop, seed = 1), des) + expect_equal(shown, paste0("replicate 1 of 50 | 30 draws, ", + length(unique(first)), " distinct rows of 240")) + # The matrix outputs give the same picture. + plot(design_bootstrap(n_replicates = 50, n = 30, output = "weights"), pop, + seed = 1) + expect_equal(shown, paste0("replicate 1 of 50 | 30 draws, ", + length(unique(first)), " distinct rows of 240")) + + # Both views of every output mark the rows of the first replicate. The + # map drew the count matrix of output = "weights" as row numbers. + located <- data.frame(id = 1:30, x = 1:30 %% 7, y = 1:30 %/% 7) + boot <- draw(located, design_bootstrap(n_replicates = 20, n = 3), seed = 1) + real <- plot_counts + marked <- NULL + local_mocked_bindings(plot_counts = function(x, y, seed) { + out <- real(x, y, seed) + marked <<- which(out > 0) + out + }) + for (output in c("rows", "indices", "weights")) { + for (type in c("selection", "map")) { + marked <- NULL + plot(design_bootstrap(n_replicates = 20, n = 3, output = output), + located, type = type, coords = c("x", "y"), seed = 1) + expect_equal(marked, sort(unique(boot$id[boot$.replicate == 1])), + info = paste(output, type)) + } + } + + # The probability view has nothing to show and does not point to the + # selection view either. + err <- tryCatch(plot(des, pop, type = "probability"), error = identity) + expect_match(conditionMessage(err), "has no inclusion probability") + expect_no_match(conditionMessage(err), "type = \"selection\"", fixed = TRUE) +}) + +test_that("palette, main and sub are checked before anything is drawn", { + pop <- data.frame(id = 1:50) + d <- design_simple(n = 5) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + op <- graphics::par(mar = c(5.1, 4.1, 4.1, 2.1)) + on.exit(graphics::par(op), add = TRUE, after = FALSE) + before <- graphics::par(c("mar", "bg")) + + expect_error(plot(d, pop, palette = list(surface = "offwhite")), + "`palette$surface` must be one colour", fixed = TRUE) + expect_identical(graphics::par(c("mar", "bg")), before) + expect_error(plot(d, pop, palette = list(acent = "red")), + "`palette` has an entry `acent`, which the plot does not use", + fixed = TRUE) + expect_error(plot(d, pop, palette = list(accent = NULL)), + "`palette$accent` must be one colour, a name from colors() or a code such as \"#1B6B52\", not NULL.", + fixed = TRUE) + expect_error(plot(d, pop, palette = list(accent = c("red", "blue"))), + "`palette$accent` must be one colour", fixed = TRUE) + expect_error(plot(d, pop, palette = "red"), "named list of colours") + expect_error(plot(d, pop, main = c("a", "b")), + "`main` must be a single string, an expression or NULL") + expect_error(plot(d, pop, sub = 1), "`sub` must be a single string or NULL") + expect_error(plot(d, pop, palette = c(accent = "red", "blue")), + "`palette` entry 2 has no name. Name each entry after the colour it replaces", + fixed = TRUE) + # A function has no value to show. is.na() of it warned. + expect_no_warning( + expect_error(plot(d, pop, main = mean), + "`main` must be a single string, an expression or NULL, not a function.", + fixed = TRUE) + ) + # An empty expression stopped partway through the plot, after a warning + # from max(), and the parts of a longer one were drawn over each other. + expect_no_warning( + expect_error(plot(d, pop, main = expression()), + "`main` is a length-0 expression, which has nothing to draw. Pass one expression", + fixed = TRUE) + ) + expect_error(plot(d, pop, main = expression(alpha, beta)), + "`main` is a length-2 expression, whose parts would be drawn over each other.", + fixed = TRUE) + expect_no_warning( + expect_error(plot(d, pop, palette = list(accent = mean)), + "`palette$accent` must be one colour, a name from colors() or a code such as \"#1B6B52\", not a function.", + fixed = TRUE) + ) + expect_identical(graphics::par(c("mar", "bg")), before) + + # A name is plotmath, as a call is. + expect_no_condition(plot(d, pop, seed = 1, main = quote(alpha))) + + # A named character vector is a palette too, and an expression a title. + shown <- NULL + local_mocked_bindings(draw_titles = function(main, sub, pal) { + shown <<- list(main = main, accent = pal$accent) + }) + plot(d, pop, seed = 1, palette = c(accent = "red"), + main = expression(alpha)) + expect_identical(shown, list(main = expression(alpha), accent = "red")) + plot(d, pop, seed = 1, main = quote(alpha)) + expect_identical(shown$main, quote(alpha)) +}) + +test_that("an error while drawing leaves the margins as they were", { + pop <- data.frame(id = 1:50, x = 1:50, y = 50:1) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + op <- graphics::par(mar = c(5.1, 4.1, 4.1, 2.1)) + on.exit(graphics::par(op), add = TRUE, after = FALSE) + before <- graphics::par(c("mar", "bg")) + local_mocked_bindings(draw_titles = function(main, sub, pal) stop("boom")) + for (type in c("selection", "probability", "map")) { + expect_error(plot(design_simple(n = 5), pop, type = type, + coords = c("x", "y"), seed = 1), "boom") + expect_identical(graphics::par(c("mar", "bg")), before, info = type) + } + # A background par() refuses after it has set the margins. The margins + # were left set for the next plot. + local_mocked_bindings(check_palette = function(palette) { + utils::modifyList(drawn:::drawn_pal(), list(surface = "offwhite")) + }) + for (type in c("selection", "probability", "map")) { + expect_error(plot(design_simple(n = 5), pop, type = type, + coords = c("x", "y"), seed = 1), "offwhite") + expect_identical(graphics::par(c("mar", "bg")), before, info = type) + } +}) + +test_that("`sub` is added to the line under the title in every view", { + pop <- data.frame(id = 1:100, x = (1:100) %% 10, y = (1:100) %/% 10) + d <- design_simple(n = 10) + shown <- NULL + local_mocked_bindings(draw_titles = function(main, sub, pal) shown <<- sub) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + + plot(d, pop, seed = 1, sub = "pilot frame, May") + expect_equal(shown, "10 of 100 rows selected | pilot frame, May") + plot(d, pop, type = "probability", sub = "pilot frame, May") + expect_equal(shown, "range 0.1 to 0.1 | pilot frame, May") + # The map stopped with 'graphical parameter "bg" has the wrong length'. + plot(d, pop, type = "map", coords = c("x", "y"), seed = 1, + sub = "pilot frame, May") + expect_equal(shown, "10 of 100 rows selected | pilot frame, May") +}) + +test_that("graphical parameters in `...` replace the plot's own", { + pop <- data.frame(id = 1:100, x = (1:100 %% 10) * 1000, y = (1:100) %/% 10) + window <- function(calls) calls[["C_plot_window"]] + + # Each of these stopped with 'matched by multiple actual arguments'. + calls <- recorded_calls(plot(design_simple(n = 10), pop, + type = "probability", ylim = c(0, 1), + xlim = c(1, 50))) + expect_equal(window(calls)[[1]], c(1, 50)) + expect_equal(window(calls)[[2]], c(0, 1)) + # The rules and the axis follow the limits given. + axes <- calls[names(calls) == "C_axis"] + side_2 <- axes[vapply(axes, function(a) a[[1]] == 2, logical(1))][[1]] + expect_equal(side_2[[2]], seq(0, 1, by = 0.2)) + expect_equal(calls[["C_segments"]][[1]], 1) + expect_equal(calls[["C_segments"]][[3]], 50) + + calls <- recorded_calls(plot(design_simple(n = 10), pop, seed = 1, + xlim = c(0, 30))) + expect_equal(window(calls)[[1]], c(0, 30)) + + calls <- recorded_calls(plot(design_simple(n = 10), pop, type = "map", + coords = c("x", "y"), seed = 1, asp = 1, + xlim = c(0, 5000))) + expect_equal(window(calls)[[1]], c(0, 5000)) + expect_equal(window(calls)[[4]], 1) + + # Coordinates a design measures distance in get one scale on both axes; + # other columns, and scaled ones, fill the panel. + asp_of <- function(design, ...) { + window(recorded_calls(plot(design, pop, type = "map", seed = 1, ...)))[[4]] + } + expect_equal(asp_of(design_spread(c("x", "y"), n = 10, scale = FALSE)), 1) + expect_true(is.na(asp_of(design_spread(c("x", "y"), n = 10)))) + expect_true(is.na(asp_of(design_simple(n = 10), coords = c("x", "y")))) + expect_true(is.na(asp_of(design_spread(c("x", "y"), n = 10, scale = FALSE), + asp = NA))) +}) + +test_that("a longitude/latitude map is scaled by its middle latitude", { + skip_if_not_installed("sf") + pop <- data.frame(id = 1:100, lon = (1:100 %% 10) / 10, + lat = 59.5 + (1:100 %/% 10) / 10) + box <- sf::st_sfc(sf::st_polygon(list(cbind(c(0, 1, 1, 0, 0), + c(59, 59, 61, 61, 59)))), + crs = 4326) + des <- design_spatial(c("lon", "lat"), box, n = 10) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + asp <- NULL + local_mocked_bindings(panel_frame = function(defaults, dots) { + asp <<- defaults$asp + do.call(graphics::plot, defaults) + }) + suppressWarnings(plot(des, pop, type = "map", seed = 1)) + expect_equal(asp, 1 / cos(mean(range(pop$lat)) * pi / 180)) +}) + +test_that("`...` takes graphical parameters and nothing else", { + pop <- data.frame(id = 1:50) + d <- design_simple(n = 5) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + expect_error(plot(d, pop, simulate = TRUE), + "plot() for a design does not take `simulate`.", fixed = TRUE) + expect_error(plot(d, pop, simulate = TRUE, R = 10), + "does not take `simulate` or `R`.", fixed = TRUE) + expect_error(plot(d, pop, panel.first = stop("evaluated")), + "does not take `panel.first`", fixed = TRUE) + expect_error(plot(d, pop, "selection", 1, NULL, 4000, NULL, NULL, NULL, + NULL, 5), + "must be named graphical parameters") + expect_silent(plot(d, pop, seed = 1, col = "red", cex = 2, las = 1)) +}) + +test_that("the map names columns it leaves out and rows it cannot place", { + pop <- data.frame(id = 1:240, x = (1:240 * 7) %% 31, yy = (1:240 * 11) %% 37, + z = (1:240 * 13) %% 41) + shown <- NULL + local_mocked_bindings(draw_titles = function(main, sub, pal) shown <<- sub) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + + plot(design_spread(c("x", "yy", "z"), n = 30, scale = FALSE), pop, + type = "map", seed = 5) + expect_equal(shown, + "30 of 240 rows selected | placed by x and yy, not z") + + d <- design_simple(n = 30) + ids <- draw(pop, d, seed = 5)$id + gaps <- pop + gaps$x[ids[1:3]] <- NA + gaps$yy[ids[4]] <- Inf + plot(d, gaps, type = "map", coords = c("x", "yy"), seed = 5) + expect_equal(shown, paste0("30 of 240 rows selected | 4 selected rows ", + "not shown, missing x or yy")) + + # The background holds the 210 rows not selected, and 50 of them are drawn. + plot(d, pop, type = "map", coords = c("x", "yy"), seed = 5, max_dots = 50) + expect_equal(shown, paste0("30 of 240 rows selected | background ", + "thinned to 50 of 210")) + + gaps$x <- NA_real_ + expect_error(plot(d, gaps, type = "map", coords = c("x", "yy"), seed = 5), + "`x` and `yy` are not both finite in any row of `y`", + fixed = TRUE) +}) + +test_that("the default title gives the arguments that differ by design", { + label <- drawn:::design_label + expect_equal(label(design_stratified(c("site", "flag"), n = 30)), + paste0("design_stratified(strata = c(\"site\", \"flag\"), ", + "n = 30, allocation = \"proportional\")")) + expect_equal(label(design_simple(n = 10, replace = TRUE)), + "design_simple(n = 10, replace = TRUE)") + expect_equal(label(design_systematic(interval = 8, start = 3, + order_by = "w")), + "design_systematic(interval = 8, start = 3, order_by = \"w\")") + expect_equal(label(design_reservoir(n = 30, max_items = 150)), + "design_reservoir(n = 30, max_items = 150)") + expect_equal(label(design_reservoir(n = 30)), "design_reservoir(n = 30)") + expect_equal(label(design_certainty("w", 100, design_simple(n = 20))), + paste0("design_certainty(above = \"w\", threshold = 100, ", + "rest = design_simple(n = 20))")) + expect_equal(label(design_bootstrap(20, method = "block", + block_length = 5)), + paste0("design_bootstrap(n_replicates = 20, ", + "method = \"block\", block_length = 5)")) + expect_equal(label(design_temporal("ts", "2024-01-01", "2024-01-02", 24, + 5)), + paste0("design_temporal(time = \"ts\", interval = 24, ", + "unit = \"hours\", per_interval = 5)")) + expect_equal(label(design_stratified("site", n = 30, allocation = "neyman", + allocation_by = "w", + min_per_stratum = 2)), + paste0("design_stratified(strata = \"site\", n = 30, ", + "allocation = \"neyman\", allocation_by = \"w\", ", + "min_per_stratum = 2)")) + expect_equal(label(design_cluster("cl", n_clusters = 4)), + "design_cluster(clusters = \"cl\", n_clusters = 4)") + expect_equal(label(design_spread(c("x", "y"), n = 10, scale = FALSE)), + paste0("design_spread(across = c(\"x\", \"y\"), n = 10, ", + "scale = FALSE)")) + + # Without sf regions or functions, a label is the call that builds the + # design. + designs <- list( + design_simple(n = 10, replace = TRUE), + design_stratified(c("site", "flag"), n = 30, min_per_stratum = 1, + na_rm = TRUE), + design_systematic(interval = 7, n_starts = 2), + design_multistage("cl", n_clusters = 2, n = 6, min_per_cluster = 1), + design_weighted("w", n = 5, method = "poisson"), + design_certainty("w", 10, design_stratified("s", 5, + allocation = c(a = 2L, b = 3L))), + design_bootstrap(20, method = "circular", output = "indices"), + design_reservoir(n = 3, max_items = 50, batches = TRUE) + ) + for (des in designs) { + expect_equal(eval(parse(text = label(des))), des, info = label(des)) + } +}) + +test_that("plot names `y` when it is not a data frame", { + expect_error(plot(design_simple(n = 2), as.list(data.frame(id = 1:5))), + "`y` must be a data frame, not a list.", fixed = TRUE) + expect_error(plot(design_simple(n = 2), data.frame(id = integer())), + "`y` has no rows.", fixed = TRUE) +}) + +test_that("a title too long for the figure is shrunk to fit", { + pop <- data.frame(id = 1:50) + title_of <- function(main) { + calls <- recorded_calls(plot(design_simple(n = 5), pop, seed = 1, + main = main)) + calls[names(calls) == "C_mtext"][[1]] + } + short <- title_of("short") + expect_equal(short[[1]], "short") + expect_equal(short[[8]], 0.9) + main <- strrep("design_stratified(strata = \"band\") ", 3) + long <- title_of(main) + expect_equal(long[[1]], main) + expect_lt(long[[8]], 0.9) + expect_gt(long[[8]], 0.6) + # Past two thirds of its size, the text is cut and says so. + longest <- title_of(strrep("x", 1000)) + expect_equal(longest[[8]], 0.6) + expect_match(longest[[1]], "^x+\\.\\.\\.$") + expect_lt(nchar(longest[[1]]), 1000) +}) + +test_that("a frame with the column plot() tags rows with is refused", { + pop <- data.frame(id = 1:20, x = 1:20, .drawn_plot_id = 1) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + for (type in c("selection", "map")) { + expect_error(plot(design_simple(n = 5), pop, type = type, seed = 1, + coords = c("id", "x")), + "`y` already has a column called `.drawn_plot_id`.", + fixed = TRUE) + } + names(pop)[3] <- "tag" + expect_invisible(plot(design_simple(n = 5), pop, seed = 1)) }) diff --git a/tests/testthat/test-pps.R b/tests/testthat/test-pps.R index c4f1159..3fec602 100644 --- a/tests/testthat/test-pps.R +++ b/tests/testthat/test-pps.R @@ -40,6 +40,26 @@ test_that("certainty treatment iterates when removing units creates new ones", { expect_equal(p[4:5], c(1, 1)) }) +test_that("a unit whose share comes to 1 gets exactly 1", { + # 5 * (2.3 / 11.5) is 1 in exact arithmetic and came out 1 - 1e-16 in + # floating point, while the same sizes times 10 gave exactly 1. + pop <- data.frame(id = 1:8, w = c(1.1, 0.2, 1.8, 1.3, 1.5, 1.6, 2.3, 1.7)) + d <- design_weighted("w", n = 5, method = "systematic") + expect_identical(inclusion_prob(pop, d)[7], 1) + expect_identical(inclusion_prob(transform(pop, w = w * 10), d)[7], 1) + expect_equal(sum(inclusion_prob(pop, d)), 5) + + # A census then reads as one: every .prob is 1 and the total is exact, + # where it had a small standard error under a Deville note. + pop3 <- data.frame(id = 1:41, w = 0.1, y = 100 + (1:41)) + s <- draw(pop3, design_weighted("w", n = 41, method = "systematic"), + seed = 1, weights = TRUE) + expect_true(all(s$.prob == 1)) + r <- ht_total(s, "y") + expect_equal(r$variance, 0) + expect_match(r$note, "exact rather than estimated") +}) + test_that("realised inclusion matches the claim for systematic PPS", { df <- data.frame(id = 1:8, w = c(1, 1, 2, 2, 3, 3, 4, 4)) d <- design_weighted("w", n = 3, method = "systematic") @@ -81,6 +101,54 @@ test_that("successive sampling really does differ from proportional", { expect_gt(max(abs(obs - target) / target), 0.2) }) +test_that("successive sampling of 1:10 at n = 5 is up to 36% off, exactly", { + # Every ordered draw enumerated; ?design_weighted and ?inclusion_prob + # quote the figure. + enumerate <- function(w, n) { + p <- numeric(length(w)) + step <- function(chosen, prob, left) { + if (length(chosen) == n) { + p[chosen] <<- p[chosen] + prob + return(invisible()) + } + for (i in left) { + step(c(chosen, i), prob * w[i] / sum(w[left]), setdiff(left, i)) + } + } + step(integer(0), 1, seq_along(w)) + p + } + w <- 1:10 + exact <- enumerate(w, 5) + expect_equal(sum(exact), 5) + expect_equal(max(abs(exact / (5 * w / sum(w)) - 1)), 0.3626, + tolerance = 1e-3) + sim <- inclusion_prob(data.frame(w = w), design_weighted("w", n = 5), + simulate = TRUE, R = 2000, seed = 1) + expect_equal(sim, exact, tolerance = 0.05) +}) + +test_that("Poisson takes rows past certainty and rescales the rest", { + # Capping n * p_i at 1 alone would leave the light rows at 0.12 and an + # expected size of 1.6 rather than 3. + df <- data.frame(id = 1:6, w = c(1, 1, 1, 1, 1, 20)) + p <- inclusion_prob(df, design_weighted("w", n = 3, method = "poisson")) + expect_equal(p, c(rep(0.4, 5), 1)) + expect_equal(p, inclusion_prob(df, design_weighted("w", n = 3, + method = "systematic"))) +}) + +test_that("only successive PPS returns rows in draw order", { + df <- data.frame(id = 1:120, w = 1 + (1:120 * 37) %% 53) + for (m in c("systematic", "poisson")) { + for (i in 1:3) { + ids <- draw(df, design_weighted("w", n = 15, method = m), seed = i)$id + expect_false(is.unsorted(ids)) + } + } + expect_true(is.unsorted(draw(df, design_weighted("w", n = 15), seed = 1)$id)) +}) + test_that("replace = TRUE cannot be combined with the PPS methods", { expect_error(design_weighted("w", n = 5, replace = TRUE, method = "systematic"), "cannot be combined") @@ -99,3 +167,292 @@ test_that("PPS methods refuse to draw more rows than exist", { test_that("an unknown method is rejected at construction", { expect_error(design_weighted("w", n = 5, method = "pps")) }) + +test_that("an empty Poisson sample estimates a total of 0 with no variance", { + # Poisson sampling can draw nothing. Its total is then 0, which keeps the + # estimator unbiased over repeated draws, so a simulation loop gets a number + # instead of an error. One empty draw has no variance to report. + pop <- data.frame(id = 1:50, w = 1 + (1:50 %% 4), y = 1:50) + des <- design_weighted("w", n = 1, method = "poisson") + for (i in 1:100) { + s <- draw(pop, des, seed = i, weights = TRUE) + if (!nrow(s)) break + } + expect_equal(nrow(s), 0L) + + r <- ht_total(s, "y") + expect_equal(r$total, 0) + expect_true(is.na(r$variance)) + expect_true(all(is.na(r$ci))) + expect_equal(r$df, 0) + expect_equal(r$method, "none") + expect_match(r$note, "The sample is empty") + expect_output(print(r), "The sample is empty") + expect_equal(nrow(ht_total(s, "y", by = "id")), 0L) + + # The Hajek mean is 0 / 0; the Horvitz-Thompson mean divides by N + expect_error(ht_mean(s, "y"), "Hajek mean is 0 / 0") + expect_equal(ht_mean(s, "y", estimator = "ht")$mean, 0) + + skip_if_not_installed("survey") + expect_error(as_svydesign(s), "`sample` has no rows", fixed = TRUE) +}) + +test_that("an empty sample from a design that reaches no row is refused", { + pop <- data.frame(id = 1:20, w = 1:20, y = 1:20) + s <- draw(pop, design_simple(n = 0), seed = 1, weights = TRUE) + expect_error(ht_total(s, "y"), "probability of 0") +}) + +test_that("weights whose total overflows still give probabilities summing to n", { + # Positive weights near 1e306 summed to Inf, which made every probability 0 + # and every sample empty. + pop <- data.frame(id = 1:40, w = c(1:39, 100)) + pop$big <- pop$w * 1e306 + pop$small <- pop$w * 1e-300 + expect_false(is.finite(sum(pop$big))) + for (m in c("systematic", "poisson")) { + want <- inclusion_prob(pop, design_weighted("w", n = 10, method = m)) + for (col in c("big", "small")) { + des <- design_weighted(col, n = 10, method = m) + p <- inclusion_prob(pop, des) + expect_equal(p, want, info = paste(m, col)) + expect_equal(sum(p), 10) + } + } + expect_equal(nrow(draw(pop, design_weighted("big", n = 10, + method = "systematic"), + seed = 1)), 10) + expect_equal(nrow(draw(pop, design_weighted("big", n = 10), seed = 1)), 10) + s <- draw(pop, design_spread("id", n = 10, size = "big"), seed = 1, + weights = TRUE) + expect_equal(nrow(s), 10) + expect_equal(sum(inclusion_prob(pop, design_spread("id", n = 10, + size = "big"))), 10) + cert <- design_certainty("id", 40, design_weighted("big", n = 5, + method = "systematic")) + expect_equal(nrow(draw(pop, cert, seed = 1)), 6) +}) + +test_that("weights a double cannot scale together are refused, not zeroed", { + # Divided by the largest, weights 1e-320 apart in scale from it underflow + # to 0 and leave the probabilities short of n. + w <- c(1e308, 1e308, 1e-320, 1e-320) + expect_error(drawn:::pps_pi(w, 3), "summing to 2, where `n` is 3", + fixed = TRUE) + expect_equal(drawn:::pps_pi(c(1e300, 1e-300, 1e-300), 2), c(1, 0.5, 0.5)) +}) + +test_that("certainty_set() gives the rows taken with certainty and the cut-off", { + pop <- data.frame(id = 1:12, w = c(1:10, 60, 90)) + for (m in c("systematic", "poisson")) { + des <- design_weighted("w", n = 4, method = m) + cs <- certainty_set(pop, des) + expect_identical(as.vector(cs), which(inclusion_prob(pop, des) == 1)) + expect_identical(as.vector(cs), 11:12) + expect_identical(attr(cs, "threshold"), 60) + # The same rows, and the same probabilities, with the cut-off explicit. + same <- design_certainty("w", attr(cs, "threshold"), + rest = design_weighted("w", n = 4 - length(cs), + method = m)) + expect_equal(inclusion_prob(pop, same), inclusion_prob(pop, des)) + } + + sp <- design_spread("id", n = 4, size = "w") + expect_identical(as.vector(certainty_set(pop, sp)), 11:12) + + none <- certainty_set(pop, design_weighted("w", n = 1, method = "poisson")) + expect_length(none, 0) + expect_identical(attr(none, "threshold"), NA_real_) + + na_pop <- pop + na_pop$w[12] <- NA + cs <- certainty_set(na_pop, design_weighted("w", n = 3, method = "poisson", + na_rm = TRUE)) + expect_identical(as.vector(cs), 11L) + + expect_error(certainty_set(pop, design_simple(n = 3)), + "not proportional to size", fixed = TRUE) + expect_error(certainty_set(pop, design_weighted("w", n = 3)), + "method = \"successive\"", fixed = TRUE) + expect_error(certainty_set(pop, design_spread("id", n = 3)), + "not proportional to size", fixed = TRUE) + expect_error(certainty_set(pop, "w"), "must come from one of the design") + expect_error(certainty_set(pop, design_weighted("w", n = 20, + method = "systematic")), + "cannot exceed the number of rows (12)", fixed = TRUE) +}) + +# ---- within strata ----------------------------------------------------------- + +strata_pps_pop <- function() { + data.frame( + id = 1:60, + g = rep(c("a", "b", "c"), times = c(30, 20, 10)), + w = c(1:29, 200, (1:20) * 2, c(5, 5, 6, 6, 7, 7, 8, 8, 9, 9)), + y = (1:60) %% 7 * 3 + c(1:29, 200, (1:20) * 2, + c(5, 5, 6, 6, 7, 7, 8, 8, 9, 9)) * 2 + ) +} + +test_that("PPS within strata draws each stratum's share of n", { + pop <- strata_pps_pop() + d <- design_weighted("w", n = 12, method = "systematic", strata = "g") + tab <- allocation_table(pop, d) + expect_identical(tab$n, c(6L, 4L, 2L)) + expect_identical(tab$status, rep("rule", 3)) + expect_true(all(is.na(tab$prob))) + for (i in 1:20) { + s <- draw(pop, d, seed = i) + expect_identical(as.vector(table(factor(s$g, c("a", "b", "c")))), + c(6L, 4L, 2L)) + } + p <- inclusion_prob(pop, d) + expect_equal(as.vector(tapply(p, pop$g, sum)), c(6, 4, 2)) + # Proportional to size within each stratum, with the heavy row of `a` + # taken with certainty and the rest of its share spread over the others. + expect_identical(p[30], 1) + expect_equal(p[1:29], 5 * pop$w[1:29] / sum(pop$w[1:29])) + expect_equal(p[31:50], 4 * pop$w[31:50] / sum(pop$w[31:50])) + expect_identical(as.vector(certainty_set(pop, d)), 30L) + expect_identical(attr(certainty_set(pop, d), "threshold"), NA_real_) + + eq <- design_weighted("w", n = 12, method = "poisson", strata = "g", + allocation = "equal") + expect_equal(as.vector(tapply(inclusion_prob(pop, eq), pop$g, sum)), + c(4, 4, 4)) + counts <- design_weighted("w", method = "systematic", strata = "g", + allocation = c(a = 2, b = 3, c = 5)) + expect_identical(counts$n, 10L) + expect_identical(allocation_table(pop, counts)$status, rep("count", 3)) + expect_equal(as.vector(tapply(inclusion_prob(pop, counts), pop$g, sum)), + c(2, 3, 5)) +}) + +test_that("PPS within strata includes each row as often as it claims", { + skip_on_cran() + pop <- strata_pps_pop()[c(1:8, 31:36, 51:55), ] + for (m in c("systematic", "poisson")) { + d <- design_weighted("w", n = 7, method = m, strata = "g") + expect_equal(inclusion_prob(pop, d, simulate = TRUE, R = 2000, seed = 1), + inclusion_prob(pop, d), tolerance = 0.06) + } +}) + +test_that("Deville within strata is sampling::varest() added over strata", { + skip_if_not_installed("sampling") + pop <- strata_pps_pop() + d <- design_weighted("w", n = 18, method = "systematic", strata = "g") + for (i in 1:3) { + s <- draw(pop, d, seed = i, weights = TRUE) + r <- ht_total(s, "y") + free <- s$.prob < 1 + ref <- sum(vapply(split(which(free), s$g[free]), function(j) { + sampling::varest(s$y[j], pik = s$.prob[j]) + }, numeric(1))) + expect_equal(r$variance, ref) + expect_identical(r$method, "deville") + # Rows below certainty less the strata that hold them. + expect_identical(r$df, sum(free) - 3) + } +}) + +test_that("a stratum with one sampled row below certainty is refused by name", { + pop <- strata_pps_pop() + d <- design_weighted("w", method = "systematic", strata = "g", + allocation = c(a = 4, b = 4, c = 1)) + s <- draw(pop, d, seed = 1, weights = TRUE) + r <- ht_total(s, "y", variance = "analytic") + expect_true(is.na(r$se)) + expect_match(r$note, "The stratum `c` has a single sampled row", + fixed = TRUE) + expect_match(r$note, "count of 2 or more for each in `allocation`", + fixed = TRUE) + # The jackknife refuses it too, rather than leave the stratum out. + expect_true(is.na(ht_total(s, "y")$se)) + # A domain with no unit in that stratum is measured. + pop$dom <- ifelse(pop$g == "c", "out", "in") + s2 <- draw(pop, d, seed = 1, weights = TRUE) + by <- ht_total(s2, "y", by = "dom", variance = "analytic") + expect_false(is.na(by$se[by$dom == "in"])) + expect_true(is.na(by$se[by$dom == "out"])) +}) + +test_that("the jackknife of PPS within strata deletes rows within strata", { + pop <- strata_pps_pop() + s <- draw(pop, design_weighted("w", n = 18, method = "systematic", + strata = "g"), seed = 2, weights = TRUE) + jk <- ht_total(s, "y", variance = "jackknife") + expect_match(jk$note, "in 3 strata", fixed = TRUE) + expect_match(jk$note, "the 1 taken with certainty adds no variance", + fixed = TRUE) + expect_gt(jk$se, 0) +}) + +test_that("Poisson within strata keeps the Poisson variance", { + pop <- strata_pps_pop() + s <- draw(pop, design_weighted("w", n = 18, method = "poisson", + strata = "g"), seed = 3, weights = TRUE) + r <- ht_total(s, "y") + expect_equal(r$variance, sum((1 - s$.prob) / s$.prob^2 * s$y^2)) + free <- s$.prob < 1 + expect_identical(r$df, + as.numeric(sum(free) - length(unique(s$g[free])))) +}) + +test_that("strata need a closed-form PPS method; allocation needs strata", { + expect_error(design_weighted("w", n = 10, strata = "g"), + "cannot be combined with method = \"successive\"", + fixed = TRUE) + expect_error(design_weighted("w", n = 10, method = "poisson", + allocation = "equal"), + "`strata` is NULL", fixed = TRUE) + expect_error(design_weighted("w", n = 10, method = "poisson", strata = "g", + allocation = "neyman"), + "`allocation` must be one of", fixed = TRUE) + expect_error(design_weighted("w", method = "poisson", strata = "g"), + "`n` is missing", fixed = TRUE) + expect_error(design_weighted("w", n = 9, method = "poisson", strata = "g", + allocation = c(a = 2, b = 3)), + "not the sum of the counts", fixed = TRUE) + pop <- strata_pps_pop() + expect_error(inclusion_prob(pop, design_weighted( + "w", method = "systematic", strata = "g", + allocation = c(a = 2, b = 3, c = 11))), + "Stratum `c` has 10 row(s) but `allocation` asks for 11. Lower its count.", + fixed = TRUE) + expect_error(inclusion_prob(pop, design_weighted( + "w", method = "systematic", strata = "g", + allocation = c(a = 2, b = 3, c = 5, d = 1))), "`d`", fixed = TRUE) + expect_error(inclusion_prob(pop, design_weighted( + "w", method = "systematic", strata = "g", + allocation = c(a = 2, b = 3))), "`c`", fixed = TRUE) +}) + +test_that("a missing stratum key follows na_rm, like a missing weight", { + pop <- strata_pps_pop() + pop$g[2] <- NA + d <- design_weighted("w", n = 12, method = "systematic", strata = "g") + expect_error(draw(pop, d, seed = 1), "1 row(s) have a missing stratum key", + fixed = TRUE) + kept <- design_weighted("w", n = 12, method = "systematic", strata = "g", + na_rm = TRUE) + p <- inclusion_prob(pop, kept) + expect_identical(p[2], 0) + expect_equal(sum(p), 12) + expect_identical(allocation_table(pop, kept)$N, c(29L, 20L, 10L)) +}) + +test_that("samples bound stratum by stratum are refused, with strata the way", { + pop <- strata_pps_pop() + parts <- lapply(c("a", "b", "c"), function(h) { + draw(pop[pop$g == h, ], design_weighted("w", n = 4, + method = "systematic"), + seed = 1, weights = TRUE) + }) + expect_error(ht_total(do.call(rbind, parts), "y"), + "more than once, as rbind() of samples", fixed = TRUE) + whole <- draw(pop, design_weighted("w", n = 12, method = "systematic", + strata = "g"), seed = 1, weights = TRUE) + expect_false(is.na(ht_total(whole, "y")$se)) +}) diff --git a/tests/testthat/test-survey.R b/tests/testthat/test-survey.R index 925ac41..bf837cb 100644 --- a/tests/testthat/test-survey.R +++ b/tests/testthat/test-survey.R @@ -1,5 +1,5 @@ svy_pop <- function(N = 400) { - set.seed(1212) + local_seed(1212) d <- data.frame( id = seq_len(N), site = rep(c("a", "b", "c", "d"), times = c(N / 2, N / 4, N * 0.15, @@ -14,28 +14,6 @@ svy_pop <- function(N = 400) { d } -test_that("survey and this package agree on a stratified total", { - skip_if_not_installed("survey") - d <- svy_pop() - s <- draw(d, design_stratified("site", n = 80), seed = 1, weights = TRUE) - des <- as_svydesign(s) - - ours <- ht_total(s, "spend") - theirs <- survey::svytotal(~spend, des) - expect_equal(as.numeric(theirs), ours$total) - expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-6) -}) - -test_that("survey and this package agree on a simple random total", { - skip_if_not_installed("survey") - d <- svy_pop() - s <- draw(d, design_simple(n = 100), seed = 2, weights = TRUE) - ours <- ht_total(s, "spend") - theirs <- survey::svytotal(~spend, as_svydesign(s)) - expect_equal(as.numeric(theirs), ours$total) - expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-6) -}) - test_that("a cluster design maps to cluster ids, and the means agree", { skip_if_not_installed("survey") d <- svy_pop() @@ -65,16 +43,6 @@ test_that("extra arguments reach svydesign", { expect_s3_class(des, "survey.design") }) -test_that("a reservoir sample is simple random sampling, and maps as one", { - skip_if_not_installed("survey") - d <- svy_pop() - r <- draw(d, design_reservoir(n = 100), seed = 6, weights = TRUE) - ours <- ht_total(r, "spend") - theirs <- survey::svytotal(~spend, as_svydesign(r)) - expect_equal(as.numeric(theirs), ours$total) - expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-6) -}) - test_that("a bootstrap design is refused", { skip_if_not_installed("survey") d <- svy_pop(100) @@ -86,8 +54,13 @@ test_that("a bootstrap design is refused", { fake <- d[1:10, ] fake$.weight <- 1 attr(fake, "drawn_design") <- design_bootstrap(n_replicates = 3) + attr(fake, "drawn_rows") <- 1:10 attr(fake, "drawn_population") <- d expect_error(as_svydesign(fake), "no survey equivalent") + expect_error(ht_total(fake, "spend"), "comes from a bootstrap design", + fixed = TRUE) + expect_error(replicate_weights(fake), "comes from a bootstrap design", + fixed = TRUE) }) test_that("as_svydesign needs a sample carrying its design", { @@ -124,6 +97,7 @@ test_that("survey reproduces this package's standard error, design by design", { test_that("a temporal design maps to strata over its intervals", { skip_if_not_installed("survey") + local_seed(126) d <- data.frame( id = 1:480, ts = rep(seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "day", @@ -138,22 +112,62 @@ test_that("a temporal design maps to strata over its intervals", { expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-6) }) -test_that("compositions with no survey equivalent are refused, not fudged", { +test_that("certainty over clusters or Poisson sampling agrees with survey", { skip_if_not_installed("survey") + # These were refused as having no single survey design. The certainty rows + # are one more unit beside the clusters, and Poisson sampling covers the + # whole sample with the certainty rows at probability 1. d <- svy_pop() - for (rest in list(design_cluster("cl", n_clusters = 6), - design_multistage("cl", n_clusters = 6, n = 30), - design_weighted("spend", n = 40, method = "poisson"))) { - s <- draw(d, design_certainty("spend", 400, rest), seed = 1, + d$g <- ifelse(d$id %% 3 == 0, "u", "v") + rests <- list( + cluster = design_cluster("cl", n_clusters = 6), + multistage = design_multistage("cl", n_clusters = 6, n = 30), + one_row = design_multistage("cl", n_clusters = 6, n = 6), + balanced = design_cluster("cl", n_clusters = 6, balanced = TRUE), + poisson = design_weighted("spend", n = 40, method = "poisson"), + poisson_strata = design_weighted("size", n = 40, method = "poisson", + strata = "site") + ) + for (nm in names(rests)) { + s <- draw(d, design_certainty("spend", 400, rests[[nm]]), seed = 1, weights = TRUE) - expect_error(as_svydesign(s), "no single survey equivalent") + expect_true(any(s$.prob == 1), label = nm) + sv <- as_svydesign(s) + ours <- ht_total(s, "spend") + theirs <- survey::svytotal(~spend, sv) + expect_equal(as.numeric(theirs), ours$total, tolerance = 1e-8, + label = nm) + expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-8, + label = nm) + expect_equal(survey::degf(sv), ours$df, label = nm) + expect_equal(as.numeric(survey::SE(survey::svymean(~spend, sv))), + ht_mean(s, "spend")$se, tolerance = 1e-8, label = nm) + by_theirs <- suppressWarnings( + survey::svyby(~spend, ~g, sv, survey::svytotal)) + expect_equal(ht_total(s, "spend", by = "g")$se, + as.numeric(survey::SE(by_theirs)), tolerance = 1e-8, + label = nm) + } +}) + +test_that("a certainty sample whose Poisson `rest` drew nothing is refused", { + skip_if_not_installed("survey") + d <- data.frame(v = c(100, 200, rep(1, 30)), y = c(10, 20, 1:30)) + des <- design_certainty("v", 50, design_weighted("v", n = 1, + method = "poisson")) + for (i in 1:50) { + s <- draw(d, des, seed = i, weights = TRUE) + if (nrow(s) == 2L) break } + expect_equal(nrow(s), 2L) + expect_error(as_svydesign(s), paste0("`sample` holds none of the 30 rows ", + "with `v` below 50"), fixed = TRUE) }) test_that("a spatial design's population is the region, not the frame", { skip_if_not_installed("survey") skip_if_not_installed("sf") - set.seed(3) + local_seed(3) pop <- data.frame(lon = stats::runif(60, -10, 10), lat = stats::runif(60, -10, 10), y = round(stats::runif(60, 5, 200))) @@ -171,7 +185,7 @@ test_that("a `rest` design that puts a row at probability 1 is not a certainty r # Classifying by `.prob == 1` filed such rows into the certainty stratum, # whose fpc counts only the true certainty rows -- svydesign() then rejected # the whole design with "FPC implies >100% sampling in some strata". - set.seed(8) + local_seed(8) pop <- data.frame(v = c(100, 100, 1:10), y = stats::rnorm(12, 50, 5)) s <- draw(pop, design_certainty("v", 50, design_simple(n = 10)), seed = 1, weights = TRUE) @@ -189,7 +203,7 @@ test_that("a `rest` design that puts a row at probability 1 is not a certainty r test_that("a multistage design is handed over as two stages, and agrees exactly", { skip_if_not_installed("survey") - set.seed(3) + local_seed(3) sizes <- rep(c(8, 12, 16), length.out = 20) d <- data.frame(cl = rep(paste0("k", 1:20), times = sizes)) d$y <- stats::rnorm(nrow(d), rep(stats::rnorm(20, 50, 20), times = sizes), 8) @@ -201,9 +215,41 @@ test_that("a multistage design is handed over as two stages, and agrees exactly" expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-8) }) +test_that("a sample weighted conditional on its clusters agrees with survey", { + skip_if_not_installed("survey") + sizes <- rep(c(5, 9, 14, 7, 11), 4) + d <- data.frame(id = seq_len(sum(sizes)), + cl = rep(sprintf("k%02d", 1:20), times = sizes)) + d$y <- rep((1:20 * 17) %% 23 * 3, times = sizes) + d$id %% 9 + d$g <- ifelse(d$id %% 3 == 0, "u", "v") + designs <- list( + design_cluster("cl", n_clusters = 5, balanced = TRUE), + design_multistage("cl", n_clusters = 5, n = 23), + design_multistage("cl", n_clusters = 5, n = 25, + allocation = "proportional", min_per_cluster = 2) + ) + for (des in designs) { + s <- draw(d, des, seed = 4, weights = TRUE) + sv <- as_svydesign(s) + ours <- ht_total(s, "y") + theirs <- survey::svytotal(~y, sv) + expect_equal(as.numeric(theirs), ours$total, tolerance = 1e-8) + expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-8) + expect_equal(survey::degf(sv), ours$df) + m_ours <- ht_mean(s, "y") + m_theirs <- survey::svymean(~y, sv) + expect_equal(as.numeric(survey::SE(m_theirs)), m_ours$se, + tolerance = 1e-8) + by_ours <- ht_total(s, "y", by = "g") + by_theirs <- survey::svyby(~y, ~g, sv, survey::svytotal) + expect_equal(by_ours$se, as.numeric(survey::SE(by_theirs)), + tolerance = 1e-8) + } +}) + test_that("a capped reservoir's population is the rows the stream reached", { skip_if_not_installed("survey") - set.seed(1) + local_seed(1) d <- data.frame(y = stats::rnorm(300, 10, 3)) s <- suppressWarnings(draw(d, design_reservoir(n = 30, max_items = 100), seed = 1, weights = TRUE)) @@ -213,7 +259,7 @@ test_that("a capped reservoir's population is the rows the stream reached", { test_that("systematic PPS maps to survey's Brewer approximation, and agrees closely", { skip_if_not_installed("survey") - set.seed(5) + local_seed(5) pop <- data.frame(x = stats::rgamma(300, 2, 0.1)) pop$y <- 3 * pop$x + stats::rnorm(300, 0, 15) for (des in list( @@ -240,3 +286,977 @@ test_that("deff() works whether or not survey's has masked it", { "spend") expect_equal(survey::deff(m), drawn::deff(m)) }) + +test_that("a reordered certainty sample hands survey the right strata", { + skip_if_not_installed("survey") + d <- svy_pop() + s <- draw(d, design_certainty("size", 900, design_simple(n = 40)), seed = 1, + weights = TRUE) + want <- ht_total(s, "spend")$se + r <- s[order(s$spend), ] + se <- as.numeric(survey::SE(survey::svytotal(~spend, as_svydesign(r)))) + expect_equal(se, want) +}) + +test_that("survey gets its own copy of the sample", { + skip_if_not_installed("survey") + skip_if_not_installed("data.table") + d <- svy_pop() + s <- draw(d, design_stratified("site", n = 60), seed = 1, weights = TRUE) + des <- as_svydesign(s) + before <- as.numeric(survey::SE(survey::svytotal(~spend, des))) + data.table::setorderv(s, "spend") + expect_equal(as.numeric(survey::SE(survey::svytotal(~spend, des))), before) +}) + +test_that("survey's copy of the sample keeps S4 vector columns", { + skip_if_not_installed("survey") + d <- svy_pop() + d$per <- lubridate::hours(d$id %% 24L) + s <- draw(d, design_stratified("site", n = 60), seed = 1, weights = TRUE) + des <- as_svydesign(s) + expect_identical(des$variables$per, s$per) + got <- survey::svytotal(~I(lubridate::period_to_seconds(per)), des) + s$sec <- lubridate::period_to_seconds(s$per) + expect_equal(as.numeric(coef(got)), ht_total(s, "sec")$total) +}) + +test_that("as_svydesign says what dropped a sample's design", { + skip_if_not_installed("survey") + d <- svy_pop() + s <- draw(d, design_stratified("site", n = 60), seed = 1, weights = TRUE) + merged <- merge(s, data.frame(id = s$id, resp = 1), by = "id") + expect_error(as_svydesign(merged), "does not carry its design") + expect_error(as_svydesign(merged), "merge()", fixed = TRUE) + expect_error(as_svydesign(s[s$site == "a", ]), "rows that were drawn") +}) + +test_that("survey follows `.weight`, while ht_total keeps to `.prob`", { + skip_if_not_installed("survey") + d <- svy_pop() + s <- draw(d, design_stratified("site", n = 60), seed = 1, weights = TRUE) + w <- s + w$.weight <- w$.weight * 1.1 + theirs <- survey::svytotal(~spend, as_svydesign(w)) + expect_equal(as.numeric(theirs), 1.1 * ht_total(s, "spend")$total) + expect_warning(ours <- ht_total(w, "spend"), class = "drawn_weight_edited") + expect_equal(ours$total, ht_total(s, "spend")$total) + + p <- s + p$.prob <- p$.prob / 2 + expect_error(as_svydesign(p), "`.prob` was changed after draw()", + fixed = TRUE) +}) + +test_that("survey gets the strata and clusters drawn, whatever the sample says", { + skip_if_not_installed("survey") + d <- svy_pop() + designs <- list( + site = design_stratified("site", n = 60), + cl = design_cluster("cl", n_clusters = 8), + cl = design_multistage("cl", n_clusters = 8, n = 40) + ) + for (i in seq_along(designs)) { + key <- names(designs)[i] + s <- draw(d, designs[[i]], seed = 1, weights = TRUE) + want <- ht_total(s, "spend")$se + renamed <- s + names(renamed)[names(renamed) == key] <- "renamed" + recoded <- s + recoded[[key]] <- rev(recoded[[key]]) + for (e in list(renamed, recoded)) { + se <- as.numeric(survey::SE(survey::svytotal(~spend, as_svydesign(e)))) + expect_equal(se, want, tolerance = 1e-8, label = key) + } + } +}) + +# ---- units taken with certainty ---------------------------------------------- + +dominant_svy <- function() { + # Four units heavy enough that PPS of 8 takes them with certainty + pop <- data.frame(id = 1:40, v = c(1000, 900, 300, 280, 1 + (1:36 %% 5)), + a = cos(1:40), b = sin(1.7 * (1:40))) + pop$y <- 2 * pop$v + 2 * cos(3 * (1:40)) + pop$flag <- pop$y > stats::median(pop$y) + pop +} + +test_that("units PPS takes with certainty are a stratum of their own", { + skip_if_not_installed("survey") + # Left in the Brewer stratum, they put survey's standard error at 35 and 25 + # times this package's here. + pop <- dominant_svy() + for (des in list( + design_weighted("v", n = 8, method = "systematic"), + design_certainty("v", 500, design_weighted("v", n = 6, + method = "systematic")) + )) { + s <- draw(pop, des, seed = 1, weights = TRUE) + expect_equal(sum(s$.prob == 1), 4L) + sv <- as_svydesign(s) + ours <- ht_total(s, "y") + theirs <- survey::svytotal(~y, sv) + expect_equal(as.numeric(theirs), ours$total) + expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 5e-3) + expect_equal(as.numeric(survey::SE(survey::svymean(~y, sv))), + ht_mean(s, "y")$se, tolerance = 5e-3) + expect_equal(survey::degf(sv), ours$df) + expect_equal(ours$df, 3) + } +}) + +test_that("Poisson sampling hands its certain units over the same way", { + skip_if_not_installed("survey") + pop <- dominant_svy() + s <- draw(pop, design_weighted("v", n = 8, method = "poisson"), seed = 2, + weights = TRUE) + expect_equal(sum(s$.prob == 1), 4L) + sv <- as_svydesign(s) + ours <- ht_total(s, "y") + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, sv))), ours$se, + tolerance = 1e-8) + expect_equal(survey::degf(sv), ours$df) + expect_equal(ours$df, nrow(s) - 5) +}) + +test_that("spread with size leaves its certain units out of Brewer", { + skip_if_not_installed("survey") + pop <- dominant_svy() + s <- draw(pop, design_spread(c("a", "b"), n = 8, size = "v"), seed = 1, + weights = TRUE) + expect_equal(sum(s$.prob == 1), 4L) + sv <- as_svydesign(s) + free <- as.data.frame(s)[s$.prob < 1, ] + brewer <- survey::svydesign(ids = ~1, fpc = ~.prob, weights = ~.weight, + data = free, pps = "brewer") + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, sv))), + as.numeric(survey::SE(survey::svytotal(~y, brewer)))) + expect_equal(survey::degf(sv), ht_total(s, "y")$df) +}) + +test_that("certainty designs agree with survey on degrees of freedom", { + skip_if_not_installed("survey") + # The certainty rows were each a unit of survey's, so survey::degf() counted + # them and survey's t and logit intervals came out narrower. + d <- svy_pop() + d$flag <- d$spend > 250 + d$tiny <- c(rep("x", 6), rep("y", nrow(d) - 6)) + designs <- list( + cert_srs = design_certainty("size", 900, design_simple(n = 40)), + cert_str = design_certainty("size", 900, + design_stratified("site", n = 40)), + take_all = design_stratified("tiny", n = 30, allocation = "equal") + ) + for (nm in names(designs)) { + s <- draw(d, designs[[nm]], seed = 1, weights = TRUE) + expect_true(any(s$.prob == 1), label = nm) + sv <- as_svydesign(s) + ours <- ht_total(s, "spend") + expect_equal(survey::degf(sv), ours$df, label = nm) + expect_equal(as.numeric(survey::SE(survey::svytotal(~spend, sv))), + ours$se, tolerance = 1e-8, label = nm) + expect_equal(unname(stats::confint(survey::svytotal(~spend, sv), + df = survey::degf(sv))[1, ]), + ours$ci, tolerance = 1e-8, label = nm) + ci <- attr(survey::svyciprop(~flag, sv, method = "xlogit"), "ci") + expect_equal(unname(ci), ht_mean(s, "flag")$ci, tolerance = 1e-8, + label = nm) + } + + # A systematic PPS `rest` agrees on the degrees of freedom; the standard + # errors differ by Brewer against Deville. + s <- draw(d, design_certainty("size", 900, + design_weighted("size", n = 40, + method = "systematic")), + seed = 1, weights = TRUE) + expect_equal(survey::degf(as_svydesign(s)), ht_total(s, "spend")$df) +}) + +test_that("a census is handed to survey with a variance of 0", { + skip_if_not_installed("survey") + # The PPS mappings stated a census as probabilities of 1, and svydesign() + # stopped with "subscript out of bounds". + pop <- dominant_svy() + for (des in list(design_weighted("v", n = 40, method = "systematic"), + design_weighted("v", n = 40, method = "poisson"), + design_spread(c("a", "b"), n = 40, size = "v"), + design_certainty("v", 500, + design_weighted("v", n = 38, + method = "systematic")), + design_stratified("flag", n = 40))) { + s <- draw(pop, des, seed = 1, weights = TRUE) + expect_true(all(s$.prob == 1)) + sv <- as_svydesign(s) + theirs <- survey::svytotal(~y, sv) + expect_equal(as.numeric(theirs), sum(pop$y)) + expect_equal(as.numeric(survey::SE(theirs)), 0) + # The one place the degrees of freedom differ, with nothing to scale + expect_equal(survey::degf(sv), 39) + expect_equal(ht_total(s, "y")$df, Inf) + } +}) + +test_that("clusters taken whole are a stratum of their own", { + skip_if_not_installed("survey") + # With every cluster selected, a cluster whose rows were all drawn is in + # every sample. ht_total() leaves it out of the degrees of freedom and the + # jackknife holds it fixed, while `survey` counted it as one more unit and, + # in one stage, gave it a share of the variance between clusters. + cl_pop <- function(sizes) { + d <- data.frame(cl = rep(letters[seq_along(sizes)], times = sizes)) + d$y <- 50 + (seq_len(nrow(d)) * 3) %% 17 + 10 * match(d$cl, letters) + d$g <- rep(c("u", "v", "w"), length.out = nrow(d)) + d$v <- 1 + d + } + with_big <- function(d) { + rbind(d, data.frame(cl = "z", y = 900, g = "u", v = 100)) + } + cases <- list( + two_stage = list(cl_pop(c(5, 20, 20)), + design_multistage("cl", n_clusters = 3, n = 15)), + two_whole = list(cl_pop(c(5, 5, 20, 20)), + design_multistage("cl", n_clusters = 4, n = 20)), + balanced = list(cl_pop(c(4, 20, 20)), + design_cluster("cl", n_clusters = 3, balanced = TRUE)), + one_stage = list(cl_pop(c(1, 20, 20)), + design_multistage("cl", n_clusters = 3, n = 3)), + in_rest = list(with_big(cl_pop(c(5, 20, 20))), + design_certainty("v", 50, design_multistage( + "cl", n_clusters = 3, n = 15))) + ) + for (nm in names(cases)) { + s <- draw(cases[[nm]][[1]], cases[[nm]][[2]], seed = 3, weights = TRUE) + expect_true(any(s$.prob == 1 & s$cl != "z"), label = nm) + sv <- as_svydesign(s) + ours <- ht_total(s, "y") + # Two clusters below certainty, one stratum + expect_equal(ours$df, 1, label = nm) + expect_equal(survey::degf(sv), ours$df, label = nm) + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, sv))), ours$se, + tolerance = 1e-8, label = nm) + expect_equal(as.numeric(survey::SE(survey::svymean(~y, sv))), + ht_mean(s, "y")$se, tolerance = 1e-8, label = nm) + by_theirs <- survey::svyby(~y, ~g, sv, survey::svytotal) + expect_equal(ht_total(s, "y", by = "g")$se, + as.numeric(survey::SE(by_theirs)), tolerance = 1e-8, + label = nm) + } +}) + +test_that("an empty sample is refused before it reaches survey", { + skip_if_not_installed("survey") + pop <- dominant_svy() + s <- draw(pop, design_spread(c("a", "b"), n = 0), seed = 1, weights = TRUE) + expect_error(as_svydesign(s), "`sample` has no rows", fixed = TRUE) +}) + +test_that("strata from several columns reach survey without carriage returns", { + skip_if_not_installed("survey") + d <- svy_pop() + d$flag <- d$spend > 250 + s <- draw(d, design_stratified(c("site", "flag"), n = 60, + min_per_stratum = 2), seed = 7, weights = TRUE) + st <- as.character(as_svydesign(s)$strata[, 1]) + expect_false(any(grepl("\r", st, fixed = TRUE))) + expect_setequal(unique(st), paste(s$site, s$flag, sep = " . ")) + expect_equal(as.numeric(survey::SE(survey::svytotal(~spend, + as_svydesign(s)))), + ht_total(s, "spend")$se, tolerance = 1e-6) + + # Labels that would read alike once joined are handed over as codes, so + # survey keeps the two strata apart. + e <- data.frame(id = 1:40, a = rep(c("x . y", "x"), each = 20), + b = rep(c("z", "y . z"), each = 20), + spend = 1:40 + 0.5 * (1:40 %% 3)) + s2 <- draw(e, design_stratified(c("a", "b"), n = 8), seed = 1, + weights = TRUE) + st2 <- as.character(as_svydesign(s2)$strata[, 1]) + expect_equal(length(unique(st2)), 2L) + expect_equal(as.numeric(survey::SE(survey::svytotal(~spend, + as_svydesign(s2)))), + ht_total(s2, "spend")$se, tolerance = 1e-6) +}) + +test_that("ci_method = \"beta\" is survey's beta interval", { + skip_if_not_installed("survey") + # Clusters that differ in their share of flagged rows, so the effective + # sample size, p(1 - p) / v, is well below the 60 rows and is not capped. + d <- data.frame(id = 1:200, cl = rep(1:20, each = 10)) + d$flag <- (d$id %% 10) < rep(c(1, 9, 2, 8, 0, 10, 3, 7, 5, 4), 2)[d$cl] + s <- draw(d, design_cluster("cl", n_clusters = 6), seed = 3, weights = TRUE) + sv <- as_svydesign(s) + for (level in c(0.95, 0.90)) { + ours <- ht_mean(s, "flag", ci_method = "beta", level = level) + expect_true(ours$mean * (1 - ours$mean) / ours$variance < ours$n) + theirs <- survey::svyciprop(~flag, sv, method = "beta", level = level) + expect_equal(ours$ci, unname(as.vector(attr(theirs, "ci"))), + tolerance = 1e-10) + } + expect_equal(ht_mean(s, "flag", ci_method = "beta")$ci_scale, "beta") +}) + +test_that("deff agrees with survey's where the design reaches part of the frame", { + skip_if_not_installed("survey") + check <- function(s, label) { + sv <- as_svydesign(s) + tot <- ht_total(s, "y") + m <- ht_mean(s, "y") + expect_equal(tot$deff, + unname(survey::deff(survey::svytotal(~y, sv, deff = TRUE))), + tolerance = 1e-8, label = label) + expect_equal(m$deff, + unname(survey::deff(survey::svymean(~y, sv, deff = TRUE))), + tolerance = 1e-8, label = label) + expect_true(abs(tot$deff - 1) < 0.35, label = label) + } + + # The first 100 of 400 rows + d <- data.frame(y = 50 + (1:400 * 37) %% 23) + expect_warning( + s <- draw(d, design_reservoir(n = 20, max_items = 100), seed = 1, + weights = TRUE), "max_items") + check(s, "reservoir") + + # Two days of a four-day frame + dt <- data.frame(ts = seq(as.POSIXct("2020-01-01", tz = "UTC"), by = "hour", + length.out = 96), + y = 50 + (1:96 * 37) %% 23) + st <- draw(dt, design_temporal("ts", "2020-01-02", "2020-01-04", + interval = 12, per_interval = 4), + seed = 2, weights = TRUE) + check(st, "temporal") + + # Points in half the frame's extent + skip_if_not_installed("sf") + sp <- data.frame(lon = -10 + (1:80 * 7) %% 20, lat = -10 + (1:80 * 3) %% 20, + y = 50 + (1:80 * 37) %% 23) + region <- sf::st_sfc( + sf::st_polygon(list(cbind(c(-10.5, 0, 0, -10.5, -10.5), + c(-10.5, -10.5, 10, 10, -10.5)))), crs = 4326) + ss <- draw(sp, design_spatial(c("lon", "lat"), region, n = 12), seed = 1, + weights = TRUE) + expect_true(sum(attr(ss, "drawn_pi") == 0) > 0) + check(ss, "spatial") +}) + +test_that("a systematic design's fpc counts the rows its walk can reach", { + skip_if_not_installed("survey") + # Rows `na_rm` drops from the walk can never be drawn. The same draw from + # the frame without them gets the same design. + d <- data.frame(id = 1:60, a = (1:60 %% 7) / 7, y = 10 + (1:60 * 13) %% 17) + d$a[5:8] <- NA + s1 <- draw(d, design_systematic(interval = 5, order_by = "a", na_rm = TRUE), + seed = 4, weights = TRUE) + s2 <- draw(d[!is.na(d$a), ], design_systematic(interval = 5, order_by = "a"), + seed = 4, weights = TRUE) + expect_equal(s1$id, s2$id) + sv1 <- as_svydesign(s1) + expect_equal(unique(sv1$fpc$popsize[, 1]), 56) + expect_equal(survey::SE(survey::svytotal(~y, sv1)), + survey::SE(survey::svytotal(~y, as_svydesign(s2)))) +}) + +test_that("PPS within strata maps to strata, with Brewer's in each", { + skip_if_not_installed("survey") + d <- svy_pop() + d$size[c(1, 250)] <- c(9000, 7000) + for (m in c("systematic", "poisson")) { + s <- draw(d, design_weighted("size", n = 60, method = m, strata = "site"), + seed = 1, weights = TRUE) + des <- as_svydesign(s) + ours <- ht_total(s, "spend") + theirs <- survey::svytotal(~spend, des) + expect_equal(as.numeric(theirs), ours$total, tolerance = 1e-8) + expect_equal(survey::degf(des), ours$df) + if (m == "poisson") { + expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-8) + } else { + # Deville here, Brewer there, stratum by stratum. + expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 5e-3) + } + } +}) + +test_that("clusters selected by size go to survey in two stages", { + skip_if_not_installed("survey") + sizes <- c(120, 90, rep(c(8, 12, 16, 20), length.out = 28)) + d <- data.frame(cl = rep(sprintf("k%02d", 1:30), times = sizes)) + d$rows <- rep(sizes, times = sizes) + d$y <- rep((1:30 * 37) %% 41 + 20, times = sizes) + + seq_len(nrow(d)) %% 9 * 2 + # Ten clusters take k01 and k02 with certainty; without them, none is. + cases <- list(list(d, 10), list(d[!d$cl %in% c("k01", "k02"), ], 6)) + for (case in cases) { + n_clusters <- case[[2]] + s <- draw(case[[1]], design_multistage("cl", n_clusters = n_clusters, + n = 4 * n_clusters, size = "rows"), + seed = 2, weights = TRUE) + des <- as_svydesign(s) + ours <- ht_total(s, "y") + theirs <- survey::svytotal(~y, des) + expect_equal(as.numeric(theirs), ours$total, tolerance = 1e-8) + expect_equal(survey::degf(des), ours$df) + # Brewer and Deville at the first stage, the same terms within clusters. + expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 5e-3) + } + expect_identical(length(unique(as_svydesign(s)$strata[, 1])), 1L) +}) + +# ---- column names -------------------------------------------------------------- + +test_that("cluster and strata columns of any name reach survey", { + skip_if_not_installed("survey") + # The cluster column's name went into the `ids` formula as it stood: a + # space stopped svydesign(), and `cl-1` beside a column `cl` was read as + # `cl - 1`, so survey clustered on `cl`. + d <- data.frame(`cl-1` = rep(paste0("B", 1:8), each = 30), + check.names = FALSE) + d$cl <- rep(c("north", "south"), each = 120) + d$y <- rep(c(140, 60, 95, 130, 70, 110, 85, 120), each = 30) + + (1:240 * 7) %% 11 + s <- draw(d, design_cluster("cl-1", n_clusters = 4), seed = 2, + weights = TRUE) + sv <- as_svydesign(s) + expect_equal(length(unique(sv$cluster[, 1])), 4L) + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, sv))), + ht_total(s, "y")$se, tolerance = 1e-8) + expect_equal(survey::degf(sv), 3) + + names(d)[1] <- "cluster id" + d$`site name` <- rep(c("a", "b"), 120) + for (des in list(design_cluster("cluster id", n_clusters = 4), + design_multistage("cluster id", n_clusters = 4, n = 20), + design_stratified("site name", n = 20))) { + s <- draw(d, des, seed = 2, weights = TRUE) + expect_equal(as.numeric(survey::SE(survey::svytotal(~y, + as_svydesign(s)))), + ht_total(s, "y")$se, tolerance = 1e-8) + } +}) + +test_that("a sample with a column as_svydesign() writes is refused", { + skip_if_not_installed("survey") + # A user column `.stratum` was overwritten with the design's strata, so + # survey::svyby(~y, ~.stratum) estimated by site. + d <- svy_pop() + d$.stratum <- ifelse(d$spend > 250, "hi", "lo") + s <- draw(d, design_stratified("site", n = 40), seed = 7, weights = TRUE) + expect_error(as_svydesign(s), + "`sample` already has `.stratum`; as_svydesign() would overwrite it.", + fixed = TRUE) + d$.fpc <- 1 + s <- draw(d, design_simple(n = 40), seed = 7, weights = TRUE) + expect_error(as_svydesign(s), "already has `.stratum` and `.fpc`", + fixed = TRUE) + + # Renamed in the sample, the design is unchanged. + names(s)[names(s) %in% c(".stratum", ".fpc")] <- c("band", "f") + expect_equal(as.numeric(survey::SE(survey::svytotal(~spend, + as_svydesign(s)))), + ht_total(s, "spend")$se, tolerance = 1e-8) + + # A design column of a reserved name is in the sample too. + e <- svy_pop() + names(e)[names(e) == "cl"] <- ".cluster" + s <- draw(e, design_cluster(".cluster", n_clusters = 8), seed = 1, + weights = TRUE) + expect_error(as_svydesign(s), "already has `.cluster`", fixed = TRUE) + names(s)[names(s) == ".cluster"] <- "cl" + expect_equal(as.numeric(survey::SE(survey::svytotal(~spend, + as_svydesign(s)))), + ht_total(s, "spend")$se, tolerance = 1e-8) +}) + +test_that("each column as_svydesign() writes is refused in the sample", { + skip_if_not_installed("survey") + d <- svy_pop(100) + for (col in drawn:::survey_columns()) { + e <- d + e[[col]] <- 1 + s <- draw(e, design_stratified("site", n = 20), seed = 1, weights = TRUE) + expect_error(as_svydesign(s), paste0("`sample` already has `", col, "`"), + fixed = TRUE, label = col) + } +}) + +test_that("unnamed arguments to as_svydesign() are refused", { + skip_if_not_installed("survey") + # modifyList() dropped them, so as_svydesign(s, ~cl) ignored the ~cl. + d <- svy_pop() + s <- draw(d, design_simple(n = 40), seed = 1, weights = TRUE) + expect_error(as_svydesign(s, ~cl), + "Argument 1 of `...` has no name", fixed = TRUE) + expect_error(as_svydesign(s, nest = TRUE, ~cl, TRUE), + "Arguments 2 and 3 of `...` have no name", fixed = TRUE) + expect_s3_class(as_svydesign(s, ids = ~cl), "survey.design") +}) + +test_that("one row from a cluster of several goes to survey as ultimate clusters", { + skip_if_not_installed("survey") + # Two stages made survey stop with "has only one PSU at stage 2", where + # ht_total() falls back to the delete-a-cluster jackknife. + sizes <- rep(c(5, 9, 14, 7, 11), 4) + d <- data.frame(id = seq_len(sum(sizes)), + cl = rep(sprintf("k%02d", 1:20), times = sizes)) + d$y <- rep((1:20 * 17) %% 23 * 3, times = sizes) + d$id %% 9 + d$g <- ifelse(d$id %% 3 == 0, "u", "v") + designs <- list( + design_multistage("cl", n_clusters = 5, n = 5), + design_multistage("cl", n_clusters = 6, n = 9, + allocation = "proportional", min_per_cluster = 1) + ) + for (des in designs) { + s <- draw(d, des, seed = 4, weights = TRUE) + sv <- as_svydesign(s) + ours <- ht_total(s, "y") + expect_equal(ours$method, "jackknife") + expect_null(sv$fpc$popsize) + theirs <- survey::svytotal(~y, sv) + expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-8) + expect_equal(survey::degf(sv), ours$df) + expect_equal(as.numeric(survey::SE(survey::svymean(~y, sv))), + ht_mean(s, "y")$se, tolerance = 1e-8) + by_theirs <- survey::svyby(~y, ~g, sv, survey::svytotal) + expect_equal(ht_total(s, "y", by = "g")$se, + as.numeric(survey::SE(by_theirs)), tolerance = 1e-8) + } +}) + +test_that("one row per cluster selected by size goes to survey in one stage", { + skip_if_not_installed("survey") + # Two stages made survey stop with "has only one PSU at stage 2", where + # ht_total() falls back to the delete-a-cluster jackknife. + sizes <- c(1, rep(c(3, 5, 8, 4), 5)) + d <- data.frame(cl = rep(c("big", sprintf("k%02d", 1:20)), times = sizes)) + d$M <- ave(seq_len(nrow(d)), d$cl, FUN = length) + d$y <- seq_len(nrow(d)) %% 7 * 3 + match(d$cl, unique(d$cl)) * 2 + d$g <- ifelse(seq_len(nrow(d)) %% 3 == 0, "u", "v") + # `big` is a cluster of one row taken with certainty, so taken whole. + big <- d + big$M[1] <- 500 + for (frame in list(d, big)) { + s <- draw(frame, design_multistage("cl", n_clusters = 6, n = 6, + size = "M"), seed = 3, weights = TRUE) + sv <- as_svydesign(s) + ours <- ht_total(s, "y") + expect_equal(ours$method, "jackknife") + theirs <- survey::svytotal(~y, sv) + expect_equal(as.numeric(survey::SE(theirs)), ours$se, tolerance = 1e-8) + expect_equal(survey::degf(sv), ours$df) + expect_equal(as.numeric(survey::SE(survey::svymean(~y, sv))), + ht_mean(s, "y")$se, tolerance = 1e-8) + by_theirs <- survey::svyby(~y, ~g, sv, survey::svytotal) + expect_equal(ht_total(s, "y", by = "g")$se, + as.numeric(survey::SE(by_theirs)), tolerance = 1e-8) + } + expect_true("big" %in% s$cl) + expect_equal(ours$df, 4) + + # A certain cluster that gives one row of several has nothing to compare + # it with in either package. + wide <- d + wide$M[wide$cl == "k03"] <- 500 + s <- draw(wide, design_multistage("cl", n_clusters = 6, n = 6, size = "M"), + seed = 3, weights = TRUE) + expect_true(is.na(ht_total(s, "y")$se)) + expect_error(survey::svytotal(~y, as_svydesign(s)), "only one PSU") +}) + +test_that("spread and systematic samples go to survey as their simple designs", { + skip_if_not_installed("survey") + # survey's standard error is that of the first-order design. For spread it + # is the larger when y varies smoothly over the coordinates, and the + # smaller here, where y has no spatial pattern and half the frame is drawn. + i <- 1:200 + d <- data.frame(x = (i * 0.618034) %% 1, yy = (i * 0.414214) %% 1) + d$smooth <- 100 + 80 * d$x + 60 * d$yy + d$flat <- 50 + (i * 37) %% 23 + srs_se <- function(s, y) { + plain <- survey::svydesign(ids = ~1, fpc = rep(nrow(d), nrow(s)), + weights = ~.weight, data = as.data.frame(s)) + as.numeric(survey::SE(survey::svytotal(stats::as.formula(y), plain))) + } + s <- draw(d, design_spread(c("x", "yy"), n = 20), seed = 1, weights = TRUE) + se <- as.numeric(survey::SE(survey::svytotal(~smooth, as_svydesign(s)))) + expect_equal(se, srs_se(s, "~smooth")) + expect_gt(se, ht_total(s, "smooth")$se) + s <- draw(d, design_spread(c("x", "yy"), n = 100), seed = 1, + weights = TRUE) + se <- as.numeric(survey::SE(survey::svytotal(~flat, as_svydesign(s)))) + expect_equal(se, srs_se(s, "~flat")) + expect_lt(se, ht_total(s, "flat")$se) + + # Systematic: the simple-random variance against successive differences + d$trend <- i + 10 * sin(i) + s <- draw(d, design_systematic(interval = 10), seed = 3, weights = TRUE) + se <- as.numeric(survey::SE(survey::svytotal(~trend, as_svydesign(s)))) + expect_equal(se, srs_se(s, "~trend")) + expect_gt(se, 2 * ht_total(s, "trend")$se) +}) + +# survey::svrepdesign() over replicate_weights(), with the attributes passed +# as they come. +rep_design <- function(s, rw = replicate_weights(s)) { + survey::svrepdesign(data = as.data.frame(s), repweights = rw, + weights = ~.weight, type = attr(rw, "type"), + scale = attr(rw, "scale"), + rscales = attr(rw, "rscales"), combined.weights = TRUE) +} + +rep_se <- function(s, y = "spend", rw = replicate_weights(s)) { + as.numeric(survey::SE(survey::svytotal(stats::as.formula(paste0("~", y)), + rep_design(s, rw)))) +} + +test_that("replicate weights give the jackknife's standard error", { + skip_if_not_installed("survey") + d <- svy_pop() + designs <- list( + simple = design_simple(n = 60), + stratified = design_stratified("site", n = 60), + cluster = design_cluster("cl", n_clusters = 8), + pps = design_weighted("size", n = 40, method = "systematic"), + certainty = design_certainty("size", 900, design_simple(n = 30)) + ) + for (nm in names(designs)) { + s <- draw(d, designs[[nm]], seed = 6, weights = TRUE) + rw <- replicate_weights(s) + jk <- ht_total(s, "spend", variance = "jackknife") + sv <- rep_design(s, rw) + expect_equal(nrow(rw), nrow(s), info = nm) + expect_equal(attr(rw, "type"), "JKn", info = nm) + expect_equal(as.numeric(coef(survey::svytotal(~spend, sv))), jk$total, + info = nm) + expect_equal(rep_se(s, rw = rw), jk$se, tolerance = 1e-8, info = nm) + expect_equal(survey::degf(sv), jk$df, info = nm) + } + + # One replicate per cluster, and each stratum's correction in `rscales`. + s <- draw(d, design_cluster("cl", n_clusters = 8), seed = 6, weights = TRUE) + expect_equal(ncol(replicate_weights(s)), 8L) + s <- draw(d, design_stratified("site", n = 60), seed = 6, weights = TRUE) + rw <- replicate_weights(s) + n_h <- as.numeric(table(s$site)) + N_h <- as.numeric(table(d$site)) + expect_equal(sort(unique(round(attr(rw, "rscales"), 12))), + sort(unique(round((1 - n_h / N_h) * (n_h - 1) / n_h, 12)))) +}) + +test_that("survey's jackknife of balanced clusters keeps a stage-one fpc", { + skip_if_not_installed("survey") + d <- svy_pop() + s <- draw(d, design_cluster("cl", n_clusters = 6, balanced = TRUE), + seed = 6, weights = TRUE) + jk <- ht_total(s, "spend", variance = "jackknife") + expect_equal(rep_se(s), jk$se, tolerance = 1e-8) + # as.svrepdesign() applies 1 - 6 / 40 for the clusters and warns that it + # dropped the second stage's correction. + rep <- suppressWarnings(survey::as.svrepdesign(as_svydesign(s))) + se <- as.numeric(survey::SE(survey::svytotal(~spend, rep))) + expect_equal(se^2, (1 - 6 / 40) * jk$se^2, tolerance = 1e-8) +}) + +test_that("survey's jackknife keeps a stage-one fpc for two stages without size", { + skip_if_not_installed("survey") + d <- svy_pop() + s <- draw(d, design_multistage("cl", n_clusters = 6, n = 24), seed = 2, + weights = TRUE) + jk <- ht_total(s, "spend", variance = "jackknife") + expect_warning(rep <- survey::as.svrepdesign(as_svydesign(s)), + "after first stage") + se <- as.numeric(survey::SE(survey::svytotal(~spend, rep))) + expect_equal(se^2, (1 - 6 / 40) * jk$se^2, tolerance = 1e-8) + + # A spread sample without `size` gets the jackknife's standard error. + d$x <- d$id %% 20 + d$yy <- d$id %/% 20 + s <- draw(d, design_spread(c("x", "yy"), n = 30, scale = FALSE), seed = 2, + weights = TRUE) + rep <- survey::as.svrepdesign(as_svydesign(s)) + expect_equal(as.numeric(survey::SE(survey::svytotal(~spend, rep))), + ht_total(s, "spend", variance = "jackknife")$se, + tolerance = 1e-8) +}) + +test_that("rows above a certainty threshold keep their weight in every replicate", { + skip_if_not_installed("survey") + d <- svy_pop() + s <- draw(d, design_certainty("size", 900, design_simple(n = 30)), seed = 2, + weights = TRUE) + rw <- replicate_weights(s) + above <- s$size >= 900 + expect_true(any(above)) + expect_equal(rw[above, , drop = FALSE], + matrix(s$.weight[above], sum(above), ncol(rw))) + expect_equal(ncol(rw), sum(!above)) +}) + +test_that("JK1 is the same jackknife where it has one stratum, and refused with more", { + skip_if_not_installed("survey") + d <- svy_pop() + s <- draw(d, design_simple(n = 50), seed = 3, weights = TRUE) + rw <- replicate_weights(s, type = "JK1") + expect_equal(attr(rw, "type"), "JK1") + expect_equal(attr(rw, "rscales"), rep(1, 50)) + expect_equal(attr(rw, "scale"), (1 - 50 / 400) * 49 / 50) + expect_equal(rep_se(s, rw = rw), rep_se(s), tolerance = 1e-10) + + st <- draw(d, design_stratified("site", n = 60), seed = 3, weights = TRUE) + expect_error(replicate_weights(st, type = "JK1"), + "jackknife has 4 strata", fixed = TRUE) + expect_error(replicate_weights(st, type = "JK2"), + "`type` must be one of \"JKn\" or \"JK1\"", fixed = TRUE) +}) + +test_that("systematic samples get successive differences along the walk", { + skip_if_not_installed("survey") + i <- 1:203 + d <- data.frame(id = i, x = (i * 0.618034) %% 1) + d$spend <- 100 + 400 * d$x + (i * 37) %% 23 + d$site <- rep(c("a", "b", "c"), times = c(100, 63, 40)) + designs <- list( + sorted = design_systematic(interval = 10, order_by = "x"), + fixed_n = design_systematic(n = 25, order_by = "x"), + within = design_stratified("site", n = 30, + within = design_systematic(order_by = "x")) + ) + for (nm in names(designs)) { + s <- draw(d, designs[[nm]], seed = 5, weights = TRUE) + rw <- replicate_weights(s) + expect_equal(attr(rw, "type"), "other", info = nm) + expect_equal(rep_se(s, rw = rw), ht_total(s, "spend")$se, + tolerance = 1e-8, info = nm) + expect_true(all(rw > 0), info = nm) + } + + # 203 rows at an interval of 10 give 20 or 21 rows, so the variance has a + # term for the random size. By hand, with no pair joining the two ends of + # the walk: + s <- draw(d, designs$sorted, seed = 5, weights = TRUE) + u <- (s$spend / s$.prob)[order(s$x)] + n <- length(u) + by_hand <- 0.9 * n / (2 * (n - 1)) * sum(diff(u)^2) + + mean(u)^2 * 0.3 * 0.7 + expect_equal(rep_se(s)^2, by_hand, tolerance = 1e-8) +}) + +test_that("successive differences filled in blocks keep the variance", { + skip_if_not_installed("survey") + i <- 1:3301 + d <- data.frame(id = i, x = (i * 0.618034) %% 1) + d$spend <- 100 + 400 * d$x + (i * 37) %% 23 + s <- draw(d, design_systematic(interval = 3, order_by = "x"), seed = 2, + weights = TRUE) + # About 1,100 rows and 2,048 replicates, filled in three blocks of columns. + rw <- replicate_weights(s) + expect_equal(ncol(rw), 2048L) + expect_gt(nrow(rw) * ncol(rw), 2 * 2^20) + expect_equal(rep_se(s, rw = rw), ht_total(s, "spend")$se, tolerance = 1e-8) + expect_true(all(rw > 0)) + + # The rows of a Sylvester Hadamard matrix are orthogonal, and those past + # the first sum to 0. + h <- hadamard_entries(1:64, 1:64) + expect_equal(h %*% t(h), diag(64, 64)) + expect_equal(rowSums(h)[-1], rep(0, 63)) + # Entry (i, j) is -1 to the number of bits i - 1 and j - 1 share, past + # 16 bits too: 2 and 1 share none, and 69999 shares one with 1, one with 2 + # and 9 with itself. + expect_equal(hadamard_entries(c(3, 70000), c(2, 70000)), + matrix(c(1, -1, -1, -1), 2)) +}) + +test_that("several systematic starts get one replicate each, empty ones too", { + skip_if_not_installed("survey") + i <- 1:203 + d <- data.frame(id = i, spend = 20 + (i * 7) %% 11 + i / 10) + s <- draw(d, design_systematic(interval = 10, n_starts = 4), seed = 2, + weights = TRUE) + rw <- replicate_weights(s) + expect_equal(ncol(rw), 4L) + expect_equal(rep_se(s, rw = rw), ht_total(s, "spend")$se, tolerance = 1e-8) + expect_equal(rep_se(s, rw = rw), + as.numeric(survey::SE(survey::svytotal(~spend, + as_svydesign(s)))), + tolerance = 1e-8) + + # On 25 rows, starts 26 to 30 of 1:30 fall past the last row and draw + # nothing. as_svydesign() refuses such a sample; its replicates count the + # empty start as a total of 0, as ht_total() does. + small <- d[1:25, ] + empty <- 0L + for (seed in 1:20) { + s <- draw(small, design_systematic(interval = 10, n_starts = 3), + seed = seed, weights = TRUE) + rw <- replicate_weights(s) + expect_equal(ncol(rw), 3L) + expect_equal(rep_se(s, rw = rw), ht_total(s, "spend")$se, + tolerance = 1e-8) + if (nrow(s) < 3L) { + empty <- empty + 1L + expect_error(as_svydesign(s), "empty replicate") + } + } + expect_gt(empty, 0L) +}) + +test_that("replicate weights are refused where no replicates describe the design", { + skip_if_not_installed("survey") + d <- svy_pop() + s <- draw(d, design_weighted("size", n = 40, method = "poisson"), seed = 1, + weights = TRUE) + expect_error(replicate_weights(s), "Poisson sampling selects rows") + s <- draw(d, design_certainty("size", 900, + design_weighted("size", n = 40, + method = "poisson")), + seed = 1, weights = TRUE) + expect_error(replicate_weights(s), "Poisson sampling selects rows") + + s <- draw(d, design_stratified("site", n = 8, allocation = c( + a = 3, b = 3, c = 1, d = 1)), seed = 1, weights = TRUE) + expect_error(replicate_weights(s), + "`sample` has no replicate weights. 2 strata `c`, `d`", + fixed = TRUE) + + edited <- draw(d, design_simple(n = 10), seed = 1, weights = TRUE) + edited$.weight[2] <- NA + expect_error(replicate_weights(edited), + "missing or not finite in 1 row(s): 2.", fixed = TRUE) + # A start past the last of 30 rows draws none. + empty <- suppressWarnings(draw(d[1:30, ], design_systematic(interval = 50), + seed = 7, weights = TRUE)) + expect_equal(nrow(empty), 0L) + expect_error(replicate_weights(empty), "has no rows") +}) + +test_that("a census gets one replicate and a variance of 0", { + skip_if_not_installed("survey") + d <- svy_pop(40) + s <- draw(d, design_simple(n = 40), seed = 1, weights = TRUE) + rw <- replicate_weights(s) + expect_equal(ncol(rw), 1L) + expect_equal(rep_se(s, rw = rw), 0) +}) + +test_that("frame_totals() totals the rows the design could reach", { + d <- data.frame(id = 1:120, w = 1 + (1:120 * 7) %% 13, + site = rep(c("a", "b", "c"), each = 40)) + d$ts <- as.POSIXct("2024-03-01", tz = "UTC") + 3600 * (0:119) + # A temporal window of two days out of five + s <- draw(d, design_temporal("ts", from = "2024-03-02", to = "2024-03-04", + interval = 1, unit = "days", per_interval = 4), + seed = 1, weights = TRUE) + inside <- d$ts >= as.POSIXct("2024-03-02", tz = "UTC") & + d$ts < as.POSIXct("2024-03-04", tz = "UTC") + expect_equal(frame_totals(s, ~ w + site), + colSums(stats::model.matrix(~ w + site, d[inside, ]))) + expect_equal(unname(frame_totals(s, ~w)[1]), 48) + + # A reservoir reads its first `max_items` rows only + s <- suppressWarnings(draw(d, design_reservoir(n = 10, max_items = 50), + seed = 1, weights = TRUE)) + expect_equal(frame_totals(s, ~w), c(`(Intercept)` = 50, w = sum(d$w[1:50]))) + + # Rows `na_rm` leaves out are not in the population + d$w[c(3, 7)] <- NA + s <- draw(d, design_weighted("w", n = 20, method = "systematic", + na_rm = TRUE), seed = 1, weights = TRUE) + counts <- frame_totals(s, ~site, table = TRUE) + expect_s3_class(counts, "table") + expect_equal(c(counts), c(a = 38L, b = 40L, c = 40L)) + + # A sample saved by drawn 0.2.0 records no probabilities, so the design + # gives them again. + old <- s + old$.row <- NULL + attr(old, "drawn_pi") <- NULL + expect_equal(frame_totals(old, ~ site), frame_totals(s, ~ site)) +}) + +test_that("frame_totals() reads values defined where the formula was written", { + d <- data.frame(id = 1:40, w = 1 + (1:40 * 7) %% 13) + s <- draw(d, design_simple(n = 8), seed = 1, weights = TRUE) + cut_at <- 6 + expect_equal(frame_totals(s, ~ I(w > cut_at)), + c(`(Intercept)` = 40, `I(w > cut_at)TRUE` = sum(d$w > 6))) + over <- function(k) frame_totals(s, ~ I(w > k), table = TRUE) + expect_equal(c(over(9)), c(`FALSE` = sum(d$w <= 9), `TRUE` = sum(d$w > 9))) +}) + +test_that("frame_totals() refuses a term with no value per frame row", { + d <- data.frame(id = 1:40, w = 1 + (1:40 * 7) %% 13) + s <- draw(d, design_simple(n = 8), seed = 1, weights = TRUE) + # model.frame() builds one row from a value alone, which would total one + # row in place of 40. + n <- 8 + for (tab in c(FALSE, TRUE)) { + expect_error(frame_totals(s, ~n, table = tab), + "`formula` has `n`, which names no column", fixed = TRUE) + expect_error(frame_totals(s, ~ w + n, table = tab), + "`formula` has `n`, which names no column", fixed = TRUE) + } + expect_error(frame_totals(s, ~ I(n + 1) + T), "`I(n + 1)` and `T`, which", + fixed = TRUE) + expect_error(frame_totals(s, ~ w + I(sum(w))), + "`I(sum(w))`, which gives 1 value where the 40 frame rows", + fixed = TRUE) +}) + +test_that("frame_totals() counts a region's rows only", { + skip_if_not_installed("sf") + g <- expand.grid(lon = seq(-14.5, 14.5, by = 1), + lat = seq(-14.5, 14.5, by = 1)) + d <- data.frame(lon = g$lon, lat = g$lat, w = 1 + seq_len(nrow(g)) %% 5) + s <- draw(d, design_spatial(c("lon", "lat"), flat_box(c(-10, 0), c(-10, 10)), + n = 20), seed = 1, weights = TRUE) + inside <- d$lon > -10 & d$lon < 0 & abs(d$lat) < 10 + expect_equal(sum(inside), 200L) + expect_equal(frame_totals(s, ~w), + c(`(Intercept)` = 200, w = sum(d$w[inside]))) +}) + +test_that("frame_totals() counts the clusters a conditional sample left out", { + sizes <- rep(c(5, 9, 14, 7, 11), 4) + d <- data.frame(id = seq_len(sum(sizes)), + cl = rep(sprintf("k%02d", 1:20), times = sizes)) + s <- draw(d, design_cluster("cl", n_clusters = 5, balanced = TRUE), + seed = 4, weights = TRUE) + expect_true(anyNA(attr(s, "drawn_pi"))) + expect_equal(frame_totals(s, ~id), c(`(Intercept)` = sum(sizes), + id = sum(d$id))) +}) + +test_that("frame_totals() feeds survey's calibration and post-stratification", { + skip_if_not_installed("survey") + d <- svy_pop() + s <- draw(d, design_simple(n = 60), seed = 2, weights = TRUE) + des <- as_svydesign(s) + cal <- survey::calibrate(des, ~ size + site, + population = frame_totals(s, ~ size + site)) + expect_equal(as.numeric(coef(survey::svytotal(~size, cal))), sum(d$size)) + post <- survey::postStratify(des, ~site, + frame_totals(s, ~site, table = TRUE)) + expect_equal(as.numeric(coef(survey::svytotal(~site, post))), + as.numeric(table(d$site))) +}) + +test_that("frame_totals() refuses what it cannot total", { + d <- data.frame(id = 1:30, w = c(NA, 2:30), z = c(1:29, NA)) + s <- draw(d, design_simple(n = 5), seed = 1, weights = TRUE) + expect_error(frame_totals(s, ~ w + z + id), + "`w` and `z` are missing in 2 of the 30 frame rows", + fixed = TRUE) + expect_error(frame_totals(s, ~ nope), "`formula` uses `nope`, which is not") + # A function of the name is a misspelt column, not a value. + expect_error(frame_totals(s, ~ w + df), "`formula` uses `df`, which is not") + expect_error(frame_totals(s, id ~ w), "not `id ~ w`, which has a left-hand", + fixed = TRUE) + expect_error(frame_totals(s, "w"), "not a character.", fixed = TRUE) + expect_error(frame_totals(s, ~id, table = NA), + "`table` must be TRUE or FALSE") + expect_error(frame_totals(s, ~1, table = TRUE), "names no column") + expect_equal(frame_totals(s, ~1), c(`(Intercept)` = 30)) + expect_error(frame_totals(d, ~id), "does not carry its design") +}) diff --git a/tests/testthat/test-variance-methods.R b/tests/testthat/test-variance-methods.R index ef7e201..da758f1 100644 --- a/tests/testthat/test-variance-methods.R +++ b/tests/testthat/test-variance-methods.R @@ -3,7 +3,7 @@ # before it was a test. strata_pop <- function() { - set.seed(71) + local_seed(71) d <- data.frame(id = 1:400, g = rep(1:20, each = 20)) d$y <- stats::rnorm(400, d$g * 3, 5) d @@ -30,6 +30,55 @@ test_that("one sampled row per stratum is refused, not reported as zero", { expect_true(all(is.na(auto$ci))) }) +test_that("the jackknife's refusal of a lonely stratum stands on its own", { + # With variance = "jackknife" the note read "needs two units per stratum + # as well", with nothing before it, and `method` said "jackknife". It then + # gave a count of strata without naming any. + d <- strata_pop() + s <- draw(d, design_stratified("g", n = 20), seed = 1, weights = TRUE) + jk <- ht_total(s, "y", variance = "jackknife") + expect_equal(jk$method, "none") + expect_equal(jk$note, paste0( + "20 strata `1`, `2`, `3`, `4`, `5`, ... each have a single sampled row, ", + "so the variation within them cannot be measured and leaving them out ", + "would understate the standard error. Draw at least two rows per ", + "stratum (min_per_stratum = 2).")) + # The analytic estimator refuses in the same words, so "auto" says it once. + auto <- ht_total(s, "y") + expect_equal(auto$note, paste("No variance is available for this sample.", + jk$note)) + + t <- data.frame(ts = rep(seq(as.POSIXct("2024-01-01", tz = "UTC"), + by = "day", length.out = 6), each = 5), + y = (1:30 * 7) %% 11) + des <- design_temporal("ts", from = "2024-01-01", to = "2024-01-07", + interval = 1, per_interval = 1, unit = "days") + s <- draw(t, des, seed = 1, weights = TRUE) + r <- ht_total(s, "y", variance = "jackknife") + expect_match(r$note, paste0( + "6 intervals `2024-01-01 00:00`, `2024-01-02 00:00`, `2024-01-03 00:00`, ", + "`2024-01-04 00:00`, `2024-01-05 00:00`, ... each have"), fixed = TRUE) + expect_match(r$note, "(per_interval = 2).", fixed = TRUE) + expect_equal(ht_total(s, "y")$note, + paste("No variance is available for this sample.", r$note)) +}) + +test_that("the jackknife names the one lonely stratum among several", { + d <- data.frame(g = c(rep("small", 5), rep("big", 60)), + y = c(1:5 * 3, (1:60 * 13) %% 17 + 90)) + s <- draw(d, design_stratified("g", n = 10, min_per_stratum = 1), seed = 1, + weights = TRUE) + r <- ht_total(s, "y", variance = "jackknife") + expect_match(r$note, "^The stratum `small` has a single sampled row") + # With counts, the advice is about the counts. + s <- draw(d, design_stratified("g", allocation = c(small = 1, big = 9)), + seed = 1, weights = TRUE) + for (v in c("jackknife", "analytic")) { + expect_match(ht_total(s, "y", variance = v)$note, + "a count of 2 or more for each in `allocation`", fixed = TRUE) + } +}) + test_that("a stratum taken whole is not lonely", { d <- data.frame(g = c("solo", rep("big", 50)), y = c(1000, 1:50)) s <- draw(d, design_stratified("g", n = 11, min_per_stratum = 1), seed = 2, @@ -41,6 +90,7 @@ test_that("a stratum taken whole is not lonely", { }) test_that("one row per interval is refused the same way", { + local_seed(92) d <- data.frame( id = 1:120, ts = rep(seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "day", @@ -57,7 +107,7 @@ test_that("one row per interval is refused the same way", { # ---- stratified jackknife ---------------------------------------------------- test_that("the jackknife deletes within strata, and matches the analytic form", { - set.seed(8) + local_seed(8) d <- data.frame(id = 1:400, g = rep(c("a", "b", "c", "d"), each = 100)) d$y <- rep(c(10, 100, 300, 900), each = 100) + stats::rnorm(400, 0, 5) s <- draw(d, design_stratified("g", n = 40), seed = 2, weights = TRUE) @@ -76,7 +126,7 @@ test_that("the jackknife deletes within strata, and matches the analytic form", }) test_that("temporal intervals are jackknife strata too", { - set.seed(9) + local_seed(9) d <- data.frame( ts = rep(seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "day", length.out = 6), each = 30), @@ -105,6 +155,7 @@ test_that("an over-allocated stratum is taken whole and the rest re-split", { }) test_that("a constant stratum under Neyman is flagged, not silently dropped", { + local_seed(156) d <- data.frame(g = rep(c("a", "b", "c"), each = 100), x = c(rep(5, 100), stats::rnorm(200, 0, 10))) des <- design_stratified("g", n = 30, allocation = "neyman", @@ -129,14 +180,24 @@ test_that("an empty stratum biases a total, which is why it warns", { test_that("simulation loops do not repeat the empty-stratum warning", { d <- data.frame(g = c(rep("big", 99), "rare")) - expect_silent(inclusion_prob(d, design_stratified("g", n = 5), - simulate = TRUE, R = 50, seed = 1)) + warned <- 0L + withCallingHandlers( + inclusion_prob(d, design_stratified("g", n = 5), simulate = TRUE, + R = 50, seed = 1), + warning = function(w) { + warned <<- warned + 1L + expect_s3_class(w, "drawn_empty_stratum") + expect_match(conditionMessage(w), "50 of the 50 simulated draws", + fixed = TRUE) + invokeRestart("muffleWarning") + }) + expect_equal(warned, 1L) }) # ---- degrees of freedom and t intervals ------------------------------------- test_that("the design's degrees of freedom are PSUs minus strata", { - set.seed(3) + local_seed(3) d <- data.frame(id = 1:240, site = rep(c("a", "b", "c"), each = 80), cl = rep(paste0("c", 1:24), each = 10), y = stats::runif(240, 5, 200)) @@ -150,7 +211,7 @@ test_that("the design's degrees of freedom are PSUs minus strata", { }) test_that("the interval uses t on those degrees of freedom, or normal on request", { - set.seed(4) + local_seed(4) d <- data.frame(cl = rep(1:24, each = 10), y = stats::runif(240, 5, 200)) s <- draw(d, design_cluster("cl", n_clusters = 4), seed = 1, weights = TRUE) r <- ht_total(s, "y") @@ -164,7 +225,7 @@ test_that("the interval uses t on those degrees of freedom, or normal on request }) test_that("t intervals restore coverage with few clusters", { - set.seed(5) + local_seed(5) d <- data.frame(id = 1:240, cl = rep(1:24, each = 10)) d$y <- rep(stats::rnorm(24, 50, 20), each = 10) + stats::rnorm(240, 0, 5) truth <- sum(d$y) @@ -182,7 +243,7 @@ test_that("t intervals restore coverage with few clusters", { test_that("degrees of freedom agree with survey::degf()", { skip_if_not_installed("survey") - set.seed(6) + local_seed(6) d <- data.frame(id = 1:240, site = rep(c("a", "b", "c"), each = 80), cl = rep(paste0("c", 1:24), each = 10), y = stats::runif(240, 5, 200)) @@ -197,14 +258,14 @@ test_that("degrees of freedom agree with survey::degf()", { # ---- Deville for systematic PPS ---------------------------------------------- test_that("systematic PPS uses Deville's approximation, exactly as published", { - set.seed(5) + local_seed(5) pop <- data.frame(x = stats::rgamma(300, 2, 0.1)) pop$y <- 3 * pop$x + stats::rnorm(300, 0, 15) s <- draw(pop, design_weighted("x", n = 60, method = "systematic"), seed = 1, weights = TRUE) r <- ht_total(s, "y") expect_equal(r$method, "deville") - expect_output(print(r), "Deville approximation") + expect_output(print(r), "(deville, an approximation)", fixed = TRUE) p <- s$.prob; u <- s$y / p; c_k <- 1 - p; a <- c_k / sum(c_k) expect_equal(r$variance, @@ -214,7 +275,7 @@ test_that("systematic PPS uses Deville's approximation, exactly as published", { }) test_that("Deville tracks the real sampling variance of systematic PPS", { - set.seed(5) + local_seed(5) pop <- data.frame(x = stats::rgamma(300, 2, 0.1)) pop$y <- 3 * pop$x + stats::rnorm(300, 0, 15) d <- design_weighted("x", n = 60, method = "systematic") @@ -228,6 +289,7 @@ test_that("Deville tracks the real sampling variance of systematic PPS", { }) test_that("certainty rows add nothing to Deville's approximation", { + local_seed(289) pop <- data.frame(x = c(1000, 900, stats::runif(98, 1, 10))) pop$y <- pop$x * 2 + stats::rnorm(100) s <- draw(pop, design_weighted("x", n = 10, method = "systematic"), seed = 3, @@ -239,13 +301,183 @@ test_that("certainty rows add nothing to Deville's approximation", { expect_equal(r$variance, sum(c_k * (u - sum(a * u))^2) / (1 - sum(a^2))) }) +# ---- units taken with certainty in the jackknife ----------------------------- + +dominant_pop <- function() { + # Six units heavy enough that systematic PPS takes them with certainty. + pop <- data.frame(id = 1:60, w = c(rep(500, 6), 1 + (1:54 %% 9) * 0.8)) + pop$y <- 1.5 * pop$w + 3 * cos(1:60) + pop +} + +test_that("a census has a jackknife variance of 0", { + # With every unit taken there is nothing random. The jackknife applied no + # finite population correction at n = N and gave a six-cluster census a + # standard error of 114. + pop <- data.frame(id = 1:30, cl = rep(letters[1:6], each = 5), + g = rep(c("a", "b"), 15), w = 1:30, y = (1:30)^1.5) + for (des in list(design_simple(n = 30), design_stratified("g", n = 30), + design_cluster("cl", n_clusters = 6), + design_weighted("w", n = 30, method = "systematic"), + design_reservoir(n = 30))) { + s <- draw(pop, des, seed = 1, weights = TRUE) + r <- ht_total(s, "y", variance = "jackknife") + expect_equal(r$total, sum(pop$y)) + expect_equal(r$variance, 0) + expect_match(r$note, "exact rather than estimated") + } +}) + +test_that("the jackknife's finite population correction is 0 at a census", { + pop <- data.frame(cl = rep(letters[1:6], each = 5)) + expect_equal(drawn:::jackknife_fpc(design_cluster("cl", n_clusters = 6), + pop, 6), 0) + expect_equal(drawn:::jackknife_fpc(design_simple(n = 10), pop, 10), 2 / 3) + # Certain units come off the frame's count as well as the sample's + expect_equal(drawn:::jackknife_fpc(design_simple(n = 10), pop, 6, 4), + 1 - 6 / 26) + # The ultimate-cluster approximation keeps no correction + expect_equal(drawn:::jackknife_fpc( + design_multistage("cl", n_clusters = 6, n = 12), pop, 6), 1) +}) + +test_that("the jackknife's correction counts only rows the design can reach", { + # Rows `na_rm` drops can never be drawn. The same draw from the frame + # without them has the same jackknife. + d <- data.frame(id = 1:60, w = c(NA, NA, 1 + (1:58 %% 9)), + a = (1:60 %% 7) / 7, y = 10 + (1:60 * 13) %% 17) + d$a[5:8] <- NA + pps <- function(...) design_weighted("w", n = 12, method = "systematic", ...) + s1 <- draw(d, pps(na_rm = TRUE), seed = 4, weights = TRUE) + s2 <- draw(d[!is.na(d$w), ], pps(), seed = 4, weights = TRUE) + expect_equal(s1$id, s2$id) + expect_equal(ht_total(s1, "y", variance = "jackknife")$se, + ht_total(s2, "y", variance = "jackknife")$se) + + p1 <- draw(d, design_spread("a", n = 10, na_rm = TRUE), seed = 4, + weights = TRUE) + p2 <- draw(d[!is.na(d$a), ], design_spread("a", n = 10), seed = 4, + weights = TRUE) + expect_equal(p1$id, p2$id) + expect_equal(ht_total(p1, "y", variance = "jackknife")$se, + ht_total(p2, "y", variance = "jackknife")$se) + expect_equal(drawn:::reachable_rows(design_spread("a", n = 10, na_rm = TRUE), + d), 56) +}) + +test_that("units systematic PPS takes with certainty are held fixed", { + pop <- dominant_pop() + d <- design_weighted("w", n = 15, method = "systematic") + s <- draw(pop, d, seed = 1, weights = TRUE) + expect_equal(sum(s$.prob == 1), 6L) + + # Deleting a dominant unit and inflating the rest made the jackknife 1,700 + # times Deville's figure here. Held fixed, the two agree closely. + jk <- ht_total(s, "y", variance = "jackknife") + dev <- ht_total(s, "y") + expect_equal(dev$method, "deville") + expect_gt(jk$variance / dev$variance, 0.8) + expect_lt(jk$variance / dev$variance, 1.25) + expect_match(jk$note, "Jackknife over 9 primary sampling unit") + expect_match(jk$note, "the 6 taken with certainty") + + # The certain units' own values do not move the variance + y2 <- s$y * ifelse(s$.prob == 1, 3, 1) + expect_equal(ht_total(s, y2, variance = "jackknife")$variance, jk$variance) +}) + +test_that("the PPS jackknife tracks the sampling variance with certain units", { + skip_on_cran() + pop <- dominant_pop() + d <- design_weighted("w", n = 15, method = "systematic") + out <- vapply(1:400, function(i) { + s <- draw(pop, d, seed = i, weights = TRUE) + c(sum(s$y / s$.prob), ht_total(s, "y", variance = "jackknife")$variance) + }, numeric(2)) + ratio <- mean(out[2, ]) / stats::var(out[1, ]) + expect_gt(ratio, 0.7) + expect_lt(ratio, 1.3) +}) + +test_that("one unit below certainty gives no variance, not a jackknife figure", { + # Deville declines with one free row, and `auto` fell back to a jackknife + # that deleted the certain units too: a standard error of 1,518 on a + # sample whose true one is 14. + pop <- data.frame(id = 1:10, w = c(1000, 1000, 1000, rep(1, 7))) + pop$y <- pop$w * 2 + (1:10) + s <- draw(pop, design_weighted("w", n = 4, method = "systematic"), seed = 1, + weights = TRUE) + expect_equal(sum(s$.prob < 1), 1L) + r <- ht_total(s, "y") + expect_true(is.na(r$variance)) + expect_equal(r$method, "none") + jk <- ht_total(s, "y", variance = "jackknife") + expect_true(is.na(jk$variance)) + expect_match(jk$note, "has 1 besides the 3 taken with certainty") +}) + +test_that("the jackknife's notes count every unit it held fixed", { + # A one-cluster sample has nothing taken with certainty, so advice to draw + # more units below certainty does not apply to it. + d <- data.frame(cl = rep(letters[1:6], each = 5), y = 1:30) + s <- draw(d, design_cluster("cl", n_clusters = 1), seed = 1, weights = TRUE) + for (v in c("auto", "jackknife")) { + r <- ht_total(s, "y", variance = v) + expect_true(is.na(r$variance)) + expect_match(r$note, "this sample has 1.", fixed = TRUE) + expect_false(grepl("certainty", r$note)) + } + + # Two rows above the threshold, and two more that a systematic PPS `rest` + # took with certainty. The note counted only the second two. + pop <- data.frame(v = c(1000, 900, 300, 280, 1 + (1:36 %% 5))) + pop$y <- 2 * pop$v + 2 * cos(3 * seq_len(nrow(pop))) + des <- design_certainty("v", 500, design_weighted("v", n = 6, + method = "systematic")) + s <- draw(pop, des, seed = 1, weights = TRUE) + expect_equal(sum(s$.prob == 1), 4L) + jk <- ht_total(s, "y", variance = "jackknife") + expect_match(jk$note, paste0("the 2 rows at or above the threshold and ", + "the 2 unit(s) `rest` took with certainty ", + "add no variance"), fixed = TRUE) + + s <- draw(pop, design_certainty("v", 250, design_simple(n = 1)), seed = 1, + weights = TRUE) + jk <- ht_total(s, "y", variance = "jackknife") + expect_true(is.na(jk$variance)) + expect_match(jk$note, paste0("has 1 besides the 4 rows at or above the ", + "threshold. Draw more units below certainty."), + fixed = TRUE) + + # One unit held fixed takes a singular verb. + s <- draw(pop, design_certainty("v", 950, design_simple(n = 3)), seed = 1, + weights = TRUE) + jk <- ht_total(s, "y", variance = "jackknife") + expect_match(jk$note, paste0("; the 1 row at or above the threshold adds ", + "no variance and was held fixed."), fixed = TRUE) +}) + +test_that("a stratum taken whole adds nothing to the jackknife", { + pop <- data.frame(g = c(rep("all", 5), rep("big", 60)), + y = c(1000 * (1:5), 1:60)) + s <- draw(pop, design_stratified("g", n = 25, allocation = "equal"), + seed = 2, weights = TRUE) + expect_true(all(s$.prob[s$g == "all"] == 1)) + jk <- ht_total(s, "y", variance = "jackknife") + expect_equal(jk$variance, ht_total(s, "y", variance = "analytic")$variance) + expect_match(jk$note, "the 5 taken with certainty") + + y2 <- s$y * ifelse(s$g == "all", 10, 1) + expect_equal(ht_total(s, y2, variance = "jackknife")$variance, jk$variance) +}) + # ---- successive differences for systematic --------------------------------- test_that("successive differences follow the walk order, not frame order", { # A frame sorted on something related to y: the setting systematic sampling # is chosen for. Each population's true variance is computed exactly, by # enumerating every start, and the ratio is pooled over many populations. - set.seed(12) + local_seed(12) N <- 400; k <- 10 ratios <- vapply(1:40, function(r) { d <- data.frame(x = stats::runif(N, 0, 100)) @@ -274,7 +506,7 @@ test_that("successive differences follow the walk order, not frame order", { }) test_that("successive differences approximate the SRS figure on a shuffled frame", { - set.seed(13) + local_seed(13) d <- data.frame(y = stats::rnorm(500, 100, 20)) out <- vapply(1:500, function(i) { r <- ht_total(draw(d, design_systematic(interval = 10), seed = i, @@ -289,7 +521,7 @@ test_that("successive differences approximate the SRS figure on a shuffled frame # ---- one row per cluster ----------------------------------------------------- test_that("one row per cluster falls back to the ultimate-cluster jackknife", { - set.seed(3) + local_seed(3) d <- data.frame(cl = rep(paste0("c", 1:24), each = 10)) d$y <- rep(stats::rnorm(24, 50, 5), each = 10) + stats::rnorm(240, 0, 20) des <- design_multistage("cl", n_clusters = 8, n = 8) @@ -310,6 +542,7 @@ test_that("one row per cluster falls back to the ultimate-cluster jackknife", { # ---- printing ---------------------------------------------------------------- test_that("the HT mean is labelled as such, not as Hajek", { + local_seed(500) d <- data.frame(y = stats::runif(100)) s <- draw(d, design_simple(n = 20), seed = 1, weights = TRUE) expect_output(print(ht_mean(s, "y", estimator = "ht")), @@ -325,7 +558,7 @@ test_that("a logical y estimates a proportion", { }) test_that("a proportion's interval stays inside [0, 1] and matches survey", { - set.seed(14) + local_seed(14) d <- data.frame(site = rep(c("a", "b"), each = 200), err = stats::runif(400) < 0.05) s <- draw(d, design_stratified("site", n = 60), seed = 3, weights = TRUE) @@ -343,3 +576,152 @@ test_that("a proportion's interval stays inside [0, 1] and matches survey", { expect_equal(unname(as.numeric(theirs)), r$mean) expect_equal(unname(as.vector(attr(theirs, "ci"))), r$ci, tolerance = 1e-8) }) + +# ---- closed forms ------------------------------------------------------------ + +# Sen-Yates-Grundy over the full joint matrix, the reference each closed form +# must reproduce. A certainty design's variance is that of `rest` over the +# rows below the threshold. +syg_reference <- function(s, design, pop, z) { + if (inherits(design, "drawn_design_certainty")) { + sp <- drawn:::certainty_split(design, pop) + free <- s$.prob < 1 + pos <- match(s$.row[free], sp$keep[sp$rest]) + pij <- drawn:::joint_inclusion(design$rest, + sp$data[sp$rest, , drop = FALSE], pos) + return(drawn:::syg_variance(z[free], s$.prob[free], pij)$variance) + } + pij <- drawn:::joint_inclusion(design, pop, s$.row) + drawn:::syg_variance(z, s$.prob, pij)$variance +} + +closed_form_pop <- function() { + pop <- data.frame( + id = 1:240, + site = rep(c("a", "b", "c", "d"), times = c(120, 80, 39, 1)), + cl = rep(sprintf("c%02d", 1:24), each = 10), + cl2 = rep(sprintf("k%02d", 1:12), + times = c(5, 6, 7, 8, 9, 10, 5, 6, 7, 8, 9, 160)), + g = rep(1:6, 40), + w = 1 + (1:240 %% 13) + ) + pop$y <- 100 + 10 * cos(1:240) + (1:240) / 7 + # The eleventh day holds two rows, fewer than `per_interval`. + pop$ts <- rep(seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "day", + length.out = 12), times = c(rep(20, 10), 2, 38)) + pop +} + +test_that("the closed-form variances equal Sen-Yates-Grundy", { + # They replace sums over every pair of sampled rows, which needed n x n + # matrices, so each must give the same figure: for a total, for a domain's + # total and for a Hajek mean's residuals. + pop <- closed_form_pop() + designs <- list( + simple = design_simple(n = 30), + census = design_simple(n = 240), + reservoir = design_reservoir(n = 20, max_items = 150), + # Stratum "d" has one row and is taken whole. + stratified = design_stratified("site", n = 40, min_per_stratum = 2), + neyman = design_stratified("site", n = 30, allocation = "neyman", + allocation_by = "y", min_per_stratum = 2), + temporal = design_temporal("ts", from = "2024-01-02", to = "2024-01-12", + interval = 1, per_interval = 3, unit = "days"), + multistage = design_multistage("cl", n_clusters = 6, n = 24), + unequal = design_multistage("cl2", n_clusters = 4, n = 20), + every_cluster = design_multistage("cl", n_clusters = 24, n = 48), + certainty = design_certainty("w", 12, design_stratified( + "site", n = 20, min_per_stratum = 2)) + ) + for (nm in names(designs)) { + d <- designs[[nm]] + for (seed in 1:2) { + if (nm == "reservoir") { + expect_warning(s <- draw(pop, d, seed = seed, weights = TRUE), + "sampling only the first 150") + } else { + s <- draw(pop, d, seed = seed, weights = TRUE) + } + n_hat <- sum(1 / s$.prob) + hajek <- (s$y - sum(s$y / s$.prob) / n_hat) / n_hat + domain <- s$y * (s$g == 2) + for (z in list(s$y, hajek, domain)) { + expect_equal(drawn:::ht_variance(d, pop, s$.row, z, s$.prob)$variance, + syg_reference(s, d, pop, z), tolerance = 1e-10, + label = nm) + } + expect_equal(ht_total(s, "y", variance = "analytic")$variance, + syg_reference(s, d, pop, s$y), tolerance = 1e-10, + label = nm) + expect_equal(ht_mean(s, "y", variance = "analytic")$se^2, + syg_reference(s, d, pop, hajek), tolerance = 1e-10, + label = nm) + b <- ht_total(s, "y", by = "g", variance = "analytic") + expect_equal(b$se[b$g == 2]^2, syg_reference(s, d, pop, domain), + tolerance = 1e-10, label = nm) + } + } +}) + +test_that("a spatial sample's closed form equals Sen-Yates-Grundy", { + skip_if_not_installed("sf") + pop <- data.frame(id = 1:120, x = (1:120 * 7) %% 50, yy = (1:120 * 11) %% 50) + pop$y <- 20 + pop$x / 3 + 5 * sin(pop$id) + box <- sf::st_sfc(sf::st_polygon(list(cbind(c(0, 30, 30, 0, 0), + c(0, 0, 30, 30, 0)))), + crs = 3857) + d <- design_spatial(c("x", "yy"), box, n = 12, crs = 3857) + s <- draw(pop, d, seed = 4, weights = TRUE) + expect_lt(sum(inclusion_prob(pop, d) > 0), nrow(pop)) + expect_equal(ht_total(s, "y", variance = "analytic")$variance, + syg_reference(s, d, pop, s$y), tolerance = 1e-10) +}) + +test_that("a stratum taken whole adds exactly 0 to the closed form", { + # Including one of a single row, where the variance of one value is NA. + expect_identical(drawn:::srs_variance(c(3, 8, 1), c(1L, 2L, 2L), + c(1, 2), c(1, 2)), 0) + expect_equal(drawn:::srs_variance(c(3, 8, 1, 4), c(1L, 2L, 2L, 2L), + c(1, 3), c(1, 9)), + 9^2 * (1 - 3 / 9) * stats::var(c(8, 1, 4)) / 3) +}) + +test_that("an integer y is summed without overflowing", { + # rowsum() adds integers as integers and gives NA past 2^31 - 1. + pop <- data.frame(id = 1:200, g = rep(c("a", "b"), each = 100), + cl = rep(sprintf("c%02d", 1:20), each = 10)) + pop$y <- as.integer(4e8 + (1:200 * 7919) %% 1000 * 1e5) + for (d in list(design_simple(n = 40), design_stratified("g", n = 40), + design_multistage("cl", n_clusters = 5, n = 20))) { + s <- draw(pop, d, seed = 1, weights = TRUE) + r <- ht_total(s, "y") + expect_equal(r$method, "analytic") + expect_equal(r$variance, syg_reference(s, d, pop, as.numeric(s$y)), + tolerance = 1e-10) + } +}) + +test_that("a sample of 10,000 rows is estimated in linear time and memory", { + # The sum over pairs needed about 90 bytes for each pair of sampled rows, + # 9 GB here. + skip_on_cran() + N <- 50000 + pop <- data.frame(id = seq_len(N), g = rep(letters[1:8], length.out = N)) + pop$y <- 100 + (seq_len(N) * 7919) %% 1000 / 10 + for (d in list(design_simple(n = 10000), design_stratified("g", n = 10000))) { + s <- draw(pop, d, seed = 1, weights = TRUE) + took <- system.time(r <- ht_total(s, "y"))[["elapsed"]] + expect_equal(r$method, "analytic") + expect_lt(took, 10) + N_h <- table(pop$g) + n_h <- table(s$g) + want <- if (inherits(d, "drawn_design_simple")) { + N^2 * (1 - 10000 / N) * stats::var(s$y) / 10000 + } else { + sum(N_h^2 * (1 - n_h / N_h) * tapply(s$y, s$g, stats::var) / n_h) + } + expect_equal(r$variance, want, tolerance = 1e-10) + b <- ht_total(s, "y", by = "g") + expect_true(all(b$method == "analytic")) + } +}) diff --git a/tests/testthat/test-variance.R b/tests/testthat/test-variance.R index 2ec7f31..1b29bb6 100644 --- a/tests/testthat/test-variance.R +++ b/tests/testthat/test-variance.R @@ -1,5 +1,5 @@ var_pop <- function() { - set.seed(7) + local_seed(7) N <- 240 d <- data.frame( id = 1:N, @@ -56,6 +56,8 @@ test_that("designs without a closed form refuse", { expect_error(joint_prob(d, design_weighted("w", n = 10)), "no closed-form") expect_error(joint_prob(d, design_cluster("cl", n_clusters = 3, balanced = TRUE)), "no closed-form") + expect_error(joint_prob(d, design_cluster("cl", n_clusters = 3, balanced = TRUE)), + "joint_prob(data, design, simulate = TRUE)", fixed = TRUE) expect_error(joint_prob(d, design_bootstrap(n_replicates = 5)), "not a probability sample") expect_error(joint_prob(d, design_multistage("cl", n_clusters = 4, n = 10)), @@ -79,7 +81,9 @@ test_that("ht_total validates y and level", { d <- var_pop() s <- draw(d, design_simple(n = 30), seed = 1, weights = TRUE) expect_error(ht_total(s, "nope"), "no column") - expect_error(ht_total(s, letters[1:30]), "numeric column name") + expect_error(ht_total(s, letters[1:30]), + "one column name, several column names, or a numeric vector") + expect_error(ht_total(s, NA_character_), "It is NA, a missing column name") expect_error(ht_total(s, "y", level = 1.5), "between 0 and 1") }) @@ -102,6 +106,9 @@ test_that("the estimated variance matches the estimator's true variance", { est[i] <- r$total; vr[i] <- r$variance } ok <- !is.na(est) & !is.na(vr) + # Leaving out the samples without a variance would hide an estimator that + # declines on many of them. + expect_gt(mean(ok), 0.99, label = paste(nm, "share with a variance")) ratio <- mean(vr[ok]) / stats::var(est[ok]) expect_gt(ratio, 0.75, label = paste(nm, "variance ratio")) expect_lt(ratio, 1.35, label = paste(nm, "variance ratio")) @@ -119,6 +126,30 @@ test_that("systematic sampling reports a successive-difference variance and says expect_true(all(is.finite(r$ci))) }) +test_that("a systematic step under 2 rows is not said to lack an unbiased variance", { + d <- data.frame(id = 1:100, y = (1:100) %% 7) + # Every pair of rows can be drawn together once n is above half of N. + pairs <- joint_prob(d, design_systematic(n = 51)) + expect_true(all(pairs > 0)) + expect_true(any(joint_prob(d, design_systematic(n = 50)) == 0)) + + s <- draw(d, design_systematic(n = 70), seed = 1, weights = TRUE) + r <- ht_total(s, "y") + expect_equal(r$method, "successive difference") + expect_match(r$note, "^This is the successive-difference approximation") + s <- draw(d, design_systematic(n = 50), seed = 1, weights = TRUE) + expect_match(ht_total(s, "y")$note, "no design-unbiased variance") + + d$h <- rep(c("a", "b"), each = 50) + within <- design_systematic(order_by = "id") + s <- draw(d, design_stratified("h", n = 60, within = within), seed = 1, + weights = TRUE) + expect_match(ht_total(s, "y")$note, "^This is the sum over strata") + s <- draw(d, design_stratified("h", n = 40, within = within), seed = 1, + weights = TRUE) + expect_match(ht_total(s, "y")$note, "no design-unbiased variance") +}) + test_that("the print method shows the interval, or the reason there isn't one", { d <- var_pop() out <- capture.output(print(ht_total(draw(d, design_simple(n = 30), seed = 1, @@ -138,7 +169,7 @@ test_that("the print method shows the interval, or the reason there isn't one", }) test_that("the jackknife supplies a variance where the analytic form cannot", { - set.seed(3); N <- 240 + local_seed(3); N <- 240 pop <- data.frame(id = 1:N, cl = rep(paste0("c", 1:24), each = 10), y = round(stats::runif(N, 5, 200))) pop$w <- pop$y + 50 @@ -152,7 +183,7 @@ test_that("the jackknife supplies a variance where the analytic form cannot", { }) test_that("jackknife and analytic agree where both exist", { - set.seed(3); N <- 240 + local_seed(3); N <- 240 pop <- data.frame(id = 1:N, cl = rep(paste0("c", 1:24), each = 10), y = round(stats::runif(N, 5, 200))) for (d in list(design_simple(n = 30), design_cluster("cl", n_clusters = 6))) { @@ -164,7 +195,7 @@ test_that("jackknife and analytic agree where both exist", { }) test_that("systematic sampling refuses the jackknife too", { - set.seed(3) + local_seed(3) pop <- data.frame(id = 1:240, y = round(stats::runif(240, 5, 200))) r <- ht_total(draw(pop, design_systematic(interval = 8), seed = 1, weights = TRUE), "y", variance = "jackknife") @@ -195,7 +226,7 @@ test_that("simulated joints converge on the closed form where one exists", { }) test_that("simulation supplies joints for designs with no closed form", { - set.seed(5) + local_seed(5) d <- data.frame(id = 1:30, w = stats::runif(30, 1, 10)) des <- design_weighted("w", n = 8, method = "systematic") expect_error(joint_prob(d, des), "no closed-form joint") @@ -240,7 +271,7 @@ test_that("cluster variance is honest when clusters differ in size", { # is the same size. Sen-Yates-Grundy assumes a fixed size; applied row by row # here it came out at 0.39 of the truth, went negative on 57% of samples, and # produced zero-width intervals. - set.seed(9) + local_seed(9) sizes <- c(3, 4, 5, 6, 3, 4, 5, 6, 7, 8, 4, 5) pop <- data.frame(cl = rep(paste0("c", seq_along(sizes)), times = sizes)) pop$y <- round(stats::rnorm(nrow(pop), 100, 30) + @@ -271,7 +302,7 @@ test_that("cluster variance is honest when clusters differ in size", { }) test_that("the jackknife declines where deleting rows misrepresents the design", { - set.seed(4) + local_seed(4) pop <- data.frame(w = stats::runif(60, 1, 20), y = round(stats::rnorm(60, 100, 25))) # Poisson: rows are independent and the exact form is right there. @@ -294,7 +325,7 @@ test_that("the jackknife declines where deleting rows misrepresents the design", }) test_that("the systematic-PPS jackknife tracks the real sampling variance", { - set.seed(19) + local_seed(19) N <- 300 pop <- data.frame(w = stats::rlnorm(N, 5, 0.9)) # A response variable distinct from the size measure. Totalling the size @@ -317,7 +348,7 @@ test_that("the systematic-PPS jackknife tracks the real sampling variance", { test_that("the jackknife treats certainty rows as fixed, not as sampling units", { # Certainty rows are in every possible sample. Deleting one and inflating the # rest invents variance the design does not have -- 4.3x too much. - set.seed(12) + local_seed(12) pop <- data.frame(w = c(rep(100, 6), rep(1, 54)), y = round(stats::rnorm(60, 100, 25), 3)) des <- design_certainty("w", 50, design_simple(n = 10)) @@ -334,7 +365,6 @@ test_that("a negative analytic variance is reported, not passed on", { # Sen-Yates-Grundy can go negative on an unlucky sample. sqrt() was already # guarded, but the reason was dropped, `auto` did not fall back, and deff() # divided by it and returned a negative design effect. - fake <- list(variance = -1234, method = "analytic", note = NULL) expect_true(is.na(drawn:::deff_value(-1234, 1:10, rep(0.5, 10), 100, 10, "total"))) @@ -345,10 +375,30 @@ test_that("a negative analytic variance is reported, not passed on", { s, pop, attr(s, "drawn_rows"), s$y, s$.prob, "analytic") expect_true(is.na(bad$variance)) expect_true(nzchar(bad$note)) + + # A simple random sample's own estimator cannot go negative, so it is + # replaced here by one that does. + local_mocked_bindings( + ht_variance = function(...) list(variance = -1234, note = NULL), + .package = "drawn" + ) + a <- ht_total(s, "y", variance = "analytic") + expect_true(is.na(a$variance)) + expect_equal(a$method, "none") + expect_match(a$note, "returned a negative variance (-1230)", fixed = TRUE) + expect_true(is.na(a$deff)) + + auto <- ht_total(s, "y") + expect_equal(auto$method, "jackknife") + expect_equal(auto$variance, + ht_total(s, "y", variance = "jackknife")$variance) + expect_match(auto$note, "^The design's own estimator declined") + expect_match(auto$note, "negative variance", fixed = TRUE) + expect_gt(auto$deff, 0) }) test_that("a design neither estimator can handle says so once, truthfully", { - set.seed(3) + local_seed(3) pop <- data.frame(y = stats::rnorm(60, 10, 3), cl = rep(1:6, each = 10)) r <- ht_total(draw(pop, design_cluster("cl", n_clusters = 1), seed = 1, weights = TRUE), "y") @@ -358,3 +408,378 @@ test_that("a design neither estimator can handle says so once, truthfully", { expect_match(r$note, "at least two clusters") expect_match(r$note, "at least two primary") }) + +test_that("strata and clusters come from the frame, not the sample's columns", { + d <- var_pop() + designs <- list( + site = design_stratified("site", n = 40, min_per_stratum = 2), + cl = design_cluster("cl", n_clusters = 6), + cl = design_multistage("cl", n_clusters = 6, n = 24) + ) + for (i in seq_along(designs)) { + key <- names(designs)[i] + s <- draw(d, designs[[i]], seed = 2, weights = TRUE) + want <- ht_total(s, "y") + want_jk <- ht_total(s, "y", variance = "jackknife") + renamed <- s + names(renamed)[names(renamed) == key] <- "renamed" + recoded <- s + recoded[[key]] <- rev(recoded[[key]]) + for (e in list(renamed, recoded)) { + got <- ht_total(e, "y") + expect_equal(got$se, want$se, label = key) + expect_equal(got$df, want$df, label = key) + expect_equal(ht_total(e, "y", variance = "jackknife")$se, want_jk$se, + label = key) + } + } +}) + +test_that("dropping the cluster column leaves a cluster sample's variance alone", { + # Without the column the jackknife used to delete rows rather than clusters + # and the degrees of freedom fell to 0, which removed the interval. + d <- var_pop() + s <- draw(d, design_cluster("cl", n_clusters = 6), seed = 1, weights = TRUE) + gone <- s + gone$cl <- NULL + got <- ht_total(gone, "y") + expect_equal(got$df, 5) + expect_equal(got$ci, ht_total(s, "y")$ci) + jk <- ht_total(gone, "y", variance = "jackknife") + expect_match(jk$note, "Jackknife over 6 primary") + expect_equal(jk$se, ht_total(s, "y", variance = "jackknife")$se) +}) + +test_that("a variance that overflows is reported as missing, with no success note", { + d <- var_pop() + s <- draw(d, design_simple(n = 30), seed = 1, weights = TRUE) + huge <- rep(c(1e300, -1e300), 15) + r <- ht_total(s, huge) + expect_true(is.na(r$se)) + expect_equal(r$method, "none") + expect_match(r$note, "overflowed") + expect_false(grepl("Jackknife over", r$note)) +}) + +test_that("an overflowing variance names its cause once, in every branch", { + d <- var_pop() + s <- draw(d, design_reservoir(n = 30), seed = 1, weights = TRUE) + big <- s$y * 1e200 + for (v in c("auto", "analytic", "jackknife")) { + r <- ht_total(s, big, variance = v) + expect_true(is.finite(r$total), label = v) + expect_true(is.na(r$variance), label = v) + expect_equal(r$method, "none", label = v) + expect_equal(lengths(regmatches(r$note, gregexpr("Rescale", r$note))), 1L, + label = v) + } +}) + +# ---- what the dispatcher catches --------------------------------------------- + +test_that("an error inside a variance estimator reaches the caller", { + # Every error used to be read as the estimator declining, so running out of + # memory, or a bug, came back as a jackknife figure with the error's text in + # the note. + pop <- data.frame(id = 1:60, y = 1:60) + s <- draw(pop, design_simple(n = 20), seed = 1, weights = TRUE) + # `by` computes every domain's simple random sampling variance at once, with + # srs_variance_by(). + local_mocked_bindings(srs_variance = function(...) stop("internal failure"), + srs_variance_by = function(...) { + stop("internal failure") + }) + expect_error(ht_total(s, "y"), "internal failure") + expect_error(ht_total(s, "y", variance = "analytic"), "internal failure") + expect_error(ht_mean(s, "y"), "internal failure") + expect_error(ht_total(s, "y", by = "id"), "internal failure") +}) + +test_that("an error inside the jackknife reaches the caller", { + pop <- data.frame(id = 1:60, y = 1:60) + s <- draw(pop, design_simple(n = 20), seed = 1, weights = TRUE) + local_mocked_bindings( + jackknife_groups = function(...) stop("internal failure") + ) + expect_error(ht_total(s, "y", variance = "jackknife"), "internal failure") +}) + +test_that("an error counting the frame for the jackknife reaches the caller", { + # The jackknife's finite population correction counts the rows the design + # can reach. An error there was caught and the correction dropped, so the + # variance came back as if the frame were infinite. + pop <- data.frame(id = 1:60, y = 1:60) + s <- draw(pop, design_reservoir(n = 40), seed = 1, weights = TRUE) + want <- ht_total(s, "y", variance = "jackknife") + expect_equal(want$variance, 60^2 * (1 - 40 / 60) * stats::var(s$y) / 40, + tolerance = 1e-10) + reach <- drawn:::reservoir_reach + in_fpc <- function() { + any(vapply(sys.calls(), function(cl) { + identical(cl[[1L]], quote(jackknife_fpc)) + }, logical(1))) + } + local_mocked_bindings(reservoir_reach = function(...) { + if (in_fpc()) stop("internal failure") + reach(...) + }) + expect_error(ht_total(s, "y", variance = "jackknife"), "internal failure") + expect_error(ht_total(s, "y", by = "id", variance = "jackknife"), + "internal failure") +}) + +test_that("a declining estimator still falls back to the jackknife", { + pop <- data.frame(id = 1:60, y = 1:60) + s <- draw(pop, design_simple(n = 20), seed = 1, weights = TRUE) + want <- ht_total(s, "y", variance = "jackknife") + local_mocked_bindings(srs_variance = function(...) { + drawn:::stop_declined("No joint probabilities here.\nA second line.") + }) + r <- ht_total(s, "y") + expect_equal(r$method, "jackknife") + expect_equal(r$variance, want$variance) + expect_match(r$note, + "jackknife was used instead. No joint probabilities here.", + fixed = TRUE) + expect_false(grepl("second line", r$note)) + + a <- ht_total(s, "y", variance = "analytic") + expect_true(is.na(a$variance)) + expect_equal(a$method, "none") + expect_match(a$note, "No joint probabilities here.", fixed = TRUE) +}) + +test_that("a refusal from a design is a classed error outside the estimators", { + d <- var_pop() + err <- tryCatch(joint_prob(d, design_weighted("w", n = 10)), + error = function(e) e) + expect_s3_class(err, "drawn_declined") + expect_null(conditionCall(err)) + err <- tryCatch(inclusion_prob(d, design_systematic(8, start = 2)), + error = function(e) e) + expect_s3_class(err, "drawn_declined") +}) + +test_that("a simple random sample of 5,000 rows gets its analytic variance", { + # Sen-Yates-Grundy held about eleven n x n matrices of doubles at once; + # 8,000 rows needed 6 GB. The closed form needs none. + pop <- data.frame(id = 1:10000, y = (1:10000) %% 97) + s <- draw(pop, design_simple(n = 5000), seed = 1, weights = TRUE) + r <- ht_total(s, "y") + expect_equal(r$method, "analytic") + expect_null(r$note) + f <- 1 - 5000 / 10000 + expect_equal(r$variance, 10000^2 * f * stats::var(s$y) / 5000, + tolerance = 1e-8) + expect_equal(ht_total(s, "y", variance = "analytic")$variance, r$variance) +}) + +test_that("a multistage sample of 5,000 rows gets its two-stage variance", { + # Past the Sen-Yates-Grundy size limit a multistage sample went to the + # delete-a-cluster jackknife, which has no first-stage finite population + # correction: with half the clusters selected it doubled the variance + # between them. The two-stage form needs no joint probabilities. + pop <- data.frame(cl = rep(sprintf("c%03d", 1:200), each = 60)) + pop$y <- 100 + rep((1:200 * 37) %% 61, each = 60) + (1:12000 * 13) %% 21 + s <- draw(pop, design_multistage("cl", n_clusters = 100, n = 5000), + seed = 1, weights = TRUE) + local_mocked_bindings(joint_inclusion = function(...) { + stop("the joint matrix was built") + }) + r <- ht_total(s, "y") + expect_equal(r$method, "analytic") + expect_null(r$note) + N_i <- 60 + m <- 50 + t_i <- N_i * tapply(s$y, s$cl, mean) + between <- 200^2 * (1 - 100 / 200) * stats::var(t_i) / 100 + within <- 200 / 100 * + sum(N_i^2 * (1 - m / N_i) * tapply(s$y, s$cl, stats::var) / m) + expect_equal(r$variance, between + within, tolerance = 1e-10) + jk <- ht_total(s, "y", variance = "jackknife") + expect_gt(jk$variance, 1.5 * r$variance) +}) + +test_that("Sen-Yates-Grundy declines a sample too large to hold its matrices", { + # A design with no closed form of its own reaches the pairwise sum. It + # declines from the projected size, before allocating anything. The joint + # probabilities of two rows are asked for, to learn whether the design has + # any, and never those of the whole sample. + pop <- data.frame(id = 1:10000, y = (1:10000) %% 97) + rows <- seq(1L, 10000L, by = 2L) + fake <- structure(list(), class = c("drawn_design_nope", "drawn_design")) + local_mocked_bindings(joint_inclusion = function(design, data, rows) { + if (length(rows) > 2L) stop("the joint matrix was built") + diag(0.5, length(rows)) + }) + err <- tryCatch(drawn:::ht_variance(fake, pop, rows, pop$y[rows], + rep(0.5, 5000)), + error = function(e) e) + expect_s3_class(err, "drawn_declined") + expect_match(conditionMessage(err), + "1.6 GB of memory for its 5,000 x 5,000 matrices", fixed = TRUE) + + r <- drawn:::ht_variance_dispatch(fake, pop[rows, ], pop, rows, + pop$y[rows], rep(0.5, 5000), "auto") + expect_equal(r$method, "jackknife") + expect_match(r$note, "GB of memory") + expect_equal(r$variance, 10000^2 * 0.5 * stats::var(pop$y[rows]) / 5000, + tolerance = 1e-8) + a <- drawn:::ht_variance_dispatch(fake, pop[rows, ], pop, rows, + pop$y[rows], rep(0.5, 5000), "analytic") + expect_true(is.na(a$variance)) + expect_match(a$note, "variance = \"auto\"", fixed = TRUE) +}) + +test_that("a design with no joint probabilities says so at any sample size", { + # Past the size limit the estimator declined for memory, which hid that + # the design has no joint probabilities to fill the matrices with. + pop <- data.frame(id = 1:10000, y = (1:10000) %% 97) + fake <- structure(list(), class = c("drawn_design_nope", "drawn_design")) + for (rows in list(1:100, seq(1L, 10000L, by = 2L))) { + err <- tryCatch(drawn:::ht_variance(fake, pop, rows, pop$y[rows], + rep(0.5, length(rows))), + error = function(e) e) + expect_s3_class(err, "drawn_declined") + expect_match(conditionMessage(err), + "has no closed-form joint inclusion probability") + expect_no_match(conditionMessage(err), "GB") + } +}) + +test_that("a jackknife that gives no figure reports method 'none'", { + # ?ht_total says `method` is "none" when nothing produced a figure, but a + # refused jackknife said "jackknife", in the by table too. + pop <- data.frame(w = 1 + (1:60 * 7) %% 19, y = 100 + (1:60 * 37) %% 41, + g = rep(c("a", "b"), 30)) + for (des in list(design_weighted("w", n = 12, method = "poisson"), + design_systematic(interval = 6))) { + s <- draw(pop, des, seed = 1, weights = TRUE) + r <- ht_total(s, "y", variance = "jackknife") + expect_true(is.na(r$se)) + expect_equal(r$method, "none") + expect_true(nzchar(r$note)) + b <- ht_total(s, "y", by = "g", variance = "jackknife") + expect_true(all(is.na(b$se))) + expect_true(all(b$method == "none")) + } +}) + +test_that("a Hajek mean of a one-row sample has no standard error", { + # The residual of one row is 0, so the Poisson estimator gave 0 and a + # zero-width interval. + pop <- data.frame(w = rep(1, 40), y = 50 + (1:40 * 37) %% 23) + des <- design_weighted("w", n = 1, method = "poisson") + sizes <- vapply(1:40, function(i) nrow(draw(pop, des, seed = i)), integer(1)) + s <- draw(pop, des, seed = which(sizes == 1L)[1], weights = TRUE) + m <- ht_mean(s, "y") + expect_true(is.na(m$se)) + expect_equal(m$method, "none") + expect_match(m$note, "one row") + expect_true(all(is.na(m$ci))) + expect_equal(ht_mean(s, "y", variance = "none")$note, + "Variance not requested.") + # A total, and the mean over the known N, are still estimated. + expect_true(is.finite(ht_total(s, "y")$se)) + expect_true(is.finite(ht_mean(s, "y", estimator = "ht")$se)) + + # A census of one row is exact. + one <- draw(data.frame(y = 7), design_simple(n = 1), seed = 1, + weights = TRUE) + expect_equal(ht_mean(one, "y")$se, 0) +}) + +test_that("an interval missing for want of degrees of freedom says why", { + # A one-row Poisson sample has a standard error and 0 degrees of freedom. + # The note blamed one unit per stratum, and print left it out. + pop <- data.frame(w = rep(1, 40), y = 50 + (1:40 * 37) %% 23) + des <- design_weighted("w", n = 1, method = "poisson") + sizes <- vapply(1:40, function(i) nrow(draw(pop, des, seed = i)), integer(1)) + s <- draw(pop, des, seed = which(sizes == 1L)[1], weights = TRUE) + r <- ht_total(s, "y") + expect_equal(r$df, 0) + expect_true(is.finite(r$se)) + expect_true(all(is.na(r$ci))) + expect_match(r$note, "leaves 0 degrees of freedom") + expect_false(grepl("per stratum", r$note)) + expect_output(print(r), "leaves 0 degrees") + expect_true(all(is.finite(ht_total(s, "y", df = Inf)$ci))) +}) + +test_that("a df below 1 is refused rather than dropping the interval", { + pop <- data.frame(id = 1:100, y = 1:100) + s <- draw(pop, design_simple(n = 20), seed = 1, weights = TRUE) + expect_error(ht_total(s, "y", df = 0.5), "not 0.5") + expect_error(ht_mean(s, "y", df = 0.5), "1 or more") + r <- ht_total(s, "y", df = 1) + expect_equal(diff(r$ci) / 2, stats::qt(0.975, 1) * r$se) +}) + +test_that("an exact estimate gets a zero-width interval at any df", { + expect_equal(drawn:::interval(5, 0, 0.95, 0), c(5, 5)) + expect_equal(drawn:::interval(0.3, 0, 0.95, 0, logit = TRUE), c(0.3, 0.3)) + expect_equal(drawn:::interval(5, 1, 0.95, 0), c(NA_real_, NA_real_)) +}) + +# ---- degrees of freedom and units taken with certainty ---------------------- + +dominant8 <- function() { + # Eight units large enough that systematic PPS of 10 takes them with + # certainty, and 40 small ones from which the other two are drawn. + pop <- data.frame(x = c(rep(100, 8), 1 + 3 * (sin((1:40) * 2.3) + 1))) + pop$y <- 2 * pop$x + 3 * cos(1:48) + pop$half <- rep(c("a", "b"), 24) + pop +} + +test_that("units taken with certainty carry no degrees of freedom", { + pop <- dominant8() + pps <- design_weighted("x", n = 10, method = "systematic") + cert <- design_certainty("x", 100, design_weighted("x", n = 2, + method = "systematic")) + expect_equal(sort(inclusion_prob(pop, pps)), sort(inclusion_prob(pop, cert))) + + # The same selection built two ways had 9 and 1 degrees of freedom. + s <- draw(pop, pps, seed = 1, weights = TRUE) + expect_equal(sum(s$.prob == 1), 8L) + r <- ht_total(s, "y") + expect_equal(r$df, 1) + expect_equal(ht_total(draw(pop, cert, seed = 1, weights = TRUE), "y")$df, 1) + expect_equal(diff(r$ci) / 2, stats::qt(0.975, 1) * r$se) + expect_equal(ht_mean(s, "y")$df, 1) + expect_equal(attr(ht_total(s, "y", by = "half"), "df"), 1) +}) + +test_that("the t interval covers once certain units stop counting", { + skip_on_cran() + # On 9 degrees of freedom this interval covered 74% of the time. + pop <- dominant8() + truth <- sum(pop$y) + des <- design_weighted("x", n = 10, method = "systematic") + hit <- vapply(1:400, function(i) { + r <- ht_total(draw(pop, des, seed = i, weights = TRUE), "y") + r$ci[1] <= truth && truth <= r$ci[2] + }, logical(1)) + expect_gt(mean(hit), 0.9) +}) + +test_that("a stratum taken whole carries no degrees of freedom", { + pop <- data.frame(g = c(rep("all", 5), rep("big", 60)), + y = c(1000 * (1:5), 1:60)) + s <- draw(pop, design_stratified("g", n = 25, allocation = "equal"), + seed = 2, weights = TRUE) + expect_true(all(s$.prob[s$g == "all"] == 1)) + # 20 rows in the stratum that was sampled, less that one stratum + expect_equal(ht_total(s, "y")$df, 19) +}) + +test_that("a sample with nothing random has infinite degrees of freedom", { + pop <- data.frame(g = rep(c("a", "b"), 10), w = 1:20, y = (1:20)^1.5) + for (des in list(design_simple(n = 20), design_stratified("g", n = 20), + design_weighted("w", n = 20, method = "systematic"))) { + r <- ht_total(draw(pop, des, seed = 1, weights = TRUE), "y") + expect_equal(r$df, Inf) + expect_equal(r$variance, 0) + expect_equal(r$ci, rep(sum(pop$y), 2)) + } +}) diff --git a/tests/testthat/test-weights.R b/tests/testthat/test-weights.R index d3d1aa7..23ce32e 100644 --- a/tests/testthat/test-weights.R +++ b/tests/testthat/test-weights.R @@ -1,7 +1,8 @@ -test_that("weights = TRUE prepends .prob and .weight", { +test_that("weights = TRUE prepends .prob, .weight and .row", { df <- data.frame(id = 1:100, site = rep(letters[1:4], each = 25)) s <- draw(df, design_stratified("site", n = 12), seed = 1, weights = TRUE) - expect_identical(names(s), c(".prob", ".weight", names(df))) + expect_identical(names(s), c(".prob", ".weight", ".row", names(df))) + expect_identical(s$.row, s$id) expect_equal(s$.weight, 1 / s$.prob) expect_true(all(s$.prob > 0 & s$.prob <= 1)) }) @@ -26,8 +27,9 @@ test_that("weights are attached correctly even with duplicate rows", { test_that("with-replacement designs refuse weights rather than mislead", { # `.prob` for a with-replacement design is the chance of appearing at least # once, but the sample holds duplicates. Summing y * .weight over it counts - # every duplicate at the distinct-unit weight, which came out about 15% high - # -- and ht_total() inherited the same bias. + # every duplicate at the distinct-unit weight, so the total is high by a + # factor of (n / N) / (1 - (1 - 1 / N)^n). At n = 25 and N = 10 that factor + # is 2.69, a total 169% high. ht_total() inherited the same bias. df <- data.frame(id = 1:10, y = 1:10) for (des in list(design_simple(n = 25, replace = TRUE), design_stratified("g", n = 6, replace = TRUE))) { @@ -59,6 +61,11 @@ test_that("weights = TRUE refuses to clobber existing columns", { df2 <- data.frame(id = 1:10, .drawn_row_id = 1) expect_error(draw(df2, design_simple(n = 3), seed = 1, weights = TRUE), "already has a column called") + + df3 <- data.frame(id = 1:10, .row = 1, .weight = 2) + expect_error(draw(df3, design_simple(n = 3), seed = 1, weights = TRUE), + "already has `.weight` and `.row`; weights = TRUE would overwrite them", + fixed = TRUE) }) test_that("weights = TRUE needs a data frame", { @@ -76,7 +83,7 @@ test_that("weights = TRUE does not change which rows are drawn", { }) test_that("Horvitz-Thompson totals are unbiased across designs", { - set.seed(11) + local_seed(11) pop <- data.frame(id = 1:40, g = rep(c("a", "b"), times = c(30, 10)), cl = rep(letters[1:8], each = 5), @@ -104,3 +111,429 @@ test_that("Horvitz-Thompson totals are unbiased across designs", { expect_lt(abs(mean(est) - true) / se, 4) } }) + +test_that("a certainty design over a with-replacement rest refuses to weight", { + # A certainty design has no `replace` of its own, so checking only the + # outer design let duplicates through: the total came out about a third + # high on a 240-row frame. + df <- data.frame(id = 1:40, g = rep(c("a", "b"), each = 20), + w = c(rep(1, 36), rep(500, 4)), y = 1:40) + for (rest in list(design_simple(n = 30, replace = TRUE), + design_stratified("g", n = 30, replace = TRUE), + design_multistage("g", n_clusters = 2, n = 30, + replace = TRUE))) { + d <- design_certainty("w", 100, rest) + expect_error(draw(df, d, seed = 1, weights = TRUE), + "certainty design over a with-replacement `rest`", + fixed = TRUE) + # Without weights the draw is legitimate and still allowed. + expect_equal(nrow(draw(df, d, seed = 1)), 34) + } + s <- draw(df, design_certainty("w", 100, design_simple(n = 10)), seed = 1, + weights = TRUE) + expect_equal(nrow(s), 14) + expect_error(draw(df, design_certainty("w", 100, + design_simple(n = 30, replace = TRUE)), + seed = 1, weights = TRUE), + "Use\nreplace = FALSE in `rest`", fixed = TRUE) +}) + +test_that("a sample that carries a with-replacement design is refused", { + # drawn 0.2.0 weighted a certainty design over a with-replacement `rest`, + # so a sample it saved can hold duplicates weighted as distinct units. + df <- data.frame(id = 1:40, g = rep(c("a", "b"), each = 20), + w = c(rep(1, 36), rep(500, 4)), y = 1:40) + s <- draw(df, design_certainty("w", 100, design_simple(n = 10)), seed = 1, + weights = TRUE) + old <- s + old$.row <- NULL + attr(old, "drawn_pi") <- NULL + attr(old, "drawn_design") <- design_certainty( + "w", 100, design_simple(n = 30, replace = TRUE)) + msg <- paste0("`sample` comes from a certainty design over a ", + "with-replacement `rest`, for which `weights = TRUE` is not ", + "available.") + expect_error(ht_total(old, "y"), msg, fixed = TRUE) + expect_error(ht_mean(old, "y"), "replace = FALSE in `rest`", fixed = TRUE) + expect_error(sample_summary(old), msg, fixed = TRUE) + # A sample with its `.row` column is refused the same way. + attr(s, "drawn_design") <- attr(old, "drawn_design") + expect_error(ht_total(s, "y"), msg, fixed = TRUE) + skip_if_not_installed("survey") + expect_error(as_svydesign(old), msg, fixed = TRUE) +}) + +test_that("the with-replacement refusal gives the bias factor, not one figure", { + df <- data.frame(id = 1:10, g = rep(c("a", "b"), each = 5)) + for (des in list(design_simple(n = 25, replace = TRUE), + design_stratified("g", n = 6, replace = TRUE))) { + msg <- tryCatch(draw(df, des, seed = 1, weights = TRUE), + error = conditionMessage) + expect_match(msg, "(n / N) / (1 - (1 - 1 / N)^n)", fixed = TRUE) + expect_match(msg, "N_h / n_h * sum(y_h)", fixed = TRUE) + expect_no_match(msg, "15%\\s*high") + } +}) + +# ---- rebuilding, joining and compacting a sample ----------------------------- + +field_pop <- function() { + data.frame(id = 1:120, site = rep(c("a", "b", "c"), times = c(60, 40, 20)), + cl = rep(sprintf("c%02d", 1:12), each = 10), + y = (1:120 * 37) %% 101, w = 5 + (1:120 * 13) %% 50, + note = rep(strrep("x", 30), 120), stringsAsFactors = FALSE) +} + +test_that("as_drawn() rebuilds a sample read back from a CSV file", { + pop <- field_pop() + des <- design_stratified("site", n = 24) + s <- draw(pop, des, seed = 1, weights = TRUE) + path <- tempfile(fileext = ".csv") + on.exit(unlink(path)) + utils::write.csv(s, path, row.names = FALSE) + back <- utils::read.csv(path) + expect_error(ht_total(back, "y"), "as_drawn()", fixed = TRUE) + + # Through `.row`, with the rows in another order + rebuilt <- as_drawn(back[rev(seq_len(nrow(back))), ], des, pop) + expect_identical(names(rebuilt), names(s)) + expect_equal(ht_total(rebuilt, "y")[c("total", "se", "df")], + ht_total(s, "y")[c("total", "se", "df")]) + expect_equal(ht_mean(rebuilt, "y", by = "site")$se, + ht_mean(s, "y", by = "site")$se) + + # Through an id, with `.row` gone + back$.row <- NULL + by_id <- as_drawn(back, des, pop, by = "id") + expect_identical(by_id$.row, s$.row) + expect_equal(ht_total(by_id, "y")$se, ht_total(s, "y")$se) + expect_equal(sample_summary(by_id)$n, 24L) +}) + +test_that("as_drawn() refuses ids that are missing, repeated or unknown", { + pop <- field_pop() + des <- design_stratified("site", n = 24) + back <- as.data.frame(draw(pop, des, seed = 1, weights = TRUE)) + attributes(back) <- attributes(back)[c("names", "row.names", "class")] + ids <- back[, c("id", "y")] + + bad <- ids + bad$id[3] <- NA + expect_error(as_drawn(bad, des, pop, by = "id"), "no value of `id` in 1 row") + expect_error(as_drawn(rbind(ids, ids[2, ]), des, pop, by = "id"), + "more than one row") + bad <- ids + bad$id[3] <- 999 + expect_error(as_drawn(bad, des, pop, by = "id"), + "`id` 999, which `frame` does not have") + twice <- rbind(pop, pop[pop$id == ids$id[1], ]) + expect_error(as_drawn(ids, des, twice, by = "id"), + "`frame` has `id` .* in more than one row") + expect_error(as_drawn(rbind(back, back[1, ]), des, pop), "more than once") + expect_error(as_drawn(ids, des, pop), "no `.row` column") + expect_error(as_drawn(ids, des, pop, by = "site_id"), "`data` does not") + + # `.row` and `by` disagree when the frame was reordered since the draw + expect_error(as_drawn(back, des, pop[nrow(pop):1, ], by = "id"), + "disagrees with `id`") + # A `.prob` that the design does not give + expect_error(as_drawn(back, design_stratified("site", n = 30), pop), + "`data` has 24 rows, and `design` draws 30") + other <- back + other$.prob <- other$.prob * 1.5 + expect_error(as_drawn(other, des, pop), "differ from the probabilities") +}) + +test_that("as_drawn() refuses the responding rows alone", { + pop <- field_pop() + des <- design_stratified("site", n = 24) + s <- draw(pop, des, seed = 1, weights = TRUE) + expect_error(as_drawn(as.data.frame(s)[-(1:3), ], des, pop), + "`data` has 21 rows, and `design` draws 24") + + # Weighted conditional on the clusters: a cluster short of its take + ms <- design_multistage("cl", n_clusters = 4, n = 18) + m <- draw(pop, ms, seed = 2, weights = TRUE) + expect_error(as_drawn(as.data.frame(m)[-1, ], ms, pop), + "where `design` takes") + bal <- design_cluster("cl", n_clusters = 3, balanced = TRUE) + b <- draw(pop, bal, seed = 2, weights = TRUE) + expect_error(as_drawn(as.data.frame(b)[b$cl != b$cl[1], ], bal, pop), + "holds rows of 2 cluster") +}) + +test_that("as_drawn() refuses a frame in another order through `.row`", { + pop <- field_pop() + des <- design_cluster("cl", n_clusters = 4) + s <- draw(pop, des, seed = 1, weights = TRUE) + path <- tempfile(fileext = ".csv") + on.exit(unlink(path)) + utils::write.csv(s, path, row.names = FALSE) + back <- utils::read.csv(path) + + # Every row has probability 1/3, so `.prob` cannot tell the frames apart. + shuffled <- pop[c(seq(2, 120, by = 2), seq(1, 119, by = 2)), ] + expect_error(as_drawn(back, des, shuffled), + "`data` has `cl` values that differ from those of the `frame`") + sorted <- as_drawn(back, des, shuffled[order(shuffled$id), ]) + expect_equal(ht_total(sorted, "y")[c("total", "se", "df")], + ht_total(s, "y")[c("total", "se", "df")]) + + # A changed column is refused through `.row` and not through an id. + edited <- back + edited$note[2] <- "moved" + expect_error(as_drawn(edited, des, pop), "`note` values that differ") + expect_no_error(as_drawn(edited, des, pop, by = "id")) + + # A frame column fieldwork fills in, and a code read back as a number + pop$result <- NA_real_ + pop$code <- sprintf("%03d", pop$id) + s <- draw(pop, des, seed = 1, weights = TRUE) + utils::write.csv(s, path, row.names = FALSE) + back <- utils::read.csv(path) + back$result <- seq_len(nrow(back)) + expect_type(back$code, "integer") + expect_equal(as_drawn(back, des, pop)$.row, s$.row) +}) + +test_that("as_drawn() reads infinities, T/F text and other zones as equal", { + pop <- data.frame(id = 1:60, site = rep(c("a", "b"), times = c(40, 20)), + sex = "F", logx = log((1:60) %% 5)) + pop$at <- as.POSIXct("2024-03-01 08:00", tz = "America/Chicago") + + 3600 * (0:59) + des <- design_stratified("site", n = 12) + s <- draw(pop, des, seed = 1, weights = TRUE) + expect_true(any(s$logx == -Inf)) + expect_equal(as_drawn(s, des, pop)$.row, s$.row) + + # read.csv() and readr::read_csv() read a column of "F" back as FALSE, and + # readr::read_csv() and data.table::fread() read the clock time a CSV file + # holds as UTC. + back <- as.data.frame(s)[, c(".prob", ".weight", ".row", "sex", "at")] + back$sex <- as.logical(back$sex) + back$at <- as.POSIXct(format(s$at), tz = "UTC") + expect_equal(as_drawn(back, des, pop)$.row, s$.row) + instant <- back + instant$at <- as.POSIXct(format(s$at, tz = "UTC"), tz = "UTC") + expect_equal(as_drawn(instant, des, pop)$.row, s$.row) + + # A frame in another order is still refused. + shuffled <- pop[c(seq(2, 60, by = 2), seq(1, 59, by = 2)), ] + expect_error(as_drawn(back, des, shuffled), + "UTC where `frame` row [0-9]+ has 2024-03-0[1-3] [0-9:]+ CST") + expect_error(as_drawn(as.data.frame(s)[, c(".prob", ".weight", ".row", + "logx")], des, shuffled), + "`logx` values that differ") + males <- pop + males$sex <- "M" + expect_error(as_drawn(back, des, males), + "such as FALSE where `frame` row [0-9]+ has \"M\"") + back$sex <- TRUE + expect_error(as_drawn(back, des, pop), "`sex` values that differ") + + # readr::read_csv() reads lowercase "t" and "f", as PostgreSQL writes a + # boolean, back as TRUE and FALSE. + flags <- pop + flags$paid <- ifelse(flags$id %% 3 == 0, "t", "f") + s <- draw(flags, des, seed = 1, weights = TRUE) + read <- as.data.frame(s)[, c(".prob", ".weight", ".row", "paid")] + read$paid <- read$paid == "t" + expect_equal(as_drawn(read, des, flags)$.row, s$.row) + read$paid <- !read$paid + expect_error(as_drawn(read, des, flags), + "`paid` values that differ from those of the `frame` rows") +}) + +test_that("as_drawn() refuses clusters and certain rows left out", { + pop <- field_pop() + pop$cl <- rep(sprintf("c%02d", 1:12), times = rep(c(6, 10, 14), 4)) + strip <- function(s) { + out <- as.data.frame(s) + attributes(out) <- attributes(out)[c("names", "row.names", "class")] + out + } + whole <- design_cluster("cl", n_clusters = 4) + s <- strip(draw(pop, whole, seed = 1, weights = TRUE)) + expect_equal(nrow(as_drawn(s, whole, pop)), nrow(s)) + expect_error(as_drawn(s[-1, ], whole, pop), + "row\\(s\\) of cluster `c[0-9]+`, where `design` takes [0-9]+ from it\\.") + expect_error(as_drawn(s[s$cl != s$cl[1], ], whole, pop), + "holds rows of 3 cluster") + + # The same take from every cluster selected + ms <- design_multistage("cl", n_clusters = 4, n = 20) + m <- strip(draw(pop, ms, seed = 1, weights = TRUE)) + expect_error(as_drawn(m[-1, ], ms, pop), "where `design` takes 5 from it") + + # Rows over the threshold are in every sample. + cert <- design_certainty("w", threshold = 50, rest = whole) + cs <- strip(draw(pop, cert, seed = 1, weights = TRUE)) + top <- which(cs$.prob == 1) + expect_gt(length(top), 0L) + expect_error(as_drawn(cs[-top[1], ], cert, pop), + paste0("does not hold frame row\\(s\\) ", cs$.row[top[1]], + ", which `design` takes with certainty")) + expect_error(as_drawn(cs[-which(cs$.prob < 1)[1], ], cert, pop), + "where `design` takes") + pop$w[1:2] <- 1e4 + pois <- design_weighted("w", n = 30, method = "poisson") + p <- strip(draw(pop, pois, seed = 1, weights = TRUE)) + expect_error(as_drawn(p[p$.row != 1, ], pois, pop), + "does not hold frame row\\(s\\) 1, which") +}) + +test_that("as_drawn() rebuilds a sample weighted on its clusters", { + pop <- field_pop() + pop$cl <- rep(sprintf("c%02d", 1:12), times = rep(c(6, 10, 14), 4)) + for (des in list(design_multistage("cl", n_clusters = 5, n = 23), + design_cluster("cl", n_clusters = 4, balanced = TRUE))) { + for (seed in 1:5) { + s <- draw(pop, des, seed = seed, weights = TRUE) + plain <- as.data.frame(s) + attributes(plain) <- attributes(plain)[c("names", "row.names", "class")] + back <- as_drawn(plain[rev(seq_len(nrow(plain))), ], des, pop) + expect_equal(ht_total(back, "y")$se, ht_total(s, "y")$se) + } + } +}) + +test_that("as_drawn() keeps the class of `data`", { + skip_if_not_installed("data.table") + pop <- field_pop() + des <- design_simple(n = 10) + s <- draw(pop, des, seed = 1, weights = TRUE) + dt <- data.table::as.data.table(as.data.frame(s)[, c(".row", "id", "y")]) + # `:=` works only where data.table is attached or imported, which the + # global environment counts as. + env <- new.env(parent = globalenv()) + env$back <- as_drawn(dt, des, pop) + expect_s3_class(env$back, "data.table") + expect_equal(ht_total(env$back, "y")$se, ht_total(s, "y")$se) + expect_no_warning(evalq(back[, z := 1], env)) +}) + +test_that("add_fieldwork() joins results in the sample's order", { + pop <- field_pop() + pop_y <- pop$y + pop$y <- NULL + s <- draw(pop, design_stratified("site", n = 24), seed = 1, weights = TRUE) + field <- data.frame(id = rev(s$id), y = pop_y[rev(s$id)], ok = TRUE) + joined <- add_fieldwork(s, field, by = "id") + expect_identical(joined$.row, s$.row) + expect_identical(names(joined), c(names(s), "y", "ok")) + by_hand <- s + by_hand$y <- pop_y[s$id] + expect_identical(ht_total(joined, "y"), ht_total(by_hand, "y")) + + # A sampled row with no result gets NA + part <- add_fieldwork(s, field[-1, ], by = "id") + expect_identical(sum(is.na(part$y)), 1L) + expect_identical(is.na(part$y), part$id == field$id[1]) + + expect_error(add_fieldwork(s, rbind(field, field[1, ]), "id"), + "in more than one row") + expect_error(add_fieldwork(s, data.frame(id = c(s$id[1], 9999), y = 1), + "id"), "`id` 9999, which is not in `sample`") + expect_error(add_fieldwork(joined, field, "id"), + "`field` has `y` and `ok`, which `sample` already has") + # Removing `.weight` from the sample would break it, so the message for + # the design's own columns says to rename them in `field`. + expect_error(add_fieldwork(s, data.frame(id = s$id, .weight = 2), "id"), + "`.weight`, which draw\\(\\) sets in a weighted sample") + expect_error(add_fieldwork(s, data.frame(id = c(s$id[1], NA), y = 1), "id"), + "no value of `id` in 1 row") + expect_error(add_fieldwork(s, field["id"], "id"), "nothing to add") + expect_error(add_fieldwork(as.data.frame(as.list(s)), field, "id"), + "does not carry its design") +}) + +test_that("compact_sample() shrinks the saved sample and keeps the estimates", { + pop <- field_pop() + pop$hit <- as.numeric(pop$y > 50) + s <- draw(pop, design_stratified("site", n = 24), seed = 1, weights = TRUE) + small <- compact_sample(s) + expect_lt(length(serialize(small, NULL)), length(serialize(s, NULL)) / 2) + expect_identical(names(attr(small, "drawn_population")), "site") + expect_identical(ht_total(small, "y"), ht_total(s, "y")) + expect_identical(ht_mean(small, "y", by = "site"), + ht_mean(s, "y", by = "site")) + # A 0/1 column of the frame is still read as a proportion + expect_identical(ht_mean(small, "hit"), ht_mean(s, "hit")) + expect_identical(ht_mean(small, "hit")$ci_scale, "logit") + expect_equal(unclass(sample_summary(small)), unclass(sample_summary(s))) + skip_if_not_installed("survey") + expect_equal(survey::SE(survey::svytotal(~y, as_svydesign(small))), + survey::SE(survey::svytotal(~y, as_svydesign(s)))) +}) + +test_that("compact_sample() keeps what each design reads", { + pop <- field_pop() + pop$cs <- 10 + match(pop$cl, unique(pop$cl)) + designs <- list( + design_stratified("site", n = 24, allocation = "neyman", + allocation_by = "w"), + design_stratified("site", n = 24, + within = design_systematic(order_by = "w")), + design_systematic(n = 20, order_by = "w"), + design_cluster("cl", n_clusters = 4), + design_multistage("cl", n_clusters = 4, n = 20), + design_multistage("cl", n_clusters = 4, n = 12, size = "cs"), + design_weighted("w", n = 20, method = "systematic", strata = "site"), + design_certainty("w", 50, design_stratified("site", n = 12)), + design_spread(c("y", "w"), n = 20, strata = "site") + ) + for (des in designs) { + s <- draw(pop, des, seed = 4, weights = TRUE) + small <- compact_sample(s) + expect_false("note" %in% names(attr(small, "drawn_population"))) + expect_identical(ht_total(small, "y"), ht_total(s, "y")) + } +}) + +test_that("compact_sample() names `keep` where a dropped column is needed", { + pop <- field_pop() + pop$g <- rep(c("x", "y"), 60) + s <- draw(pop, design_stratified("site", n = 24), seed = 1, weights = TRUE) + small <- compact_sample(s) + expect_error(ht_mean(small, "y", estimator = "ht", by = "g"), + "compact_sample() dropped `g`", fixed = TRUE) + expect_error(frame_totals(small, ~w), "Name it in `keep`") + kept <- compact_sample(s, keep = c("g", "w")) + expect_identical(ht_mean(kept, "y", estimator = "ht", by = "g"), + ht_mean(s, "y", estimator = "ht", by = "g")) + expect_identical(frame_totals(kept, ~w), frame_totals(s, ~w)) + expect_error(compact_sample(small, keep = "g"), + "An earlier compact_sample() dropped `g`", fixed = TRUE) + expect_error(compact_sample(s, keep = "nope"), "is not a column") + + # A stratum with one sampled row needs the frame's `by` columns to show + # that it holds no row of a domain. + pop$g <- ifelse(pop$site == "c", "only_c", pop$g) + lonely <- draw(pop, design_stratified("site", n = 21, + allocation = c(a = 10, b = 10, c = 1)), + seed = 1, weights = TRUE) + full <- ht_mean(lonely, "y", by = "g") + expect_true(all(is.finite(full$se[full$g != "only_c"]))) + dropped <- ht_mean(compact_sample(lonely), "y", by = "g") + expect_true(all(is.na(dropped$se))) + expect_match(attr(dropped, "notes"), + "compact_sample() dropped `g` from the frame stored with", + fixed = TRUE, all = FALSE) + expect_identical(ht_mean(compact_sample(lonely, keep = "g"), "y", by = "g"), + full) +}) + +test_that("compact_sample() keeps an sf frame's geometry only when read", { + pts <- sf_points() + box <- flat_box(c(-50, 50), c(-30, 30)) + on_geometry <- draw(pts, design_spatial("geometry", region = box, n = 10), + seed = 1, weights = TRUE) + small <- compact_sample(on_geometry) + expect_s3_class(attr(small, "drawn_population"), "sf") + expect_identical(ht_total(small, "y"), ht_total(on_geometry, "y")) + on_columns <- draw(pts, design_spatial(c("lon", "lat"), region = box, + n = 10), seed = 1, weights = TRUE) + small <- compact_sample(on_columns) + expect_identical(names(attr(small, "drawn_population")), c("lon", "lat")) + expect_identical(ht_total(small, "y"), ht_total(on_columns, "y")) +}) diff --git a/tools/check-docs.R b/tools/check-docs.R index 0a906a5..d62ac26 100755 --- a/tools/check-docs.R +++ b/tools/check-docs.R @@ -6,11 +6,92 @@ # 2. Every [foo()] cross-reference in R/, README and NEWS resolves. # 3. Nothing references an identifier the package no longer has. # 4. Every design constructor appears in the overview topic, README and NEWS. -# 5. Every exported function is reachable from the overview topic, and the +# 5. Every exported function is linked from the overview topic, and the # generated Rd is real Rd -- not markdown that was never processed. # # R CMD check catches undocumented objects but not documentation that has # quietly gone stale, which is the failure mode this covers. +# +# Rscript tools/check-docs.R checks the installed package +# Rscript tools/check-docs.R --self-test checks rules 4 and 5 on +# tools/fixtures/docs + +# A name as a whole word: `draw` is not found in `drawn` or `draw_design`. +mentions <- function(text, name) { + pattern <- paste0("(?= truth }, logical(1)) mean(covered) diff --git a/vignettes/articles/estimation.Rmd b/vignettes/articles/estimation.Rmd index ea46336..474aa0e 100644 --- a/vignettes/articles/estimation.Rmd +++ b/vignettes/articles/estimation.Rmd @@ -52,9 +52,12 @@ piece as fixed, which it is not. |---|---|---|---| | simple, stratified, temporal, spatial, reservoir, multistage | Sen-Yates-Grundy with exact $\pi_{kl}$ | `"analytic"` | exact, unbiased | | cluster | between-cluster form over cluster totals | `"analytic"` | exact, unbiased | +| cluster with `balanced = TRUE`, multistage with a take that depends on the clusters selected | two-stage formula at each cluster's take, weights conditional on the clusters selected | `"analytic"` | unbiased | | weighted, `"poisson"` | $\sum (1-\pi_k) y_k^2 / \pi_k^2$ | `"analytic"` | exact, unbiased | | weighted, `"systematic"` | Deville (1999) | `"deville"` | approximation | | systematic | successive differences (Wolter 2007) | `"successive difference"` | approximation | +| systematic, `n_starts` of 2 or more | random groups (Wolter 2007) | `"analytic"` | exact, unbiased | +| stratified, `within = design_systematic()` | successive differences within strata | `"successive difference"` | approximation | | spread | local means (Stevens and Olsen 2003) | `"local mean"` | approximation, conservative | | certainty | whatever `rest` uses | as `rest` | as `rest` | | any, on request or as fallback | jackknife, stratified where there are strata | `"jackknife"` | approximation | @@ -69,7 +72,37 @@ $$\hat V_{\mathrm{SYG}} = \frac12 \sum_{k \ne l \in s} is unbiased whenever every $\pi_{kl} > 0$ (Sen 1953; Yates and Grundy 1953). For stratified simple random sampling it reduces to the textbook -$\sum_h N_h^2 (1 - f_h) s_h^2 / n_h$. +$\sum_h N_h^2 (1 - f_h) s_h^2 / n_h$, with $s_h^2$ the variance of $y$ among +the rows sampled in stratum $h$. Simple random, reservoir and spatial samples +are the case of a single stratum, and temporal intervals are strata. For +`design_multistage()` with the same take of $m$ rows from each of $a$ clusters +selected out of $A$, it reduces to the two-stage formula + +$$\hat V = A^2 \left(1 - \frac{a}{A}\right) \frac{s_t^2}{a} + +\frac{A}{a} \sum_{i \in s} N_i^2 \left(1 - \frac{m}{N_i}\right) +\frac{s_i^2}{m},$$ + +with $s_t^2$ the variance of the estimated cluster totals $N_i \bar y_i$ and +$s_i^2$ the variance within cluster $i$. `drawn` computes these forms, which +take time and memory in proportion to the number of sampled rows. The sum over +pairs needs matrices with a row and a column per sampled row, more than a +gigabyte at 4,000 rows. + +Under proportional allocation, an $n$ that does not divide by the number of +clusters, a cluster smaller than the take, or `design_cluster(balanced = TRUE)`, +the take $m_i$ from cluster $i$ depends on which clusters were selected. A +row's inclusion probability then averages over every selection; only the +balanced design has a closed form for it, and none of them has one for the +joint probabilities. `draw(weights = TRUE)` weights such a sample conditional +on the selection, $\pi_k = (a/A)\, m_i / N_i$, so the estimated total is $A/a$ +times the sum of the estimated totals of the selected clusters, unbiased given +the selection and so over every selection. The formula above, with $m_i$ in +place of $m$, is unbiased for its variance. Given the selection, the estimated +cluster totals also vary by the variance within each cluster, so the first term +holds $(A/a)^2 (1 - a/A)$ times the within-cluster variances on average, and +with the second term that makes $(A/a)^2$ times them, the variance of the +estimate given the selection. What remains of the first term is the variance +between clusters. The condition matters. **A stratum with one sampled row** has no pair inside it, so it silently contributes nothing: with one row in every stratum the sum is @@ -113,14 +146,23 @@ standard approximations for high-entropy designs. It equals ### Systematic sampling: successive differences -A systematic sample has one random start. Most pairs of rows can never be drawn -together ($\pi_{kl} = 0$), so no design-unbiased variance estimator exists at -all. The successive-difference estimator compares each sampled row with its +A systematic sample has one random start. At an interval $k$ of 2 or more, +neighbouring rows and many other pairs can never be drawn together, so their +joint probability is 0 and no design-unbiased variance estimator exists at +all. +The successive-difference estimator compares each sampled row with its neighbour in the order the design walked (Wolter 2007): $$\hat V = (1 - f)\, \frac{n}{2(n-1)} \sum_{j=2}^{n} \left(\frac{y_{(j)}}{\pi} - \frac{y_{(j-1)}}{\pi}\right)^2.$$ +When $k$ does not divide the $N$ rows the design walks, the sample +holds $\lfloor N/k \rfloor$ or $\lfloor N/k \rfloor + 1$ rows, and the total +moves with that count. Successive differences cannot see it, so +$\bar u^2 (r/k)(1 - r/k)$ is added, with $\bar u$ the mean of $y/\pi$ over the +sample and $r$ the remainder of $N/k$. Without the term a constant $y$ would +get a variance of 0. + Sorting the frame on something related to $y$ is what makes systematic sampling efficient, and this estimator can see that where the simple-random formula cannot: @@ -145,12 +187,45 @@ est <- vapply(1:200, function(i) { round(rowMeans(est) / true_var, 2) ``` -Both are ratios to the true variance; the successive-difference figure is far -closer. Its limits are shared by every estimator from a single systematic -sample: a -frame that cycles with a period matching the interval, and a trend so smooth -that the random start is almost the only source of variation, both make it run -low. +Both are ratios to the true variance. The successive-difference estimator +averaged `r round(rowMeans(est)[["successive"]] / true_var, 1)` times it on +this frame and the simple-random formula +`r round(rowMeans(est)[["as_if_srs"]] / true_var, 1)` times. Neither is +design-unbiased, and how far the successive-difference figure lands from the +truth changes from one frame to the next. + +Its limits are shared by every estimator from a single systematic sample. A +frame that cycles with a period equal to the interval, or one that divides it, +puts every row of one sample at the same phase of the cycle, and the estimate +runs far low. +A period of twice the interval puts neighbouring sampled rows at opposite +phases, and it runs high, 29 times the truth in one simulation. A trend so +smooth that the random start is almost the only source of variation makes it +run low, with no floor. For a straight line with no noise the ratio is +$6k / (n(k + 1))$, about $6/n$, for $n$ rows at interval $k$. + +### Several starts: random groups + +`design_systematic(interval = k, n_starts = m)` draws $m$ different starts +from $1, \dots, mk$ and walks each at a step of $mk$. Every row keeps its +probability of $1/k$, and two rows $i$ and $j$ in different residue classes +modulo $mk$ can now be drawn together, with $\pi_{ij} = (m-1)/(k(mk-1))$. +Each start gives a replicate whose own total $\hat t_r$ estimates $t$, the +sample's total is their mean $\bar t$, and + +$$\hat V = \left(1 - \frac1k\right) \frac{1}{m(m-1)} +\sum_{r=1}^{m} \left(\hat t_r - \bar t\right)^2$$ + +is the random group estimator (Wolter 2007), unbiased on $m - 1$ degrees of +freedom. It equals the Horvitz-Thompson variance estimator over the exact +$\pi_{ij}$, so `method` is `"analytic"`. The price is a step $m$ times as +long, so each replicate follows a sorted frame less closely, and few degrees +of freedom: with four starts a 95% interval uses $t_3$. + +`design_stratified(within = design_systematic(order_by = "x"))` instead walks +each stratum from a start of its own, at a step of $N_h / n_h$ rows. The +variance is the sum of the strata's successive-difference approximations, +on the degrees of freedom of a stratified sample. ### Spatially balanced samples: local means @@ -165,7 +240,9 @@ $$\hat V = \sum_{k \in s} \frac{|N_k|}{|N_k| - 1} \frac{y_l}{\pi_l}\right)^2$$ (Stevens and Olsen 2003; Grafström and Schelin 2014). It errs conservative, -more so as the sampling fraction grows. +more so as the sampling fraction grows. Rows that a `size` column puts past +certainty are in every sample, so the sum leaves them out, as rows and as +neighbours. ### The jackknife @@ -175,6 +252,9 @@ they are deleted *within* their stratum, with only that stratum reweighted — the stratified or JKn jackknife (Wolter 2007, chapter 4). Deleting across strata would count the differences between strata as sampling variance, which is what stratifying removes. Each stratum carries its own finite population correction. +Units taken with certainty, whether past certainty on size, in a stratum taken +whole or in a census, are in every sample, so they are held fixed instead of +deleted and the correction counts only the other units. For a stratified design the result equals the analytic figure exactly: ```{r jkn} @@ -187,8 +267,8 @@ c(analytic = ht_total(strat, "y", variance = "analytic")$se, when that declines — for instance a multistage sample with one row per cluster, where the within-cluster variation cannot be measured and the delete-a-cluster jackknife gives the standard ultimate-cluster approximation. It is refused for -systematic samples (one primary sampling unit) and Poisson samples (whose -exact variance it understates). +systematic samples, whose primary sampling units are their starts rather than +their rows, and Poisson samples, whose exact variance it understates. ## Confidence intervals @@ -214,14 +294,24 @@ rowMeans(hits) Pass `df = Inf` for the normal interval. +Units taken with certainty count in neither number. They are in every sample +and carry no variance, so counting them would make the interval too narrow. +With eight certain units among ten, systematic PPS had 9 degrees of freedom +where the variance rests on two units, and the interval covered 79%. A sample +with no unit below certainty has a variance of 0 and `df = Inf`. + ## How it was checked Every estimator is checked in the package's tests against the empirical sampling variance of its own estimator over many repeated draws, and every inclusion and joint probability against the observed frequency. A condensed -version, run when this page was built — the ratio of the average estimated -variance to the actual variance of the estimates (1 is perfect), and the -coverage of the nominal 95% interval: +version, run when this page was built, gives the ratio of the average +estimated variance to the true variance of the total (1 is perfect) and the +coverage of the nominal 95% interval. For the five designs whose joint +probabilities have a closed form, the true variance is computed from them, +$\sum_{k,l} \pi_{kl} \frac{y_k}{\pi_k} \frac{y_l}{\pi_l} - Y^2$ over the +frame. Systematic PPS and spread have none, and their ratio is to the variance +of the simulated totals: ```{r check-all} set.seed(7) @@ -246,28 +336,165 @@ designs <- list( spread = design_spread(c("x", "yy"), n = 40, scale = FALSE) ) -check <- function(d, R = 400) { +exact <- c("simple", "stratified", "cluster", "multistage", "pps_poisson") +exact_variance <- function(d) { + z <- frame$y / inclusion_prob(frame, d) + sum(joint_prob(frame, d) * outer(z, z)) - truth^2 +} + +check <- function(name, R = 1000) { + d <- designs[[name]] out <- vapply(seq_len(R), function(i) { r <- ht_total(draw(frame, d, seed = i, weights = TRUE), "y") c(r$total, r$variance, r$ci[1] <= truth && truth <= r$ci[2]) }, numeric(3)) - c(variance_ratio = mean(out[2, ]) / var(out[1, ]), - coverage = mean(out[3, ])) + against <- if (name %in% exact) "exact" else "simulated" + v <- if (name %in% exact) exact_variance(d) else var(out[1, ]) + data.frame(variance_ratio = round(mean(out[2, ]) / v, 2), against, + coverage = round(mean(out[3, ]), 2)) } -round(t(vapply(designs, check, numeric(2))), 2) +do.call(rbind, setNames(lapply(names(designs), check), names(designs))) ``` -With a few hundred replicates the ratios carry Monte Carlo error of several -percent; the test suite uses more. +Against the exact variance, the ratio's Monte Carlo error is that of the +average estimate alone, under 1.5% here. A ratio to the variance of simulated +totals also carries the error of that variance, about 5% at the 1,000 draws +used here and 7% to 9% at 400. At 400 draws the cluster and Poisson samples +gave ratios of 0.85 and 0.87 to the simulated variance and 0.98 to the exact +one. The coverage carries an error of about 0.7 percentage points. ## Agreement with `survey` `as_svydesign()` expresses each design in `survey`'s own terms (Lumley 2004), and the tests assert that the two packages agree to floating point on totals, standard errors, domain estimates and degrees of freedom for every design -`survey` can represent exactly — and within a fraction of a percent for -systematic PPS, where `survey` uses Brewer's approximation and `drawn` uses -Deville's. `?as_svydesign` has the full table. +`survey` can represent exactly. Units taken with certainty go to `survey` as +one sampling unit per stratum, taken whole, so that neither package counts +them among the degrees of freedom. For systematic PPS, `survey` uses Brewer's +approximation and `drawn` uses Deville's. The degrees of freedom still agree. +On frames of a few hundred rows with skewed sizes the standard errors of +totals usually agree within 0.5%, and usually within 3% where the +probabilities below certainty spread widely. Those of means can differ by +several percent when the sampling fraction is large. +`?as_svydesign` has the full table. + +`survey::as.svrepdesign()` cannot build replicate weights from `survey`'s +own PPS and Poisson designs, and for a systematic sample it builds a +jackknife that ignores the order of the walk. `replicate_weights()` builds +them from the sample instead: the jackknife above for most designs, and +successive differences along the walk for a systematic sample, with no +pair joining the two ends of the walk. For a systematic sample the +standard error of a total is then the one `ht_total()` gives by default: + +```{r replicates, eval = requireNamespace("survey", quietly = TRUE)} +sys <- draw(frame, design_systematic(interval = 10, order_by = "size"), + seed = 3, weights = TRUE) +rw <- replicate_weights(sys) +rep_des <- survey::svrepdesign( + data = sys, repweights = rw, weights = ~.weight, + type = attr(rw, "type"), scale = attr(rw, "scale"), + rscales = attr(rw, "rscales"), combined.weights = TRUE +) +c(drawn = ht_total(sys, "y")$se, + survey = as.numeric(survey::SE(survey::svytotal(~y, rep_des)))) +``` + +Calibration is left to `survey` too. `frame_totals()` gives the population +totals `survey::calibrate()` takes, from the frame stored with the sample +and over the rows the design could reach, so the totals need not be built +by hand. Here `size` is known for every row of the frame and related to +`y`, and calibrating a simple random sample to its total narrows the +standard error: + +```{r calibrate, eval = requireNamespace("survey", quietly = TRUE)} +srs <- draw(frame, design_simple(n = 40), seed = 3, weights = TRUE) +totals <- frame_totals(srs, ~size) +totals +cal <- survey::calibrate(as_svydesign(srs), ~size, population = totals) +c(horvitz_thompson = ht_total(srs, "y")$se, + calibrated = as.numeric(survey::SE(survey::svytotal(~y, cal)))) +``` + +With `table = TRUE`, `frame_totals()` gives the counts in each cell of its +variables instead, for `survey::postStratify()` and `survey::rake()`. + +## Fieldwork and missing values + +A weighted sample carries its design, so fieldwork results are joined to the +sample rather than the sample to the results. `add_fieldwork()` adds the +columns of a results table keyed by an id, in the sample's own order, and +leaves `y` missing for a sampled row with no result. A sample sent to the +field as a CSV file comes back with its rows and its `.row` column but not +its design, and `as_drawn()` rebuilds it from the design and the frame. +Here the sites differ in spend, and site c answered less often: + +```{r fieldwork} +set.seed(11) +shops <- data.frame(id = 1:600, + site = rep(c("a", "b", "c"), times = c(300, 200, 100))) +shops$spend <- round(c(a = 80, b = 120, c = 200)[shops$site] + + rnorm(600, 0, 25)) +listing <- shops[, c("id", "site")] +by_site <- design_stratified("site", n = 60) +s <- draw(listing, by_site, seed = 1, weights = TRUE) + +path <- tempfile(fileext = ".csv") +write.csv(s, path, row.names = FALSE) +back <- as_drawn(read.csv(path), by_site, listing) + +answered <- back$id[back$site != "c" | back$id %% 2 == 0] +results <- shops[shops$id %in% answered, c("id", "spend")] +back <- add_fieldwork(back, results, by = "id") +table(back$site, answered = !is.na(back$spend)) +``` + +`ht_total()` refuses the missing values. A total over the rows that +answered counts the others as 0, and so is low by about the share of the +weight they hold: + +```{r missing-total, error = TRUE} +ht_total(back, "spend") +``` + +`ht_mean(na_rm = TRUE)` estimates the mean over the rows with `spend` +present, treating them as a domain of the whole sample. The estimate is the +Hajek mean over them, and its variance that of the linearised residuals +over every sampled row, 0 for the rows left out. +`survey::svymean(na.rm = TRUE)` gives the same estimate and standard error. + +```{r missing-mean} +ht_mean(back, "spend", na_rm = TRUE) +``` + +```{r missing-survey, eval = requireNamespace("survey", quietly = TRUE)} +survey::svymean(~spend, as_svydesign(back), na.rm = TRUE) +``` + +That mean assumes the values are missing completely at random. Here they +are not. Site c spends the most and answered least, so the mean is low +against the frame's `r round(mean(shops$spend), 1)`. A weighting-class +adjustment assumes only that within each class, here each site, whether a +row answered is unrelated to its `spend`. Each row that answered takes on +the weight of the rows of its class that did not, and `survey` estimates +from the adjusted `.weight`: + +```{r weighting-class, eval = requireNamespace("survey", quietly = TRUE)} +answer <- !is.na(back$spend) +boost <- tapply(back$.weight, back$site, sum) / + tapply(back$.weight * answer, back$site, sum) +adjusted <- back +adjusted$.weight[answer] <- adjusted$.weight[answer] * + boost[adjusted$site[answer]] +des <- as_svydesign(adjusted) +c(mean = coef(survey::svymean(~spend, des, na.rm = TRUE)), + total = coef(survey::svytotal(~spend, des, na.rm = TRUE)), + frame_mean = mean(shops$spend), frame_total = sum(shops$spend)) +``` + +`survey` treats the adjusted weights as fixed, so its standard errors leave +out that the adjustment factors were estimated from the sample. +`ht_total()` and `ht_mean()` keep to `.prob` and warn that `.weight` was +changed. ## References diff --git a/vignettes/articles/spatial-sampling.Rmd b/vignettes/articles/spatial-sampling.Rmd index 0917eb8..1c49f07 100644 --- a/vignettes/articles/spatial-sampling.Rmd +++ b/vignettes/articles/spatial-sampling.Rmd @@ -60,7 +60,7 @@ spread <- design_spread(c("x", "y"), n = 60, scale = FALSE) op <- par(mfrow = c(1, 2)) plot(srs, grid, type = "map", coords = c("x", "y"), seed = 4, - main = "simple random") + main = "simple random", asp = 1) plot(spread, grid, type = "map", seed = 4, main = "spread") par(op) ``` @@ -118,11 +118,13 @@ nrow(plots) sample_summary(plots) ``` -After fieldwork, the total, and a mean per hectare-cell: +After fieldwork, the total, and the mean per cell: ```{r estimate} ht_total(plots, "biomass") c(truth = sum(grid$biomass)) +ht_mean(plots, "biomass") +c(truth = mean(grid$biomass)) ``` The variance is the local mean estimator: each plot is compared with its three diff --git a/vignettes/choosing-a-design.Rmd b/vignettes/choosing-a-design.Rmd index eb085dd..21a8de4 100644 --- a/vignettes/choosing-a-design.Rmd +++ b/vignettes/choosing-a-design.Rmd @@ -69,9 +69,9 @@ plan_size(margin = 100, sd = stats::sd(invoices$value), N = nrow(invoices), ``` `deff` is not a guess you have to invent — it is measurable from a comparable -past sample with `deff()`, which we come back to below. If the margin you ask -for cannot be reached by sampling at all, `plan_size()` says so rather than -returning a number bigger than your frame: +past sample with `deff()`, which we come back to below. If only a census meets +the margin you ask for, `plan_size()` says so rather than returning a number +bigger than your frame: ```{r} plan_size(margin = 2, sd = stats::sd(invoices$value), N = nrow(invoices)) @@ -401,6 +401,27 @@ of the way from stratification to PPS, and on `checks` it gives up nothing against stratifying by site, where PPS lost badly. When you are not sure the size measure predicts what you will measure, that is the safer use of it. +Strata and size also combine. With `strata`, `design_weighted()` splits `n` +over the sites as `design_stratified()` would, and samples each site in +proportion to `value` on its own, with a random start of its own. Every site +gets its share of the sample, and large invoices are still favoured within +it: + +```{r} +pps_site <- design_weighted("value", n = 60, method = "systematic", + strata = "site") +allocation_table(invoices, pps_site) +round(cbind(bet, spread = spread_sd, + pps_by_site = c(cost = spread_of(pps_site, "cost"), + checks = spread_of(pps_site, "checks"))), 1) +``` + +The invoices of every site were drawn from the same distribution, so here +the strata change little against PPS over the whole frame. They pay where +the strata differ in what you measure, and they guarantee each site its +rows either way. `ht_total()` adds up Deville's approximation over the +sites, and `as_svydesign()` hands the sites to `survey` as strata. + ## The units too big to leave to chance PPS is one answer to dominant units. The blunter one is to stop sampling them @@ -463,12 +484,11 @@ control both. ## Which designs can be estimated from -Most designs have exact inclusion probabilities. Five situations do not, and the +Most designs have exact inclusion probabilities. Four situations do not, and the package says so rather than approximating: ```{r} no_form <- list( - `balanced clusters` = design_cluster("team", n_clusters = 4, balanced = TRUE), `proportional multistage`= design_multistage("team", n_clusters = 6, n = 60, allocation = "proportional"), `uneven multistage` = design_multistage("team", n_clusters = 6, n = 61), @@ -489,16 +509,50 @@ on, because the arithmetic looks innocent. The second-stage allocation runs over the clusters that were *selected*, so a leftover row goes to the largest of them, and a cluster smaller than its target is capped with the shortfall dealt to whichever clusters came with it. A row's chance therefore depends on the -company it keeps. Averaging over the possibilities is not a closed form, and the -average is not the answer. +company it keeps. Its exact probability is its chance given the clusters +selected, averaged over every possible selection, and no formula gives that +average. + +Estimation does not need it. `draw(weights = TRUE)` weights such a sample +conditional on the clusters it selected: with `a` of `A` clusters selected and +`m_i` of the `N_i` rows of cluster `i` taken, `.prob` is `(a / A) * m_i / N_i`. +The total built from those weights is unbiased whichever clusters were +selected, and so over every selection, and `ht_total()` gives it the +two-stage standard error: + +```{r} +uneven <- draw(invoices, no_form$`uneven multistage`, seed = 1, weights = TRUE) +table(uneven$team) +ht_total(uneven, "value") +``` + +Proportional allocation needs `min_per_cluster = 1` or more for this, because a +selected cluster given no rows would count as a cluster total of 0. + +Balanced clusters, which take from each selected cluster as many rows as the +smallest of them holds, are not on the list. Their take is random too, but its +average for each cluster has an exact form, which `inclusion_prob()` uses. With +two of the four sites selected: + +```{r} +balanced <- design_cluster("site", n_clusters = 2, balanced = TRUE) +round(cbind( + exact = tapply(inclusion_prob(invoices, balanced), invoices$site, mean), + simulated = tapply(inclusion_prob(invoices, balanced, simulate = TRUE, + R = 1000, seed = 1), invoices$site, mean) +), 3) +``` + +`draw(weights = TRUE)` weights a balanced sample conditional on its clusters as +well, so that `ht_total()` can use the same two-stage standard error. Where you need a number anyway, ask for a simulation and accept the Monte Carlo error: ```{r} -sim <- inclusion_prob(invoices, no_form$`balanced clusters`, +sim <- inclusion_prob(invoices, no_form$`uneven multistage`, simulate = TRUE, R = 200, seed = 1) -round(tapply(sim, invoices$team, unique)[1:5], 3) +round(tapply(sim, invoices$team, mean)[1:5], 3) ``` The one thing simulation cannot rescue is the bootstrap, and it is refused @@ -538,7 +592,7 @@ round(cbind( ## Clusters, when fieldwork costs more than precision -Visiting five teams is cheaper than visiting twenty. `design_cluster()` takes +Visiting four teams is cheaper than visiting twenty. `design_cluster()` takes whole clusters, so the row count follows from which ones you get: ```{r} @@ -555,9 +609,30 @@ res_ms <- draw(invoices, ms, seed = 1) table(res_ms$team) ``` -Both are estimable, but cluster designs pay for their convenience in precision — -and in degrees of freedom. With four clusters there are three degrees of -freedom, and the interval uses t on three rather than the normal +The teams here are all the same size. Where clusters differ, or some matter +more than others, `size` selects them in proportion to a measure known for +every cluster, here each team's total invoice value, and still takes the same +number of rows from each. A row's inclusion probability is its team's chance +of selection times 10 out of 30: + +```{r} +teams <- transform(invoices, team_value = ave(value, team, FUN = sum)) +ms_pps <- design_multistage("team", n_clusters = 6, n = 60, + size = "team_value") +range(inclusion_prob(teams, ms_pps)) +ht_total(draw(teams, ms_pps, seed = 1, weights = TRUE), "cost") +``` + +Had the measure been each team's number of invoices, every invoice would have +had the same chance, `n / N`. + +Both are estimable. Cluster designs usually pay for their convenience in +precision, because rows of one cluster tend to resemble each other, and they +always pay in degrees of freedom. These teams are blocks of 30 invoices whose +values have nothing to do with the team, so here clustering costs no +precision on average, and the design effect estimated from one sample can +fall below 1 by chance, as it does below. With four clusters there are three +degrees of freedom, and the interval uses t on three rather than the normal distribution. That is why it is so wide, and it is right to be: a normal interval here covers about 87% of the time where it claims 95%. @@ -567,8 +642,8 @@ ht_total(draw(invoices, by_team, seed = 1, weights = TRUE), "value") ## Streams, when the data does not fit -A data frame is not a stream: its length is already known, so `design_reservoir()` -takes a direct vectorised path for one. The streaming path is for data you cannot +A data frame or a list is not a stream: its length is already known, so +`design_reservoir()` takes a direct vectorised path for one. The streaming path is for data you cannot hold — pass a connection, or a function that returns the next item and `NULL` when exhausted. @@ -584,13 +659,22 @@ drawn_ids ``` One pass, five items held, a hundred thousand seen. Algorithm L skips ahead -geometrically rather than drawing a random number per item. +geometrically rather than drawing a random number per item, and the items come +back in the order they arrived. + +Each line of a connection is an item, a CSV header included, and a function +that returns a data frame gives whole data frames as items. +`?design_reservoir` shows how to leave a header out, and how +`batches = TRUE` samples the rows of those data frames instead. ## Bootstrap, for the uncertainty of a statistic The other designs estimate a population total. The bootstrap estimates the -sampling distribution of whatever you like — here the median, which has no -convenient closed form: +sampling distribution of a statistic computed on independent rows, here the +median of the invoice values, which has no convenient closed form. A sample +drawn with strata or clusters is not made of independent rows, and +`?design_bootstrap` shows how to resample its clusters within strata with +`survey::as.svrepdesign()` instead. ```{r} reps <- draw(invoices, design_bootstrap(n_replicates = 400), seed = 1) @@ -611,6 +695,12 @@ randomly chosen runs instead of independent rows: design_bootstrap(n_replicates = 100, method = "block", block_length = 20) ``` +A run must fit inside the data, so the first and last rows are drawn less often +than the rest. `method = "circular"` lets a run wrap from the last row to the +first, which draws every row equally often on average. For many replicates of a +large frame, `output = "indices"` returns the row numbers of each replicate as a +matrix instead of copying the rows. + ## Reproducibility without side effects `seed` is local to the draw. Sampling inside a simulation does not shift the @@ -642,10 +732,10 @@ ht_total(s, "value", by = "site") ## Where this package stops -`drawn` draws samples and estimates totals, means and proportions from them, -overall or by group. It does not do regression, calibration, or quantiles with -proper standard errors — [`survey`](https://cran.r-project.org/package=survey) -does all of that, and `as_svydesign()` hands a sample straight over. +`drawn` draws samples and estimates totals, means, proportions, ratios and +quantiles from them, overall or by group. It does not do regression or +calibration. [`survey`](https://cran.r-project.org/package=survey) does both, +and `as_svydesign()` hands a sample straight over. ```{r, eval = requireNamespace("survey", quietly = TRUE), message = FALSE} library(survey) @@ -667,7 +757,7 @@ c(drawn = ht_total(s, "value")$se, From there it is `survey`'s vocabulary: ```{r, eval = requireNamespace("survey", quietly = TRUE)} -svyquantile(~value, des, quantiles = c(0.25, 0.5, 0.75)) +coef(summary(svyglm(value ~ site, des))) ``` Draw here, analyse there. diff --git a/vignettes/drawn.Rmd b/vignettes/drawn.Rmd index 50bfc32..843904e 100644 --- a/vignettes/drawn.Rmd +++ b/vignettes/drawn.Rmd @@ -185,9 +185,9 @@ size of this one for the same precision. ## 6. Hand off -`drawn` estimates totals, means and proportions. For regression, calibration -or quantiles, hand the sample to `survey`; the design is expressed in `survey`'s -own terms, so the standard errors agree. +`drawn` estimates totals, means, ratios, proportions and quantiles. For +regression or calibration, hand the sample to `survey`; the design is expressed +in `survey`'s own terms, so the standard errors agree. ```{r survey, eval = requireNamespace("survey", quietly = TRUE)} des <- as_svydesign(audit)