浏览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"

最佳答案

看起来答案就在您的示例中:

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",...)

并牺牲了不使用命名参数进行调用的能力?

关于r - S4构造函数和原型(prototype),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7852745/

10-12 23:35