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

2

21

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?

Ostrowski answered 30/6, 2017 at 15:27 Comment(1)
For why, please read bookdown.org/yihui/bookdown/figures.html. For how to prevent it, I'll leave it to other LaTeX experts to answer you.Loftus
P
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.

Packard answered 3/7, 2017 at 14:44 Comment(4)
Worked perfectly for me. Thanks Hao, I keep finding your lovely help scattered throughout the internet..Sweetandsour
@Sweetandsour haha, glad it helps! :DPackard
If, like me, you encounter the same problem simultanously for figures, here is a solution: #16626962Citizenship
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")Diplex
G
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"]
Geisler answered 29/5, 2020 at 21:53 Comment(1)
I'll reiterate that HOLD_position worked whereas hold_position did not for me.Oval

© 2022 - 2024 — McMap. All rights reserved.