如果已存在具有相同名称的函数,则定义S4方法

Roc*_*nce 2 methods r s4

我有一个函数myFunction,我需要创建一个具有相同名称的S4方法(不要问我为什么).
我想保留myFunction的旧功能.

有没有办法保持我的旧功能?

我不想为这个旧函数设置泛型,因为签名可能非常不同......

Jos*_*ien 6

是的,有一种方法可以保持旧功能.除非你希望S3和S4函数都接受相同类的相同数量的参数,否则它甚至都不复杂.

# Create an S3 function named "myFun"
myFun <- function(x) cat(x, "\n")

# Create an S4 function named "myFun", dispatched when myFun() is called with 
# a single numeric argument
setMethod("myFun", signature=signature(x="numeric"), function(x) rnorm(x))

# When called with a numeric argument, the S4 function is dispatched
myFun(6)
# [1]  0.3502462 -1.3327865 -0.9338347 -0.7718385  0.7593676  0.3961752

# When called with any other class of argument, the S3 function is dispatched
myFun("hello")
# hello 
Run Code Online (Sandbox Code Playgroud)

如果你确实希望S4函数采用与S3函数相同类型的参数,你需要做类似下面的事情,设置参数的类,以便R有一些方法来判断你的两个函数中的哪一个打算使用:

setMethod("myFun", signature=signature(x="greeting"), 
          function(x) cat(x, x, x, "\n"))

# Create an object of class "greeting" that will dispatch the just-created 
# S4 function
XX <- "hello"
class(XX) <- "greeting"
myFun(XX)
# hello hello hello 

# A supplied argument of class "character" still dispatches the S3 function
myFun("hello")
# hello
Run Code Online (Sandbox Code Playgroud)