[A programming question moved from R-help]

On Fri, 19 Jan 2007, Markus Schmidberger wrote:

> Hello,
>
> I try to write an extension in C, to get a faster functions.
> Therefore I have to add an element (vector) to a vector. The command in
> R is very simple: x = c(x,a)

I don't see how you are going to code this in C appreciably faster than 
the R developers already have.

> But in C I have the problem to reallocate my vector for getting more
> space. Everything I tried, I get a "Segmentation fault".

We have no idea how you are trying to do this, or even which interface 
(.C, .Call, .External) you are trying to use.

> So, how can I combine two vectors in C and give the result back to R
> (return(x))?

The code below is just a beginning (it does no coercion, there are missing 
cases and it can be improved by caching e.g. REAL(a)), but can be used by

> dyn.load("my_c.so")
> my_c <- function(a, b) .Call("my_c", a, b)

% cat my_c.c

#include <R.h>
#include <Rinternals.h>

SEXP my_c(SEXP a, SEXP b)
{
     SEXP ans;

     int i, na, nb;
     if(TYPEOF(a) != TYPEOF(b)) error("type mismatch");
     switch(TYPEOF(a)) {
     case LGLSXP:
     case INTSXP:
     case REALSXP:
     case STRSXP:
        break;
     default:
        error("unimplemented type");
     }
     na = LENGTH(a); nb = LENGTH(b);
     PROTECT(ans = allocVector(TYPEOF(a), na+nb));
     switch(TYPEOF(a)) {
     case LGLSXP:
     case INTSXP:
        for(i = 0; i < na; i++) INTEGER(ans)[i] = INTEGER(a)[i];
        for(i = 0; i < nb; i++) INTEGER(ans)[na+i] = INTEGER(a)[i];
        break;
     case REALSXP:
        for(i = 0; i < na; i++) REAL(ans)[i] = REAL(a)[i];
        for(i = 0; i < nb; i++) REAL(ans)[na+i] = REAL(a)[i];
        break;
     case STRSXP:
        for(i = 0; i < na; i++) SET_STRING_ELT(ans, i, STRING_ELT(a, i));
        for(i = 0; i < nb; i++) SET_STRING_ELT(ans, na+i, STRING_ELT(a, i));
        break;
     }
     UNPROTECT(1);
     return ans;
}


-- 
Brian D. Ripley,                  [EMAIL PROTECTED]
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-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to