I have done a group by using three columns now I want to get percentages for each group:
GENDER preference option num_users
<fct> <fct> <int> <int>
1 Female Sweet 1 136
2 Female Sweet 2 28
3 Female Don't Know 1 18
4 Female Don't Know 2 2
5 Female Medium Spicy 1 62
6 Female Medium Spicy 2 6
7 Female Spicy 1 84
8 Female Spicy 2 20
9 Female Hot 1 35
10 Female Hot 2 5
# ... with 17 more rows
I managed to use transmute
when I only use Gender
and Option
to group but after adding the preference
transmute
doesn't work.
Here is my approach without preference
column in the group by:
grouped_df <- df %>%
group_by(GENDER, option) %>%
summarize(num_users = n()) %>%
spread(GENDER, num_users) %>%
ungroup() %>%
transmute(option_id = option,
female_percent = Female/(Female + Male),
male_percent = Male / (Female + Male)) %>%
mutate(female_percent = round(100 * female_percent),
male_percent = round(100 * male_percent))
How can I use preference in the above approach?