Re-use R Markdown Chunks in a Function

I am writing a tutorial that will include instructions in R, Stata, SAS, and Python. Most of the tutorial is prose about the methods, and I want to include code examples in the four languages.

Below is an example of how I am putting the code examples in tabsets showing only code for R and Stata. The result of this R Markdown document is here RPubs - Multi-language Coding Tutorial

---
title: "DCA Example"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Show code for both R and Stata. Show the output from R only.

#### Syntax {.tabset .tabset-pills}

##### R

```{r, r-model, eval = FALSE}
# build logistic regression model
mod <- glm(am ~ mpg, data= mtcars, family = binomial)

# print model results
gtsummary::tbl_regression(mod, exponentiate = TRUE)
```

##### Stata

```{stata, stata-model, eval = FALSE}
# build logistic regression model
logit am mpg
```

#### {-}

<!-- This chunk runs the R code without printing the code (since that is in the tabset). -->
```{r, r-model, eval = TRUE, echo = FALSE}
```

There will be many many many of these code chunks and they will quickly make the document very large with much duplication.

I would like to save each code chunk in separate files with a defined name for each chunk. In the example above, the chunks are called "r-model" and "stata-model". Is there any way I can write a function that can print the entire tabset section, including the last chunk that evaluates the R code?

Something like this would be perfect:

---
title: "DCA Example"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Show code for both R and Stata. Show the output from R only.

`r add_tabset_codes("model")`

The add_tabset_codes("model") function would add the tabset markdown tabset syntax as well as insert the chunks "r-model" and "stata-model".

Is this possible???
Here is the R Markdown guide's section on re-using saved chunks 14.1 Reuse code chunks | R Markdown Cookbook

I ended up using this templating option I was not aware of.

1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.