Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

r - S4 Classes: Multiple types per slot

Is it possible to create an S4 class, where one or more of the slots can be of multiple classes? For example. Let's say that you had a situation where data could be either a vector, or a data.frame.

exampleClass <- setClass("exampleClass",
    representation(raw=c("data.frame","numeric","character"),
    anotherSlot=c("data.frame","numeric")) 

Or, is this the type of situation where defining a sub-class / super-class becomes necessary?

PS: Searching for a useful tutorial on S4 classes produces limited results. Links to a good tutorial on S4 class creation/usage/documentation would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...