rkablekableextra

Repeat Column Headers In Grouped Kable


I have a dataframe:

 df1 <- data.frame(inst = c("A", "B", "C", "D", "E", "F", "G"), 
         year_1_type1 = c(1,5,3,8,7,9,4), 
         year_2_type1 = c(5,7,8,3,5,2,6), 
         year_1_type2 = c(1,5,3,8,7,9,4), 
         year_2_type2 = c(5,7,8,3,5,2,6))

and I'm trying to create a grouped kable output with repeated headers. You'll see that I have a header_above feature that groups by Type to avoid confusion but it's not allowing me to repeat year_1 and year_2. I Tried adding col.names and got the error

Error in round(x[, j], digits[j]) : 
  non-numeric argument to mathematical function

df1  %>%
  kbl(caption = '<b>Table 5</b>-Comparison of Types and Years', align='l',  col.names = "inst", "year 1", "year 2", "year 1", "year 2") %>%
  kable_classic(full_width = T, html_font = "Arial Narrow") %>% 
  kable_styling() %>%
  add_header_above(c(" " = 1, "Type 1" = 2, 
                     "Type 2"=2), align = "l")

Solution

  • Your error isn't related to grouping headers, you have a typo in the call to kbl:

      kbl(..., col.names = "inst", "year 1", "year 2", "year 1", "year 2") %>%
    #                     ^^^ missing a c( to start the vector, and a closing )
    

    Try this:

    df1  %>%
      kbl(caption = '<b>Table 5</b>-Comparison of Types and Years', align='l',  
          col.names = c("inst", "year 1", "year 2", "year 1", "year 2")) %>%
      kable_classic(full_width = T, html_font = "Arial Narrow") %>% 
      kable_styling() %>%
      add_header_above(c(" " = 1, "Type 1" = 2, "Type 2"=2), align = "l")