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

Specify the calculation by column using adorn_totals()

I am trying to add a totals row usin ghte Janitor package in R, however I need 2 columns to be totaled using the sum function and one column to be a percentage (not the sum of the column).

library(tidyverse)
library(janitor)

df.1 <- tribble(
~customer  ,~period, ~cost1, ~cost2 ,
'cust1',  '202201', 5, 10,
'cust1',  '202202', 5, 10,
'cust1',  '202203', 5, 10,
'cust1',  '202204', 5, 10,
)


df.1 %>% 
  group_by(customer, period) %>% 
  summarise(cost1 = sum(cost1, na.rm = T),
            cost2 = sum(cost2, na.rm = T),
            total = cost1 + cost2,
            pct   = cost1 / cost2) %>% 
  adorn_totals(where = 'row')

Expected output would be:

customer    period    cost1    cost2    total    pct
cust1       202201       5        10        15   .33333
cust1       202202       5        10        15   .33333
cust1       202203       5        10        15   .33333
cust1       202204       5        10        15   .33333  
Total                   20        40        60   .33333

Thanks in advance for advice.

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

>Solution :

Get the percentage per row, after adorn:

df.1 %>% 
  group_by(customer, period) %>% 
  summarise(cost1 = sum(cost1, na.rm = T),
            cost2 = sum(cost2, na.rm = T),
            total = cost1 + cost2) %>% 
  adorn_totals(where = 'row') %>% 
  mutate(pct = cost1/total)
# `summarise()` has grouped output by 'customer'. You can override using the
# `.groups` argument.
# customer period cost1 cost2 total       pct
#    cust1 202201     5    10    15 0.3333333
#    cust1 202202     5    10    15 0.3333333
#    cust1 202203     5    10    15 0.3333333
#    cust1 202204     5    10    15 0.3333333
#    Total      -    20    40    60 0.3333333
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