【问题标题】:Run R markdown (.Rmd) from inside other R script to produce HTML从其他 R 脚本中运行 R markdown (.Rmd) 以生成 HTML
【发布时间】:2021-01-27 15:08:47
【问题描述】:

例如,如果您创建一个新的 R markdown 文件并将其保存为“测试”。然后可以从普通的 R 脚本中运行或部署这个 test.Rmd 文件。目的是以 HTML 格式生成输出,而无需打开 .Rmd 文件。

我希望一次创建一个主文件来为许多降价文件执行此操作;这将节省大量时间,因为您不必打开许多降价文件并等待每个文件完成。

【问题讨论】:

    标签: r r-markdown markdown


    【解决方案1】:

    您正在寻找rmarkdown::render()

    “test.Rmd”的内容

    ---
    title: "Untitled"
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    ## R Markdown
    
    This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
    
    When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
    
    ```{r cars}
    summary(cars)
    ```
    

    script.R 的内容

    # provided test.Rmd is in the working directory
    rmarkdown::render("test.Rmd")
    

    一种渲染多个 Rmd 的方法

    cwd_rmd_files <- list.files(pattern = ".Rmd$")
    lapply(cwd_rmd_files, rmarkdown::render)
    

    【讨论】:

      【解决方案2】:

      感谢the-mad-statter,您的回答很有帮助。我面临的问题,要求我动态准备降价。通过调整您的代码,这很容易实现:

      “test_dyn.rmd”的内容

      ---
      title: "Untitled"
      output: html_document
      ---
      
      The chunk below adds formatted text, based on your inputs.
      ```{r text, echo=FALSE, results="asis"}
      cat(text)
      ```
      
      The chunk below uses your input in as code.
      ```{r results}
      y
      ```
      

      “script_dyn.r”的内容

      in_text <- c("**Test 1**", "*Test 2*")
      in_y <- 1:2
      
      lapply(1:2, function(x) {
        text <- in_text[[x]]
        y <- in_y[[x]]
        rmarkdown::render(input = "test_dyn.rmd", output_file = paste0("test", x))
      })
      

      这样,您可以在代码中创建具有不同文本和不同变量值的文件。

      【讨论】:

      • 有兴趣知道渲染环境可以找到你的y值。我认为渲染发生在一个新的环境中,但显然这只适用于针织。如果您想将数据传递到 RMarkdown 文档,您可以考虑parameterized reporting
      • 谢谢,这似乎很方便!
      猜你喜欢
      • 2013-01-25
      • 2019-12-07
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      相关资源
      最近更新 更多