简体   繁体   中英

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.

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. I made a couple small edits to myFun to make it easier to see the results. 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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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