如何在编辑PDF文件时使用R中的Kable和kblextra将表格标题居中?

ljsrvy3e  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(268)

当使用kbl()函数在R中创建表格时,如果表格的标题太长,则会出现此问题。如果标题太长,文本开始换行,但随后变为左对齐。
有时候标题很短,可以通过在样式选项中添加landscape参数来解决,但我希望有一个更灵活的解决方案。kbl的样式选项提供了很多工具来操作表格单元格,但我在处理表格标题时遇到了困难。下面是导致我遇到的问题的示例代码。

kbl(mtcars, caption = "This is a really long title that will go past the borders when knitting to PDF in portrait mode. I'd love to figure out how to keep it centered even if the text is really long.", 
    booktabs = TRUE, linesep = "", align = "c") %>% 
    kable_styling(latex_options = c("striped", "hold_position"))

添加“hold_position”参数可以使表格保持居中,但标题的行为不一样。此外,如果将标题添加到HTML中,也可以,但我希望在将标题添加到PDF中时,也能使用此解决方案。
另外,使用\n来做换行符似乎不像它在其他包(如ggplot())中那样工作。

zzlelutf

zzlelutf1#

您可能需要使用LaTeX的caption包和justification=centering选项(即YAML部分的header-includes字段中的\usepackage[justification=centering]{caption})。

---
header-includes:
  - \usepackage[justification=centering]{caption}
output:
  pdf_document: default
---

```{r setup, echo=FALSE, warning=FALSE, message=FALSE}
library(tidyverse)
library(kableExtra)
kbl(mtcars,
  caption = "This is a really long title that will go past the borders when knitting to PDF in portrait mode. I'd love to figure out how to keep it centered even if the text is really long.",
  booktabs = TRUE, linesep = "", align = "c"
)  %>%
  kable_styling(latex_options = c("striped", "hold_position"))

![](https://i.stack.imgur.com/jNzF8.png)
a1o7rhls

a1o7rhls2#

如果没有@卡洛斯Luis里维拉展示的额外LaTeX包,我无法找到任何可能的方法通过使用kable来居中标题。因此,如果您不需要额外的LaTeX包,我建议使用flextable包而不是kablekableExtra。在下面的示例中,我使用pdf-latex

```{r}
library(flextable)
library(tidyverse)

set_flextable_defaults(fonts_ignore = TRUE)
mtcars |> rownames_to_column(var = "carmodel") |> 
    flextable() |> theme_zebra() |>
    align(j = ~.-carmodel, align = "center", part = "all") |>
    autofit(add_w = 0) |>
    set_caption(caption = "This is a really long title that will go past the borders 
        when knitting to PDF in portrait mode. I'd love to figure out how to keep it 
        centered even if the text is really long.")

生成的PDF表格:

相关问题