Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sometimes i cant set a class definition as slot in a s4 class? [closed]

Tags:

class

r

s4

r=ks.test(x=rnorm(100), "dnorm")
class(r)
[1] "htest"


## Doesnt work, "htest" is class in stats
setClass("Jergon", representation(fit="htest"))
[1] "Jergon"
Warning message:
undefined slot classes in definition of "Jergon": fit(class "htest")


## works "lm" 
setClass("Jergon", representation(am="lm"))
[1] "Jergon"
like image 425
Actuzo Avatar asked Sep 28 '12 08:09

Actuzo


1 Answers

The result of ks.test is (from the documentation):

A list with class "htest"

So, actually "htest" is not a formal class defined into a package, but simply, the class attribute of the list returned by ks.test, is set to "htest".

To give an example, also the following code does't work (because myclass is not a formal class):

obj = list(foo=123)
class(obj) <- "myclass"

class(obj)
[1] "myclass"

setClass("Jergon", representation(foo="myclass"))
[1] "Jergon"
Warning message:
undefined slot classes in definition of "Jergon": foo(class "myclass") 

To check if a class is formally defined (and can be used as representation), you can use getClassDef, i.e. :

> getClassDef('htest')
NULL

> getClassDef('lm')
Virtual Class "lm" [package "methods"]

Slots:

Name:   .S3Class
Class: character

Extends: "oldClass"

Known Subclasses: 
Class "mlm", directly
Class "aov", directly
Class "glm", directly
Class "maov", by class "mlm", distance 2
Class "glm.null", by class "glm", distance 2

EDIT :

As correctly pointed out by @Martin Morgan, you can formally register an old-style S3 class using setOldClass. In fact the documentation says:

Register an old-style (a.k.a. ‘S3’) class as a formally defined class. The Classes argument is the character vector used as the class attribute; in particular, if there is more than one string, old-style class inheritance is mimicked. Registering via setOldClass allows S3 classes to appear in method signatures, as a slot in an S4 class, or as a superclass of an S4 class.

Hence, this code works fine:

> setOldClass("htest")
> setClass("Jergon", representation(fit="htest"))
[1] "Jergon"
like image 125
digEmAll Avatar answered Sep 19 '22 00:09

digEmAll