Last active
April 27, 2020 11:07
-
-
Save eddjberry/f5a04f72c0fc1c6dab512f73b6a79f41 to your computer and use it in GitHub Desktop.
Get counts and proportions by group(s)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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