在 rmarkdown 的代码块中插入分页符(转换为 pdf)

Inserting a page break within a code chunk in rmarkdown (converting to pdf)

我正在使用 rmarkdown、pandoc 和 knitr 创建一个包含 r 代码块的 pdf。在一个代码块中,我有一个 for 循环,它打印了一些图表和一些统计输出。

我想在循环中插入分页符(以显示在 pdf 输出中)。此分页符将在每张图打印后发生,以确保每张图都打印在一页上,而统计输出在下一页上。

我一直找不到在我的 r 代码块中包含分页符的方法。我已经尝试了 cat("\newpage")cat("\pagebreak") 希望它能被 pandoc 识别但无济于事(它只是逐字打印在最终的 pdf 中)。

感谢建议。这是我目前的代码:

```{r, echo =FALSE, message=FALSE, warning=FALSE, comment=NA, results='asis'}
library("markdown") 
library("rmarkdown") 
library("knitr")
library("ggplot2")
for (v in Values){

# read in file
testR <- read.csv(file.path, header=T)

print(ggplot(testR, aes(x=Time, y=Value, color=Batch)) + geom_point(size = 3) +
xlab ("Timepoint") +
ylab (v) +
scale_x_continuous(breaks=seq(0, 60, by=6)) +
ggtitle(paste("Scatterplot of Batches for ", v, sep="")))
ggsave(paste(timestamp, "__", 
       "Scatterplot of Batches for ", v, ".jpeg", sep = "")) 

cat("\pagebreak")
writeLines(v)
writeLines("\n")
writeLines("\n Test for homogenity of slopes \n")
av1 <- aov(Value~Time*Batch, data=testR)
print(summary(av1))
}
```

请参阅下面的简化且可重现的示例。答案和一些一般性评论:

  • 要在降价文档中动态创建新页面或部分,请在块选项中使用 results='asis'
  • 您必须在 \pagebreak 之后添加一个换行符 (\n),否则 "ValueForV" 将直接粘贴在 "\linebreak" 之后,这会导致 Undefined control sequence 错误。
  • 确保 \newpage\pagebreak 在单独的一行中,之前使用换行符 \n
  • 转义 \newpage\pagebreak(即 \newpage\pagebreak)。

    ---
    title: "test"
    output: pdf_document
    ---
    
    ```{r, echo=FALSE, results='asis'}
    for (i in 1:3) {
      print(ggplot2::qplot(i, i+1))
      cat("\n\n\pagebreak\n")
      writeLines("ValueForV")
    }
    ```
    

如何在转换为 PDF 后仍然存在的 Rstudio .Rmd 代码块中插入分页符:

如果 \newpage\pagebreak 乳胶宏不适合您,这里有一个使用 HTML.

的解决方法

例如:

---
title: "The Rent"
output:
  pdf_document: default
  html_document: default
---

# This is pre-chunk text.

```{r, echo=FALSE, results='asis'}
print("Now we're <b>inside the chunk</b>, using the power of HTML.<br><br><br>!")

print("As you can see from the following diagram")
cat("\n")
print("The rent...<br>")
print(plot(1:10))

print("<P style='page-break-before: always'>")    #forced new-page happens here.

print("<h1>Is too damned high!!</h1>")
writeLines("\n")
print("Finished")
cat("\n\n")
```
This is post chunk text.

为我制作这个:

关键成分是块头中的 print("<P style='page-break-before: always'>"){r, echo=FALSE, results='asis'}