[Rd] S4: what to put in initialize, validity and constructor?

From: <cgenolin_at_u-paris10.fr>
Date: Fri, 02 May 2008 16:40:30 +0200


Hi the list,

I have some trouble using validity, intialize and the constructor. More precisely, what should go where?
Here is a toy exemple (seams long, but the code is very simple):

I want to define an object with two slots a and b with the properties that b will be either empty or the scare of a. Example of valid object :

  a=  b=
  a=2 b=
  a=3 b=9

So I define my object and the validity function :

setClass(

    "A",
    representation(a="numeric",b="numeric"),     validity=function(object){

        cat("Validity\n")
        if(length(object_at_b)!=0){
            if(length(object_at_a)==0){stop("Can not have empty a and non 
emty b")}else{}
            if(object_at_a^2!=object_at_b){stop("b is not the scare of a")}else{}
        }else{}
        return(TRUE)

    }
)

It works:

new("A")
new("A",a=2,b=4)
try(new("A",b=4))
new("A",a=2)
try(new("A",a=2,b=3))


Then I define the initialize function. When b is givent but not a, the initialise function set a to sqrt(b).

setMethod(

    "initialize",
    "A",
    function(.Object,a,b){

        if(missing(a)&!missing(b)){

.Object_at_b <- b
.Object_at_a <- sqrt(b)
}else{} if(!missing(a)&missing(b)){
.Object_at_a <- a
}else{} if(!missing(a)&!missing(b)){
.Object@a <- a
.Object_at_b <- b
}else{} validObject(.Object) return(.Object)

    }
)

It is fine:

new("A")
new("A",a=2,b=4)
new("A",b=9)
new("A",a=2)
try(new("A",a=2,b=3))


Then I want to set the constructor

A <- function(a,b){

    return(new("A",a,b))
}

But this does not work:

A()
A(a=2,b=4)
A(b=9)
A(a=2)


The following does not work either:

A <- function(a=numeric(),b=numeric()){

    return(new("A",a,b))
}

A()
A(a=2,b=4)
A(b=9)
A(a=2)

So is there a way to define the constructor A without dealing again with all the missing&missing staff like in initialize?

Christophe



R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Fri 02 May 2008 - 15:38:29 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 03 May 2008 - 09:31:23 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive