4

我无法在我正在编写的 R 包中定义组泛型。

这是一个相当简单的例子:

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)))

如果我将此代码粘贴到 R 终端中,那么一切都会按预期工作:

> 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)

但是,一旦我尝试将其构建到一个包中,我就会遇到以下错误:

$ 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’

我正在使用 package.skeleton() 的默认输出,并添加了:

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

进入命名空间文件

知道我做错了什么吗?

4

1 回答 1

5

如果我在加载时运行代码,我可以让它工作。这里的关键是evalqOnLoad调用

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)))

})

在一个包'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)
于 2012-10-30T10:49:06.203 回答