Skip to content

Instantly share code, notes, and snippets.

@Tutuchan
Last active December 21, 2019 14:24
Show Gist options
  • Save Tutuchan/6006628108d135675662d5947909c0b4 to your computer and use it in GitHub Desktop.
Save Tutuchan/6006628108d135675662d5947909c0b4 to your computer and use it in GitHub Desktop.
Loop over .Rmd chunks
```{r diamonds_{{color}}_{{cut}}_plot}
diamonds %>%
filter(
color == "{{color}}",
cut == "{{cut}}"
) %>%
ggplot(aes(carat, price, colour = clarity)) +
geom_point(show.legend = FALSE) +
labs(
title = 'Price by carat for diamonds with color {{color}} and cut {{cut}}'
)
```
```{r}
library(ggplot2)
library(dplyr)
loop_over_chunks <- function(ranges, chunk_path) {
combinations <- do.call(expand.grid, ranges)
variable_names <- names(ranges)
lapply(seq_len(nrow(combinations)), function(i) {
lapply(seq_along(variable_names), function(j) {
assign(variable_names[j], combinations[i, j], pos = 1)
})
knitr::knit_expand(chunk_path)
}) %>%
unlist()
}
```
```{r}
ranges <- list(
color = c("E", "J", "I"),
cut = c("Ideal", "Premium", "Good", "Very Good")
)
diamond_plots <- loop_over_chunks(ranges, "diamonds_template.Rmd")
```
`r paste(knit(text = diamond_plots), collapse = '\n')`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment