how to create a loop that includes both a code chunk and text with knitr in R

As mentioned here, you could also make use of the pander package:

# Monthly Air Quality Graphs
```{r pressure2, fig.width=6, echo=FALSE, message=FALSE, results="asis"}
library(pander)
for (i in unique(airquality$Month)) {
   # Inserts Month titles
   pander::pandoc.header(month.name[i], level = 3)
   # Section contents
   plot(airquality[airquality$Month == i,])
   # adding also empty lines, to be sure that this is valid Markdown
   pander::pandoc.p('')
   pander::pandoc.p('')
}
```

You can embed the markdown inside the loop using cat().

Note: you will need to set results="asis" for the text to be rendered as markdown. Note well: you will need two spaces in front of the \n new line character to get knitr to properly render the markdown in the presence of a plot out.

# Monthly Air Quality Graphs
```{r pressure,fig.width=6,echo=FALSE,message=FALSE,results="asis"}

attach(airquality)
for(i in unique(Month)) {
  cat("  \n###",  month.name[i], "Air Quaility  \n")
  #print(plot(airquality[airquality$Month == i,]))
  plot(airquality[airquality$Month == i,])
  cat("  \n")
}
```

Tags:

Loops

R

Knitr