Search code examples
rdocumentationpackageroxygen2

R Package Doc (roxygen2) - example part - execute example


I'm learning how to create R packages and more specificaly documentations with roxygen2.

I'm using this very simple example I found somewhere online:

#' Add together two numbers.
#' 
#' @param x A number.
#' @param y A number.
#' @return The sum of \code{x} and \code{y}.
#' @examples
#' add(1, 1)
#' add(10, 1)
#' @export

add <- function(x, y) {
  x + y
}

But what I get when I run ?add is

Examples

add(1, 1)  
add(10, 1)

While I would like to have the result of the code :

Examples

add(1, 1)  
2  
add(10, 1)  
11  

Solution

  • The code in the @examples section is meant to be executed as written, and in fact it is run every time you check the package with R CMD check ("Check Package" in R Studio). Therefore, it must not contain the output from those commands.

    However, as @SymbolixAU writes, you can add comments, e.g.:

    #' Add together two numbers.
    #' 
    #' @param x A number.
    #' @param y A number.
    #' @return The sum of \code{x} and \code{y}.
    #' @examples
    #' add(1, 1)
    #' # 2
    #'
    #' add(10, 1)
    #' # 11
    #' @export
    add <- function(x, y) {
      x + y
    }
    

    Or maybe rather:

    #' Add together two numbers.
    #' 
    #' @param x A number.
    #' @param y A number.
    #' @return The sum of \code{x} and \code{y}.
    #' @examples
    #' add(1, 1) # returns 2
    #'
    #' add(10, 1) # returns 11
    #' @export
    add <- function(x, y) {
      x + y
    }