[R] Q: replacing elements in an array

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Tue Aug 13 17:05:36 CEST 2002


On Tue, 13 Aug 2002, Laurent Gautier wrote:

> Dear all,
>
>
> I have a question about the way the replacement of elements in an array
> works in R (having a slight idea of the answer), and a question about
> the way to achieve my goals.
>
> If I have a 3 ways-array called 'a', the command
>
> a[1, , ] <- rnorm(10)  # assumes the size matches
>
> will result in having the whole object 'a' copied (since arrays are
> just 'vectors with dimensions' in R) ... and at some point
> two objects like 'a' will be in memory, right ? (this was the first
> question).

I don't think so.  See do_subassign and descendants.  It contains

    /* If there are multiple references to an object we must */
    /* duplicate it so that only the local version is mutated. */
    /* This will duplicate more often than necessary, but saves */
    /* over always duplicating. */
    /* FIXME: shouldn't x be protected? */

    if (NAMED(CAR(args)) == 2)
	x = SETCAR(args, duplicate(CAR(args)));

Now coercion can force a copy, but starting from a numeric array I think
your example does not duplicate.  And I can prove it:

> A <- array(0, dim=c(500, 500, 10))
> object.size(A)
[1] 20000128
> memory.size(T)
[1] 29028352
> A[1,,] <- 1
> memory.size(T)
[1] 29028352

so there was never a second copy.

> I have rather large arrays, and I would like to modify some of their
> elements in-situ (to save memory). Is there a way to do that ?

See above.  Do your own experiments / reading of code?

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list