I have a data frame with multiple columns and I want to add a top row with sum of all the columns.
mydf
id name val1 val2 val3 val4
1 abc 1 3 2.2 3.1
2 def 2 3 3.2 1.3
This is what I am trying
tot<-mydf %>%
summarize_if(is.numeric, sum, na.rm=TRUE)
But this would only show sum for val1 and val2.
Desired output
id name val1 val2 val3 val4
Total 3 6 5.4 4.4
1 abc 1 3 2.2 3.1
2 def 2 3 3.2 1.3
CodePudding user response:
We may need adorn_totals
library(janitor)
library(dplyr)
mydf %>%
adorn_totals()
-output
id name val1 val2 val3 val4
1 abc 1 3 2.2 3.1
2 def 2 3 3.2 1.3
Total - 3 6 5.4 4.4
Or using dplyr
library(dplyr)
mydf %>%
summarise(id = c('', id), name = c('Total', name),
across(starts_with('val'), ~c(sum(., na.rm = TRUE), .)))
id name val1 val2 val3 val4
1 Total 3 6 5.4 4.4
2 1 abc 1 3 2.2 3.1
3 2 def 2 3 3.2 1.3
data
mydf <- structure(list(id = 1:2, name = c("abc", "def"), val1 = 1:2,
val2 = c(3L, 3L), val3 = c(2.2, 3.2), val4 = c(3.1, 1.3)),
class = "data.frame", row.names = c(NA,
-2L))
CodePudding user response:
You could use tibble::add_row
:
library(tibble)
add_row(mydf, name = "Total",
summarize(mydf, across(starts_with("val"), ~ sum(., na.rm = T))))
By default, it is appended to the bottom.
Output
id name val1 val2 val3 val4
1 1 abc 1 3 2.2 3.1
2 2 def 2 3 3.2 1.3
3 NA Total 3 6 5.4 4.4