Yves
Yves

Reputation: 181

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.

Upvotes: 2

Views: 247

Answers (2)

CL.
CL.

Reputation: 14957

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)
}

Upvotes: 1

Daniel_j_iii
Daniel_j_iii

Reputation: 3242

I just recently learned that in regards to basic .Rmd file that you can use echo=2 to remove comments that are within R chunks.

---
title: "Untitled"
author: "Daniel"
date: "6/17/2021"
output: pdf_document
---

```{r setup, echo = 2}
# comment
knitr::opts_chunk$set(echo = TRUE)
```

I am not 100% sure about your .Rnw results with my answer, as I try to stay with .Rmd files for my own needs.

enter image description here

Upvotes: 4

Related Questions