5

show が S4 ジェネリックであり、S3 ディスパッチを使用して show 関数を機能させる方法が見つからないことを知って、私はかなり唖然としました。簡単なデモンストレーション:

> x <- 1:5
> xx <- structure(x,class="aClass")

> show.aClass <- function(object){
+     cat("S3 dispatching.\n")
+     print(object)
+ }

> xx
[1] 1 2 3 4 5

ここでは S3 ディスパッチはありません...

> setMethod("show","aClass",function(object){
+     cat("S4 dispatching.\n")
+     print(object)
+ })
in method for ‘show’ with signature ‘"aClass"’: no definition for class “aClass”
[1] "show"

> xx
[1] 1 2 3 4 5

どう思いました?

> print.aClass <- function(object){
+     cat("the print way...\n")
+     print(as.vector(object)) #drop class to avoid infinite loop!
+ }

> xx
the print way...
[1] 1 2 3 4 5

そして、印刷のためにそれは機能します。

S3 にとどまるかなりの理由があります (その大部分は、オブジェクトがブートストラップで広く使用されるため、オーバーヘッドの最小化です)。ここで別の show および print メソッドを定義するにはどうすればよいですか?

4

1 に答える 1

4

多分

setOldClass("aClass")
setMethod(show, "aClass", function(object) cat("S4\n"))
print.aClass <- function(object) { cat("S3... "); show(object) }

その後

> structure(1:5, class="aClass")
S3... S4

しかし、私はあなたが何をしたいのか本当に理解していません。

于 2011-12-07T17:38:59.493 に答える