6

Hadley Wickham の S4 wiki を見る: 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 のコンストラクターをどのように設計できますか (このように)

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

それはこれをしません:

> 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"
4

2 に答える 2

4

...@themel による使用の提案よりも、エンドユーザーに引数の型に関するいくつかのヒントを提供したいと思います。また、プロトタイプを放棄しlength(x@name) == 0、フィールドが初期化されていないことを示すために使用し、Peopleではなくクラスを使用しPerson、R のベクトル化された構造を反映し...、コンストラクターで使用するため、派生クラスもコンストラクターを使用できます。

setClass("People",
    representation=representation(
        firstNames="character",
        ages="numeric"),
    validity=function(object) {
        if (length(object@firstNames) != length(object@ages))
            "'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))
于 2011-10-21T18:34:17.560 に答える
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",...)

名前付き引数なしで呼び出す機能を犠牲にしますか?

于 2011-10-21T17:11:57.817 に答える