Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you share examples between functions with rOxygen2?

I know one can group multiple functions under the same documentation with the @describeIn or the @rdname tags using rOxygen. This is fine for groups of function with a similar purpose/syntax.

However, I'm writing a package where a set of functions should almost always be executed as part of a workflow. To make things cleaner I want to have a single example to illustrate this workflow and display it for all of the involved functions.

I need to keep the functions in their separate documentation page because each of them have very different purposes, parameters and require a pretty extensive doc on their own. I don't want to confuse the reader by grouping all of it together.

Is it possible to to this? Can I, for instance, have a file with the example code and include it in all function documentation ?

Just in case that help, I included some dummy code below.

#' function1
#' 
#' This does stuff
#' 
#' @param a,b a and b
#' @return c
#' @export
#' @examples 
#' # step 1 : do this
#' C <- function1(a,b)
#' 
#' # step 2 : do that
#' D <- function2(C, e, f)
#' 
#' # step 3 : profit.
function1 <- function(a,b){
  return(a+b)
}

#' function2
#' 
#' This also does stuff
#' 
#' @param C could be from function1
#' @param e,f e and f
#' @return d
#' @export
#' @examples 
#' # step 1 : do this
#' C <- function1(a,b)
#' 
#' # step 2 : do that
#' D <- function2(C, e, f)
#' 
#' # step 3 : profit.
function2 <- function(C, e, f){
  return(C+e+f)
}
like image 280
RoB Avatar asked Oct 22 '25 18:10

RoB


1 Answers

I've found a way to do this by using the @eval tag of Roxygen and storing my examples in a function returning the example code.

So in a package, you would for example have a shared_examples.R file like so :

function_examples <- function()
{
  ex <- "
@examples
# step 1 : do this
C <- function1(a,b)

# step 2 : do that
D <- function2(C, e, f)

# step 3 : profit.
"
  return(strsplit(ex, split = "\n")[[1]]) # needed to have line jumps in the doc
}

and then, your actual function documentation will look like this :

#' function1
#' 
#' This does stuff
#' 
#' @param a,b a and b
#' @return c
#' @export
#' @eval function_examples()
function1 <- function(a,b){
  return(a+b)
}

#' function2
#' 
#' This also does stuff
#' 
#' @param C could be from function1
#' @param e,f e and f
#' @return d
#' @export
#' @eval function_examples()
function2 <- function(C, e, f){
  return(C+e+f)
}

And now, the example is shared between these 2 functions!

I find this makes it pretty easy to centralize examples (or any shared documentation between functions), without having to rip your hair out repeating everything when updating.

like image 144
RoB Avatar answered Oct 24 '25 08:10

RoB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!