knitr makes PDFs out of code that is a combination of (in my case) R and LaTEX. One can assemble a document out of child documents.
As I use it right now, the docum
knitr
evaluates all chunks in a common environment (returned by knit_global()
). This is by design; just like all code in a source file runs in the same environment, all chunks are executed in a common environment. The same applies to child documents because they are (in principle, not technically) just a part of the main document, externalized to another file.
This does not necessarily lead to spaghetti code: Nothing prevents users from using functions and other objects to organize code/data in knitr
documents. But probably few users do so …
So the reason why there are no encapsulation mechanisms for chunks/child documents is that they are supposed to share a common environment as they are part of one (main) document.
However, it is possible to include child documents in a way that gives the user control over the objects child documents and the main document share. The solution is based on the function knit_child()
which is very similar to the chunk option child
. The advantage of calling knit_child()
directly (vs. implicitly via the child
option) is the possibility to set the envir
argument which defines "the environment in which the code chunks are to be evaluated" (from ?knit
).
Around knit_child()
, I wrote the wrapper IsolatedChild
to simplify matters:
IsolatedChild <- function(input, ...) {
evaluationEnv <- list2env(x = list(...), parent = as.environment(2))
cat(asis_output(knit_child(input = input, envir = evaluationEnv, quiet = TRUE)))
return(evaluationEnv)
}
Arguments passed to ...
will be available in the child document. (Name them, see example below.) The function returns the environment in which the child document has been evaluated.
Specifying parent
in list2env
is crucial and I chose as.environment(2)
according to this answer. Otherwise parent
would default to parent.frame()
, thus exposing objects in knit_global()
to the child document.
assign
can be used to make objects returned from IsolatedChild
available in the global environment.
Note the cat(asis_output())
construction around knit_child
which ensures that the output from the child document is correctly included in the main document, regardless of the results
setting in the current chunk.
Before turning to the example, two final remarks:
knit
the child document and use \include{}
to include it in the main document.knitr
options. Besides, both documents could interact via side effects (options()
, par()
, opened devices, ...).Below a complete example / demo:
inputNormal
does nothing special, it's just a demonstration of the normal behavior. inputHidden
demonstrates the use of IsolatedChild()
, passing two variables to the child document. IsolatedChild()
returns these two values along with a third object created in the child.check
demonstrates that the objects passed to/created in the "isolated child" do not pollute the global environment.import
shows how assign
can be used to "import" an object from the "isolated child" to the global environment.
main.Rnw
:
\documentclass{article}
\begin{document}
<<setup>>=
library(knitr)
objInMain <- TRUE
IsolatedChild <- function(input, ...) {
evaluationEnv <- list2env(x = list(...), parent = as.environment(2))
cat(asis_output(knit_child(input = input, envir = evaluationEnv, quiet = TRUE)))
return(evaluationEnv)
}
@
<<inputNormal, child="child_normal.Rnw">>=
@
<<inputHidden, results = "asis">>=
returned <- IsolatedChild(input = "child_hidden.Rnw",
passedValue = 42,
otherPassedValue = 3.14)
cat(sprintf("Returned from hidden child: \\texttt{%s}",
paste(ls(returned), collapse = ", ")))
@
<<check, results = "asis">>=
cat(sprintf("In global evaluation environment: \\texttt{%s}",
paste(ls(), collapse = ", ")))
@
<<import, results = "asis">>=
assign("objInChildHidden", returned$objInChildHidden)
cat(sprintf("In global evaluation environment: \\texttt{%s}",
paste(ls(), collapse = ", ")))
@
\end{document}
child_normal.Rnw
:
<<inChildNormal>>=
objInChildNormal <- TRUE # visible in main.Rnw (standard behaviour)
@
child_hidden.Rnw
:
Text in \texttt{child\_hidden.Rnw}.
<<inChildHidden>>=
objInChildHidden <- TRUE
print(sprintf("In hidden child: %s",
paste(ls(), collapse = ", ")))
# Returns FALSE.
# Would be TRUE if "parent" weren't specifiet in list2env().
exists("objInMain", inherits = TRUE)
@
main.pdf
: