我正在 rMarkdown 中编写文档,需要在生成 PDF 之前格式化表格。问题是我无法在kable
使用命令添加的标题中插入新行add_headers_above
。
目前,文本“月份(人)”(这是使用该命令添加的第一个标题)显示为一行。我想打破这一点,以便在“月”和“(人)”之间插入新行。
动机只是为了节省水平页面空间,以便我可以在一张 A4 纸上按大小放置两个表格。
我尝试\n
在add_headers_above
命令中包含:
[...] %>%
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))
```
Run Code Online (Sandbox Code Playgroud)
现在,您必须自己编写一些原始乳胶代码。
正如https://tex.stackexchange.com/questions/2441/how-to-add-a-forced-line-break-inside-a-table-cell中的答案所建议的,您可以尝试使用该makecell
包。为此,您可以使用加载乳胶包kableExtra::usepackage_latex()
,然后通过设置来破解escape = F
它add_header_above
。
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)
Run Code Online (Sandbox Code Playgroud)
更新
别介意上面的乳胶混乱,我让它在kableExtra
. 现在你只需要做
library(kableExtra)
mtcars[1:5, 1:5] %>%
kable("latex", booktabs = T) %>%
add_header_above(c(" ", "aa\na" = 2, "bbb" = 3))
Run Code Online (Sandbox Code Playgroud)