Designers and prototypes S4

View via the 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")

How can we create a constructor for Person (for example)

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

which does not do this:

> 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"
+5
source share
2 answers

It looks like the answer is right in your example:

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

gives

> 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

However, it is pretty un-S4 and duplicates the default values ​​already assigned in the class definition. You might prefer to do

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

and sacrifice the ability to call without named arguments?

+4
source

, ... by @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))
+3

All Articles