Skip to contents

Calculate proportion statistics for multiple grouping variables and multiple subject variables in a single hierarchical table.

Compared to srv_prop_stats_crossing(), which computes each grouping variable and subject variable combination independently, this function computes stats for all combinations of the selected grouping variables taken together. It also adds an overall category, all_label, to each grouping variable. For example, if two grouping variables have levels (A, B) and (X, Y), the result includes summaries for (All, A, B) x (All, X, Y).

Within each grouping combination and each subject variable, the function returns weighted counts, proportions, overall proportions, an index relative to the overall proportion, and a p-value for the difference from overall.

Usage

srv_prop_stats_hierarchical(
  data,
  grp_vars,
  sbj_vars,
  wt = NULL,
  na.rm = FALSE,
  all_label = "All"
)

Arguments

data

a dataframe

grp_vars

<tidy-select> expression for grouping variables

sbj_vars

<tidy-select> expression for subject variables

wt

optional weight variable

na.rm

drop subject variable NA categories before calculating percentages? By default is FALSE

all_label

Character. Label used for the overall category added to each grouping variable. Default is "All".

Value

A data frame with one row per grouping-variable combination, subject variable, and subject-variable level.

Examples

data("ds_newsletter")

res <-
  ds_newsletter |>
  dplyr::mutate(weight = runif(dplyr::n(), 0.8, 1.2)) |>
  dplyr::mutate(weight = weight / mean(weight)) |>
  srv_prop_stats_hierarchical(
    grp_vars = c(Region, s_race),
    sbj_vars = s_age:s_hhincome,
    wt = weight
  )

wb <- srv_prop_stats_hierarchical_xlsx(res, sheet_name = "Stats")
#> ! Found 1 column with missing or invalid labels: "Region".
#> ℹ Replacing these labels with variable names
# openxlsx::saveWorkbook(wb, "summaries/hier_prop_stats.xlsx")