Hi all,
Within a package I am working on, I am creating optional vignettes that the user can build on demand.
I want that the building of such vignettes happens in an environment that does not have the global one as parent. So, my custom vignette building function includes something like:
vignette_env <- new.env(parent = baseenv())
rmarkdown::render(path.to.file, envir = vignette_env)
The problem when I do that is that the package loaded and the objects created inside knitr chunks are not visible (in scope) to inline calls that follow, although they are visible to other chunks.
Here is a reprex that illustrates the problem by showing that a function cannot be found after a call to library()
. Sorry that it may not work out of the box on some system and that apologies for the complexity, but I have to create a package containing vignettes and functions on the fly to mimic the situation.
To avoid issues, do restart your R session when indicated to reproduce.
## define some functions
builder <- function(path.to.file) {
vignette_env <- new.env(parent = baseenv())
rmarkdown::render(path.to.file, envir = vignette_env)
}
makeone <- function() 1
## create temp folder
temp_path <- path.expand("~/folder_to_delete/") ## adjust path to your test
system("rm -d -r ~/folder_to_delete/") ## delete in case existing already
dir.create(temp_path) ## creation per se
## create a package on the fly containing the function
package.skeleton("testvignetteenv", path = temp_path,
list = c("makeone", "builder"), force = TRUE)
rm(list = c("makeone", "builder"))
## fix the package so it can be installed without crashing
man_files <- dir(paste0(temp_path, "/testvignetteenv/man"), full.names = TRUE)
file.remove(man_files)
## add an optional vignette to the package
content <- "
---
title: test
output:
rmarkdown::html_document
---
```{r}
library(testvignetteenv)
```
the value `r makeone()` crashes because the function is not found.
```{r}
makeone() ## works
```
"
dir.create(paste0(temp_path, "testvignetteenv/inst/extdata/"), recursive = TRUE)
cat(content, file = paste0(temp_path, "/testvignetteenv/inst/extdata/test.Rmd"))
## install the package
install.packages(paste0(temp_path, "/testvignetteenv"), type = "source", repos = NULL)
## PLEASE RESTART YOUR R SESSION HERE!!!
## build the vignette
temp_path <- path.expand("~/folder_to_delete/") ## adjust path to your test
library(testvignetteenv)
builder(paste0(temp_path, "/testvignetteenv/inst/extdata/test.Rmd"))
utils::browseURL(paste0(temp_path, "/testvignetteenv/inst/extdata/test.html"))
What happens when I do this is the following: