Search code examples
rknitrr-markdownflexdashboardknitrbootstrap

R - knitr:kable - removing individual headers and adding single header on multiple columns


R code in Rmarkdown file:

col1 <- c("dummydata","dummydata","dummydata")
col2 <- c("dummydata","dummydata","dummydata")  
col3 <- c("dummydata","dummydata","dummydata")
col4 <- c("dummydata","dummydata","dummydata")
col5 <- c("dummydata","dummydata","dummydata")
col6 <- c("dummydata","dummydata","dummydata")
col7 <- c("dummydata","dummydata","dummydata")
col8 <- c("dummydata","dummydata","dummydata")

df1 <- data.frame(col1,col2,col3,col4,col5,col6,col7,col8)

kable(df1, format="html",table.attr='class="myTable"') %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
add_header_above(c("Group1" = 2, "Group2" = 2,"Group3" = 2, "Group4" = 2))

Output: FlexDashBoard Kable - Dataframe as Table

ISSUE: I only want headers on combined columns i.e. Group1, Group2 etc. And I want to remove headers on individual columns i.e. col1, col2 etc.

Is there any way to do this using dataframe, html/javascript, Rmarkdown or any R package?


Solution

  • You should get comfortable with regular expressions and the gsub-function if you come accros such problems more often.

    here is a solution, the first row is your last line of code enhanced by "x <-"

    x <- kable(df1, format="html",table.attr='class="myTable"') %>%
    kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
    add_header_above(c("Group1" = 2, "Group2" = 2,"Group3" = 2, "Group4" = 2))
    
    gsub("</th></tr><tr>.*</thead>","</thead>",x)
    

    gsub works as follows: look for a match to the first parameter, replace it with the second and do all that to the variable provdided as third parameter. The dot star (.*) within the first parameter says that any type and number of characters can follow before the closing follows in the third parameter. The algorithm is greedy that is it tries to find the longest matching string. Since there is only one in this input parameter, this works fine here.