3

问题描述:

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

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

动机只是为了节省水平页面空间,以便我可以在一张 A4 纸上按大小放置两个表格。

我的修复尝试

我试图\nadd_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))

  ```
4

2 回答 2

2

现在,您将不得不自己编写一些原始的乳胶代码。

正如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)

更新

别介意上面的乳胶混乱,我让它在kableExtra. 现在你就做

library(kableExtra)

mtcars[1:5, 1:5] %>%
  kable("latex", booktabs = T) %>%
  add_header_above(c(" ", "aa\na" = 2, "bbb" = 3))
于 2018-04-02T17:53:32.877 回答
0

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

于 2018-04-02T15:35:04.083 回答