如何阻止 bookdown 表格浮动到 pdf 页面底部?

How to stop bookdown tables from floating to bottom of the page in pdf?

我正在使用 bookdown 创建 pdf 报告,但我的 table 都浮动到页面底部,无论 space 有多少。看这个例子:

---
title: "test_doc"
author: "Jake Thompson"
date: "6/30/2017"
output:
  bookdown::pdf_document2:
    toc: false
---

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

# Test heading

Let make a data frame and print it in Table \@ref(tab:test-table)

```{r test-table}
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
  knitr::kable(caption = "This is a test")
```

生成的 pdf 如下所示:

为什么 table 会转到页面底部?有没有办法防止这种行为?

您可以通过

kableExtra 解决这个问题
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
  knitr::kable(caption = "This is a test") %>%
  kableExtra::kable_styling(latex_options = "hold_position")

它基本上是在 LaTeX table 环境中插入一个 [!h],这将防止浮动行为并将 table 固定在当前位置。

我不得不使用

kable_styling(latex_options = "HOLD_position")

注意大写 HOLD_position,不同于 hold_position。另见 here.

为了能够使用它,我还必须添加到文档的顶部部分(来自 How to build a latex kable through bookdown::render_book?):

output:
  pdf_document:
    extra_dependencies: ["float"]