How to summarise values according to different values and then aggregate it?

Viewed 37

I'm trying to summarise values according to different groups.
Here's my example below.
Is there a way to get the expected result in a more robust way ?
Many thanks in advance !

library(dplyr)

tab1 <- starwars %>% 
  slice(1:8) %>% 
  group_by(eye_color,sex) %>% 
  summarise(value=sum(mass,na.rm = T)) %>% 
  ungroup()

tab2 <- tab1 %>% 
  group_by(eye_color) %>%
  summarise(pourcentage=round(value/sum(value)*100,1))

# What I want
tibble(
  eye_color = tab1$eye_color,
  sex = tab1$sex,
  value = tab1$value,
  pourcentage = tab2$pourcentage,
)
# A tibble: 6 x 4
  eye_color sex    value pourcentage
  <chr>     <chr>  <dbl>       <dbl>
1 blue      female    75        27.6
2 blue      male     197        72.4
3 brown     female    49       100  
4 red       none      64       100  
5 yellow    male     136        64.5
6 yellow    none      75        35.5
1 Answers

summarise by default drops one level of grouping, so you can add a mutate after the first summarise to calculate the percentage.

library(dplyr)

starwars %>% 
  slice(1:8) %>% 
  group_by(eye_color,sex) %>% 
  summarise(value=sum(mass,na.rm = T)) %>%
  mutate(percentage = round(prop.table(value) * 100, 1)) %>%, 
  #prop.table is same as value/sum(value)
  #percentage=round(value/sum(value)*100,1)) %>%
  ungroup

#  eye_color sex    value percentage
#  <chr>     <chr>  <dbl>      <dbl>
#1 blue      female    75       27.6
#2 blue      male     197       72.4
#3 brown     female    49      100  
#4 red       none      64      100  
#5 yellow    male     136       64.5
#6 yellow    none      75       35.5
Related