gpt4 book ai didi

r - 使用对象向量作为插槽创建 S4 对象

转载 作者:行者123 更新时间:2023-12-03 10:02:43 24 4
gpt4 key购买 nike

我正在尝试定义一个带有插槽的 S4 类,该插槽是包含来自另一个 S4 类的对象的向量。我能够创建一个带有整数向量的插槽:

> setClass("foo", slots=c(myInt = "vector"), prototype=list(myInt=vector("integer", 25)))
> new("foo")
An object of class "foo"
Slot "myInt":
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

但是,当我尝试使用我自己的类的向量时,出现错误:

> setClass("DistributionConstraintObj",
+ slots = c(p = "numeric", minSize = "integer", maxSize = "integer"))
> setClass("SampleSizeDistribution",
+ slots = c(sampleSizeDistDictionary = "vector", numEntries = "integer", limitSampleSize = "integer"),
+ prototype = list(sampleSizeDistDictionary = vector("DistributionConstraintObj", 25), numEntries = as.integer(0), limitSampleSize = as.integer(25)))
Error in vector("DistributionConstraintObj", 25) :
vector: cannot make a vector of mode 'DistributionConstraintObj'.

我也试过在调用 vector 时说“class”和“class DistibutionConstraintObj”,结果相同。

如何创建包含 S4 对象的向量?

感谢您的帮助。芭芭拉

最佳答案

您不能创建对象的矢量,请参阅 ?vector:

模式
命名原子模式或“列表”或“表达式”或(矢量除外)“任何”的字符串。

setClass("DistributionConstraintObj",slots = c(p = "numeric", minSize = "integer", maxSize = "integer"))
vector("DistributionConstraintObj", 25)
Error in vector("DistributionConstraintObj", 25) : vector: cannot make a vector of mode 'DistributionConstraintObj'.

所以要么使用列表,要么使用 mode="list"如果你仍然想预分配内存:

setClass("DistributionConstraintObj",
slots = c(p = "numeric", minSize = "integer", maxSize = "integer"))
setClass("SampleSizeDistribution",
slots = c(sampleSizeDistDictionary = "vector", numEntries = "integer", limitSampleSize = "integer"),
prototype = list(sampleSizeDistDictionary = vector("list", 25),
numEntries = as.integer(0), limitSampleSize = as.integer(25)))

关于r - 使用对象向量作为插槽创建 S4 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22830705/

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