rstudio / rmarkdown-cookbook

R Markdown Cookbook. A range of tips and tricks to make better use of R Markdown.
https://bookdown.org/yihui/rmarkdown-cookbook/
578 stars 224 forks source link

A trick to reuse some code in an Rmarkdown, like ggplot theme #138

Closed cderv closed 4 years ago

cderv commented 5 years ago

This comes from https://github.com/yihui/knitr-examples/blob/master/083-ggplot2-reference.Rmd and I did not know about that

# Externalize ggplot2 code

You may have your own layout code like [this one](http://stackoverflow.com/q/14802183/559676), 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`:

```{r my-layout, eval=FALSE}
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>>
cderv commented 5 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. 🤔 
yihui commented 4 years ago

https://bookdown.org/yihui/rmarkdown-cookbook/reuse-chunks.html