在R包中定义组通用函数

时间:2012-09-11 11:14:39

标签: r s4

我在编写正在编写的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文件

知道我做错了吗?

1 个答案:

答案 0 :(得分: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)