问题
This maybe trivial but I haven't found anything online. Is it possible to create a vector of empty S4 objects in R? Something like:
s4Vec<-rep(emptyS4Object,10)
Thanks
回答1:
Like this:
s4Vec <- lapply( rep("yourClass", 10), new )
?
回答2:
I'd be tempted to go with
.A <- setClass("A", representation(x="integer"))
a <- list(.A())[rep(1, 100)]
which makes a single instance (using the convenient generator returned by setClass
) and then replicates that object as R would replicate any other object in a list -- the elements of a
are actually the same instance, marked ready to be duplicated when changed; you can see this from
> .Internal(inspect(a))
@4e3bc1d8 19 VECSXP g0c2 [NAM(2)] (len=2, tl=0)
@60b738b8 25 S4SXP g0c0 [OBJ,NAM(2),S4,gp=0x10,ATT]
ATTRIB:
[...]
@60b738b8 25 S4SXP g0c0 [OBJ,NAM(2),S4,gp=0x10,ATT]
where @4e3bc1d8
is the address of the list and @60b738b8 25 S4SXP g0c0 [OBJ,NAM(2),S4,gp=0x10,ATT]
mark the start of the description of each S4 element, all actually at the same location in memory @60b738b8
and with the so-called NAMED field set to 2 NAM(2)
. Note that changing a single element of the list likely triggers a copy of the entire list.
But if each of your "A" objects are meant to represent say a "row" in a traditional data base, then you should re-think your design and have "A" represent the entire table and slots represent columns. So you'd just create one "A", rather than many, and populate it's slots with equal-length vectors. This will be memory efficient, and will set you up for efficient vectorized calculations down-stream, rather than iterations.
来源:https://stackoverflow.com/questions/16366739/create-a-vector-of-empty-s4-objects