【问题标题】:Adding titles inside loop/function of knitr spin script在 knitr spin 脚本的循环/函数中添加标题
【发布时间】:2017-01-28 17:40:59
【问题描述】:

我有一个 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)
  }
}

【问题讨论】:

    标签: r knitr r-markdown knitr-spin


    【解决方案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 文件如下所示:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 2019-09-23
      • 2013-06-17
      相关资源
      最近更新 更多