Closed cderv closed 4 years ago
Working example
---
title: "reuse some code"
output: html_document
---
# Externalize ggplot2 code
```{r}
library(ggplot2)
You may have your own layout code like this one, and you do not want to type the code again and again. One way to avoid repeating the code explicitly is to use chunk references. Although knitr is based on the idea of literate programming, but we rarely need programming, and this is one case in which literate programming may be helpful.
We simplify the layout code in the original post and put it in a code chunk named my-layout
:
theme(legend.text = element_text(size = 12, angle=45))+
theme (legend.position = "bottom")
Now we can use <<>>
to reference it.
library(ggplot2)
qplot(carat, price, data=diamonds, color=cut)+
<<my-layout>>
Another test:
qplot(carat, data=diamonds, fill=cut)+
<<my-layout>>
The part with `<<chunk name>>` are replaced by the literal code inside the rendered rmarkdown.
Pretty awesome feature of literate programming.
Only drawback: you cannot run the Rmd file chunk by chunk in RStudio. You can only knit the file...
Not sure yet if it is a feature that should be presented. 🤔
This comes from https://github.com/yihui/knitr-examples/blob/master/083-ggplot2-reference.Rmd and I did not know about that
Now we can use
<<>>
to reference it.Another test: