如何设置已用包中已存在的通用方法?
How to set a generic method which already exists in a used package?
我正在修改一个S4-Class s4c
,想添加一个方法index
。由于 class 在我的自定义包中被广泛使用,重命名是别无选择的。所以我
setGeneric(where = environment(), name="index",
def=function(x,include.from=T, include.to=T) standardGeneric("index")
)
#' @export
setMethod(
f = "index",
signature = "s4c",
definition = function (x, include.from, include.to) {
...
方法有效。我的问题是我还想使用 zoo
-package,其中通用函数 index
已经存在。如果我加载并附加包,我会收到消息
The following objects are masked by ‘.GlobalEnv’:
index
并且,假设 z
是 class zoo
的对象,如果我输入 index(zoo)
我得到错误
Error in (function (classes, fdef, mtable) : unable to find an
inherited method for function ‘index’ for signature ‘"zoo"’
以前我使用更像 S3 的方法,比如
index.s4c <- function (x, include.from, include.to) {
...
它奏效了。但我想避免这种情况以获得 'pure' S4-class。
我尝试通过 where = environment()
使用本地环境无效。如何处理?
非常感谢,米卡
使用 setGeneric
创建一个 S4 泛型 index
,它使用 S3 泛型作为默认值,如下面标记为 ### 的行所示。然后通过使用组件 x
和该 class 的对象创建一个新的 class "A"
来测试它:
library(zoo)
setGeneric("index") ###
# test it out
setClass("A", representation(x = "numeric"))
setMethod("index", "A", function(x) x@x)
a <- new("A", x = 99)
index(a) # index works on an object of our new class A
## [1] 99
z <- zoo(100) # zoo object with value 100 and index 1
index(z) # index still works on zoo objects
## [1] 1
我正在修改一个S4-Class s4c
,想添加一个方法index
。由于 class 在我的自定义包中被广泛使用,重命名是别无选择的。所以我
setGeneric(where = environment(), name="index",
def=function(x,include.from=T, include.to=T) standardGeneric("index")
)
#' @export
setMethod(
f = "index",
signature = "s4c",
definition = function (x, include.from, include.to) {
...
方法有效。我的问题是我还想使用 zoo
-package,其中通用函数 index
已经存在。如果我加载并附加包,我会收到消息
The following objects are masked by ‘.GlobalEnv’: index
并且,假设 z
是 class zoo
的对象,如果我输入 index(zoo)
我得到错误
Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘index’ for signature ‘"zoo"’
以前我使用更像 S3 的方法,比如
index.s4c <- function (x, include.from, include.to) {
...
它奏效了。但我想避免这种情况以获得 'pure' S4-class。
我尝试通过 where = environment()
使用本地环境无效。如何处理?
非常感谢,米卡
使用 setGeneric
创建一个 S4 泛型 index
,它使用 S3 泛型作为默认值,如下面标记为 ### 的行所示。然后通过使用组件 x
和该 class 的对象创建一个新的 class "A"
来测试它:
library(zoo)
setGeneric("index") ###
# test it out
setClass("A", representation(x = "numeric"))
setMethod("index", "A", function(x) x@x)
a <- new("A", x = 99)
index(a) # index works on an object of our new class A
## [1] 99
z <- zoo(100) # zoo object with value 100 and index 1
index(z) # index still works on zoo objects
## [1] 1