0

我正在尝试实施该vctrs软件包,但具体而言,我正在尝试使vec_arith双重调度正常工作。

如果我将它加载到全局环境中,下面的示例代码可以工作,但是如果从它自己的包命名空间中调用,它似乎找不到正确的调度。

#' @import vctrs
NULL

#' @export
foo <- function(x = double()) new_vctr(x, class = "Foo")

#' @export
vec_arith.Foo <- function(op, x, y, ...){
  UseMethod("vec_arith.Foo", y)
}

#' @export
vec_arith.Foo.default <- function(op, x, y, ...){
  stop_incompatible_op(op, x, y)
}

#' @export
vec_arith.Foo.Foo <- function(op, x, y, ...) {
  switch(op,
         "+" = foo(vec_data(x)+vec_data(y)),
         stop_incompatible_op(op, x, y))
}

# After build

library(foo)
foo(1) + foo(2)
#Error in UseMethod("vec_arith.Foo", y) : 
#  no applicable method for 'vec_arith.Foo' applied to an object of class "c('Foo',     'vctrs_vctr')"
foo(1) + 2
#Error in UseMethod("vec_arith.Foo", y) : 
#  no applicable method for 'vec_arith.Foo' applied to an object of class "c('double', 'numeric')"
2 + foo(1)
#Error: <double> + <Foo> is not permitted
#Run `rlang::last_error()` to see where the error occurred.

如果你只用这个文件构建一个包,有人可以告诉我这是否可以重现吗?

我不知道它是否重要,但描述文件如下所示:

Package: foo
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line)
    Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.1.1
Imports:
  vctrs
Roxygen: list(markdown = TRUE)
4

1 回答 1

0

我想到了...

至少您需要包含以下文档,roxygen2以便 S3 方法正确导出

#' @method vec_arith.Foo Foo
#' @export
vec_arith.Foo.Foo <- function(op, x, y, ...) {
  switch(op,
         "+" = foo(vec_data(x)+vec_data(y)),
         stop_incompatible_op(op, x, y))
}
于 2021-03-14T15:19:21.273 回答