Consider the file foo.Rmd
following:
```{r foo, echo=yes}
print("Hello")
```
Note that the echoing of the chunk code is not constant, but depends on the value of the variable yes
set outside foo.Rmd
.
One can set the value of the knitting variable, e.g. yes <- TRUE
, and then call knit("foo.Rmd")
. However this makes the code fragile. In fact, if the calling code sets yes
for its own needs, this will affect the knitting. For large/complex Rmd's it can be easy to have variable clashes: for example you forget to set a variable for knitting, but this variable happens to be already defined for some reason, and you get unpredictable/wrong results.
A hypothetical solution is to explicitly set knitting variables via the knit()
argument envir
. That is:
e <- new.env()
e$yes <- TRUE
knit("foo.Rmd", envir=e)
foo.Rmd
is now evaluated in the e
environment, where yes
has value TRUE
.
In case of multiple definitions there is no risk of clashes:
e <- new.env()
e$yes <- TRUE
yes <- FALSE
knit("foo.Rmd", envir=e)
The resulting markdown echoes the chunk, that is yes <- FALSE
set in the parent environment does not affect the value explicitly set via e
in chunk evaluations.
Now you might expect:
e <- new.env()
yes <- FALSE
knit("foo.Rmd", envir=e)
to produce an error such as object 'yes' not found
. Unfortunately the knitting works using yes <- FALSE
in the parent.
This is less problematic, but still, for a complex Rmd, you might forget to set some knitting variables and obtain wrong results.
Is there a way to allow only explicitly set variables during knitting?