Conditionally include a list of child documents in RMarkdown with knitr

后端 未结 2 844
[愿得一人]
[愿得一人] 2021-02-08 11:33

Given a list of child documents, how can you choose which to insert into a master document based on some criteria?

In my use case, I am matching the unknown entries in o

2条回答
  •  名媛妹妹
    2021-02-08 12:07

    You can dynamically render a child document

    ```{r, result='asis'}
    cat(knitr::knit_child("child.Rmd", quiet=TRUE))
    ```
    

    which gives you great flexibility.

    The "trick" is the result='asis' so that the output is then passed on for conversion (as opposed to "knitting").

    Alternatively, you can tag the object and avoid the "asis" in the chunk options:

    ```{r}
    cat(knitr::asis_output(knitr::knit_child("child.Rmd", quiet=TRUE)))
    ```
    

    This is more robust, as it allows you to use this in nested functions, etc., and not have to rely on the caller having set the "correct" chunk options.

    If you want to pass in "current" variables and libraries, pass in the current environment too:

    ```{r, result='asis'}
    cat(knitr::knit_child("child.Rmd", quiet=TRUE, envir=environment()))
    ```
    

提交回复
热议问题