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

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Fri, 19 Oct 2007 08:46:39 +0100 (BST)

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

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Fri 19 Oct 2007 - 08:00:08 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 25 Oct 2007 - 11:37:11 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.