How to embed headings and charts within a for loop in Rmarkdown

76 Views Asked by At

I would like to embed both a heading and chart into an Rmarkdown document. I have done this using the mtcars dataset and a for loop . Knitting the rmarkdown document prints the code, rather than executing the code. Please advise.

---
output: html_document
---

```{r echo=FALSE}
library(ggplot2)

 vec <- c("cyl", "disp", "hp")

 for (i in seq_along(vec)) {
  cat(paste("# ", vec[i], "\n"))
  cat(paste("```{r} \n"))
  
  cat(paste0("ggplot(mtcars, aes(x=mpg, y=",vec[i],")) + geom_plot()  \n" ))
  cat("```\n\n")
}
```
1

There are 1 best solutions below

1
On

There is no need to create your plotting code as a character string. Also, if you want to dynamically create your headers use chunk option results='asis'. Finally note the use of the .data pronoun to use column names passed as character strings inside aes().

---
output: html_document
---

```{r echo=FALSE, results='asis'}
library(ggplot2)

vec <- c("cyl", "disp", "hp")

for (i in vec) {
  cat(paste("# ", i, "\n"))

  p <- ggplot(mtcars, aes(x = mpg, y = .data[[i]])) +
    geom_point()

  print(p)

  cat("\n\n")
}
```

enter image description here