Adding Headers to a table using formattable in R

Viewed 333

I would like to add headers entitled "Category 1", "Category 2", "Category 3" and "Category 4" to a table, separated by a black line. I would like it to look like the picture attached. Please see the code for the table without the Categories/black lines between columns:

library(formattable)
data(mtcars)

df <- mtcars

formattable(df)

Desired plot

enter image description here

1 Answers

Here is one with kable where can use add_header_above by passing a vector of key/value pair with key suggesting the name and value for the number of columns to be expanded

library(kableExtra)
library(dplyr)
library(kableExtra)
mtcars %>%
   kable() %>%
  kable_styling(bootstrap_options = "bordered",
                full_width = FALSE)  %>%
 add_header_above(c("", "Category1" = 3, "Category2" = 3,
                           "Category3" = 3, "Category4" = 2)) %>%
  collapse_rows(columns = 1,
                valign = "middle")

-output

enter image description here


Some of the styling can be changed as well

mtcars %>%
   kable() %>%
  kable_styling(bootstrap_options = "responsive",
                full_width = FALSE)  %>%
 add_header_above(c("", "Category1" = 3, "Category2" = 3,
                           "Category3" = 3, "Category4" = 2)) %>%
  collapse_rows(columns = 1,
                valign = "middle")
Related