admin管理员组

文章数量:1310221

I want to place a table using table1() function with knitr()and because the table has long rows, I am using longtable=T within kable(). Because I'm using longtable=T, the table starts right after the code when I knit it into PDF. But I want to place it at the top of the next page. How can I do that? My code is below.

t1 <- table1(~ . - Subject | sex, data = dataset)
df_t1 <- as.data.frame(t1)

kable(df_t1, digits=2, format="latex", longtable=T, linesep="", booktab=T, caption = "Baseline Characteristics") %>%
  kable_styling(latex_options = c("repeat_header","HOLD_positions"))

I want to place a table using table1() function with knitr()and because the table has long rows, I am using longtable=T within kable(). Because I'm using longtable=T, the table starts right after the code when I knit it into PDF. But I want to place it at the top of the next page. How can I do that? My code is below.

t1 <- table1(~ . - Subject | sex, data = dataset)
df_t1 <- as.data.frame(t1)

kable(df_t1, digits=2, format="latex", longtable=T, linesep="", booktab=T, caption = "Baseline Characteristics") %>%
  kable_styling(latex_options = c("repeat_header","HOLD_positions"))
Share Improve this question edited Feb 2 at 21:15 Jan 9,4686 gold badges20 silver badges33 bronze badges asked Feb 2 at 15:53 Stats_BeginnerStats_Beginner 111 bronze badge 1
  • Welcome to Stack Overflow! I added an answer with what I think is your expected result. "But I want to place it at the top of the next page." -> So you want to print the code, jump to the next page and then have the table on top? – Tim G Commented Feb 2 at 22:06
Add a comment  | 

1 Answer 1

Reset to default 0

You mean like this? You can add a cat("\\pagebreak") after the table definition to jump to the next page. Then run another chunk to print this table to the next page.

---
title: "Long Table to next page"
output:
  pdf_document: default
  html_document:
    df_print: paged
date: "2025-02-02"
---

```{r setup, include=FALSE}
library(dplyr)
library(kableExtra)
library(table1)
```

```{r, echo=T, results='asis'}

df_t1 <- data.frame(
  Subject = 1:1000, sex = factor(sample(c("Male", "Female"), 1000, replace = TRUE))
)

# Create the formatted table
table <- kable(
  df_t1,
  digits = 2,
  format = "latex",
  longtable = TRUE,
  linesep = "",
  booktabs = TRUE,
  caption = "Baseline Characteristics"
) %>%
  kable_styling(latex_options = c("repeat_header", "HOLD_positions")) 

cat("\\pagebreak") # added a page break for the table to start on top of the next page :3

```

```{r, echo=F}
table
```

本文标签: rPlace a table of knitr at the top of the next page of pdf while using longtableTStack Overflow