0

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.

I did try kableextra which adds another row with names such as v1 v2 v3 v4.

kable(data, format = "html", caption = "Demo Table") %>%
  kable_styling(bootstrap_options = "striped",
                full_width = F) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2[note]" = 2)) %>%
  add_footnote(c("table footnote"))
SNT
  • 1,283
  • 3
  • 32
  • 78
  • 1
    Check out the `kableExtra` package. It builds on `kable` and has a function to add headers just like this, and it's well documented – camille May 24 '18 at 01:11
  • @camille I did try that too.Have added my code above. – SNT May 24 '18 at 04:01

0 Answers0