Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the load order of files in an R package

Tags:

package

r

build

I'm writing a package for R in which the exported functions are decorated by a higher-order function that adds error checking and some other boilerplate code.

However, because this code is at the top-level it is evaluated after parsing. These means that the load order of the package files is important.

To give an equivalent but simplified example, suppose I have a package with two files (Negate2 and Utils), and I require Negate2.R to be loaded first for the function 'isfalse( )' to be defined without throwing an error.

# /Negate2.R
Negate2 <- Negate

# -------------------

# /Utils.R
istrue <- isTRUE
isfalse <- Negate2(istrue)

Is it possible to structure NAMESPACE, DESCRIPTION (collate) or another package file in order to change the load order of files? The internal working of the R package structure and CRAN are still black magic to me.

It is possible to get around this problem using awkward hacks, but the least repetitive way of solving this problem. The wrapper function must be a higher-order function, since it also changes the function call semantics of its input function. The package is code heavy (~6000 lines, 100 functions) so repetition would be...problematic.

Solution

As @Manetheran points out, to change the load order you just change the order of the file names in the DESCRIPTION file.

# /DESCRIPTION
Collate:
    'Negate2.R'
    'Utils.R'
like image 623
Róisín Grannell Avatar asked Aug 26 '13 09:08

Róisín Grannell


2 Answers

The Collate: field of the DESCRIPTION file allows you to change the order files are loaded when the package is built.

I stumbled across the answer to this question yesterday while reading up on Roxygen. If you've been documenting your functions with Roxygen, it can try to intelligently order your R source files in the Collate: field (based on where S4 class and method definitions are). This can be done by adding "collate" to the roclets argument of roxygenize. Alternatively if you're developing in RStudio there is a simple box that can be checked under Build->Configure Build Tools->Configure... (Button next to "Generate documentation with Roxygen").

like image 82
Scott Ritchie Avatar answered Nov 12 '22 20:11

Scott Ritchie


R loads files in alphabetical order. To change the order, Collate field could be used from the DESCRIPTION file.

roxygen2 provides an explicit way of saying that one file must be loaded before another: @include. The @include tag gives a space separated list of file names that should be loaded before the current file:

#' @include class-a.r
setClass("B", contains = "A")

If any @include tags are present in the package, roxygen2 will set the Collate field in the DESCRIPTION.

You need to run generation of roxygen2 documentation in order to changes to take effect.

like image 38
Kirill Kost Avatar answered Nov 12 '22 19:11

Kirill Kost