11

Roxygen comments involve prefixing lines with #'. When writing and testing examples for functions, it's nice to be able to toggle the comments on and off. I could copy and paste the code back and forward to vim and remove or add those comments, but that's not very elegant.

  • Is there any easy way to toggle roxygen comments in Rstudio?
  • Alternatively, is there another way to efficiently run example R code that is commented out by roxygen comment characters?

Update: Thinking laterally, I suppose using @example examples/foo.r is an alternative way of avoiding having to use Roxygen comments for the actual example code (i.e., by sourcing the example from a file, i.e., examples/foo.r).

Jeromy Anglim
  • 33,939
  • 30
  • 115
  • 173

2 Answers2

4

With respect to your proposed alternative:

  • Alternatively, is there another way to efficiently run example R code that is commented out by roxygen comment characters?

If you press CTRL+[Enter] within a Roxygen2 @examples block, Rstudio will send the selected code (line or highlighted section) to the R console. To use just declare the @examples code block on a line preceding your roxygen commented code.

#' @examples
#'   ... your original roxygen commented code ...

You can put an @examples block anywhere in your code. This becomes a drag if you are developing a package and you are using the block for its intended purpose.

If you are looking for a way to toggle code, I would use the approach proposed by @Roman in in the comments to your question.

ctbrown
  • 2,271
  • 17
  • 24
2

You can write your own function that extract example code from your R file. This is analogous to purl in knit package or Stangle. Here an example of what you can do. The function is not efficient but I write it just to show the idea. It should be a good start point. It assumes also that you already source your R file or at least that the documented function already exist in the R session.

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

Then you can call it like this for example:

lapply(purl.examples('code.R'), 
       function(ex) eval(parse(text=ex))) ## safer to use evaluate package here
agstudy
  • 119,832
  • 17
  • 199
  • 261