R/helpers-multilevel-regression-poststratification.R

Defines functions post_stratification_helper

Documented in post_stratification_helper

#' Post stratification estimator helper
#'
#' Calculates predicted values from a multilevel regression and the post-stratified state-level estimates
#'
#' Please see https://book.declaredesign.org/observational-descriptive.html#multi-level-regression-and-poststratification
#'
#' @param model_fit a model fit object from, e.g., glmer or lm_robust
#' @param data a data.frame
#' @param group unquoted name of the group variable to construct estimates for
#' @param weights unquoted name of post-stratification weights variable
#'
#' @return data.frame of post-stratified group-level estimates
#'
#' @export
#'
#' @importFrom prediction prediction
#' @importFrom dplyr group_by summarize
#' @importFrom stats weighted.mean
#' @importFrom rlang `!!` enquo
#'
post_stratification_helper <- function(model_fit, data, group, weights) {
  prediction(
    model_fit,
    data = data,
    allow.new.levels = TRUE,
    type = "response"
  ) %>%
    group_by({{group}}) %>%
    summarize(estimate = weighted.mean(fitted, !!enquo(weights)), .groups = "drop")
}

Try the rdddr package in your browser

Any scripts or data that you put into this service are public.

rdddr documentation built on July 3, 2022, 5:06 p.m.