2

関数myFunctionがあり、同じ名前の S4 メソッドを作成する必要があります (理由は聞かないでください)。myFunction
の古い機能を維持したいと思います。

古い機能を維持する方法はありますか?

シグネチャが大きく異なる可能性があるため、この古い関数のジェネリックを設定したくありません...

4

1 に答える 1

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 

S4 関数に S3 関数と同じ型の引数をとらせたい場合は、次のようにして、引数のクラスを設定して、R が 2 つの関数のどちらを使用するかを割り出す方法を用意する必要があります。使用する予定です:

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
于 2011-12-27T09:10:44.980 に答える