20

I am using bookdown to create pdf reports, but my tables are all floating down to the bottom of the page, regardless of how much space there is. See this example:

---
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")
```

The resulting pdf looks like this:

pdf-output

Why does the table go to the bottom of the page? And is there a way to prevent this behavior?

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
Jake Thompson
  • 2,591
  • 1
  • 16
  • 32
  • For why, please read https://bookdown.org/yihui/bookdown/figures.html. For how to prevent it, I'll leave it to other LaTeX experts to answer you. – Yihui Xie Jul 01 '17 at 02:54

2 Answers2

36

You can solve this problem with kableExtra by

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")

It basically insert a [!h] to the LaTeX table environment which will prevent the floating behavior and pin the table at current location.

Hao
  • 7,476
  • 1
  • 38
  • 59
  • Worked perfectly for me. Thanks Hao, I keep finding your lovely help scattered throughout the internet.. – Nova Sep 27 '18 at 19:46
  • @Nova haha, glad it helps! :D – Hao Sep 27 '18 at 20:44
  • 2
    If, like me, you encounter the same problem simultanously for figures, here is a solution: https://stackoverflow.com/questions/16626462/figure-position-in-markdown-when-converting-to-pdf-with-knitr-and-pandoc/33801326#33801326 – puslet88 May 27 '19 at 16:37
  • 1
    I just wanted to add a comment that you must call the dataframe in the chunk first as shown in the answer. If you use the code below it will not work `knitr::kable(myDataFrame, caption = "This is a test") %>% kableExtra::kable_styling(latex_options = "hold_position")` – Patrick Apr 26 '20 at 21:15
10

I had to use

kable_styling(latex_options = "HOLD_position")

Note the uppercase HOLD_position, different from hold_position. See also here.

To be able to use that, I also had to add to the top section of the doc (from How to build a latex kable through bookdown::render_book?):

output:
  pdf_document:
    extra_dependencies: ["float"]
dfrankow
  • 20,191
  • 41
  • 152
  • 214