My package的DESCRIPTION
文件有 httr
在其 Imports 指令中:
Imports:
httr (>= 1.1.0),
jsonlite,
rstudioapi
httr
exports an S3method对于 length.path
.S3method(length,path)
它是 defined as :
#' @export
length.path <- function(x) file.info(x)$size
在我的包中,我有将类“路径”分配给的对象。每次我将类“路径”分配给任何对象时,无论我是否曾调用
length()
在对象上,这被打印到标准输出:Error in file.info(x) : invalid filename argument
这是每个人都可以运行的一些可重现的代码:
> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.5 (El Capitan)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] tools_3.3.1
> thing = 1:5
> class(thing) = 'path'
> requireNamespace('httr')
Loading required namespace: httr
> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.5 (El Capitan)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] httr_1.2.1 R6_2.1.2 tools_3.3.1
> thing = 1:5
> class(thing) = 'path'
Error in file.info(x) : invalid filename argument
我尝试在
try
中捕获它但这不起作用:set_class = function(obj, c) {
class(obj) = c
return(obj)
}
thing = 1:5
thing = try(set_class(thing, 'path'), silent=TRUE)
产量:
Error in file.info(x) : invalid filename argument
我试过
assignInNamespace
覆盖函数:base_length = function(obj) {
return(base::length(obj))
}
assignInNamespace('length.path', base_length, 'httr')
thing = 1:5
class(thing) = 'path'
但我得到
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
当我使用
httr
我的包中的函数我将它们与 httr::function
一起使用所以我不知道这是怎么回事length.path
函数泄漏到我的命名空间并覆盖了基本长度函数。我也试过明确的 @importFrom httr function
对于我使用而不是使用 httr::function
的每个函数但这也不起作用。我还发现了这个:
https://support.bioconductor.org/p/79059/
但解决方法似乎是编辑
httr
的源代码,因为我的包导入了它,所以我不能这样做。我怎样才能解决这个问题?
最佳答案
一种可能是创建一个函数 length.path()
在你自己的包里。如果您的 path
的基本类型-objects 与 base::length()
兼容您可以将其取消分类以避免无限递归:
length.path <- function(x) length(unclass(x))
但是,与直接调用
base::length()
相比,这可能会很慢。因为它复制对象并且需要两次方法分派(dispatch)。
关于r - 如何覆盖导入中列出的 R 包中的导出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39185171/