如何在Rstudio中切换roxygen评论?

Jer*_*lim 9 r rstudio roxygen2

Roxygen注释涉及为行添加前缀#'.在编写和测试函数示例时,能够打开和关闭注释很好.我可以将代码复制并粘贴到vim并删除或添加这些注释,但这不是很优雅.

  • 有没有简单的方法来在Rstudio中切换roxygen评论?
  • 或者,是否有另一种方法可以有效地运行由roxygen注释字符注释掉的示例R代码?

更新:横向思考,我认为使用@example examples/foo.r是另一种避免必须对实际示例代码使用Roxygen注释的方法(即,通过从文件中获取示例,即examples/foo.r).

ags*_*udy 2

您可以编写自己的函数,从 R 文件中提取示例代码。这类似于purlin knitpackage 或Stangle. 这是您可以执行的操作的示例。该函数效率不高,但我编写它只是为了展示这个想法。这应该是一个很好的起点。它还假设您已经获取了 R 文件,或者至少记录的函数已存在于 R 会话中。

purl.examples <- function(fileName){
  ll <- readLines(fileName)
  ex.lines <- grep('@examples',ll)   ## get the example's lines
  ## for each example loop till
  ## there is no comment (inefficient)
  examples  <- lapply(ex.lines , function(x){
    i <- x+1
    code <- list()
    while(grepl("#'",ll[i])){
      l <- c(code,gsub("#'","",ll[i],fixed=TRUE))
      i <- i+1      
    }
    code
  })
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用它,例如:

lapply(purl.examples('code.R'), 
       function(ex) eval(parse(text=ex))) ## safer to use evaluate package here
Run Code Online (Sandbox Code Playgroud)