2011-12-27 42 views
2

我有一个函数myFunction我需要创建一个同名的S4方法(不要问我为什么)。
我想保留myFunction的旧功能。定义一个S4方法,如果已经有一个同名的函数

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

我宁愿没有设置一个通用的这个旧的函数作为签名可能会非常不同......

+0

基本上我想知道这是否是**冲突的情况下**(我已经删除了两个中的一个来解决) ,或者如果S4系统被设计来处理这个问题。我不想欺骗这个系统。 – RockScience 2011-12-27 03:50:20

回答

5

是的,有保持你的旧功能的一种方式。除非你希望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 

如果希望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 
+0

如果旧的myFun没有参数,会发生什么情况? – RockScience 2011-12-27 10:19:49

+0

你的意思是没有正式的参数(例如'search()'),或者没有默认参数?在任何情况下,它都不应该产生重大影响。 (不过,我会稍微编辑我的答案,以删除我给S3函数的无关缺省参数。) – 2011-12-27 10:22:38

+0

是的我的意思是没有正式的参数。它确实有所作为,因为在设置新方法时,R使用旧的myFun作为此方法的泛型。并且我收到一条错误消息,指出使用此功能无法完成调度。 从我现在了解的情况来看,这样的函数可能不是一个通用的候选对象,我不确定使用具有这个名称的方法不是一个好习惯。我认为这是一个冲突的情况。你有什么想法通常解决这个问题? – RockScience 2011-12-28 03:51:37

相关问题