How to use the envir argument in knit_child?

knitr, r, r-markdown

Solution

This should be fixed in the development version of knitr (>= v1.6.3): `knit_child()` has gained a new argument `envir`, and you can pass an arbitrary environment to it.

Problem

I'm writing an R package in which I have such a Rmd template: child.Rmd: ```` ```{r} print(x) ``` ```` and such a function: ``` child <- function(){ myenv <- new.env() assign("x", 0, envir=myenv) # knit: output <- knit_child("child.Rmd", envir=myenv) return(output) } ``` Then I knit such a file : ```` ```{r, echo=FALSE} library(mypackage) ``` `r child()` ```` But that doesn't work, the output is: ``` print(x) ## Error: object 'x' not found ``` Below is a self-contained example, without involving any package, I don't know whether this is really equivalent and what I really need is the package structure: ```` ```{r} child <- function(){ myenv <- new.env() assign("x", 0, envir=myenv) # knit: output <- knit_child("child.Rmd", envir=myenv) return(output) } ``` `r child()` ````

Original source