Last active
March 22, 2021 18:50
-
-
Save jennybc/1f747c5bb84aa9be9c3c to your computer and use it in GitHub Desktop.
Nested render confuses RStudio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
output: | |
html_document | |
--- | |
```{r setup, echo = FALSE} | |
knitr::opts_chunk$set( | |
collapse = TRUE, | |
comment = "#>" | |
) | |
``` | |
*UPDATE: JJ provided the magic missing piece, so this gist now shows a successful attempt at nested render, complete with expected RStudio behavior. This gist relates to [issue #491 on rstudio/rmarkdown](https://github.com/rstudio/rmarkdown/issues/491).* | |
I have some R commands into a file `foo.R`: | |
```{r define-demo-code} | |
demo_code <- c( | |
"(y <- 1:4)", | |
"mean(y)" | |
) | |
writeLines(demo_code, "foo.R") | |
``` | |
I want to cause `foo.R` to be rendered, in the process of rendering THIS file. | |
It is already well-known that a chunk like this will NOT work (see [issue #248](https://github.com/rstudio/rmarkdown/issues/248)) | |
```{r eval = FALSE} | |
## not run | |
rmarkdown::render("foo.R") | |
``` | |
It produces this error: | |
``` | |
Error in env$metadata <- list() : | |
cannot change value of locked binding for 'metadata' | |
Calls: <Anonymous> | |
Execution halted | |
``` | |
Thanks to that issue, however, I learned a trick: create a wrapper script and use `devtools::clean_source()` to execute that in a fresh R environment. *Thanks to [an exchange with JJ](https://github.com/rstudio/rmarkdown/issues/491) I learned another thing: use `quiet = TRUE` inside `render()` to keep it from emitting messages that cause the RStudio IDE to display the rendered child instead of parent.* | |
```{r render-via-wrapper} | |
## implementing JJ's suggestion to use 'quiet' arg to suppress message output | |
writeLines('rmarkdown::render("foo.R", "md_document", quiet = TRUE)', | |
"render_wrapper.R") | |
devtools::clean_source("render_wrapper.R", quiet = TRUE) | |
file.remove("render_wrapper.R") | |
``` | |
Which does indeed cause `foo.R` to be rendered to `foo.md`: | |
```{r} | |
list.files(pattern = "foo") | |
``` | |
~~But if you render *this document* via the Knit button in RStudio, the preview window pops up `foo.md`, not an HTML preview of *this document*. Which is weird. This document is successfully compiled to `.html` but you have to visit it in the file browser and "View in Web Browser".~~ | |
And indeed Just Works. The End. |
how do I use the clean_source
function now?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that
clean_source()
has been deprecated in favor of the callr package.