Reputation: 34907
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.
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
).
Upvotes: 11
Views: 1358
Reputation: 2361
With respect to your proposed alternative:
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.
Upvotes: 4
Reputation: 121568
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
Upvotes: 2