2016-11-14 4 views
1

は、2つのオブジェクトがあるとしましょう:Rの複数のクラスに対して "ネスト"メソッドを持つことは可能ですか?

a = 1:3 
class(a) = append("myclass", class(a)) 
class(a) 
[1] "myclass" "integer" 

b = c("a", "b", "c") 
class(b) = append("myclass", class(b)) 
class(b) 
[1] "myclass" "character" 

「MyClassの」と他の/基本的なカスタムクラスの両方を依存することになるネストされたメソッドを定義することが可能ですか?例えば。

print.myclass.integer = function(x) { some code } 
print.myclass.character = function(x) { different code } 

もしそうなら、正しい手順は何ですか?

+1

S3にはないと思います。 S4は引数に基づいて複数のディスパッチを行いますが、これはあなたが思うものではありません。それを超えるとおそらく参照クラスやR6に向ける必要があるでしょう。 – joran

答えて

1

print.myclassのオブジェクトの他のクラスをチェックすることで回避できます。例えば:

print.myclass<-function(x,...) { 
    if ("integer" %in% class(x)) print("some code") else 
     if ("character" %in% class(x)) print("some other code") 
} 
a 
#[1] "some code" 
b 
#[1] "some other code" 
+1

また、dispatch-yを保つために、 'if("%class(x)の整数%)print.myclass.integer(x、...)) ' – Gregor

+0

これはかなり柔軟性があるようです。 – jakub

0

は、あなただけの巣UseMethod()に持っ倍数クラスのメソッドを入れ子にしているために:あなたはprint()を使用する場合

print.myclass <- function(x) { 
    UseMethod("print.myclass", x) 
} 

print.myclass.integer <- function(x) { 
    print(paste("This method only prints the higher 'x': ", max(x))) 
} 

print.myclass.character <- function(x) { 
    cat("This method scrambles the 'x' values:\n") 
    print(sample(x, length(x))) 
} 

print(a) # [1] "This method only prints the hihger 'x': 3" 
print(b) #This method scrambles the 'x' values: 
     # [1] "a" "c" "b" 

、それはmyclass方法を確認するであろう、UseMethod()を呼び出します。その後、もう一度UseMethod()が呼び出され、print.myclass関数の2番目のクラス(integerまたはcharacter)へのメソッドがチェックされます。

?UseMethod,methods(print)およびThe R Language Definition、p.28-31を参照してください。それは私を助けた。

+1

興味深いパッケージ内のメソッドをエクスポートするときに、このアプローチに問題がありますか? – jakub

+0

私には分かりませんが、なぜそこにあると思いますか? –

関連する問題