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

时间:2014-04-03 07:30:43

标签: r s4

我正在尝试使用插槽定义一个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对象的矢量?

感谢您的帮助。 巴巴拉

1 个答案:

答案 0 :(得分:2)

您无法创建对象矢量,请参阅?vector:

模式
命名原子模式的字符串或" list"或"表达"或(除了矢量)"任何"。

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