# \donttest{
# Load an example dataset that uses unequal probability sampling ----
data('election', package = 'survey')
# Create matrix to represent the Horvitz-Thompson estimator as a quadratic form ----
n <- nrow(election_pps)
pi <- election_jointprob
horvitz_thompson_matrix <- matrix(nrow = n, ncol = n)
for (i in seq_len(n)) {
for (j in seq_len(n)) {
horvitz_thompson_matrix[i,j] <- 1 - (pi[i,i] * pi[j,j])/pi[i,j]
}
}
## Equivalently:
horvitz_thompson_matrix <- make_quad_form_matrix(
variance_estimator = "Horvitz-Thompson",
joint_probs = election_jointprob
)
# Make generalized bootstrap adjustment factors ----
bootstrap_adjustment_factors <- make_gen_boot_factors(
Sigma = horvitz_thompson_matrix,
num_replicates = 80,
tau = 'auto'
)
# Determine replication scale factor for variance estimation ----
tau <- attr(bootstrap_adjustment_factors, 'tau')
B <- ncol(bootstrap_adjustment_factors)
replication_scaling_constant <- tau^2 / B
# Create a replicate design object ----
election_pps_bootstrap_design <- svrepdesign(
data = election_pps,
weights = 1 / diag(election_jointprob),
repweights = bootstrap_adjustment_factors,
combined.weights = FALSE,
type = "other",
scale = attr(bootstrap_adjustment_factors, 'scale'),
rscales = attr(bootstrap_adjustment_factors, 'rscales')
)
# Compare estimates to Horvitz-Thompson estimator ----
election_pps_ht_design <- svydesign(
id = ~1,
fpc = ~p,
data = election_pps,
pps = ppsmat(election_jointprob),
variance = "HT"
)
svytotal(x = ~ Bush + Kerry,
design = election_pps_bootstrap_design)
svytotal(x = ~ Bush + Kerry,
design = election_pps_ht_design)
# }
Run the code above in your browser using DataLab