Defines target shares for one or more categorical variables (e.g. a known
population split by gender or region). Once set, the summary helpers
(calc_percentage(), calc_nps(), calc_summary(), crosstab()) weight
their results automatically, so the weighted margins match your targets. Pass
weights = FALSE to any of them to opt out for a single call.
Arguments
- ...
One scheme per variable. Two forms are accepted:
vector form (one argument per variable) carrying a
variableentry and a share per category:c(variable = "demo_gender", Male = 0.49, Female = 0.50, "Non-binary" = 0.01);named form:
demo_gender = c(Male = 0.49, Female = 0.50), where the argument name is the column. Shares need not sum to 1 – they are normalised per variable (so raw percentages or counts work too).
Details
With a single variable the weights are exact post-stratification:
target_share / sample_share for each category. With several variables the
weights are found by raking (iterative proportional fitting) so every variable's
weighted margin matches its targets. Weights are normalised to mean 1 (so the
weighted base equals the sample size), and respondents whose weighting value is
blank / a non-answer (see na_blank()) are left unadjusted. A category that
appears in the data but is missing from your targets is an error – give every
observed category a share. If a default dataset is set, this prints the Kish
design effect and the effective sample size so you can see the precision cost.
See also
clear_weights(), get_weights(), weight_vector(),
calc_percentage().
Other weighting:
clear_weights_cache(),
get_weights(),
weight_vector()
Examples
set_weights(c(variable = "demo_gender",
"Male" = 0.49, "Female" = 0.50,
"Non-binary" = 0.01))
#> Weighting scheme stored for: demo_gender. It applies once a dataset is in play.
calc_percentage(podracing_survey, satis_return) # gains a wpct column
#> # A tibble: 5 × 4
#> satis_return n pct wpct
#> <ord> <int> <dbl> <dbl>
#> 1 Very unlikely 75 8 8
#> 2 Unlikely 162 16 16
#> 3 Not sure 238 24 24
#> 4 Likely 270 27 27
#> 5 Very likely 255 26 25
clear_weights()
