|
| 1 | +#' Extract Precinct-Level Estimates from ei.MD.bayes Object |
| 2 | +#' |
| 3 | +#' Extracts precinct-specific ecological inference estimates from ei_rxc() output. |
| 4 | +#' Uses exact string matching to handle variation column names |
| 5 | +#' |
| 6 | +#' @param eivote `ei_rxc()` output object containing `stat_objects` |
| 7 | +#' @param cand_cols Character vector of candidate column names (e.g., `c("pct_cand_A", "pct_cand_B")`) |
| 8 | +#' @param race_cols Character vector of race column names (e.g., `c("pct_black", "pct_white")`) |
| 9 | +#' @param dat Original data frame used in `ei_rxc()` call |
| 10 | +#' @param precinct_id Column name for precinct identifier (must exist in `dat`) |
| 11 | +#' |
| 12 | +#' @return Data frame with precinct IDs and race×candidate estimate columns |
| 13 | +#' |
| 14 | +#' @details |
| 15 | +#' The function extracts `md_out$draws$Beta` from the `ei_rxc()` output, which contains |
| 16 | +#' MCMC draws for each precinct-race-candidate combination. Beta column names follow |
| 17 | +#' the format `"beta.race_name.cand_name.precinct_idx"`. The function computes posterior |
| 18 | +#' means across MCMC iterations for each precinct. |
| 19 | +#' |
| 20 | +#' Output columns follow `expand.grid(cand, race)` ordering, with column names formatted |
| 21 | +#' as `paste0(race, cand)` (e.g., `"pct_blackpct_cand_A"`). |
| 22 | +#' |
| 23 | +#' @examples |
| 24 | +#' \donttest{ |
| 25 | +#' |
| 26 | +#' # library(eiCompare) |
| 27 | +#' # data(gwinnett_ei) |
| 28 | +#' # |
| 29 | +#' # gwinnett_ei$precinct <- 1:nrow(gwinnett_ei) |
| 30 | +#' # |
| 31 | +#' # eivote <- ei_rxc( #this will take some time |
| 32 | +#' # data = gwinnett_ei, |
| 33 | +#' # cand_cols = c("kemp", "abrams", "metz"), |
| 34 | +#' # race_cols = c("white", "black", "other"), |
| 35 | +#' # totals_col = "turnout", |
| 36 | +#' # seed = 12345 |
| 37 | +#' #) |
| 38 | +#' |
| 39 | +#' # # Extract precinct-level estimates |
| 40 | +#' # precinct_results <- extract_rxc_precinct( |
| 41 | +#' # eivote = eivote, |
| 42 | +#' # cand_cols = c("kemp", "abrams"), |
| 43 | +#' # race_cols = c("white", "black", "other"), |
| 44 | +#' # dat = gwinnett_ei, |
| 45 | +#' # precinct_id = "precinct" |
| 46 | +#' #) |
| 47 | +#' |
| 48 | +#' #head(precinct_results) |
| 49 | +#' } |
| 50 | +#' |
| 51 | +#' @export |
| 52 | +extract_rxc_precinct <- function(eivote, cand_cols, race_cols, dat, precinct_id) { |
| 53 | + |
| 54 | + # Extract md_out object from ei_rxc wrapper |
| 55 | + eiMD_object <- eivote$stat_objects[[1]] |
| 56 | + |
| 57 | + # Extract Beta matrix (MCMC iterations × beta parameters) |
| 58 | + Beta <- eiMD_object$draws$Beta |
| 59 | + |
| 60 | + # Check that precinct_id column exists in dat |
| 61 | + if(!precinct_id %in% colnames(dat)) { |
| 62 | + stop(paste0("Column '", precinct_id, "' not found in dat. ", |
| 63 | + "Available columns: ", paste(colnames(dat), collapse = ", "))) |
| 64 | + } |
| 65 | + |
| 66 | + n_precincts <- nrow(dat) |
| 67 | + beta_colnames <- colnames(Beta) |
| 68 | + |
| 69 | + # Initialize result matrix (precincts × race-candidate combinations) |
| 70 | + result_matrix <- matrix(NA, |
| 71 | + nrow = n_precincts, |
| 72 | + ncol = length(race_cols) * length(cand_cols)) |
| 73 | + |
| 74 | + # Loop through race-candidate combinations and extract precinct estimates |
| 75 | + col_idx <- 1 |
| 76 | + for(race in race_cols) { |
| 77 | + for(cand in cand_cols) { |
| 78 | + |
| 79 | + # Build expected prefix pattern for exact matching |
| 80 | + # Format: beta.race.cand.precinct_number |
| 81 | + expected_prefix <- paste0("beta.", race, ".", cand, ".") |
| 82 | + |
| 83 | + # Find Beta columns matching this race-candidate pair |
| 84 | + matching_cols <- grep(paste0("^", gsub("\\.", "\\\\.", expected_prefix)), |
| 85 | + beta_colnames, |
| 86 | + value = FALSE) |
| 87 | + |
| 88 | + # Validation - should have exactly n_precincts matches |
| 89 | + if(length(matching_cols) != n_precincts) { |
| 90 | + stop(paste0("Column matching error for race='", race, "', cand='", cand, |
| 91 | + "': found ", length(matching_cols), " columns but expected ", |
| 92 | + n_precincts, " precincts")) |
| 93 | + } |
| 94 | + |
| 95 | + # Extract precinct indices and reorder to match dat row order |
| 96 | + precinct_nums <- sub(expected_prefix, "", beta_colnames[matching_cols]) |
| 97 | + precinct_order <- order(as.numeric(precinct_nums)) |
| 98 | + matching_cols_ordered <- matching_cols[precinct_order] |
| 99 | + |
| 100 | + # Calculate mean across MCMC iterations for each precinct |
| 101 | + result_matrix[, col_idx] <- colMeans(Beta[, matching_cols_ordered]) |
| 102 | + col_idx <- col_idx + 1 |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + # Create column names (race + candidate, matching expand.grid order) |
| 107 | + col_names_df <- expand.grid(cand = cand_cols, race = race_cols) |
| 108 | + col_names <- paste0(col_names_df$race, col_names_df$cand) |
| 109 | + |
| 110 | + # Convert to data frame with column names |
| 111 | + result_df <- as.data.frame(result_matrix) |
| 112 | + colnames(result_df) <- col_names |
| 113 | + |
| 114 | + # Attach precinct IDs from original data as first column |
| 115 | + result_df <- cbind(dat[, precinct_id, drop = FALSE], result_df) |
| 116 | + |
| 117 | + return(result_df) |
| 118 | +} |
0 commit comments