Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R package - @example function can't be tested if the function is not exported

Tags:

r

I'm developping a custom R package with RStudio, documented with roxygen2.

Please consider this function:

#' Get "test"
#'
#' @return String
#' @export
#'
#' @examples getTest()
getTest <- function() {
  return("test")
}

If I run a R CMD check with the function documentation written as above, everything is fine, the check is passed with success.

Now, if I remove the @export (because I don't want this function to be visible from outside the package), I get the following error:

* checking examples ... ERROR
Running examples in 'MyPackageName-Ex.R' failed
The error most likely occurred in:

> ### Name: getTest
> ### Title: Get "test"
> ### Aliases: getTest
> 
> ### ** Examples
> 
> getTest()
Error: could not find function "getTest"
Execution halted

It looks like the test of the functions in @examples is run from outside the package!?

How do I test the examples of non-exported function?

like image 532
Blacksad Avatar asked Dec 10 '15 08:12

Blacksad


1 Answers

I respectfully disagree with @Roland's comment, in that having an example proximal to the documentation is helpful to know what the heck I was thinking 6 months down the road. Having it checked automatically with check() means it has a fighting chance to stay synced with the code. I have not seen any prohibition or exhortation in the R docs against documenting non-exported functions.

Thankfully, you can call the unexported function with the triple-colon ::: operator. Example:

 ##' Drop specified dimension from an array
 ##'
 ##' Like drop(x) but only dropping specified dimensions.
 ##' There is no testing that the specified dimensions are actually     singletons.
 ##' @param x array of at least d dimensions
 ##' @param d dimension(s) to drop
 ##' @return array x
 ##' @examples
 ##' x = array(1:4, dim=c(1, 2, 1, 2))
 ##' dx = MAST:::Drop(x, 1)
 ##' stopifnot(all(dim(dx)==c(2,1,2)))
 ##' 
    Drop <- function(x, d){
        dim(x) <- dim(x)[-d]
        x
    }
like image 78
Andrew M Avatar answered Nov 20 '22 04:11

Andrew M