The following .Rmd
is what I think should produce what I'm looking for:
---
title: "Untitled"
date: "10/9/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
full_var <- function(var) {
cat("### `", var, "` {-} \n")
cat("```{r}", "\n")
cat("print('test')", "\n")
cat("```", "\n")
}
vars <- c("1", "2", "3")
```
```{r results = "asis"}
purrr::walk(vars, full_var)
```
Instead, it looks like:
Why is the print('test')
not being evaluated and instead being presented as a code block?
In your "code execution" line, use cat(eval())
:
---
title: "Untitled"
date: "10/9/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
full_var <- function(var) {
cat("### ", var, "{-}", "\n")
cat("```{r}", "\n")
cat(eval(print('test')), "\n")
cat("```", "\n")
}
vars <- c("1", "2", "3")
purrr::walk(vars, full_var)
Notice that I also changed the heading line slightly.
Thanks! I thought the answer to this would help me solve my problem, but apparently not:
Consider if print('test')
was actually a much lengthier chunk of Markdown and code block and so I wrote it in a separate .Rmd file.
full_var <- function(var) {
cat("### ", var, "{-}", "\n")
cat("```{r child = '", var, ".Rmd'}", "\n", sep = "")
cat("```", "\n")
}
This simply returns {r child = 'var.Rmd'}
but does not actually pull in the Markdown from the other file. Any idea why this may not be working?
Make use of the knitr::knit_child()
call in your function:
---
title: "Untitled"
date: "10/9/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
full_var <- function(var) {
cat("### ", var, "{-}", "\n")
cat("\n")
child <- knitr::knit_child(paste0(var, ".Rmd"), quiet = TRUE)
cat(child, sep = "\n")
}
vars <- c("1", "2", "3")
```
```{r results = "asis"}
purrr::walk(vars, full_var)
```
This should read your child .Rmd files, provided, of course, that they are located in your working directory.
1 Like
Thank you! I've been beating my head against a wall trying to get this to work - it was so simple the whole time.
cderv
6
Yes knit_child()
is a good solution.
If you want to go further, have a look in the R Markdown cookbook. There are seveal chapter with recipes to help with such task.
Hope it helps
1 Like
system
Closed
7
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.