How to use the envir argument in knit_child?
-
21-12-2019 - |
Question
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()`
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.
OTHER TIPS
knit_child
does not seem to pass envir
to knit
. I don't really know why.
One thing you can do is to move myenv
outside the function so that it is available to the child.
```{r}
myenv <- new.env()
child <- function(){
assign("x", 0, envir=myenv)
# knit:
output <- knit_child("child.Rmd")
return(output)
}
```
`r child()`
child.Rmd
```{r}
print(get('x', envir=myenv))
```
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow