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

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% 

Leave a Reply