r markdown - 在编织成 PDF 时如何将表格向左对齐而不是居中?

问题描述 投票:0回答:2

会认为这很容易解决吗?

在 R markdown 中,当编织成 PDF 时,如何让所有表格左对齐而不是居中?

r latex r-markdown
2个回答
3
投票

在写入 PDF 的 R Markdown 文档中左对齐表格的一种方法是在

format = latex
函数中使用
booktabs = TRUE
kable()
的组合。

---
title: "Left Align Tables"
date: "2023-04-14"
output: 
     pdf_document:
         extra_dependencies: ["booktabs"]

---

```{r aTable}
library(knitr)
kable(head(mtcars[,1:5]),format = "latex",booktabs = TRUE)
```

这导致以下 PDF 内容:

Try again without the options...

```{r aTable2}
library(knitr)
kable(head(mtcars[,1:5]),)
```

...产生以下内容:

请注意,为了完整性,我在 R Markdown Cookbook 的第 10.1.10 节中包含了“booktabs”的 YAML pdf 文档依赖项,即使代码按预期工作而没有在 YAML 中指定依赖项。

当表格包含标题时会发生什么?

这里是基本答案开始变得复杂的地方。为什么?包含标题的表格在 LaTeX 所称的表格环境中进行管理。不幸的是,LaTeX 表格环境中表格的默认对齐方式是居中的。

Things get more complicated when a table has a caption. 

```{r aTable3}
kable(head(mtcars[,1:5]),format = "latex",booktabs = TRUE,
      caption = "1973 - 1974 Cars from Motor Trend")
```

要将表格与标题左对齐,我们需要将

centering = TRUE
选项添加到
kable()
。另请注意,LaTeX 现在将表格定位在页面底部,但管理 LaTeX 文档上的浮动超出了这个问题的范围。

```{r aTable4}
kable(head(mtcars[,1:5]),format = "latex",booktabs = TRUE,centering = FALSE,
      caption = "1973 - 1974 Cars from Motor Trend - Noncentered")
```

啊!现在我们的表格左对齐,但标题居中。为了修复标题,我们需要在 YAML 中添加另一个 LaTeX 包,即

caption
包,添加
header-includes
内容以使用标题包,然后使用
kableExtra()
重新格式化标题。

完整的解决方案如下所示:

---
title: "Left Align Tables"
date: "2023-04-14"
output: 
  pdf_document:
    extra_dependencies: ["booktabs","caption"]
header-includes:
   - \usepackage[singlelinecheck=false]{caption}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE) 
library(knitr)
```


Hmm... now the table is left aligned, but the caption is not. To left align the caption, we need to add some LaTeX header content in the YAML, and add the LaTeX caption package. Then we use kableExtra to format the caption. 

```{r aTable5}
library(kableExtra)
kable(head(mtcars[,1:5]),format = "latex",booktabs = TRUE,centering = FALSE,
      caption = "1973 - 1974 Cars from Motor Trend - Noncentered") %>%
     kable_styling(position = "left")
```

瞧!我们现在有一个左对齐的表格和一个左对齐的标题。管理浮动(表格在页面上的位置)的代码留给读者作为一个小练习。


0
投票

我的解决方案是 kable.extra 包:

df_df %>% 
   kbl(caption = " caption") %>% 
   kable_styling(bootstrap_options = c("striped", "hover"), position = "left", full_width = FALSE, fixed_thead = T)
© www.soinside.com 2019 - 2024. All rights reserved.