Adding header rows to group columns r

I am trying to group headers using r. Here is the input dataframe I am using.

  |usage     |flavor |variable     |level |      mean|        se|
  |:---------|:------|:------------|:-----|---------:|---------:|
  |Every Day |Yes    |a            |NA    | 0.1844236| 0.0645649|
  |Every Day |No     |a            |NA    | 0.2074303| 0.0830913| 
  |Some Days |Yes    |a            |NA    | 0.1748468| 0.0279065| 
  |Some Days |No     |a            |NA    | 0.2720068| 0.0512438|

I used the following code to do the grouping

kable(data) %>%
  kable_styling("striped") %>%
  add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2))

And the output I get is:

        |V1           |V2           |V3           |V4           |
  |:--------|:------------|:------------|:------------|:------------|
  |usage    |Every Day    |Every Day    |Some Days    |Some Days    |
  |flavor   |Yes          |No           |Yes          |No           |
  |variable |a            |a            a             |a            |
  |level    |NA           |NA           |NA           |NA           |
  |mean     |0.1844236    |0.2074303    |0.1748468    |0.2720068    |

What I am trying to condense the input data frame is something like this:

            |EVERYDAY                   |SOMEDAYS                   
            ---------------------------------------------------------
            |flavor yes   |flavor no    |flavor yes   |flavor no    |
  |:--------|:------------|:------------|:------------|:------------|
  |variable |a            |a            a             |a            |
  |level    |NA           |NA           |NA           |NA           |
  |mean     |0.1844236    |0.2074303    |0.1748468    |0.2720068    |

How could this grouping be done as above.
Thank you.

You should be able to do this with the kableExtra package
https://haozhu233.github.io/kableExtra/awesome_table_in_html.html#grouped_columns__rows

1 Like