简体   繁体   English

在 knitr 旋转脚本的循环/函数中添加标题

[英]Adding titles inside loop/function of knitr spin script

I have an r script that I'd like to use to generate an HTML report using knitr spin.我有一个 r 脚本,我想用它来使用 knitr spin 生成 HTML 报告。

Much of the code that runs is within loops/functions.运行的大部分代码都在循环/函数中。 How can I generate titles within the document for content that is created within those functions/loops?如何在文档中为在这些函数/循环中创建的内容生成标题?

I have tried a couple different ways and nothing has worked so far.我尝试了几种不同的方法,但到目前为止没有任何效果。 A reproducible example of something that won't have any titles when spun is given below:下面给出了旋转时没有任何标题的可重复示例:

#' ---
#' title: "My Doc"
#' author: "ME"
#' date: "January 28, 2017"
#' ---
library(ggplot2)
myFun = function(){
  for(i in seq(from=1,to=3, by=1)){
    #' ## This title won't show up
    cat("\n## Nor will this one\n")
    plot = ggplot(aes(x=mpg,y=cyl),data=mtcars) + geom_point()
    print(plot)
  }
}

The key to this problem is putting the call to myFun as a code chunk with results = "asis" as an option.这个问题的关键是把对myFun的调用作为一个代码块,并将results = "asis"作为一个选项。 I made a couple small edits to myFun to make it easier to see the results.我对myFun进行了一些小的编辑,以便更容易地查看结果。 See below:见下文:

#' ---
#' title: "My Doc"
#' author: "ME"
#' date: "January 28, 2017"
#' ---
#+ label = "setup", include = FALSE
library(ggplot2)
myFun = function(){
  for(i in seq(from=1,to=3, by=1)){
    cat("\n\n\n## This is title", i, "\n\n\n")
    plot = ggplot(aes(x=mpg,y=cyl),data=mtcars) +
      geom_point(color = i)
    print(plot)
  }
}

#' Generate three plots:

#+ echo = FALSE, results = "asis"
myFun()


# /* build this file via
knitr::spin("answer.R", knit = FALSE)
rmarkdown::render("answer.Rmd")
# */

The resulting .html file looks something like this:生成的 .html 文件如下所示:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM