微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

`vec_arith` 包的双重调度错误

如何解决`vec_arith` 包的双重调度错误

我正在尝试实现 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,...){
  stop_incompatible_op(op,y)
}

#' @export
vec_arith.Foo.Foo <- function(op,...) {
  switch(op,"+" = foo(vec_data(x)+vec_data(y)),stop_incompatible_op(op,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)

解决方法

我想通了...

您至少需要在 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,y))
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。