[Rd] allocVector reference

Matthew Dowle Matthew at CONCORDIAFUNDS.com
Wed Mar 14 18:44:04 CET 2007


I'm trying to write a function to return an R vector which points
directly to a contiguous subset of another vector, without taking a
copy.  Since SEXPREC is a header followed by the data, rather than the
header plus a pointer to the data, I'm not sure what I'm trying to do is
possible.  Is there a way of doing this?  Similar in spirit to how the R
assignment "x=y" does not copy y until x is modified, but for a
contiguous subset of y e.g. "x=y[5:9]" would become "x=vecref(y,5,5)".

SEXP vecref(SEXP v, SEXP offset, SEXP len)
    // assuming v is an integer vector, offset>=0, len>=0 and
    SEXP ans;
    PROTECT(ans = allocVector(INTSXP, 0));
    DATAPTR(ans) = INTEGER(v) + INTEGER(offset)[0];		// this
line doesn't work since DATAPTR is really an offset by the header
    LENGTH(ans) = INTEGER(len)[0];

Thanks in advance,

More information about the R-devel mailing list