Use Loop to Generate Section of Text in Rmarkdown

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

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

R Markdown - format text as a header in a loop seems to be working for 1st loop iteration only

I don't know why this works, but try one line instead of three:

cat("\n\n### ", experiment_names[id], "\n")

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 you cat() 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.

how to use a for loop in rmarkdown?

You can use the asis option:

---
title: "Untitled"
output: ioslides_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(dplyr)
# needed so r will include javascript/css dependencies needed for striped tables:
kable(cars, "html") %>% kable_styling(bootstrap_options = "striped")
```

```{r, results = "asis"}
for (threshold in c(20, 25)) {
cat("\n\n##\n\n")
x <- cars %>%
filter(dist < threshold) %>%
kable('html') %>%
kable_styling(bootstrap_options = "striped")
cat(x)
}
```

Loop in R markdown

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.



Related Topics



Leave a reply



Submit