2011-10-21 121 views
5

通過哈德利韋翰的S4維基展望: https://github.com/hadley/devtools/wiki/S4S4構造函數和原型

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

我們如何可以設計的人一個構造函數(像這樣)

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" 
+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提供的...。還放棄原型並使用length([email protected]) == 0作爲該字段未初始化的指示,使用People類而不是Person,反映了R的向量化結構,並且在構造函數中使用...,所以派生類也可以使用構造函數。

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)) 
相關問題