Search code examples
rr-markdownbookdownkablekableextra

r - use kable to group columns with sub columns having the same name


I am trying to use kable and kableextra to create a table that has different grouped headers but the same column names in the sub-headers

For example, if you look at the section "Grouped Columns/Headers" (page 14) of Create Awesome LaTeX Table with knitr::kable andkableExtra it is grouped but the sub-header names are different:

library(knitr)
library(kableExtra)
dt <- mtcars[1:5, 1:6]

kable(dt, "latex", booktabs = T) %>%
kable_styling() %>%
add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))

What I am trying to do is something like this with the cars as groups (only using two cars for example):

Mazda RX4 | Datsun 710
----------------------
mpg | cyl | mpg | cyl
----------------------
21.0|   6 | 21.4|   6

or as another example:

Group 1 | Group 2
------------------
x  |  y | x  |  y
------------------
a  |  1 | b  |  2
c  |  3 | d  |  4

Is this possible?


Solution

  • I had the same problem. Hope this helps:

    EDIT: Changed the answer to make a HTML table but the logic remains!!

    library(kableExtra)
    library(tidyverse)
    library(knitr)
    
    df <- tibble('mpg_Mazda_RX4' = 21,
                 'cyl_Mazda_RX4' = 6,
                 'mpg_Datsun_710' = 21.4,
                 'cyl_Datsun_710' = 6)
    kable(df,
          "html",
          booktabs = T,
          align = c("r"),
          col.names = c("mpg","cyl","mpg","cyl")) %>%
      kable_styling("striped", full_width = F,
                    position = "left", font_size = 12) %>%
      add_header_above(c("Mazda RX4" = 2, "Datsun 710" = 2))
    

    You have to pass column names directly to kable (doesn't change the dataframe column names).

    Result:

    Result: