将新行插入到kable标题中

时间:2018-03-29 01:47:02

标签: r knitr kable

问题描述:

我在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))

  ```

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:0)

这很难,因为LaTeX不喜欢表格单元格中的换行符 - 例如https://tex.stackexchange.com/questions/2441/how-to-add-a-forced-line-break-inside-a-table-cell了解这有多难。你几乎肯定会更好地为&#34;(人)和#34;插入一个单独的行。等等。