library(svyplan)
library(samplyr)
library(dplyr)3 A tour of svyplan and samplyr
Two packages do most of the work of this book. svyplan plans. It turns precision targets, design effects and response rates into sample sizes, takes and allocations, and it never touches a frame. samplyr draws. It declares a design as a sequence of stages, applies it to a frame, and returns the selected units with their weights. The plan says how many, and the design says which.
This chapter follows one short thread through both packages on the data of The Gambia. It sizes one LGA, chooses a take, shares the clusters among the strata, draws the clusters and the households, and hands the sample to the survey package. Each step is a sketch. The chapters of Parts II and III return to each one with the care a real design needs, and the table at the end of the chapter says where. The terms used here (inclusion probability, weight and design effect) are defined in Chapter 4, which comes next. A reader who meets them here for the first time can read the code for its shape and come back later.
3.1 svyplan, one number at a time
The inputs are those of the 2019-20 DHS report, one row per LGA. The derived columns are those of Chapter 1. married_hh is the number of married women in a completed household, and resp the share of selected households completed times the response rate of women. Chapter 7 derives them in detail.
inputs <- read.csv("data/gmb_dhs2019_lga.csv") |>
mutate(
interviewed = selected * completed,
married_hh = married / women_rr / interviewed,
children_hh = children / women_rr / interviewed,
resp = completed * women_rr
)
kerewan <- filter(inputs, lga == "Kerewan")
select(kerewan, lga, mcpr, mcpr_deft, married_hh, resp)
#> lga mcpr mcpr_deft married_hh resp
#> 1 Kerewan 0.208 1.494 1.374866 0.9109983.1.1 A sample size
The functions of svyplan come in pairs. A function whose name starts with n_ returns a sample size for a precision target, and its partner starting with prec_ returns the precision of a given sample size. n_prop() sizes the estimate of a proportion. Here the target is a relative standard error of 10% on mCPR in Kerewan, cv = 0.10.
mcpr_kerewan <- n_prop(kerewan$mcpr, cv = 0.10,
deff = kerewan$mcpr_deft^2,
resp_rate = kerewan$resp,
eligible_per_unit = kerewan$married_hh)
mcpr_kerewan
#> Sample size for proportion (wald)
#> n = 679 gross (eligible respondents: 851) (p = 0.21, cv = 0.100, deff = 2.23, resp_rate = 0.91, eligible_per_unit = 1.375)
#> expected cases = 176.9
#> # summary() for the precision at the field size and the derived sizesEach argument removes one simplification. Without deff, the size would be that of a simple random sample of married women. The report gives a DEFT, a ratio of standard errors, so the design effect is its square. Without resp_rate and eligible_per_unit, the size would count married women who respond. With them it counts households to select, here 679, which are expected to yield 850 interviews with married women.
The result is an object, not a bare number. Printing it shows the whole calculation. The continuous size is kept in $n, and as.integer() gives the whole number of households to field.
c(continuous = mcpr_kerewan$n, fielded = as.integer(mcpr_kerewan))
#> continuous fielded
#> 678.5554 679.0000Keeping the continuous value avoids rounding twice when the result feeds another calculation.
3.1.2 Response and eligibility
A report counts losses in two places. Some selected dwellings turn out to be vacant, destroyed or without their household, and some households in scope do not respond. The share completed of the DHS table mixes the two, and the household response rate hrr of the same table keeps only the second. svyplan takes them apart. eligibility_rate is the share of issued units in scope, here completed / hrr, and resp_rate the response among them, here hrr times the response of women.
kerewan_split <- kerewan |>
mutate(lga, completed, hrr, in_scope = completed / hrr,
resp_in_scope = hrr * women_rr, .keep = "none")
kerewan_split
#> lga completed hrr in_scope resp_in_scope
#> 1 Kerewan 0.963 0.99 0.9727273 0.93654
n_prop(kerewan$mcpr, cv = 0.10, deff = kerewan$mcpr_deft^2,
eligibility_rate = kerewan_split$in_scope,
resp_rate = kerewan_split$resp_in_scope,
eligible_per_unit = kerewan$married_hh)$n
#> [1] 678.5554The size does not move, since only the product of the two rates enters a sample size, and the product is resp. The split matters when the size of the population counts. With a finite population, the units in scope are the frame count times eligibility_rate, and an allocation weights its strata by them. Chapter 7 reads both rates for every LGA.
3.1.3 The round trip
A prec_ function takes a sample size and returns its precision. Given the result of n_prop(), prec_prop() reads every assumption from it and returns the target that was asked for.
prec_prop(mcpr_kerewan)$cv
#> [1] 0.1The same function answers the question in the other direction, for a size chosen on other grounds. In 2019-20, Kerewan selected 800 households.
prec_prop(kerewan$mcpr, n = kerewan$selected, deff = kerewan$mcpr_deft^2,
resp_rate = kerewan$resp, eligible_per_unit = kerewan$married_hh)
#> Sampling precision for proportion (wald)
#> n = 800 (eligible respondents: 1002, eligible_per_unit = 1.375)
#> se = 0.0192, moe = 0.0375, cv = 0.0921, rmoe = 0.1805
#> expected cases = 208.4The 800 households yield the 1,002 married women the report counts, and an RSE of 9.2%, against 9.2% in Appendix B. Fed with the last round’s sample, the formula returns the last round’s precision. This is the backtest of Chapter 1 in its smallest form, and Chapter 8 runs it for every LGA.
3.1.4 Sweeping an input
A design effect from one round is a guess for the next. predict() reruns a result over new values of its inputs and keeps the rest. The DEFTs below span those of the other LGAs.
predict(mcpr_kerewan, data.frame(deff = c(1.2, kerewan$mcpr_deft, 1.8)^2)) |>
select(deff, n, cv)
#> deff n cv
#> 1 1.440000 437.7706 0.1
#> 2 2.232036 678.5554 0.1
#> 3 3.240000 984.9839 0.1The size grows in proportion to the design effect. A DEFT of 1.8 instead of 1.494 asks for 45% more households. Chapter 9 models the design effect so that it can be predicted for a new take rather than borrowed.
3.1.5 Effective sample size
effective_n() turns a size into the size of a simple random sample with the same precision, n * resp_rate / deff. The plan above delivers 850 married women.
effective_n(n = mcpr_kerewan$n * kerewan$resp * kerewan$married_hh,
deff = kerewan$mcpr_deft^2)
#> [1] 380.7692These women carry the information of 381 women drawn at random, which is the size of the simple random sample that meets the target, n_prop(kerewan$mcpr, cv = 0.10). The design effect is the price of the clusters.
3.1.6 A plan profile
The same assumptions recur in every call for one domain. svyplan() stores them once as a profile. A profile is passed as plan =, or piped as the first argument, and an argument given in the call overrides it.
kerewan_plan <- svyplan(deff = kerewan$mcpr_deft^2, resp_rate = kerewan$resp,
eligible_per_unit = kerewan$married_hh)
kerewan_plan
#> svyplan profile
#> deff = 2.232036
#> resp_rate = 0.910998
#> eligible_per_unit = 1.3748658065111
kerewan_plan |> n_prop(p = kerewan$mcpr, cv = 0.10)
#> Sample size for proportion (wald)
#> n = 679 gross (eligible respondents: 851) (p = 0.21, cv = 0.100, deff = 2.23, resp_rate = 0.91, eligible_per_unit = 1.375)
#> expected cases = 176.9
#> # summary() for the precision at the field size and the derived sizes
kerewan_plan |> prec_prop(p = kerewan$mcpr, n = 1000)
#> Sampling precision for proportion (wald)
#> n = 1000 (eligible respondents: 1253, eligible_per_unit = 1.375)
#> se = 0.0171, moe = 0.0336, cv = 0.0824, rmoe = 0.1615
#> expected cases = 260.5
kerewan_plan |> n_prop(p = kerewan$vacc, cv = 0.10, deff = kerewan$vacc_deft^2,
eligible_per_unit = kerewan$children_hh)
#> Sample size for proportion (wald)
#> n = 50 gross (eligible respondents: 14) (p = 0.91, cv = 0.100, deff = 1.31, resp_rate = 0.91, eligible_per_unit = 0.3032)
#> expected cases = 12.5
#> # summary() for the precision at the field size and the derived sizesThe first call gives the size found above. The second gives the RSE of 1,000 households. The third sizes full vaccination, which counts children aged 12 to 23 months and has its own design effect, so deff and eligible_per_unit are overridden and the response rate is kept. Coverage near 91% is cheap to measure under a relative target, and 50 households would do. Chapter 8 combines several indicators with n_multi().
3.2 Clusters and strata
3.2.1 The take
A design effect depends on the number of interviews per cluster. varcomp() backs an intraclass correlation out of a published design effect, given the interviews per cluster it was measured at. Kerewan interviewed 1,002 married women in 32 clusters.
b <- kerewan$married / (kerewan$eas_urban + kerewan$eas_rural)
kerewan_icc <- varcomp(deff = kerewan$mcpr_deft^2, take = b)$icc
kerewan_icc
#> [1] 0.04064449n_cluster() finds the cheapest take for that correlation. It needs the cost of a cluster relative to an interview. Say the travel, listing and supervision of a cluster cost as much as 40 household interviews. A household yields k interviews with married women, so an interview costs 1 / k of a household. The names given to the costs label the two stages of the result.
k <- kerewan$married_hh * kerewan$resp
take <- n_cluster(stage_cost = c(cluster = 40, interview = 1 / k),
icc = kerewan_icc, cv = 0.10,
unit_relvar = (1 - kerewan$mcpr) / kerewan$mcpr)
take
#> Optimal 2-stage allocation
#> field design: cluster = 26 | interview = 35 -> total n = 910
#> cv = 0.0998, cost = 1767
#> design df = 25
#> # summary() for the continuous optimum, the design effect and costsThe optimum is about 34 interviews per cluster, or 27 households, close to the 25 of the DHS. The correlation above still carries the weighting loss of the 2019-20 design, and the cost of 40 is an assumption. Chapter 9 removes the first and tests the second.
3.3 samplyr, a design and then a frame
3.3.1 Declaring the design
A samplyr design is written before any frame is read. sampling_design() starts it, add_stage() opens each stage, and within a stage stratify_by(), cluster_by() and draw() say how its units are selected. The clusters are drawn within the 14 strata by systematic sampling, with probability proportional to their households (the measure of size, mos), along the frame sorted by district and ward (the control columns). The households are then drawn by systematic sampling from each cluster’s listing.
design <- sampling_design("A first design for The Gambia") |>
add_stage("Clusters") |>
stratify_by(lga, urban_rural) |>
cluster_by(cluster) |>
draw(n = select(allocation$detail, lga, urban_rural, n = n_1_int),
method = "pps_systematic", mos = households,
control = c(district, ward)) |>
add_stage("Households") |>
draw(n = 25, method = "systematic")
design
#> ── Sampling Design: A first design for The Gambia ───────────────
#>
#> ℹ 2 stages
#>
#> ── Stage 1: Clusters ────────────────────────────────────────────
#> • Strata: lga, urban_rural
#> • Cluster: cluster
#> • Draw: n = <custom data frame, per stratum>, method = pps_systematic, mos = households, control = c(district, ward)
#>
#> ── Stage 2: Households ──────────────────────────────────────────
#> • Draw: n = 25 (per cluster), method = systematicThe take of the first stage is a data frame with one row per stratum, keyed by the stratification columns, which is how a svyplan allocation reaches a samplyr design. A single number would give every stratum the same take.
3.3.2 Checking before drawing
A cluster whose share of its stratum’s households exceeds the sampling interval is selected with certainty, and changes the weights and the variance. frame_summary() reads the chance of every cluster from the design and the frame, before anything is drawn.
frame_summary(design, clusters, stages = 1, detail = "unit") |>
summarise(largest = max(chance), certain = sum(is_certainty))
#> # A tibble: 1 × 2
#> largest certain
#> <dbl> <int>
#> 1 0.186 0No cluster comes near certainty here. Chapter 11 reads the same check on frames where some do.
3.3.3 Drawing the clusters
execute() applies the design to a frame. stages = 1 stops after the clusters, since the households of a cluster are known only once a team has listed it. The seed makes the draw reproducible.
selected <- execute(design, clusters, stages = 1, seed = 2025)
selected
#> # A tbl_sample: 280 × 12 | A first design for The Gambia
#> # Stages: 1/2
#> # Sampling: 1 stage | 280 units
#> # Weights: 17.57 [5.38, 40.32]
#> lga urban_rural cluster district ward households .weight
#> * <chr> <chr> <chr> <chr> <chr> <int> <dbl>
#> 1 Banjul Urban 1021011 Banjul Ce… New … 60 18.3
#> 2 Banjul Urban 1022010 Banjul Ce… New … 98 11.2
#> 3 Banjul Urban 1031005 Banjul No… Box … 77 14.3
#> 4 Banjul Urban 1032012 Banjul No… Camp… 94 11.7
#> 5 Banjul Urban 1011005 Banjul So… Half… 88 12.5
#> 6 Banjul Urban 1013001 Banjul So… Port… 54 20.4
#> 7 Basse Rural 8022011 Basse Sabi 37 30.6
#> 8 Basse Rural 8012012 Jimara Gamb… 53 21.4
#> 9 Basse Rural 8011015 Jimara Jula… 43 26.3
#> 10 Basse Rural 8011041 Jimara Jula… 41 27.6
#> # ℹ 270 more rows
#> # ℹ 5 more variables: .sample_id <int>, .stage <int>,
#> # .weight_1 <dbl>, .fpc_1 <int>, .certainty_1 <lgl>The result is a table of the selected clusters with their frame columns, and with columns of its own that start with a dot. .weight_1 is the inverse of a cluster’s inclusion probability at stage 1; .weight is the weight so far; .fpc_1, used for the finite population correction, is the number of clusters in the cluster’s stratum; and .certainty_1 flags certainty units. .sample_id numbers the rows. The table also carries the design and a record of the execution, which is what lets the next call continue it.
3.3.4 Listing and drawing the households
A synthetic listing stands in for the fieldwork, as in Chapter 12. Each selected cluster lists its frame count times a random factor around 1.05, for growth since the frame was made, and at least 25 households.
set.seed(2026)
listing <- selected |>
as.data.frame() |>
mutate(listed = pmax(25L, as.integer(round(
households * exp(rnorm(n(), log(1.05), 0.2)))))) |>
reframe(hh_id = seq_len(listed), .by = c(lga, urban_rural, cluster))
head(listing, 3)
#> lga urban_rural cluster hh_id
#> 1 Banjul Urban 1021011 1
#> 2 Banjul Urban 1021011 2
#> 3 Banjul Urban 1021011 3
issued <- execute(selected, listing, seed = 2027)
summary(issued)
#> ── Sample Summary: A first design for The Gambia ────────────────
#>
#> ℹ n = 7,000 | stages = 2/2 | seed = 2027
#>
#> ── Stage 1: Clusters ────────────────────────────────────────────
#> • pps_systematic, MOS households, cluster cluster, by lga, urban_rural
#> • 14 strata: N_h 16-1,554, n_h 2-98, f_h 0.0393-0.1250
#>
#> ── Stage 2: Households ──────────────────────────────────────────
#> • systematic
#> • 280 pools: N_h 30-176, n_h 25, f_h 0.1420-0.8333 | eligible units under realized parents
#>
#> ── Weights ──────────────────────────────────────────────────────
#> • Mean 47.8 [25.2, 79.58] | CV 0.2 | Kish DEFF 1.04 | n_eff 6,738The listing has one row per listed household, keyed to its cluster. execute(), given the partial sample and the listing, continues the same design. It does not start a new one, so each household’s weight is the product of the weight of its cluster and the inverse of its chance within the listing, .weight_1 times .weight_2. The summary gives the strata, the sampling fractions and the spread of the weights. Their Kish design effect, the loss from unequal weights alone, is small, because a cluster drawn proportional to its frame count and a fixed take give nearly equal weights. They differ at all because the listing counts differ from the frame counts, and because the floor gives Kuntaur Urban more than its share. Chapter 12 explains the first.
Some surveys hold a reserve of households in each cluster, released one at a time when a household fails. draw(n = 25, reserve = 5) lists 30 households in a random order, and after fieldwork execute(sample, response_status = ) settles each list from the codes the field recorded and weights the interviews. Section 17.4 shows the protocol and what it does to the weights.
3.3.5 Handing the sample to survey
The selected households are interviewed, and the answers are joined to the sample by household. Here a made-up indicator, a user of modern contraception in about one household in six, stands for the data that come back. as_svydesign() turns the sample into a design object of the survey package, with its strata, clusters, weights and finite population corrections, and the estimation is survey’s.
set.seed(1)
observed <- issued |>
mutate(user = rbinom(n(), 1, 0.17))
analysis <- as_svydesign(observed, systematic_variance = "approximate")
survey::svymean(~user, analysis)
#> mean SE
#> user 0.1792 0.0045The estimate is close to the 0.17 used to simulate the answers. survey has no exact variance for systematic selection, so samplyr approximates it and asks the analyst to accept the approximation with systematic_variance = "approximate". Without the argument it warns. Chapter 13 tests how good the approximation is on the synthetic Gambia.
3.3.6 Saving the design
A design is also a record. write_design() writes it to a JSON file, and read_design() reads it back. With the same frame and seed, the design read back draws the same clusters.
path <- tempfile(fileext = ".json")
write_design(design, path)
again <- execute(read_design(path), clusters, stages = 1, seed = 2025)
identical(again$cluster, selected$cluster)
#> [1] TRUEChapter 14 writes the executed sample, with its execution record and a fingerprint of the frame, to the file that accompanies the sample design report.
3.4 Where each piece returns
The thread above took every step in a few lines. The table gives the chapter that takes each step in full.
| Step | Functions | Chapter |
|---|---|---|
| Size a domain from a target | n_prop(), prec_prop(), n_multi(), svyplan() |
8 |
| Model the design effect and choose the take | varcomp(), design_effect(), n_cluster(), effective_n(), design_df() |
9 |
| Allocate among strata and domains | n_alloc(), prec_alloc(), predict() |
10 |
| Prepare the frame and draw the clusters | merge_psus(), frame_summary(), execute(stages = 1) |
11 |
| List and draw the households | execute() on a listing, draw(reserve = ) |
12 |
| Weights and standard errors | as_svydesign() |
13 |
| Report and archive the design | summary(), write_design() |
14 |
3.5 Exercises
- Use
kerewan_planto size Kerewan for an RSE of 8% on mCPR. By how much does the size grow against 10%, and why by about that factor? - A design selects 240 clusters in the same 14 strata. How many degrees of freedom will its variance estimates have? Use
design_df()withn_psuandn_strata. - Draw the clusters again with
seed = 2026. Are the same clusters selected? Does a cluster selected in both draws carry the same.weight_1? - With an infinite population, why does splitting
resp_rateintoeligibility_rateandresp_rateleave the size ofn_prop()unchanged?
kerewan_plan |> n_prop(p = kerewan$mcpr, cv = 0.08)gives 1,061 households, against- The size varies with the inverse square of the target, and \((10/8)^2 = 1.56\).
design_df(n_psu = 240, n_strata = 14)gives 226, the clusters minus the strata.- Mostly other clusters are selected, since systematic selection starts from a new random point. A cluster selected in both carries the same
.weight_1, because its inclusion probability depends only on its households, its stratum’s households and the stratum’s take, not on the seed. - The issued sample is the respondents divided by the product of the two rates, so only the product counts. The split changes a result only through a finite population, where the units in scope are
Ntimeseligibility_rate.