From Matthew at CONCORDIAFUNDS.com  Wed Mar 14 18:44:04 2007
From: Matthew at CONCORDIAFUNDS.com (Matthew Dowle)
Date: Wed, 14 Mar 2007 17:44:04 -0000
Subject: [Rd] allocVector reference
Message-ID: <946928E281E8FD4B91D5B2CC3C91967DAA9912@lnex01.CONCORDIAFUNDS.COM>


Hi,

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
(offset+len)<length(v)
    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];
    UNPROTECT(1);
    return(ans);
}

Thanks in advance,
Matthew



[Rd] allocVector reference
Matthew Dowle