Search code examples
rdplyrsumcumulative-sum

creating row total in R


Being quite new on R, i would like to create a row "total" with the sum of the lines of each column, for the columns "nb de sejours" and "activite en valeur" (for each year). Could anyone help me ?

dput(head(computing))

structure(list(000), class = "data.frame")

I have tried the following, without success :

computing %>%
  group_by(`trip`) %>%
  summarise(total = sum(as.numeric('trip N2')))

I would appreciate any advice. Thanks in advance !


Solution

  • you may need to convert numeric columns from characters to numeric first, then we use adorn_totals() from package janitor

    fra_computing %>% mutate(across(-c("type de sejour"), as.numeric)) %>% adorn_totals("row")
    
    type de sejour nb de sejours N2 annee N2 nb de sejours N1 annee N1 nb de sejours N annee N activite en valeur N2
       Ambulatoires             5774     2019             4689     2020            5944    2021             566.41150
           Externes                7     2019                0     2020               2    2021              10.28571
        Hospitalisé             9478     2019             7362     2020            7502    2021            2409.20004
            Séances               86     2019                9     2020               3    2021             197.40698
              Total            15345     8076            12060     8080           13451    8084            3183.30423
     activite en valeur N1 activite en valeur N
                  623.2261             712.3407
                       NaN              24.0000
                 2507.3627            2728.7683
                  188.7778             202.3333
                 3319.3665            3667.4423