Create sections through a loop with knitr
R package pander
can generate Pandoc's markdown on the fly.
The key is to use the chunk option results='asis'
to tell R Markdown to render pander's output as Markdown.
You just need to be careful to generate valid Markdown!
Try this:
---
title: "Test sections"
output: html_document
---
## A function that generates sections
```{r}
library(pander)
create_section <- function() {
# Inserts "## Title (auto)"
pander::pandoc.header('Title (auto)', level = 2)
# Section contents
# e.g. a random plot
plot(sample(1000, 10))
# a list, formatted as Markdown
# adding also empty lines, to be sure that this is valid Markdown
pander::pandoc.p('')
pander::pandoc.list(letters[1:3])
pander::pandoc.p('')
}
```
## Generate sections
```{r, results='asis'}
n_sections <- 3
for (i in seq(n_sections)) {
create_section()
}
```
It still looks hackish, but Markdown has its limits...
how to create a loop that includes both a code chunk and text with knitr in R
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")
}
```
how do you create sections and new lines in knitr
Is something like this what you're looking for?
---
title: "My Report"
output:
pdf_document:
number_sections: yes
toc: yes
---
# Application `r 1+1`
```{r qplot,fig.width=10, fig.height=8, message=FALSE, results = 'asis', echo=FALSE, warning=FALSE, fig.cap='long caption', fig.scap='short', tidy=FALSE}
library(ggplot2)
ggplot(iris, aes(Sepal.Length, Sepal.Width))+geom_line()
```
Create RMarkdown chuncks in a loop
If you want to create headings + outputs within a loop, you can do:
```{r species_loop, results='asis'}
for(i in c("setosa", "versicolor", "virginica")) {
cat(paste0("\n\n## ", i, "\n"))
p <- df %>%
dplyr::filter(Species == i) %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
print(p)
}
```
So:
- Using
results='asis'
to allow output that youcat()
to be interpreted as Markdown syntax cat()
ing the required markdown syntax to produce the headers (surrounded by some newlines to make sure it's interpreted properly)- Explicitly
print()
ing the plot within the loop.
R markdown: Use for loop to generate text and display figure/table
You can use result = 'asis'
inside the r chunk
and use cat()
to create the sections.
---
title: "R Notebook"
output:
html_document
---
## Example
```{r, results='asis'}
require(ggplot2)
for(i in 1:5){
cat("### Section ", i, "\n")
df <- mtcars[sample(5),]
tb <- knitr::kable(df, caption = paste0("Table",i))
g1 <- ggplot2::ggplot(df, aes(x = mpg, y = disp, fill = gear)) +
ggplot2::geom_point() +
ggplot2::labs(title = paste0("Figure ", i))
cat("\n")
print(g1)
print(tb)
cat("\n")
}
```
R knitr Markdown: Output Plots within For Loop
Wrap the qplot
in print
.
knitr
will do that for you if the qplot
is outside a loop, but (at least the version I have installed) doesn't detect this inside the loop (which is consistent with the behaviour of the R command line).
looping in knitr through captions and graphs
Is this a-OK?
```{r, results='asis'}
cat(sprintf('![%s](%s)', df$caption, df$png_file), sep = '\n')
```
Related Topics
Logistic Regression - Defining Reference Level in R
How to Compute Roc and Auc Under Roc After Training Using Caret in R
Marking Specific Tiles in Geom_Tile()/Geom_Raster()
Rescaling the Y Axis in Bar Plot Causes Bars to Disappear:R Ggplot2
Showing Different Axis Labels Using Ggplot2 with Facet_Wrap
Barplot with 2 Variables Side by Side
How to Transpose a Dataframe in Tidyverse
How to Have Conditional Markdown Chunk Execution in Rmarkdown
Dplyr - Summary Table for Multiple Variables
Monitoring for Changes in File(S) in Real Time
Find the Index Position of the First Non-Na Value in an R Vector
Generating a Vector of Difference Between Two Vectors
Pandoc Insert Appendix After Bibliography
Clipping Raster Using Shapefile in R, But Keeping the Geometry of the Shapefile
How to Skip an Error in a Loop
Change Color of Leaflet Marker
How to Append Data from a Data Frame in R to an Excel Sheet That Already Exists