I want to calculate the %'s of items within groups. For example, there are 2 groups and each contain 3 fruits. I want to know within each group, what are the proportions of fruit (i.e. each group should add up to 100%). I can achieve this using the below code but it feels too verbose. Can anyone suggests any improvements or a function that already exists to simplify it?
library(tidyverse)
#some data
fruit <- rep(c("apples", "oranges", "bananas"),
times=c(3, 2, 5))
group <- rep(c(1, 2), times=c(35, 65))
df <- data.frame(fruit, group, stringsAsFactors=FALSE)
#get %'s for each fruit within each group
df2 <- df %>%
#get numerator
group_by(fruit, group) %>%
summarise(`Total by fruit and group` = n()) %>%
#get denominator
left_join(df %>%
group_by(group) %>%
summarise(`Total by group` = n())) %>%
#work out % as numerator/denominator *100
mutate(`%`=`Total by fruit and group` / `Total by group`*100 ) %>%
select(fruit, group, `%`) %>%
arrange(group)