`source` command in RMarkdown fails to render plot

With the intention of making a project more manageable, I am trying to split up a long Rmd file into several smaller R scripts, each sourced by a master Rmd file.

The problem I am having is that plots generated by the subsidiary R scripts are not being included in the knitted output from the Rmd file.

I have made a small, hopefully reproducible, example to demonstrate the problem.

A. This works when knitted with knitr:

---
title: "Test"
output:
  html_document:
    toc: false
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = TRUE,
  error = TRUE,
  message = FALSE,
  warning = FALSE,
  cache = FALSE,
  out.width = "80%")

library(ggplot2)
```

```{r test_chunk}
ggplot(trees, aes(Girth, Height)) +
  geom_point()
```

B. This doesn't:

---
title: "Test"
output:
  html_document:
    toc: false
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = TRUE,
  error = TRUE,
  message = FALSE,
  warning = FALSE,
  cache = FALSE,
  out.width = "80%")

library(ggplot2)
```

```{r test_chunk}
source("01_plot.R")
```

where 01_plot.R is:

ggplot(trees, aes(Girth, Height)) +
  geom_point()

i.e. the same code as included in the chunk in example A.

Now I can't find too much online about to use source in an RMarkdown document, but this post from Yihui implies that it should be the way to read in and evaluate external code. So what's wrong here?

For this use case, you can also use child document

It allows to split your code in several Rmd document.

Also, you can import some Rscript as code for you chunk using code chunk option

---
title: "Test"
output:
  html_document:
    toc: false
---

```{cat, engine.opts = list(file = "01_plot.R")}
library(ggplot2)
ggplot(trees, aes(Girth, Height)) +
  geom_point()
```

```{r test_chunk, code = readLines('01_plot.R')}
```

This will write the R code to a file and import it in the chunk after, in the code chunk and running the code.

About your specific issue here, I think this because the print call that print the ggplot is not happening in the document. If you create the ggplot object assigning result to p for example, you can call p in your document

---
title: "Test"
output:
  html_document:
    toc: false
---

```{r test_chunk}
source("01_plot.R")
p
```

Or you may activate printing of what is evaluated

---
title: "Test"
output:
  html_document:
    toc: false
---

```{r test_chunk}
source("01_plot.R", print.eval = TRUE)
```

Hope it helps

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.