测试S4对象是否是实例

时间:2012-06-02 00:14:50

标签: r cran s4

如何测试对象是否是S4类的实例(不确定这是否是正确的术语)?我知道函数isS4但是,对于类定义等也会返回true。例如:

traj <- setClass(
  Class="Trajectories",
  representation=representation(
    times = "numeric",
    traj = "matrix"
  )
)

trajclass <- getClass("Trajectories")
trajobject <- new(Class="Trajectories",times=c(1,3),traj=matrix(1:4,ncol=2))

isS4(traj)
isS4(trajclass)
isS4(trajobject)

我只对包含数据的对象感兴趣,在这种情况下为trajobject;与方法或类定义无关。是否有一个本机函数可用于测试S4对象是否是实际对象?即使用print(object)时,输出以:

开头

“foo”类的对象.....

1 个答案:

答案 0 :(得分:3)

使用S4类(cool(?)eh?)来定义S4类(和参考类,对于那个问题以及可能让一些人感到懊恼)

> class(trajclass)
[1] "classRepresentation"
attr(,"package")
[1] "methods"
> getClass(class(trajclass))
Class "classRepresentation" [package "methods"]

Slots:

Name:             slots         contains          virtual        prototype
Class:             list             list          logical              ANY

Name:          validity           access        className          package
Class: OptionalFunction             list        character        character

Name:        subclasses       versionKey           sealed
Class:             list      externalptr          logical

Known Subclasses: "ClassUnionRepresentation", "refClassRepresentation"

我认为你能做的最好的就是

isS4(trajclass) && !is(trajclass, "classRepresentation")

S4使用show作为print的同义词(某种类型); show的{​​{1}}方法是

classRepresentation

> selectMethod(show, class(traj)) Method Definition: function (object) { cat(gettextf("Class generator function for class \"%s\" from package \"%s\"\n", object@className, object@package)) show(as(object, "function")) } <bytecode: 0x1522d40> <environment: 0xf1d808> Signatures: object target "classGeneratorFunction" defined "classGeneratorFunction" 的{​​{1}}方法是默认值,即

show

将肉放在trajobject中。我想你可以实现

> selectMethod(show, class(trajobject))
Method Definition (Class "derivedDefaultMethod"):

function (object) 
showDefault(object, FALSE)
<bytecode: 0x1516d08>
<environment: namespace:methods>

Signatures:
        object        
target  "Trajectories"
defined "ANY"