[英]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}
表格沒有居中。 如果我使用kable_stylying
中的kableExtra
,其選項position
的值默認為center
,我會使用 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}
但是,我只想制作一個小的、幾乎是內聯的表格。 我不想讓它漂浮。 我不想要字幕等。我想要的是生成 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}
這可能使用knitr
和kableExtra
嗎?
我可以使用解決方法。 例如,使用塊選項results='asis'
,並在塊中執行
cat("\\begin{center}",sep='\n')
knitr::kable(head(cars),
format = 'latex')
cat("\\end{center}",sep='\n')
但是,我想知道如果沒有解決方法,這是否可行,以及我是否遺漏了什么。
以下是生成上述三種表格的 RMarkdown 文檔的最小工作示例。 依賴項是magrittr
、 knitr
和kableExtra
。
---
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')
```
您只需要將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()
不夠聰明,無法反轉添加\end{}
標記時,需要使用回文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.