[Rd] append/concatenate an element to a list in C-language

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Oct 19 09:46:39 CEST 2007


On Thu, 18 Oct 2007, Robert Castelo wrote:

> dear people,
>
> i need to code a function in C working in R and receives two R SEXP
> objects as parameters, where one is a list and another is a vector of
> integers:
>
> void f(SEXP list, SEXP vector) {
>
>  ...
>
>  return list;
> }

You are returning an result in a function that returns void: the compiler 
will complain at you.

> and it should return the given list with the integer vector concatenated
> at the end (as the last element of the list). the list can be really big
> so i would not like to create a new list from scratch and copy all the
> elements, including the additional one. i'm also interested in knowing
> how should i properly handle protections of the SEXP objects when doing
> this.

If you study the R Internals manual you will see that there is no space on 
the original VECSXP for another element, so you do *need* to create a new 
VECSXP.  Note that creating a new list does not mean necessarily copying 
the elements, but you do need to think about the NAMED bits.

If you are doing this repeatedly you could think about exploiting the 
TRUELENGTH field to create a list with spare space that you could exploit 
in future calls.

It is often possible to avoid copying, but considerable care is needed to 
ensure that you do not end up with an object that does not effectively 
share elements with another user-visible one.

> i've been looking at the R source code for everything that has to do
> with CAR, CDR, CONS, and even found functions with promising names like
> listAppend or GrowList but i have not been able to figure this out nor i
> haven't been able to find any reference on how to do this by googling
> all around, so any help will be very much appreciated.

Those are for pairlists, not (vector) lists.


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