How to group columns in R markdown?

2019-08-01 16:17发布

问题:

I am trying to generate a table using kable and saving the output as a markdown. I am later using pandoc to convert markdown to pdf. For my table I would like to group my table columns into two groups. It seems that this could be achieved using the kableExtra "add_header_above" function, but unfortunately the output cannot be stored as markdown. Is there a way to group columns using markdown? I am pasting my dummy code below. Appreciate all comments and suggestions.

library(knitr)
library(kableExtra)
test <- head(mtcars, head=10)
test <- test[,c(1:6)]
kable(test, "markdown")

I have tried grouping the columns like below but it doesn't seem to work.

       |                  |     GroupA     |      GroupB     |
       |:-----------------|:---------------|:----------------|
       |                  |  mpg| cyl| disp|  hp| drat|    wt|
       |:-----------------|----:|---:|----:|---:|----:|-----:|
       |Mazda RX4         | 21.0|   6|  160| 110| 3.90| 2.620|
       |Mazda RX4 Wag     | 21.0|   6|  160| 110| 3.90| 2.875|
       |Datsun 710        | 22.8|   4|  108|  93| 3.85| 2.320|
       |Hornet 4 Drive    | 21.4|   6|  258| 110| 3.08| 3.215|
       |Hornet Sportabout | 18.7|   8|  360| 175| 3.15| 3.440|
       |Valiant           | 18.1|   6|  225| 105| 2.76| 3.460|

回答1:

Why would you store the output in markdown and then later using pandoc to convert markdown to pdf. Why not in one step?

library(knitr)
library(kableExtra)

test <- head(mtcars, head = 10)
test <- test[, c(1:6)]

p <- kable(test) %>%
  add_header_above(c(" " = 1, "Group 1" = 3, "Group 2" = 3))
p

According to your chosen output, you would get a table with grouped headings in "HTML" or "PDF" output.

You could use p to store the "HTML" output and use the pandoc binary to convert it to markdown. But the binary

pandoc itself knows nothing about R. So apart from the metaphysical difficulty of getting the code back from the output it created, you have a tool mismatch.

(Quote from Dirk Edelbuettel)

If you use the direct conversion to PDF you wouldn't need p.