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

1

5

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?

Sweetie answered 25/10, 2019 at 20:12 Comment(2)
I don't think it's possible with knitr::kable, but you might try gt.Strapper
or kableExtraViradis
F
8

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:

Fiveandten answered 26/12, 2019 at 17:1 Comment(3)
hi @LuisSilva, i am trying to output to html. I think i follow your logic but the code you provided is not producing a table.Sweetie
hi. The code you provided in your question was for a latex table thus i thought you wanted to make a PDF. Fixed the answer for HTML. Please try it now!Fiveandten
@Fiveandten thanks! This saved me a ton of work! Exactly what I was trying to figure out.Butadiene

© 2022 - 2024 — McMap. All rights reserved.