Search code examples
rpackager6

Include R6 class object in R package


I am currently developing an R package and I want to include an object of class R6, which is basically an environment, so that users can easily use it (same way it works with datasets in a package).

I have an R6ClassConstructor Gridworld:

Gridworld <- R6::R6Class( ... )

Then I can create a new instance using grid = Gridworld$new(), which generates an R6 class. I then want to save this object grid in the package, so that a user can use it by just typing in grid.

I tried to save grid as an .RData object in the /data folder and document the R6 class in the /R folder:

#' Gridworld
#' @format R6 class
"grid"

but this causes an error in devtools::document: file 'grid.RData' has magic number 'X'

How can I include this R6 class object in the package?


Solution

  • Maybe it would be best to call new when the package is loaded. This way you will not have any troubles regarding reference semantics.

    See the answer here

    In your case, this would look like

    # file R/zzz.R
    .onLoad <- function(libname, pkgname){
      gridworldInstance <- Gridworld$new() 
    }
    
    # documentation
    #' Instance of grid world
    #' 
    #' some description
    #'
    #' @name gridworldInstance
    NULL
    #' @export