51

I have an R markdown document like this:

The following graph shows a histogram of variable x:

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

I want to introduce a loop, so I can do the same thing for multiple variables. Something hypothetically like this:

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

Is that even possible?

PS: The greater plan is to create a program that would go over a data frame and automatically generates appropriate summaries for each column (e.g. histogram, tables, box plots, etc). The program then can be used to automatically generate a markdown document that contains the exploratory analysis you would do when seeing a data for the first data.

Merik
  • 2,767
  • 6
  • 25
  • 41
  • You could generate multiple plots inside one chunk. Could you explain what the rationale for your solution is as opposed to having a loop inside one chunk that produces multiple plots? – akhmed Oct 21 '15 at 21:58
  • 1
    I came here for the same question. My rationale is to produce several versions of an RMarkdown report. The reports will be the answer for an exercise given to my students, but since every one work with different data, I want to personalise the reports for every student. The accepted answer can be useful, but it would be better to actually have markdown inside the loop, to use markdown features like captions, formulas, formatting and so. – Pere Jan 22 '17 at 11:00

2 Answers2

51

Could that be what you want?

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

This answer was more or less stolen from here.

JD Long
  • 59,675
  • 58
  • 202
  • 294
Alex
  • 4,925
  • 2
  • 32
  • 48
  • It wasn't clear (to me at least) from the other answer that this could be done in markdown without having to first stitch together an R file. Great to see I can stick to just RMarkdown now. – Henry E May 23 '16 at 15:06
  • For me, the two headings appear before both graphs. – Nova Jun 16 '17 at 17:28
  • I rerun this code with the current package version. For me it still works. Did you change the sample code in some way? – Alex Jun 16 '17 at 21:17
6

As already mentioned, any loop needs to be in a code chunk. It might be easier to to give the histogram a title rather than add a line of text as a header for each one.

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

However, if you would like to create multiple reports then check out this thread.

Which also has a link to this example.
It seems when the render call is made from within a script, the environmental variables can be passed to the Rmd file.

So an alternative might be to have your R script:

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

And then your Rmd chunk would look like:

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

Disclaimer: I haven't tested this.

Will Hore-Lacy
  • 131
  • 1
  • 6