如何测试对象是否是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
;在方法或类定义上没有那么多。是否可以使用 native 函数测试S4对象是否为实际对象? IE。当使用print(object)
时,输出以以下内容开头:类“foo”的对象.....
最佳答案
使用S4类(很酷(?)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
,有一个S4 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"
而
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)
关于r - 测试S4对象是否为实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10858807/