是否有可能创建一个或多个插槽可以是多个类的S4类?例如。假设您有一个数据可以是向量或数据帧的情况。
exampleClass <- setClass("exampleClass",
representation(raw=c("data.frame","numeric","character"),
anotherSlot=c("data.frame","numeric"))
或,这是必需定义子级/超级阶级的情况的类型吗?
ps:在S4类中搜索有用的教程会产生有限的结果。将不胜感激的是指向S4类创建/用法/文档的良好教程的链接。
r具有'class unions',所以
setOldClass("data.frame")
setClassUnion("data.frameORvector", c("data.frame", "vector"))
类data.frameORvector
是虚拟的,因此不能实例化,但可以在其他插槽(representation=
)中使用,作为包含类(contains=
),并且用于dispatch
A = setClass("A",
representation=representation(x="data.frameORvector"))
> A(x=1:3)
An object of class "A"
Slot "x":
[1] 1 2 3
> A(x=data.frame(x=1:3, y=3:1))
An object of class "A"
Slot "x":
x y
1 1 3
2 2 2
3 3 1
方法实现可能很棘手,因为您所知道的只是插槽包含类联合类的父类型之一。
setGeneric("hasa", function(object) standardGeneric("hasa"))
setMethod("hasa", "data.frameORvector", function(object) typeof(object@x))
> hasa(A(x=1:5))
[1] "integer"
> hasa(A(x=data.frame(y=1:5)))
[1] "list"
我实际上在?Classes
,?Methods
,?setClass
和朋友上找到了文档。哈德利·威克姆(Hadley Wickham)有一个教程(此页面上的示例不那么强,它实例化了Person
,而概念上,人们会编写People
来利用R的矢量化强度),并且在最近的生物导体课程中有一个部分。我认为这两个都不详细介绍班级工会。