0

I have some code that I want to run when a user loads my package. That code includes creating a reference class (Parent) and sourceing a file stored under inst. Here is a toy version:

Parent <- setRefClass("Parent",
    methods = list(
        initialize = function() { }
    )
)

.onLoad <- function(libname, pkgname){
    temp <- new.env()
    file <- system.file("example.R", package = "examplerefclass")
    sys.source(file, envir = temp)
    objects <- ls(temp)
    print(objects)
}

example.R file defines a reference class.

library(methods)
Child <- setRefClass("Child", contains = "Parent")

I had to call library(methods) because the methods package is not defined when .onLoad runs. So, this works, but I get an error when I run R CMD check and I don't know how to avoid it.

Error : .onLoad failed in loadNamespace() for 'examplerefclass', details:
  call: initialize(value, ...)
  error: attempt to apply non-function

The error refers to the initialize function defined in Parent. Somehow, the Child class is not seeing it during the R CMD check process, but it works in interactive mode.

I know what I'm doing is unconventional but I don't see any other way to meet my design requirements. For a number of reasons example.R must be stored in inst, and I need to check what objects are defined in example.R without sourcing it in the current environment (if the right objects are defined, I then go on to source example.R but that is another story).

Any suggestions on how to fix this?

I've set up the toy example in a git repo for easy testing: https://github.com/nachocab/examplerefclass

nachocab
  • 13,328
  • 21
  • 91
  • 149
  • 1
    Does it work if `example.R` is put in the `R` folder? Having R code outside of that location is liable to break things. – Richie Cotton Jul 01 '13 at 09:50
  • Also, consider having an explicit dependency on the `methods` package in your `DESCRIPTION` file. – Richie Cotton Jul 01 '13 at 09:51
  • Thanks for your comment. R loads `methods` by default. The only reason why I make the explicit call is because it is loaded *after* `.onLoad`. Also, if I put `example.R` in the `R` folder the example no longer makes sense. – nachocab Jul 01 '13 at 12:10
  • I'm not quite sure what you are trying to do with `example.R`. If it demonstrates a function, then it belongs in that function's `Rd` file in the `man` directory. If it is a longer example then it should be in a demo (in the `demo` dir) or a vignette (in the `vignettes` dir). In any case, you shouldn't be calling it from `.onLoad`. – Richie Cotton Jul 01 '13 at 12:40
  • The point of the package I'm building is to allow users to share visualization functions (bit.ly/rclickme) without having them create individual R packages. `example.R` would provide R helper functions to use with a specific visualization. I know this goes beyond conventional R usage, that's why I wanted to conform as much as possible to R CMD check. – nachocab Jul 01 '13 at 13:30

0 Answers0