S4 Classes: Multiple types per slot

孤街浪徒 提交于 2019-11-28 23:18:19

R has 'class unions', so

setOldClass("data.frame")
setClassUnion("data.frameORvector", c("data.frame", "vector"))

The class data.frameORvector is virtual, so can't be instantiated but can be used in other slots (representation=), as a contained class (contains=), and for 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

Methods can be tricky to implement because all you know is that the slot contains one of the parent types of the class union.

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"

I actually find the documentation on ?Classes, ?Methods, ?setClass, and friends helpful. Hadley Wickham has a tutorial (the example on this page isn't that strong, it instantiates Person, whereas conceptually one would write a People to exploit R's vectorization strengths) and there is a section in this recent Bioconductor course. I don't think either goes in to detail about class unions.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!