Issue
I'm trying to make a pie chart, and the first step is to calculate the actual percent share of each section. I thought I should be able to use mutate
but it's giving me 100% across the board:
starwars %>%
group_by(gender) %>%
count() %>%
mutate(percent = n / sum(n) * 100)
I expected to see calculated percents, like this:
gender n percent
female 19 22
hermaphrodite 1 1
male 62 71
none 2 2
NA 3 3
But instead every row appears to be 100%:
gender n percent
female 19 100
hermaphrodite 1 100
male 62 100
none 2 100
NA 3 100
What do I need to change here so I'm getting the percent of the sum of n?
Solution
You need to do ungroup first otherwise you are doing the sum(n)
groupwise.
starwars %>%
group_by(gender) %>%
count() %>% ungroup() %>%
mutate(percent = n / sum(n) * 100)
As noted in the comments, an alternate structure would be:
starwars %>%
group_by(gender) %>%
summarise(n=n(), percent = n / nrow(.) * 100)
Strictly, mutate adds the percentage to each row of the original tibble. summarise gives the summary requested.
Answered By - Jakub.Novotny Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.