0

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?

antonio
  • 10,629
  • 13
  • 68
  • 136
  • what about using YAML parameters? – s_baldur Jan 30 '20 at 14:22
  • @sindri_baldur: For a single report I can change the Rmd header params. If I want to create several reports based on params, manually changing them, rather than setting them from the calling script, is time consuming and very prone to errors. – antonio Jan 30 '20 at 17:16
  • @sindri_baldur: Not yet tried, but one approach could be an initial setup chunk, exploring the environment passed to `envir` argument in `knit()` by means of `knit_global()` and raising a critical error if the expected variables are not found. – antonio Jan 30 '20 at 17:18

0 Answers0