[Rd] Rcpp from C++

Peter Peyk Peter.Peyk at unibas.ch
Fri Jul 18 07:06:34 CEST 2008

Hi Sri,

I haven't really elaborated on it having other stuff to prepare first, but as 
far as I got you first assign data to a vector:

#include <R.h>
#include <Rinternals.h>
#include <Rembedded.h>
#include "Rcpp.hpp" 
#include <R_ext/Parse.h>
#include <Rinternals.h>
#include <Rdefines.h>

    //assigning a vector
    SEXP ab;
    PROTECT(ab = allocVector(REALSXP, 2));
    REAL(ab)[0] = 123.45;
    REAL(ab)[1] = 67.89;

the attach a R variable name to the data using

void defineVar(SEXP symbol, SEXP value, SEXP rho)
void setVar(SEXP symbol, SEXP value, SEXP rho)

but I haven't tried that yet in detail.

getVar is the other way around and finds the data to an R variable name:

SEXP getVar(SEXP name, SEXP rho)
    SEXP ans;     
    if(!isString(name) || length(name) != 1)
        error("name is not a single string");
        error("rho should be an environment");
    ans = findVar(install(CHAR(STRING_ELT(name, 0))), rho);
    return ans;

To get the data of an R-variable you should be able to use the constructors 
from Rcpp that take an SEXP as argument, but i also haven't tried that yet.

What I found to be useful too is the routine for evaluating R-commands:

    //evaluating commands
    int errorOccurred;
    ParseStatus status;
    SEXP cmdSexp, cmdexpr, ans = R_NilValue;
    PROTECT(cmdSexp = Rf_allocVector(LANGSXP, 1));
    char* cArr[4];
    cArr[0] = "a <- seq(1,20)";  
    cArr[1] = "b <- seq(1,20)";
    cArr[2] = "c <- a+ b";
    cArr[3] = "print(c)";
    for (int CommandInd = 0; CommandInd<4; CommandInd++)
        PROTECT(cmdSexp = allocVector(STRSXP, 1));
        SET_STRING_ELT(cmdSexp, 0, mkChar(cArr[CommandInd]));
        cmdexpr = PROTECT(R_ParseVector(cmdSexp, -1, &status, R_NilValue));
        if (status != PARSE_OK) {
            error("invalid call!");
        for(int i = 0; i < length(cmdexpr); i++)
            ans = eval(VECTOR_ELT(cmdexpr, i), R_GlobalEnv);

hope that helps

P.S.: let me know if that works and what you find out!

More information about the R-devel mailing list