2017-10-16 8 views
0

私はドキュメントで迷子になり、実際に何をすべきか分からなくなっています。解決策は環境を使用することだと思いますが、それが複雑ではないと感じたとしても、私はどのように理解できません。ここでS4メソッドサブセット汎用環境を置換する

は、2つのクラスを使用した簡単な例である:ここでは

Person <- setClass(  
    Class = "Person", 
    slots = c(name = "character", 
      id = "numeric", 
      age = "numeric")); 

PersonList <- setClass( 
    Class = "PersonList", 
    slots = c(datasetList = "list")); 

は、オブジェクトの作成です:

mary <- new("Person", name = "Mary", id = 1, age = 35); 
peter <- new("Person", name = "Peter", id = 2, age = 39); 
john <- new("Person", name = "John", id = 3, age = 25); 
employees <- new("PersonList", datasetList = list(mary, peter, john)); 

私は、年齢やID、およびメソッドを設定するために2つのメソッドを定義していますサブ設定PersonListのために:

setGeneric(name = "setAge<-", def = function(theObject, value){standardGeneric("setAge<-");}); 
setGeneric(name = "setid<-", def = function(theObject, value){standardGeneric("setid<-");}); 

setReplaceMethod(

    f = "setAge", 

    signature = "Person", 

    definition = function(theObject, value){ 
     [email protected] <- value; 
     return(theObject); 
    }); 

setReplaceMethod(

    f = "setid", 

    signature = "Person", 

    definition = function(theObject, value){ 
     [email protected] <- value; 
     return(theObject); 
    }); 

setMethod(

    f = "[[", 

    signature = c("PersonList", "ANY", "ANY"), 

    definition = function(x, i, j, ...){ 

     return([email protected][[i]]); 
    }); 

は、今ここでの問題は次のとおりです。

> setAge(employees[[1]]) <-56 
Error in `[[<-`(`*tmp*`, 1, value = new("Person", 
      name = "Mary", id = 1, : 
        [[<- defined for objects of type "S4" only for subclasses of environment 

私が正しく理解していれば、私のような何かを得るために環境を使用する必要があります。これは本当に複雑になっているドキュメントを通って行く

setMethod(

    f = "[[<-", 

    signature = c("PersonList", "ANY", "ANY"), 

    definition = function(x, i, j, ...){ 

     if environment is setid return(setId(x[[i]])) 
     if environment is setAge return(setAge(x[[i]])) 
    }); 

を。誰も私にこれを行う方法のヒントを与えることができますか?

ありがとうございます。

答えて

1

必要なのは、あなたのPersonListクラスの[[<-を定義することです:

setMethod(
    f = "[[<-", 
    signature = c("PersonList"), 
    definition=function(x,i,j,value) { 
     [email protected][[i]] <- value 
     return(x) 
    }) 

次に、あなたのコードが動作するはずです。あなたは、しかし、整合性をチェックするいくつかのコードを追加することができます。 inherits(value, "Person")およびmissing(j)のようになります。

+0

ありがとうございます!これは分かりにくいですが、うまくいきました。 – nicoluca

+0

はい、扱いにくいですが、コマンド行 'setAge(employees [[1]])<-56'は' employees @ datsetList'に書き込むべきであることをどのように知っていますか?それがあなたにとって有益だったら、自由にアップホート/回答を受け入れてください。 –

関連する問題