将新行插入 kable headers

Inserting new lines into kable headers

问题描述:

我正在用 rMarkdown 编写文档,我需要在生成 PDF 之前格式化 table。问题是我无法在使用 add_headers_above 命令添加的 kable header 中插入新行。

目前文本 "Month (persons)" - 这是第一个用该命令添加的 header - 显示为一行。我想打破它,以便在 "Month" 和“(persons)”之间插入一个新行。

动机只是为了节省水平页面 space 这样我就可以在一张 A4 sheet.

上按尺寸放两个 tables

我的修复尝试

我尝试在 add_headers_above 命令中包含 \n

[...] %>% add_header_above(c(" ", 'Month \n (persons)' = 1, "TTY \n (persons)" = 1, "TTY \n (% chg.)" = 1)) 但这并没有奏效。

可重现的例子:

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kableExtra)
library(tibble)
```
```{r}
df <- tribble(~Location, ~Jan_Qrt, ~Jan_year, ~growth,
"New South Wales",  16000,  403300,       3.30,
"Victoria",        -21200,    134100,       3.50,
"Queensland",        2100,  100200,       3.20,
"South Australia",  19700,  117900,       5.00,
"Western Australia",   5300,   13200,     1.60,
"Tasmania",         -8900,   24300,     1.90,
"Northern Territory",    -400,    5700,    2.40,
"Australian Cap",     300,   -4300,    -3.10,
"Australia",         800,   10600,     4.80)

kable(df, format = 'latex', booktabs = T, align = 'r') %>%
  kable_styling(full_width = F, font_size = 8) %>%
  row_spec(row = 9, bold = TRUE) %>%
  add_header_above(c(" ", 'Month (persons)' = 1, "TTY (persons)" = 1, "TTY (% chg.)" = 1))

  ```

这会很难,因为 LaTeX 不喜欢 table 单元格内的换行符 - 参见例如https://tex.stackexchange.com/questions/2441/how-to-add-a-forced-line-break-inside-a-table-cell 来感受一下这有多难。几乎可以肯定,为“(人)”等插入一个单独的行会更好。

现在,您必须自己编写一些原始的 Latex 代码。

按照https://tex.stackexchange.com/questions/2441/how-to-add-a-forced-line-break-inside-a-table-cell中的答案建议,您可以尝试使用makecell包。为此,您可以使用 kableExtra::usepackage_latex() 加载 latex 包,然后通过在 add_header_above 中设置 escape = F 来破解它。

usepackage_latex("makecell")
kable(df, format = 'latex', booktabs = T, align = 'r') %>%
  kable_styling(full_width = F, font_size = 8) %>%
  row_spec(row = 9, bold = TRUE) %>%
  add_header_above(c(" ",
                     '\\thead{Month\\\\(persons)}' = 1,
                     "\\thead{TTY\\\\(persons)}" = 1,
                     "\\thead{TTY\\\\(\\% chg.)}" = 1),
                   escape = F)

更新

别介意上面的乳胶混乱,我让它在 kableExtra 的开发版本中工作。现在你只需

library(kableExtra)

mtcars[1:5, 1:5] %>%
  kable("latex", booktabs = T) %>%
  add_header_above(c(" ", "aa\na" = 2, "bbb" = 3))