How to create a slot in the S4 class for reliable linear models?

I would like to create an S4 class with slots that can contain robust linear models.

Reliable linear models are a type of linear model from the MASS package. They carry all the information that the linear model has, and a little more.

 library(MASS) x <- 1:5 y <- 1:5 mylm <- lm(x~y) myrlm <- rlm(x~y) 

Here is my class:

 .MyClass <- setClass("MyClass", list(a="lm", id="numeric")) 

Even if .MyClass(a=mylm, id=1) creates the expected object, initializing the object with rlm fails:

 > .MyClass(a=myrlm, id=1) Error in validObject(.Object) : invalid class "MyClass" object: 1: invalid object for slot "a" in class "MyClass": got class "rlm", should be or extend class "lm" invalid class "MyClass" object: 2: invalid object for slot "a" in class "MyClass": got class "lm", should be or extend class "lm" 

I would think that since is(myrlm, "lm") returns TRUE , there would be no problem and the object could fit in a slot. Also, since it tells me that I created an invalid object twice, why does the second say that lm not itself? Is it because lm is a virtual class?

I tried setting a="list" in the view (since lm and rlm are both lists), but this causes a similar error. Does the slot require a different type of class? I also tried setting a="rlm" , but the rlm class is not defined.

+5
source share
1 answer

The problem is that rlm objects have two S3 classes. I suggest, as a workaround, define the constructor and change the class of slots before creating the object. Something like that:

  library(MASS) x <- 1:5 y <- 1:5 mylm <- lm(x~y) myrlm <- rlm(x~y) .MyClass <- setClass("MyClass", list(a="lm", id="numeric")) MyClass<-function(a,id) { if (!is(a,"lm")) stop("error") class(a)<-"lm" new("MyClass",a=a,id=id) } MyClass(myrlm,1) 
+1
source

Source: https://habr.com/ru/post/1203746/


All Articles