Run selected chunks from one Rmd in another

Viewed 1149

I've run my analyses in a source Rmd file and would like to knit a clean version from a final Rmd file using only a few of the chunks from the source. I've seen a few answers with regard to pulling all of the chunks from a source Rmd in Source code from Rmd file within another Rmd and How to source R Markdown file like `source('myfile.r')`?. I share the concern with these posts in that I don't want to port out a separate .R file, which seems to be the only way that read_chunk works.

I think I'm at the point where I can import the source Rmd, but now I'm not sure how to call specific chunks from it in the final Rmd. Here's a reproducible example:

SourceCode.Rmd

---
title: "Source Code"
output:
  pdf_document:
    latex_engine: xelatex
---

```{r}
# Load libraries
library(knitr) # Create tables
library(kableExtra) # Table formatting
# Create a dataframe
df <- data.frame(x = 1:10,
                 y = 11:20,
                 z = 21:30)
```

Some explanatory text

```{r table1}
# Potentially big block of stuff I don't want to have to copy/paste
# But I want it in the final document
kable(df, booktabs=TRUE,
      caption="Big long title for whatever") %>%
  kable_styling(latex_options=c("striped","HOLD_position")) %>%
  column_spec(1, width="5cm") %>%
  column_spec(2, width="2cm") %>%
  column_spec(3, width="3cm")
```

[Some other text, plus a bunch of other chunks I don't need for anyone to see in the clean version.]

```{r}
save(df, file="Source.Rdata")
```

FinalDoc.Rmd

---
title: "Final Doc"
output:
  pdf_document:
    latex_engine: xelatex
---

```{r setup, include=FALSE}
# Load libraries and data
library(knitr) # Create tables
library(kableExtra) # Table formatting
opts_chunk$set(echo = FALSE)
load("Source.Rdata")
```

As far as I can tell, this is likely the best way to load up SourceCode.Rmd (from the first linked source above):

```{r}
options(knitr.duplicate.label = 'allow')
source_rmd2 <- function(file, local = FALSE, ...){
  options(knitr.duplicate.label = 'allow')

  tempR <- tempfile(tmpdir = ".", fileext = ".R")
  on.exit(unlink(tempR))
  knitr::purl(file, output=tempR, quiet = TRUE)

  envir <- globalenv()
  source(tempR, local = envir, ...)
}

source_rmd2("SourceCode.Rmd")
```

At this point, I'm at a loss as to how to call the specific chunk table1 from SourceCode.Rmd. I've tried the following as per instructions here with no success:

```{r table1}
```

```{r}
<<table1>>
```

The first seems to do nothing, and the second throws an unexpected input in "<<" error.

1 Answers

I wrote a function source_rmd_chunks() that sources chunk(s) by label name. See gist.

Related