[R] creating list with 200 identical objects
Wacek Kusnierczyk
Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Mon Jun 1 23:36:27 CEST 2009
Wacek Kusnierczyk wrote:
>
> consider:
>
> setClass('foo',
> representation=representation(content='environment'))
> setMethod('initialize', 'foo', function(.Object) {
> .Object at content = new.env()
> .Object at content$name = 'foo'
> .Object })
>
> foos = rep(list(new('foo')), 2)
> foos[[1]]@content$name = 'bar'
> foos[[2]]@content$name
> # 'bar'
>
> of course, because you have just one object twice on the list, its
> content is an environment, and with environments r does not pretend to
> be functional. but:
>
> foos = lapply(1:2, function(x) new('foo'))
> foos[[1]]@content$name = 'bar'
> foos[[2]]@content$name
> # 'foo'
>
> of course, because you have two distinct objects, and assignment to one
> of them has no effect on the other. similarly if 'foo' is defined as
> follows:
>
> setClass('foo',
> representation=representation(content='environment'))
> setMethod('initialize', 'foo', function(.Object) {
> .Object at content$name = 'foo'
> .Object })
>
> or as follows:
>
> setClass('foo',
> representation=representation(content='environment'),
> prototype=list(content={
> e=new.env()
> e$name='foo'
> e }))
>
>
actually, not the last one; i got caught by that redefining 'foo' with
setClass does not remove the initializer. so here's another situation
(best to execute in a fresh session) you should beware:
setClass('foo',
representation=representation(content='environment'),
prototype=list(content={
e=new.env()
e$name='foo'
e }))
foos = lapply(1:2, function(x) new('foo'))
foos[[1]]@content$name = 'bar'
foos[[2]]@content$name
# "bar"
in this case, even if you're careful enough to create two objects, they
share the representation because they both get it from the same prototype.
vQ
More information about the R-help
mailing list