R - Print table with columns sums below

Viewed 9516

Example: I have a simple data frame

df <- data.frame(date=c("2016-01-01", "2016-01-02")
                 , sales_a = c(2,3)
                 , sales_b = c(1,1)
                 , diff=c(1,2))

I am currently printing this df using kable in an RMarkDown document. I would like to produce a row underneath with the sums of the columns (not date) with a line separating the df from the totals. Is this possible with any R package without writing latex code which I'm not too familiar with?

Thanks

2 Answers

I took the answer of https://stackoverflow.com/a/36069586/8076560 as an inspiration to create the following in R with RStudio. The table can then be exported (knit) to pdf/html as needed.

Screenshot of Finished Table

And now to the code...

```{r name-of-chunk, echo=FALSE}    

# Load packages
library(dplyr)
library(kableExtra)

# Make lists
types <- c("Heating", "Water Heating", "Electricity")
heat_per_person <- c (9.59, 1.32, 1.95)
heat_per_area <- c(95.26, 13.55, 20.03)

# Make dataframe
results_df <- data.frame(types , heat_per_person, heat_per_area, stringsAsFactors = FALSE)

# Sum the last row of each column if numeric 
func <- function(z) if (is.numeric(z)) sum(z) else '' 
sumrow <- as.data.frame(lapply(results_df, func))

# Give name to the first element of the new data frame created above
sumrow[1] <- "Total"

# Add the original and new data frames together
summed_results_df <- rbind(results_df, sumrow)

# Name the columns
colnames <- data.frame("Service", "Amount per Person","Amount per Area", stringsAsFactors = FALSE)
colnames(summed_results_df) <- colnames

# Make Table
kable(summed_results_df, caption = "Normalized Annual Energy Demand", booktabs = TRUE) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "condensed")) %>%
  row_spec(dim(summed_results_df)[1], bold = T) %>% # format last row
  column_spec(1, italic = T) # format first column

```

You can refer to the table in the Rmarkdown/ Rmd text with the name of the code chunk as shown here: \@ref(tab:name-of-chunk)

Related