Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate percentage in R by aggregating based on condition

I do not know how to properly setup a table while asking a question, but this one is fairly simple so I should be able to explain it anyway.

I have a database such as:

Parent Type Value
A blue 35
A red 65
B blue 23
C blue 22
C blue 35
C yellow 3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I need is to know is what percentage of each color each parent has, based on the value.

I.e. the parent A has a total value of 35+65 = 100. What I need to obtain is a new column named value percentage with 35% in the blue row and 65% in the red row.

Thank you!

>Solution :

You can use a tidyverse for that:

read.table(text="Parent Type Value
A blue 35
A red 65
B blue 23
C blue 22
C blue 35
C yellow 3", header =T) %>% 
 group_by(Parent) %>% 
 mutate(perc = scales::percent(Value/sum(Value)))
# A tibble: 6 × 4
# Groups:   Parent [3]
  Parent Type   Value perc 
  <chr>  <chr>  <int> <chr>
1 A      blue      35 35%  
2 A      red       65 65%  
3 B      blue      23 100% 
4 C      blue      22 37%  
5 C      blue      35 58%  
6 C      yellow     3 5% 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading