Can anyone help in how to write a reproducible comment in Rmarkdown?
For example, we have the data set as shown below:
age | fnlwgt | education_num |
---|---|---|
39 | 77516 | 13 |
50 | 83311 | 13 |
38 | 215646 | 9 |
53 | 234721 | 7 |
In Rmarkdown report comments are typed using # before the text within code chunk. I want to write a reproducible comment for mean age.
# The average age is 45
Is there any way to write the above comment as reproducible? In case I change the values for age variable, the average value should automatically updated in the comment...
I would be thankful for your kind support.
Regards, Farhan
One option could be generating the code chunk dynamically using chunk option results="asis"
.
---
title: "Reproducible comments"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r dt, echo=FALSE}
df <- tibble::tribble(
~age, ~fnlwgt, ~education_num,
39L, 77516L, 13L,
50L, 83311L, 13L,
38L, 215646L, 9L,
53L, 234721L, 7L
)
```
```{r results="asis", echo=FALSE}
cmnt <- paste0(
"```{r}\n",
"df <- tibble::tribble(
~age, ~fnlwgt, ~education_num,
39L, 77516L, 13L,
50L, 83311L, 13L,
38L, 215646L, 9L,
53L, 234721L, 7L
)\n\n",
"# The average age is ", mean(df$age), "\n",
"```\n"
)
cat(cmnt)
```
Another option could be using knitr::knit_expand
to dynamically expand the comments with {{}}
in a template r-markdown file.
Suppose this is the template r-markdown file,
template.Rmd
```{r}
mean_age <- mean(dat$age)
# The mean age is {{age}}
mean_educ <- mean(dat$education_num)
# The mean education_num is {{educ}}
```
Now to expand these comments in our main document, we use knitr::knit_expand
and pass the variable to be expanded in the comments, and then we add the contents of template.Rmd
using knitr::knit_child
.
---
title: "Reproducible comments"
output:
html_document:
keep_md: TRUE
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r}
dat <- tibble::tribble(
~age, ~fnlwgt, ~education_num,
39L, 77516L, 13L,
50L, 83311L, 13L,
38L, 215646L, 9L,
53L, 234721L, 7L
)
```
## Comments reproduced dynamically
```{r, echo=FALSE, results='asis'}
src = knitr::knit_expand(
"template.Rmd",
age = mean(dat$age),
educ = mean(dat$education_num)
)
res = knitr::knit_child(text = src, quiet = TRUE)
cat(res, sep = '\n')
```