[Rd] dynamic array output by .C

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Apr 15 08:26:46 CEST 2005


On Thu, 14 Apr 2005, Simon Urbanek wrote:

> On Apr 14, 2005, at 6:01 PM, Tib wrote:
>
>> from the examples of Writing R Extensions,  I see one still has to
>> declare the size of arrays by NEW_NUMERIC(n) or
>> allocVector(REALSXP,n), how can I extend arrays?
>
> AFAIR you cannot extend vectors - it's like in C, you cannot extend allocated 
> memory without changing the pointer (i.g.). In order to get a vector of a 
> different size, you have to allocate a new one and copy the common contents. 
> If you are concerned about efficiency, why don't you just use arbitrary large 
> vectors and pass along the number of used elements? Then you can easily add 
> elements without re-allocating and just return the number of elements used 
> after the operation. That way you can control the probability of having to 
> allocate a new vector, possibly making it zero.

That's not a particularly good idea, as R keeps the length in the vector.
There is a way to do this, lengthgets().  That shortens vectors in one 
case, and reallocates and copies contents if extending.  Quite a lot of 
internal code does use long vectors and call lengthgets() at the end to 
shorten them to the right size.  (Other code duplicates that in 
lengthgets.)

As the name implies, this is the internal form of length(x) <- value.

Yes, it does change the pointer because it creates (potentially a new 
object).  But since an R object is just a few parameters (e.g. type and 
length) and a pointer, you could in fact extend an R vector `in place'.

-- 
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 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list