Skip to content

Instantly share code, notes, and snippets.

@eddjberry
Last active April 27, 2020 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddjberry/f5a04f72c0fc1c6dab512f73b6a79f41 to your computer and use it in GitHub Desktop.
Save eddjberry/f5a04f72c0fc1c6dab512f73b6a79f41 to your computer and use it in GitHub Desktop.
Get counts and proportions by group(s)
group_prop <- function(df, ...) {
# enquo the dots
vars <- enquos(...)
# count then calculate
# proportions
df_count <- df %>%
count(!!!vars)
if (length(vars) > 1) {
df_count %>%
group_by(!!vars[[1]]) %>%
mutate(prop = n / sum(n),
prop_se = sqrt(prop * (1 - prop) / sum(n))) %>%
ungroup()
} else {
df_count %>%
mutate(prop = n / sum(n),
prop_se = sqrt(prop * (1 - prop) / sum(n))) %>%
ungroup()
}
}
@eddjberry
Copy link
Author

Updated to divide by the total sample size rather than the number in each category for the prop_se. See e.g. https://stats.stackexchange.com/questions/396952/standard-error-of-individual-groups-in-a-multinomial-distribution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment