在 R markdown 中循环

Loop in R markdown

我有一个这样的 R markdown 文档:

The following graph shows a histogram of variable x:

```{r}
hist(x)
```

我想引入一个循环,这样我就可以对多个变量做同样的事情。假设是这样的:

for i in length(somelist) {
  output paste("The following graph shows a histogram of somelist[[" , i, "]]")
  ```{r}
  hist(somelist[[i]])
  ```

这可能吗?

PS:更大的计划是创建一个程序来遍历数据框并自动为每一列(例如直方图、表格、箱形图等)生成适当的摘要。然后该程序可用于自动生成一个降价文档,其中包含您在查看第一个数据时所做的探索性分析。

这就是你想要的吗?

---
title: "Untitled"
author: "Author"
output: html_document
---


```{r, results='asis'}
for (i in 1:2){
   cat('\n')  
   cat("#This is a heading for ", i, "\n") 
   hist(cars[,i])
   cat('\n') 
}
```

这个答案或多或少是从 here 那里偷来的。

如前所述,任何循环都需要在代码块中。给直方图一个标题可能比为每个直方图添加一行文本作为 header 更容易。

```{r}
    for i in length(somelist) {
        title <- paste("The following graph shows a histogram of", somelist[[ i ]])
        hist(somelist[[i]], main=title)
    }
```

但是,如果您想创建多个报告,请查看 this thread.

里面还有一个link到this example.
似乎在脚本中进行渲染调用时,环境变量可以传递给 Rmd 文件。

因此,另一种方法可能是使用您的 R 脚本:

for i in length(somelist) {
    rmarkdown::render('./hist_.Rmd',  # file 2
               output_file =  paste("hist", i, ".html", sep=''), 
               output_dir = './outputs/')
}

然后你的 Rmd 块看起来像:

```{r}
    hist(i)
```

免责声明:我还没有测试过这个。