在knitr旋转脚本

时间:2017-01-28 17:40:59

标签: r knitr r-markdown knitr-spin

我有一个r脚本,我想使用knitr spin来生成HTML报告。

大部分运行的代码都在循环/函数中。如何在文档中为在这些函数/循环中创建的内容生成标题?

我尝试了几种不同的方法,到目前为止还没有任何工作。下面给出了一个可复制的例子:在旋转时不会有任何标题:

#' ---
#' 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)
  }
}

1 个答案:

答案 0 :(得分:1)

此问题的关键是将调用作为代码块放置到myFun上,并选择results = "asis"。我对myFun进行了一些小修改,以使查看结果更容易。见下文:

#' ---
#' 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")
# */

生成的.html文件如下所示:

enter image description here