2011-10-21 6 views
5

S4コンストラクタとハドレーウィッカムのS4のWikiを通じて探しプロトタイプ

:我々はこれを実行しません(このような)者のコンストラクタ

Person<-function(name=NA,age=NA){ 
new("Person",name=name,age=age) 
} 

を設計することができますどのように https://github.com/hadley/devtools/wiki/S4

setClass("Person", representation(name = "character", age = "numeric"), 
    prototype(name = NA_character_, age = NA_real_)) 
hadley <- new("Person", name = "Hadley") 

> Person() 
Error in validObject(.Object) : 
    invalid class "Person" object: 1: invalid object for slot "name" in class "Person": got class "logical", should be or extend class "character" 
invalid class "Person" object: 2: invalid object for slot "age" in class "Person": got class "logical", should be or extend class "numeric" 
+0

更新:setClassは、デフォルトコンストラクタを返します。 人< - SetClass( "人物"、...) – ctbrown

答えて

4

答えはあなたの例のとおりです:

Person<-function(name=NA_character_,age=NA_real_){ 
new("Person",name=name,age=age) 
} 

利回り

> Person() 
An object of class "Person" 
Slot "name": 
[1] NA 

Slot "age": 
[1] NA 

> Person("Moi") 
An object of class "Person" 
Slot "name": 
[1] "Moi" 

Slot "age": 
[1] NA 

> Person("Moi", 42) 
An object of class "Person" 
Slot "name": 
[1] "Moi" 

Slot "age": 
[1] 42 

しかし、それはかなり非S4で、すでにクラス定義に割り当てられたデフォルト値を複製します。

Person <- function(...) new("Person",...) 

名前付き引数なしで呼び出す機能を犠牲にしないでください。

3

@themelで...を使用する提案よりも、エンドユーザーに引数の種類に関するヒントを与えたいと考えています。また、プロトタイプを避けて、PersonではなくPeopleクラスを使用し、Rのベクトル化された構造を反映し、...をコンストラクタに使用することで、フィールドが初期化されていないことを示すようにlength([email protected]) == 0を使用すると、コンストラクタも使用できます。

setClass("People", 
    representation=representation(
     firstNames="character", 
     ages="numeric"), 
    validity=function(object) { 
     if (length([email protected]) != length([email protected])) 
      "'firstNames' and 'ages' must have same length" 
     else TRUE 
    }) 

People = function(firstNames=character(), ages=numeric(), ...) 
    new("People", firstNames=firstNames, ages=ages, ...) 

そして

People(c("Me", "Myself", "I"), ages=c(NA_real_, 42, 12)) 
関連する問題