if (FALSE) {
library(survey)
# 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 replication adjustment factors ----
adjustment_factors <- make_fays_gen_rep_factors(
Sigma = horvitz_thompson_matrix,
max_replicates = 50
)
attr(adjustment_factors, 'scale')
# Compute the Horvitz-Thompson estimate and the replication estimate
ht_estimate <- svydesign(data = election_pps, ids = ~ 1,
prob = diag(election_jointprob),
pps = ppsmat(election_jointprob)) |>
svytotal(x = ~ Kerry)
rep_estimate <- svrepdesign(
data = election_pps,
weights = ~ wt,
repweights = adjustment_factors,
combined.weights = FALSE,
scale = attr(adjustment_factors, 'scale'),
rscales = rep(1, times = ncol(adjustment_factors)),
type = "other",
mse = TRUE
) |>
svytotal(x = ~ Kerry)
SE(rep_estimate)
SE(ht_estimate)
SE(rep_estimate) / SE(ht_estimate)
}
Run the code above in your browser using DataLab