Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the envir argument in knit_child?

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()` 
like image 253
Stéphane Laurent Avatar asked Jan 28 '26 07:01

Stéphane Laurent


1 Answers

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.

like image 189
Yihui Xie Avatar answered Jan 30 '26 00:01

Yihui Xie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!