Search code examples
rknitrkableextra

How can you specify grouped column names inside a function with kableExtra?


library(tidyverse)
library(knitr)
library(kableExtra)


kable(head(mpg)) %>% kable_styling %>% add_header_above(c(" " = 6,
                                               "foobar" = 5))

Works well when you want to specify the grouped column header manually:

enter code here

However I want to put this feature inside a function, I've tried:

a_function <- function(my_column_head_name){
kable(head(mpg)) %>% kable_styling %>% add_header_above(c(" " = 6,
                                               my_column_head_name = 5))
}

a_function("foobar")

But this returns the named argument as the column header name:

enter image description here

I'm guessing this is something to do with lazy evaluation?


Solution

  • The header is a named character vector with colspan as values. You have to create the vector and assign names with names().

    a_function <- function(my_column_head_name){
      myHeader <- c(" " = 6, my_column_head_name = 5)
      names(myHeader) <- c(" ", my_column_head_name)
      kable(head(mpg)) %>% kable_styling %>% add_header_above(myHeader)
    }
    
    a_function("foobar")