Search code examples
htmlheaderfont-sizekablekableextra

Changing the font size of headers of kableExtra table


I am trying to change the font size of various headers in the following table.

library(knitr)
library(kableExtra)
dt <- mtcars[1:5, 1:6]
kable(dt) %>%
kable_styling(c("striped", "bordered")) %>%
add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
add_header_above(c(" ", "Group 6" = 6))

Image of the table from the code above:

Image of table from code above

However, I would like the header group 6 to be far bigger than Group 4 and 5 and groups 1,2,3 to be smaller again. Is this possible?

In addition to this is it possible to call an object for titleing the "Group6" header rather than having to type the string?

Thank you in advance,


Solution

    • The uppermost grouping rows added on top of the table include dynamic labels as requested;
    • The following grouping rows added on top of the table use manually set labels.

    Credits to @Rene for his post how to use dynamic labeling for grouping rows added on top of the table with add_header_above().

    vec <- c("Properties A", "Properties B")
    mtcars[1:3,1:4] %>% kable() %>% 
      kable_styling() %>% 
      # 2nd. level of grouping rows: manual labels
      add_header_above(
        c(" " = 1, 
          "Features" = 2, 
          "Features" = 2), 
        font_size = 15) %>%
      # 1st. level of grouping rows: dynamic labels
      add_header_above(
        c(" " = 1, 
        setNames(2, vec[1]),
        setNames(2, vec[1])), 
        font_size = 25)