用于隐藏 roxygen 注释的 knitr 代码块选项

knitr code chunk option to hide roxygen comments

是否可以添加一些新的代码块选项以便 在块中隐藏 roxygen 注释(以 #'##' 开头)?

我的动机是我使用 knitr.Rnw 文件。我用 knitr::knit2pdf 处理这个文件以获得 pdf 文件并使用 knitr::purl 来获取与该文件相关的 R 文件 幻灯片。如果我可以在我的代码块中使用,那就太好了 roxygen 仅在 purl 生成的 R 文件中显示但不显示的注释 在 pdf 中,代码块必须非常简洁。然后我可以 用很棒的 knitr::spin 转换我的 R 文件以获得 rmarkdown 将代码块注释转换为纯 rmarkdown 文本的文件。

例如 beamer .Rnw 文件中的以下代码

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

roxygen 注释 ##' 不会显示在 pdf 中,但最终会显示在 rmarkdown 代码中

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

当然做个脚本跳转也不复杂 在 .Rnw 文件中进行 roxygen 注释,然后再继续 knitr:knit2pdf,因为 roxygen 注释标记似乎不会干扰 LaTeX。

我最近了解到,关于基本的 .Rmd 文件,您可以使用 echo=2 删除 R 块中的注释。

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

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

我不能 100% 确定您的 .Rnw 结果是否符合我的回答,因为我尽量保留 .Rmd 文件以满足我自己的需要。

以下解决方案使用 source output hook 过滤掉以 #'##'.

开头的行

只有当块选项 hideRoxygenTRUE 时挂钩才会“激活”。输出的实际过滤发生在行 x <- x[!grepl("^#'|^##'", x)] 中。在此之后,执行默认钩子(保存在hook_old中),如上面link中所建议的那样。

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

输出:

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