Pergunta

I am trying to define an S4 class with a slot that is a vector containing objects from another S4 class. I am able to create a slot with a vector of integers:

> 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

When I try to use a vector of my own classes, though, I get an error:

> 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'.

I have also tried saying "class" and "class DistibutionConstraintObj" in the call to vector, with the same result.

How do I create a vector that contains S4 objects?

Thanks for your help. Barbara

Foi útil?

Solução

You can not create vector of objects, see ?vector:

mode
character string naming an atomic mode or "list" or "expression" or (except for vector) "any".

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'.

So either use a list, or use mode="list" if you still want to pre-allocate the memory:

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)))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top