PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, April 23, 2022

[FIXED] Why are both of these values showing up as 100%?

 April 23, 2022     dplyr, pie-chart, r     No comments   

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 

enter image description here

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

enter image description here

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing