Rmarkdown 设置 kable 的位置

Rmarkdown setting the position of kable

我有以下问题,一旦将 Rstudio 中的 Rmarkdown 编织成 PDF,我的表格就不会出现在它们在 Rmarkdown 文件中的位置,而是出现在页面顶部。我尝试添加:

header-includes:
  - \usepackage{float}

```{r setup, include=FALSE}
knitr::opts_chunk$set(... fig.pos = "H")
```

但是没有用。 Linux 上的 R 和 Rstudio 运行,LaTeX 引擎是 "pdflatex"

完全可重现的示例:

---
title: "Untitled"
output: pdf_document
header-includes:
  - \usepackage{float}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message=FALSE, warning = FALSE, fig.align = "center", dev = "cairo_pdf", fig.pos = "H")
```

```{r}
library(kableExtra)
library(tidyverse)
```
## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

\newpage

## Including Plots

You can also embed plots, for example:

```{r pressure, echo=FALSE}
plot(pressure)
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

```{r}    
kable(cars %>% filter(cars$speed>=23), caption = "Speed vs distance")
```

要修复 Latex 文档中的 table 位置,您不需要包含 header 选项,也不需要设置 opts_chunk 配置。为此,您应该通过在 kable [1].

中添加 kable_styling() 函数来将 latex_options 指定为 hold_position

所以最后一个块将是:

```{r}    
kable(cars %>% filter(cars$speed>=23), caption = "Speed vs distance") %>%
  kable_styling(latex_options = "hold_position")
```

您可以将 claudius answer 中的 "hold_position" 替换为 "HOLD_position":

```{r}    
kable(cars %>% filter(cars$speed>=23), caption = "Speed vs distance") %>%
  kable_styling(latex_options = "HOLD_position")
```

如 kableExtra 包中所述:

if you find hold_position is not powerful enough to literally PIN your table in the exact position, you may want to use HOLD_position, which is a more powerful version of this feature. For those who are familiar with TeX, hold_position uses[!h] and HOLD_position uses [H] and the float package.

参考:https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

您可能还想通过将 fig.pos='H' 添加到图形块 header 来控制图形位置 header。

为 R Markdown Latex 或 Beamer 输出设置 kable 对象位置的另一种方法是将 table 包含在“文本块”环境中,如发布的那样 here

YAML 将包括:

header-includes:
- \usepackage[absolute,overlay]{textpos}
  \setlength{\TPHorizModule}{1mm}
  \setlength{\TPVertModule}{1mm}

R 代码块(前后为“文本块”的乳胶代码)如下所示:

\begin{textblock}{}(21.5, 51.5)
\footnotesize
```{r}    
kable(cars %>% filter(cars$speed>=23), caption = "Speed vs distance") 
```
\end{textblock} 

此方法允许在页面或 beamer 幻灯片上更精细地调整 kable 输出的位置。