Search code examples
rr-packager-extension

Change size of vector with R's C API


I'm allocating an R vector using allocVector in a C function called with .Call from R. Is it possible to change the size/length of the vector after it has been allocated? I.e., similar to how realloc works in C.

In code, I'm looking for a function reallocVector so that the following to functions do the same thing.

SEXP my_function1(SEXP input){
    SEXP R_output = PROTECT(allocVector(REALSXP, 100));

    // Do some work on R_output

    // Keep only the first 50 items
    reallocVector(R_output, 50); 

    UNPROTECT(1);
    return R_output;
}

SEXP my_function1(SEXP input){
    SEXP tmp_output = PROTECT(allocVector(REALSXP, 100));

    // Do the same work on tmp_output

    // Keep only the first 50 items
    SEXP R_output = PROTECT(allocVector(REALSXP, 50));
    for (int i = 0; i < 50; ++i) {
        REAL(R_output)[i] = REAL(tmp_output)[i];
    }

    UNPROTECT(2);
    return R_output;
}

Solution

  • It seems that the SETLENGTH macro defined in the Rinternals.h header is the best choice to solve this. I.e.:

    SEXP my_function1(SEXP input){
        SEXP R_output = PROTECT(allocVector(REALSXP, 100));
    
        // Do some work on R_output
    
        // Keep only the first 50 items
        SETLENGTH(R_output, 50);
    
        UNPROTECT(1);
        return R_output;
    }