Search code examples
rkableextra

R kableExtra 1 column header spanning multiple columns


I am making a table using kableExtra package in R.

iris2 <- head(iris)
iris2[6] <- NA
kbl(iris2) %>%
kable_classic()

enter image description here

What I want is for "Species" to span both column 5 and 6 (so the column name "V6" is removed"). Something like this (edited photo)... enter image description here

How can I accomplish this? I have tried add_header_above() to create a new header which works, but I can't remove the original header.


Solution

  • How about this?

    Hide the original column names and use add_header_above to assign the columns as per choice.

    library(kableExtra)
    
    iris2 <- head(iris)
    
    iris2[6] <- NA
    kbl(iris2, col.names = NULL) %>%
      add_header_above(c(names(iris2)[1:4], "Species" = 2)) %>%
      kable_classic()
    

    enter image description here