Search code examples
rr-markdownrnotebook

Excluding part of the R markdown (html_notebook) from the final html output


I am writing a relatively long report using R Notebook that makes use of R markdown language which combines text and code in the same document and generates html output.

I would like to be able to exclude some of the analysis (both text and R code) from showing in the final HTML. This is very useful if I want to create two versions of the report - a full/detailed version, as well as a shorter version with main graphs and conclusions.

Obviously, I can create separate Rmd file for each type of report (or comment out pieces of the report that need to be excluded for the shorter version), but I was wondering if there is a more elegant way to do it.

Something like this:

     if (Version == "full_text"){

                Full analysis goes here 

                ```{r}
                R code goes here (could be multiple chunks)
                ```
     }
     else {
                The shorter version goes here 
                ```{r}
                R code goes here 
                ```
    }

Solution

  • Place the "detailed" part of the report in a knitr child document which you call optionally from the main document. Detailed content can then be switched on by calling the child document and it can be switched off by setting the variable child_docs to NULL. For example here are a main and a child document below.

    Child document

    Save this document under knitr-child.Rmd

    ---
    title: "knitr child"
    output: html_document
    ---
    
    # Details from the child document
    Hi, there. I'm a child with a plot and as many details as necessary.
    
    ```{r test-child}
    plot(cars)
    ```
    

    Main document - full/detailed version

    ---
    title: "Report"
    output: html_document
    ---
    
    # Summary 
    
    ```{r setup}
    child_docs <- c('knitr-child.Rmd')
    # child_docs <- NULL
    ```
    
    ```{r test-main, child = child_docs}
    ```
    
    # Conclusion
    

    full version

    Main document shorter version

    ---
    title: "Report"
    output: html_document
    ---
    
    # Summary 
    
    ```{r setup}
    # child_docs <- c('knitr-child.Rmd')
    child_docs <- NULL
    ```
    
    ```{r test-main, child = child_docs}
    ```
    
    # Conclusion
    

    shorter version