是否可以创建一个S4类,其中一个或多个插槽可以是多个类?例如.假设您遇到的情况是数据可能是向量,也可能是data.frame.
exampleClass <- setClass("exampleClass",
representation(raw=c("data.frame","numeric","character"),
anotherSlot=c("data.frame","numeric"))
Run Code Online (Sandbox Code Playgroud)
或者,这是否需要定义子类/超类?
PS:搜索有关S4类的有用教程会产生有限的结果.将非常感谢有关S4类创建/使用/文档的良好教程的链接.
Mar*_*gan 30
R有'阶级工会',所以
setOldClass("data.frame")
setClassUnion("data.frameORvector", c("data.frame", "vector"))
Run Code Online (Sandbox Code Playgroud)
该类data.frameORvector是虚拟的,因此无法实例化但可以在其他slot(representation=)中使用,作为包含的类(contains=),以及用于调度
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
Run Code Online (Sandbox Code Playgroud)
方法实现起来可能很棘手,因为您只知道插槽包含类联合的父类型之一.
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"
Run Code Online (Sandbox Code Playgroud)
我居然就找到文档?Classes,?Methods,?setClass,和朋友们有所帮助.Hadley Wickham有一个教程(这个页面上的例子不是很强大,它实例化Person,而概念上人们会编写一个People来利用R的矢量化强度),最近的Bioconductor课程中有一节.我不认为要详细介绍班级联盟.