Search code examples
rreference-class

Inheritance leads to error when using reference class


Here is the code:

Myclass = setRefClass("Myclass",
                       fields = list(
                           fa = "numeric",
                           fb = "numeric",
                           filename = "character",
                           data = "data.frame"
                       )
)


Myclass$methods(
    initialize = function(fa = 0, fb = 0, filename = "") {
        message("Initializing object in class...")
        .self$fa = fa
        .self$fb = fb
        .self$data = read.table(.self$filename, header=TRUE)
    }
)


# Myclass1 = setRefClass("Myclass1",
#                        fields = list(
#                            fc = "numeric"
#                        ),
#                        contains = "Myclass"
# )
# 
# Myclass1$methods(
#     initialize = function(..., fc = 0) {
#         message("Initializing object in class1...")
#         callSuper(...)
#         .self$fc = fc
#     }
# )
# 
# Myclass2 = setRefClass("Myclass3",
#                        fields = list(
#                            fd = "numeric"
#                        ),
#                        contains = "Myclass1"
# )
# 
# Myclass2$methods(
#     initialize = function(..., fe = 0) {
#         message("Initializing object in class2...")
#         callSuper(...)
#         .self$fe = fe
#     }
# )

This loads ok. But if you uncomment the subclasses R will complain when loading:

==> R CMD INSTALL --no-multiarch --with-keep.source testLoadRef

* installing to library ‘/Library/Frameworks/R.framework/Versions/3.1/Resources/library’
* installing *source* package ‘testLoadRef’ ...
** R
** preparing package for lazy loading
Initializing object in class...
Error in file(file, "rt") : invalid 'description' argument
Error : unable to load R code in package ‘testLoadRef’
ERROR: lazy loading failed for package ‘testLoadRef’
* removing ‘/Library/Frameworks/R.framework/Versions/3.1/Resources/library/testLoadRef’
* restoring previous ‘/Library/Frameworks/R.framework/Versions/3.1/Resources/library/testLoadRef’

Exited with status 1.

Solution

  • I do not know exactly why, but the parent's class initialize method is called by setRefClass. Therefore you should ensure that your parent class can be constructed with no arguments. e.g.:

    Myclass$methods(
      initialize = function(fa = 0, fb = 0, filename = "") {
        message("Initializing object in class...")
        .self$fa = fa
        .self$fb = fb
        if (nzchar(filename)) {
          .self$data = read.table(.self$filename, header = TRUE)
        }
      }
    )