Bootstrap weights

library(dplyr)
library(canpumf)
options(canpumf.cache_path = Sys.getenv("COMPILE_VIG_CANPUMF"))

PUMF data are a synthetic sample, altered from the original survey responses for privacy reasons. As with any survey sample, point estimates carry sampling uncertainty, and it is good practice to quantify it. Some PUMF ship with bootstrap weights for exactly this purpose; when they do not, canpumf can generate them with add_bootstrap_weights().

The weights a survey ships with need no extra step: they are columns of the table get_pumf() returns (BSW1, …, BSW1000 for the Survey of Financial Security, WT1, …, WT16 for the Census). bsw_info() lists them as source = "survey", next to the source = "generated" weights this vignette is about:

get_pumf("SFS", "2019") |> bsw_info()
#> # A tibble: 1 x 7
#>   source weight_col prefix bsw_table     temporary n_replicates size_mb
#>   <chr>  <chr>      <chr>  <chr>         <lgl>            <int>   <dbl>
#> 1 survey NA         BSW_   eng_EFAM_PUMF FALSE             1000    83.4

This vignette explains how add_bootstrap_weights() works: the method it uses, where the weights live, how stratification works, and — importantly — what happens when you call it again on a dataset that already has weights.

The method: a resampling bootstrap

For each of n_replicates replicates, a sample of n rows is drawn with replacement from the n rows of the (stratum of the) survey. The bootstrap weight for row \(i\) in replicate \(b\) is

\[ w^{*}_{i,b} = w_i \cdot c_{i,b}, \]

where \(w_i\) is the original survey weight and \(c_{i,b}\) is the number of times row \(i\) was selected in replicate \(b\). Because each row is selected once on average, \(\mathbb{E}[c_{i,b}] = 1\) and the replicate weights are unbiased for the original weights. The spread of an estimate across the replicates is what gives you its sampling variance (see Estimating uncertainty).

The default is n_replicates = 500. Pass seed for reproducibility.

Two modes

add_bootstrap_weights() works on two kinds of input and behaves differently for each:

cis <- get_pumf("CIS", "2019")

cis_bsw <- cis |>
  add_bootstrap_weights(weight_col = "FWEIGHT", n_replicates = 200, seed = 42)

# 200 replicate columns CPBSW1 … CPBSW200 are now available
grep("^CPBSW", colnames(cis_bsw), value = TRUE) |> head()
#> [1] "CPBSW1" "CPBSW2" "CPBSW3" "CPBSW4" "CPBSW5" "CPBSW6"

Where the weights are stored (DuckDB path)

The replicate weights are not copied into the main survey table. They are written to a separate table, auto-named paste0("pumf_bsw_", tolower(weight_col)) (e.g. pumf_bsw_fweight). The auto-naming means generating weights for two different weight columns (e.g. a household weight and a person weight) produces two independent BSW tables that never collide.

add_bootstrap_weights() works on the connection of the table it is given. It never closes or reopens one, so what it can store depends on that connection:

# once: store the weights
close_pumf(cis)     # the read-only table opened above holds the database
cis_rw <- get_pumf("CIS", "2019", read_only = FALSE)
cis_rw |> add_bootstrap_weights(weight_col = "FWEIGHT", n_replicates = 200, seed = 42)
close_pumf(cis_rw)

# from then on, in any session: the stored weights are found and joined
cis_bsw <- get_pumf("CIS", "2019") |>
  add_bootstrap_weights(weight_col = "FWEIGHT", n_replicates = 200)

bsw_info() summarises the bootstrap weights of the table. source tells the generated weights (temporary says whether they are stored) from replicate weights that came with the survey, which the CIS does not have:

bsw_info(cis_bsw)
#> # A tibble: 1 × 7
#>   source    weight_col prefix bsw_table        temporary n_replicates size_mb
#>   <chr>     <chr>      <chr>  <chr>            <lgl>            <int>   <dbl>
#> 1 generated FWEIGHT    CPBSW  pumf_bsw_fweight FALSE              200    116.

The weights always cover the complete survey table. For a temporary table that is rows x replicates x 8 bytes, which is small for most surveys and several gigabytes for the Census or the full LFS; add_bootstrap_weights() warns before it builds a temporary table of more than about 2 GB. Store such weights through a write connection, or collect_pumf() the rows of interest and add the weights to the data frame.

Identifying rows

To join replicate weights back to the survey rows a key that identifies each row is needed. With id_col = NULL (the default):

You can always pass id_col explicitly to use a natural key, which may consist of several columns. A table built by an earlier version of canpumf that has none of these needs a rebuild (get_pumf(..., refresh = TRUE)) or an id_col.

Stratified bootstrap weights

Many survey designs are stratified, and the resampling should respect that: each replicate should resample within each stratum, preserving the stratum sample sizes. Pass strata_cols:

cis_bsw <- cis |>
  add_bootstrap_weights(weight_col = "FWEIGHT", strata_cols = "PROV",
                        n_replicates = 200, seed = 42)

Resolution order for the strata:

  1. strata_cols if you pass it,
  2. otherwise the registry bsw_strata for the survey,
  3. otherwise, for the LFS, the default c("SURVYEAR", "SURVMNTH") so each month is resampled separately,
  4. otherwise unstratified.

Pass strata_cols = character(0) to force unstratified weights even when a default exists (e.g. for the LFS).

Estimating uncertainty

To get a bootstrap standard error for an estimate, compute the estimate once with the original weights and once with each replicate weight; the spread of the replicate estimates is the sampling variability. The example below estimates the total population represented by the survey (the sum of the weights), which depends only on the weight columns, but the same pattern applies to any weighted statistic — replace sum(.x) with your estimator (a weighted mean, share, total, …) evaluated with each weight column.

est <- cis_bsw |>
  summarise(across(c(FWEIGHT, matches("^CPBSW[0-9]+$")), ~ sum(.x))) |>
  collect_pumf()

point_estimate      <- est$FWEIGHT
replicate_estimates <- est |> select(matches("^CPBSW[0-9]+$")) |> unlist()

# Bootstrap variance: mean squared deviation of the replicate estimates from
# the full-sample estimate; the standard error is its square root.
# Confidence intervals can be obtained by taking the appropriate quantiles.
confidence_interval <- quantile(replicate_estimates,c(0.025,0.975))
std_error <- sqrt(mean((replicate_estimates - point_estimate)^2))

c(estimate = point_estimate, se = std_error, conf=confidence_interval)
#>   estimate         se  conf.2.5% conf.97.5% 
#>   36831173     170660   36493061   37126328

The same pattern works after group_by() / summarise(): carry the CPBSW* columns through the summary, then collapse them into a standard error per group.

Incremental re-runs

Calling add_bootstrap_weights() again on a survey that already has weights does only the work needed to satisfy the request. The decision is driven by two questions: are there enough replicate columns, and do all rows have weights?

Reuse — nothing to do

If the weights already cover every row and there are at least n_replicates of them, they are reused without recomputation (requesting fewer than exist simply returns a subset). This is why repeatedly opening a survey with stored weights is cheap. On a read-only connection the temporary weights of that connection are looked at first, then the stored ones.

More replicates requested

If you ask for more replicates than exist (and no rows were added), the additional replicate columns are generated and appended; the existing columns are kept unchanged. When stratified, the new columns are resampled within strata, consistent with the existing ones.

# First 200 replicates …
cis_bsw <- add_bootstrap_weights(cis, "FWEIGHT", n_replicates = 200, seed = 42)
# … later, extend to 500: only CPBSW201 … CPBSW500 are generated.
cis_bsw <- add_bootstrap_weights(cis, "FWEIGHT", n_replicates = 500, seed = 42)

Rows added to the survey table

This is the subtle case. A bootstrap replicate resamples the full population (or full stratum), so adding rows invalidates the replicate weights of the affected resampling universe — you cannot simply generate weights for the new rows in isolation. add_bootstrap_weights() detects that not all rows have weights and deletes and regenerates the affected weights:

Extending the number of replicates and adding rows can happen in the same call; each is handled on the rows it applies to.

On a read-only connection both cases are worked out in the temporary table: the stored replicates are copied into it, so they keep their values, and the stored weights stay as they are.

Extending a weighted table after appending rows relies on the new rows having a valid identifier. Use a natural id_col (or the registry bsw_join_key) when you expect to grow the table, so the new rows can be matched.

Forcing a full regeneration

Pass overwrite = TRUE to discard the weights and regenerate from scratch regardless of what is already there: the stored weights on a write connection, the temporary ones on a read-only connection.

cis_bsw <- add_bootstrap_weights(cis, "FWEIGHT", n_replicates = 200,
                                 seed = 42, overwrite = TRUE)

Multiple weight columns

Because each BSW table is named after its weight column, hierarchical surveys with several weights are handled by simply calling the function once per weight. By default all replicate columns share the CPBSW prefix, and a call replaces the replicate columns of its prefix that the input already carries. Give each weight column a distinct prefix to have both sets of replicates in one table (the column names are survey-specific):

tbl <- get_pumf("<series>", "<version>") |>
  add_bootstrap_weights(weight_col = "<household_weight>", prefix = "HHBSW") |>
  add_bootstrap_weights(weight_col = "<person_weight>",    prefix = "PPBSW")

What the input table carries

Bootstrap weights always cover the complete physical survey table, so every subset is weighted from the same replicates. The result is the input tbl joined to the weights: a filter(), select(), mutate() or label_pumf_columns() applied before the call is still in effect afterwards.

cis |>
  filter(PROV == "Ontario") |>
  label_pumf_columns() |>
  add_bootstrap_weights(weight_col = "FWEIGHT", n_replicates = 200, seed = 42)
#> the Ontario rows, with labelled columns and CPBSW1 ... CPBSW200

Two things to keep in mind:

Connection lifecycle

add_bootstrap_weights(), bsw_info() and remove_bootstrap_weights() never close a connection. The table passed in, and every other table on the same connection, stays valid, and the returned table lives on that connection too. Temporary weights last exactly as long as it does: after close_pumf() they are gone, and the next call generates them again (or finds stored ones).

Inspecting and removing weights

bsw_info(cis_bsw)                      # the survey's own and the generated weights, replicate counts
cis_clean <- remove_bootstrap_weights(cis_bsw, weight_col = "FWEIGHT")

remove_bootstrap_weights() drops the temporary weights of the connection and returns a tbl on the original survey table. Stored weights are dropped on a write connection only; on a read-only connection they are kept. The replicate weights that came with the survey are part of the survey table and are never removed.