使用 knitr kable 制作居中的 LaTeX 表格 table

Make centered LaTeX tabular table using knitr kable

带有 latex 格式选项的 knitr::kable 生成表格环境。 例如,

# produces a tabular environment
knitr::kable(head(cars),
             format = 'latex')

产生

\begin{tabular}{r|r}
\hline
speed & dist\
\hline
4 & 2\
\hline
4 & 10\
\hline
7 & 4\
\hline
7 & 22\
\hline
8 & 16\
\hline
9 & 10\
\hline
\end{tabular}

table没有居中。如果我使用 kableExtra 中的 kable_stylying,其选项 position 的值默认为 center,我会得到居中浮动 table,使用 LaTeX table 环境。 例如,这个

# produces a tabular environment inside a table
knitr::kable(head(cars),
             format = 'latex') %>% 
  kableExtra::kable_styling()

产生

\begin{table}
\centering
\begin{tabular}{r|r}
\hline
speed & dist\
\hline
4 & 2\
\hline
4 & 10\
\hline
7 & 4\
\hline
7 & 22\
\hline
8 & 16\
\hline
9 & 10\
\hline
\end{tabular}
\end{table}

不过,我只想做一个小的,几乎是内联的,table。我不想让它漂浮。我不想要字幕等。我想要的是生成这样的 LaTeX 代码:

\begin{center}
\begin{tabular}{r|r}
\hline
speed & dist\
\hline
4 & 2\
\hline
4 & 10\
\hline
7 & 4\
\hline
7 & 22\
\hline
8 & 16\
\hline
9 & 10\
\hline
\end{tabular}
\end{center}

可以使用 knitrkableExtra 吗?

我可以使用解决方法。例如,使用块选项 results='asis',并在块中执行

cat("\begin{center}",sep='\n')

knitr::kable(head(cars),
             format = 'latex')

cat("\end{center}",sep='\n')

但是,我想知道如果没有解决方法是否可行,以及我是否遗漏了什么。

最小的可重现示例

以下是生成上述三种 table 的 RMarkdown 文档的最小工作示例。依赖项是 magrittrknitrkableExtra

---
output: pdf_document
---

```{r}
library(magrittr)
```

This produces a `tabular`, non-floating, table. But it is not centered.
```{r}
knitr::kable(head(cars), format = 'latex')
```

The following code produces a centered table, but using a `table` environment, so it floats (in this case to the top of the page), which is probably what we usually want, but we don't *always* want.
```{r}
knitr::kable(head(PlantGrowth), format = 'latex') %>% 
  kableExtra::kable_styling()
```

We can produce a centered `tabular` environment using chunk option `results='asis'` etc.
```{r, echo=FALSE, results='asis'}
cat("\begin{center}",sep='\n')

knitr::kable(head(ToothGrowth),
             format = 'latex')

cat("\end{center}",sep='\n')
```

渲染此内容(作为 pdf_document)创建包含以下内容的单页 pdf:

如果您使用 \centering,您将避免来自 center 环境的额外垂直间距:

---
output: 
  pdf_document: 
    keep_tex: true
header-includes:
  - \AddToHook{env/tabular/before}{\begingroup\centering}
  - \AddToHook{env/tabular/after}{\par\endgroup}
---

```{r}
library(magrittr)
```

text



```{r}
knitr::kable(head(cars), format = 'latex')
```

text

您只需将 table.envir 参数设置为 "center" 即可将 \tabular 包裹在 \begin{center} ... \end{center} 中。在您的 MRE 中:

---
output: pdf_document
---

```{r}
library(magrittr)
```

This produces a `tabular`, non-floating, table, and it *is* centered:
```{r}
knitr::kable(head(cars), format = 'latex', table.envir = "center")
```

如果你想将它包裹两次(例如居中和粗体),你可以使用类似 table.envir = c("bf", "center", "bf") 的东西:因为 kable() 不够聪明,无法在添加 [= 时颠倒顺序17=]标记,需要使用回文。