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(fra_computing))
structure(list(`type de sejour` = c("Ambulatoires", "Externes",
"Hospitalisé", "Séances"), `nb de sejours N2` = c("5774", "7",
"9478", "86"), `annee N2` = c("2019", "2019", "2019", "2019"),
`nb de sejours N1` = c("4689", "0", "7362", "9"), `annee N1` = c("2020",
"2020", "2020", "2020"), `nb de sejours N` = c("5944", "2",
"7502", "3"), `annee N` = c("2021", "2021", "2021", "2021"
), `activite en valeur N2` = c("566.41149982681", "10.2857142857143",
"2409.200042203", "197.406976744186"), `activite en valeur N1` = c("623.226060993815",
"NaN", "2507.36267318663", "188.777777777778"), `activite en valeur N` =
c("712.340679676985",
"24", "2728.76832844575", "202.333333333333")), row.names = c(NA,
4L), class = "data.frame")
I have tried the following, without success :
fra_computing %>%
group_by(`type de sejour`) %>%
summarise(total = sum(as.numeric('nb de sejours N2')))
I would appreciate any advice. Thanks in advance !
CodePudding user response:
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