gpt4 book ai didi

r - 测试 S4 对象是否是一个实例

转载 作者:行者123 更新时间:2023-12-04 20:50:54 25 4
gpt4 key购买 nike

如何测试对象是否为 实例 S4 类(class)的(不确定这是否是正确的术语)?我知道这个功能 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 对象是否为实际对象的 native 函数? IE。使用时 print(object)输出开始于:

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

最佳答案

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")

S4 使用 show作为 print 的同义词(有点) ;有一个 S4 show 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com