5

如何测试对象是否是 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”类的对象.....

4

1 回答 1

3

S4 类(和参考类,就此而言,也许让一些人感到懊恼)是使用 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")

S4show用作 ; 的同义词(某种)print。有一个 S4show方法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"

而 for 的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"         

里面有肉methods::showDefault。我想你可以实现

setGeneric("isNotS4ClassDef",
    function(object) standardGeneric("isNotS4ClassDef"))

setMethod(isNotS4ClassDef, "ANY",
    function(object) TRUE)

setMethod(isNotS4ClassDef, "classRepresentation",
    function(object) FALSE)
于 2012-06-02T00:31:01.630 回答