Question

I'm having trouble defining a group generic within an R package that I'm writing.

Here is a fairly minimal example:

setGroupGeneric('FooBarFunctions', function(x, y) NULL)

setGeneric('foo', group = 'FooBarFunctions', function(x, y) standardGeneric('foo'))
setGeneric('bar', group = 'FooBarFunctions', function(x, y) standardGeneric('bar'))

setMethod('foo', signature(x = 'ANY', y = 'ANY'),
function(x, y)
  cat(sprintf('foo,ANY (%s),ANY (%s)\n', x, y)))

setMethod('bar', signature(x = 'ANY', y = 'ANY'),
function(x, y)
  cat(sprintf('bar,ANY (%s),ANY (%s)\n', x, y)))

setMethod('FooBarFunctions', signature(x = 'character', y = 'ANY'),
function(x, y)
  cat(sprintf('FooBarFunctions,character (%s),ANY (%s)\n', x, y)))

If I paste this code into an R terminal, then everything works as expected:

> foo(1, 2)
foo,ANY (1),ANY (2)
> bar(1, 2)
bar,ANY (1),ANY (2)
> foo('a', 2)
FooBarFunctions,character (a),ANY (2)
> bar('a', 2)
FooBarFunctions,character (a),ANY (2)

However, as soon as I try to build this into a package I run into the following error:

$ R CMD INSTALL .
* installing to library ‘~/R/x86_64-pc-linux-gnu-library/2.15’
* installing *source* package ‘anRpackage’ ...
** R
** preparing package for lazy loading
** help
No man pages found in package  ‘anRpackage’ 
*** installing help indices
** building package indices
** testing if installed package can be loaded
**Error in .setupMethodsTables(generic) : 
  trying to get slot "group" from an object of a basic class ("NULL") with no slots**
Error: loading failed
Execution halted
ERROR: loading failed
* removing ‘~/R/x86_64-pc-linux-gnu-library/2.15/anRpackage’

I'm using the default output from package.skeleton(), having added:

exportPattern("^[[:alpha:]]+")

into the NAMESPACE file

Any idea what I'm doing wrong?

Was it helpful?

Solution

I can get this to work if I run the code on load. The key here is the evalqOnLoad call

evalqOnLoad({

    setGroupGeneric('FooBarFunctions', function(x, y) NULL)

    setGeneric('foo', group = 'FooBarFunctions', function(x, y) standardGeneric('foo'))
    setGeneric('bar', group = 'FooBarFunctions', function(x, y) standardGeneric('bar'))

    setMethod('foo', signature(x = 'ANY', y = 'ANY'),
    function(x, y)
      cat(sprintf('foo,ANY (%s),ANY (%s)\n', x, y)))

    setMethod('bar', signature(x = 'ANY', y = 'ANY'),
    function(x, y)
      cat(sprintf('bar,ANY (%s),ANY (%s)\n', x, y)))

    setMethod('FooBarFunctions', signature(x = 'character', y = 'ANY'),
    function(x, y)
      cat(sprintf('FooBarFunctions,character (%s),ANY (%s)\n', x, y)))

})

in a package 'bla' :

> require( bla )
Le chargement a nécessité le package : bla
> foo(1, 2 )
foo,ANY (1),ANY (2)
> bar(1, 2 )
bar,ANY (1),ANY (2)
> foo("a", 2 )
FooBarFunctions,character (a),ANY (2)
> bar("a", 2 )
FooBarFunctions,character (a),ANY (2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top