Search code examples
rr-markdownknitrroxygen2beamer

knitr code chunk option to hide roxygen comments


Would it be possible to add some new code chunk option in order to hide roxygen comments (beginning by #' or ##') in the chunk?

My motivation is that I use knitr to create beamer slides from a .Rnw file. I process this file with knitr::knit2pdf to get a pdf file and also with knitr::purl to get an R file related to the slides. It would be great if I could use in my code chunks roxygen comments that would show only in the R file produced by purl but not in the pdf, where code chunks must be very concise. Then I could transform my R file with the great knitr::spin to get a rmarkdown file with the code chunks comments turned into plain rmarkdown text.

For example the following code in a beamer .Rnw file

% One slide
\frame[containsverbatim]{
We now show how to use the of \verb@each@ formal of the `rep` function.
<<myChunk, roxcomments.hide="knitr2pdf">>=
##' Using the `each` formal of `rep`
rep(1:2, each = 3)
@      
}

The roxygen comment ##' would not be shown in the pdf, but would eventually be shown in the rmarkdown code

Using the `each` formal of `rep`
```{r myChunk} 
rep(1:2, each = 3)
```

Of course, it would not be complicated to make a script skipping roxygen comments in the .Rnw file before proceeding it with knitr:knit2pdf, since roxygen comment marks do not seem to interfer with LaTeX.


Solution

  • The following solution uses the source output hook to filter out lines starting with #' or ##'.

    The hook is only "active" if the chunk option hideRoxygen is TRUE. The actual filtering of the output occurs in the line x <- x[!grepl("^#'|^##'", x)]. After this, the default hook (saved in hook_old) is executed, as recommended in the link above.

    ```{r setup, echo = FALSE}
    
    hook_old <- knitr::knit_hooks$get("source")
    knitr::knit_hooks$set(source = function(x, options) {
      if(!is.null(options$hideRoxygen) && options$hideRoxygen) {
        x <- x[!grepl("^#'|^##'", x)]
      }
      
      hook_old(x, options)
    })
    
    ```
    
    ```{r, hideRoxygen = TRUE}
    #' A sample function
    #'
    #' @param x A parameter that will be ignored.
    sampleFunction <- function(x) {
      return(NA)
    }
    ```
    

    Output:

    sampleFunction <- function(x) {
      return(NA)
    }