【问题标题】:How to run a rmarkdown to create multiple html with different parameters?如何运行 rmarkdown 以创建具有不同参数的多个 html?
【发布时间】:2021-01-25 11:53:20
【问题描述】:

我在 R 中有一个代码,在 rMarkdown 中完成,它需要运行多次,但参数值不同。

我该如何解决?我已经举了一个简化问题的例子。

假设我需要在一个循环中打印不同的值,为了简单起见,我使用了简单的循环。

对于这两个循环的每个组合,我想制作一个 html 文件,例如表示 200 *400 个不同的 html 报告文件。

---
title: "file1"
author: "user"
date: "25 1 2021"
output: html_document
---

# The first loop should be done, from 1:100, 101:200 ... to ...   20001:20100
  ```{r}
  i=getfirst()
  j=getsecond()
  ```

```{r}

for (i in i:j) print(i)
```

# The second loop should be done, from 1:50, 51:100  ... to ...  20001:20050
```{r}
for (i in i-50:j-50) print(i)
```

假设每次我们可能有不同的 i 和 j 应该传递到 markdown 文件中。

【问题讨论】:

    标签: r r-markdown


    【解决方案1】:

    我只需创建一个包装脚本(即单独的例如.R)文件,您可以在其中指定:

    R 文件

    for (i in 1:10){
      j = i+50
      if(!dir.exists(paste0("directory_",i))){dir.create(paste0("directory_",i))}
      knitr::knit(input = "markdown.Rmd",output = paste0("directory_",i,"/output",i,"_",j,".html"))
    }
    

    然后您的 Rmd 文件(在此示例中保存为 markdown.Rmd)如下所示:

    RMarkdown 文件

    ---
    title: "file1"
    author: "user"
    date: "25 1 2021"
    output: html_document
    ---
    
    # The first loop should be done, from 1:100, 101:200 ... to ... 20001:20100
    
    ```{r}
    for (i in i:j) print(i)
    ```
    
    # The second loop should be done, from 1:50, 51:100 ... to ... 20001:20050
    
    ```{r}
    for (i in i-50:j-50) print(i)
    ```
    

    【讨论】:

    • 谢谢,如何将参数传递给markdown文件?
    • 当您执行knit 命令时,它也会使用您的工作目录——因此run_chunk 变量会自动传递给降价文件。所以这应该可以工作并导致两个不同的 html 文件具有不同的输出。
    • 请看一下我的新代码,假设每次我可能有不同的参数,我需要存储例如100 个不同的 html 文件。
    • 好的,现在我已经修改了 R 文件,只在一些 i 值上创建了一个简单的循环。这里的j 只是一个标准的i + 50,但如果你愿意,你可以在它周围包裹另一个j 循环。现在可以了吗?
    • 我建议将 csv 和 html 的路径保存为变量,然后在保存时使用该变量。如果 csv 文件已经在该文件夹中,那么您可以使用 list.files 动态查找路径 - 如果要保存它,则可以复制 paste0 命令以获得 write_csv 命令或其他内容。除了上述之外,恐怕我有点难以理解您的确切工作流程......
    【解决方案2】:

    a dedicated chapter in the official documentation,“使用参数编织”,概述了如何在您的用例中进行操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2021-11-06
      • 2014-09-13
      相关资源
      最近更新 更多