Last active
June 21, 2023 02:22
-
-
Save charliejhadley/642dec788104beba5089f47707c706be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
title: "Untitled" | |
output: bookdown::html_document2 | |
--- | |
```{r setup, include=FALSE} | |
knitr::opts_chunk$set( | |
echo = FALSE, | |
message = FALSE, | |
warning = FALSE | |
) | |
library(tidyverse) | |
library(gapminder) | |
library(knitr) | |
``` | |
# The function | |
This function generates the scatter plots | |
```{r} | |
gapminder_continent_scatter <- function(continent){ | |
gg_scatter <- gapminder %>% | |
filter(continent == {{continent}}, | |
year == 1952) %>% | |
ggplot(aes(x = pop, | |
y = gdpPercap)) + | |
geom_point() | |
ggsave(str_glue("gapminder_{tolower(continent)}_scatter.png"), | |
gg_scatter, | |
width = 6, | |
height = 3) | |
} | |
walk(unique(gapminder$continent), gapminder_continent_scatter) | |
``` | |
# Manual | |
## Explanation | |
I want to programmatically generate code chunks as follows, so that I can use internal cross-referencing properly. | |
- This bullet refers to the figure for Africa correctly: Figure \@ref(fig:gg-gapminder-africa-scatter) | |
I would manally use this code (commented out for simplicity): | |
<!-- # ```{r gg-gapminder-europe-scatter, fig.cap="Scatter plot for Europe"} --> | |
<!-- # knitr::include_graphics("gapminder_europe_scatter.png") --> | |
<!-- # ``` --> | |
<!-- # --> | |
<!-- # ```{r gg-gapminder-africa-scatter, fig.cap="Scatter plot for Africa"} --> | |
<!-- # knitr::include_graphics("gapminder_africa_scatter.png") --> | |
<!-- # ``` --> | |
<!-- # --> | |
<!-- # ```{r gg-gapminder-oceania-scatter, fig.cap="Scatter plot for Oceania"} --> | |
<!-- # knitr::include_graphics("gapminder_oceania_scatter.png") --> | |
<!-- # ``` --> | |
# Programmatic Insertion | |
To programmatically insert these we need `knitr::knit_expand()` and the (annoying) step of inlining the code afterwards. | |
Thanks to this [stackoverflow answer](https://stackoverflow.com/a/14368148/1659890) for help! | |
```{r, results='asis'} | |
src <- map(levels(unique(gapminder$continent)), function(continent) | |
knit_expand(text = c( | |
"```{r gg-gapminder-{{tolower(continent)}}-scatter, fig.cap='Scatter plot for {{continent}}'}", | |
"knitr::include_graphics('gapminder_{{tolower(continent)}}_scatter.png')", | |
"```" | |
))) | |
``` | |
`r knit(text = unlist(src))` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment