Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide group sum by total sum

I am using the dplyr package. Let's suppose I have the below table.

Group count
A 20
A 10
B 30
B 35
C 50
C 60

My goal is to create a summary table that contains the mean per each group, and also, the percentage of the mean of each group compared to the total means added together. So the final table will look like this:

Group avg prcnt_of_total
A 15 .14
B 32.5 .31
C 55 .53

For example, 0.14 is the result of the following calculation: 15/(15+32.5+55)

Right now, I was only able to produce the first column code that calculates the mean for each group:

summary_df<- df %>% 
             group_by(Group)%>% 
             summarise(avg=mean(count))

I still don't know how to produce the prcnt_of_total column. Any suggestions?

like image 895
GitZine Avatar asked Nov 30 '25 02:11

GitZine


1 Answers

You can use the following code:

df <- read.table(text="Group    count
A   20
A   10
B   30
B   35
C   50
C   60", header = TRUE)

library(dplyr)
df %>%
  group_by(Group) %>%
  summarise(avg = mean(count)) %>%
  ungroup() %>%
  mutate(prcnt_of_total = prop.table(avg))
#> # A tibble: 3 × 3
#>   Group   avg prcnt_of_total
#>   <chr> <dbl>          <dbl>
#> 1 A      15            0.146
#> 2 B      32.5          0.317
#> 3 C      55            0.537

Created on 2022-07-14 by the reprex package (v2.0.1)

like image 163
Quinten Avatar answered Dec 01 '25 16:12

Quinten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!