我在我正在编写的 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:]]+")

进入 NAMESPACE 文件

知道我做错了什么吗?

最佳答案

如果我在加载时运行代码,我可以让它工作。这里的关键是 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)

关于r - 在 R 包中定义组通用函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12368439/

10-12 17:14