user1521655
user1521655

Reputation: 484

What is the R to C++ syntax for vectors?

I am an R and C programmer trying to use Rcpp to create an R (and C++) wrapper for a program written in C. I'm not really familiar with C++.

Can someone help me understand the documentation on how to import an R object as a C++ vector? (I'm specifically trying to import an R list that includes a mixture of int, double, and numeric lists.)

The Rcpp-introduction.pdf states:

The reverse conversion from an R object to a C++ object is implemented by variations of the Rcpp::as template whose signature is:

template <typename T> T as(SEXP x);

It offers less sexibility and currently handles conversion of R objects into primitive types (e.g., bool, int, std::string, ...), STL vectors of primitive types (e.g., std::vector<bool>, std::vector<double>, ...) and arbitrary types that offer a constructor that takes a SEXP.

I am confused as to what this means, i.e. what gets filled in for "template", "typename T", and "T". I've seen what appear to be lots of examples for the primitives, e.g.

int dx = Rcpp::as<int>(x);

but I don't understand how this syntax maps to the template documentation above, and (more importantly) don't understand how to generalize this to STL vectors.

Upvotes: 0

Views: 900

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368439

Maybe you are making it too complicated. An R vector just becomes a C++ vector "because that is what Rcpp does for you".

Here it is using Rcpp::NumericVector:

R> library(Rcpp)
R> cppFunction('NumericVector ex1(NumericVector x) { return x + 2;}')
R> ex1(1:4)  # adds two
[1] 3 4 5 6
R> 

This uses the fact that we defined + for our NumericVector types. You can also pass a std::vector<double> in and out, but need to add some operations which is often more than one statement so I didn't here...

So in short, keep reading the documentation and ask on rcpp-devel or here if you need help.

Edit: For completeness, the same with a STL vector

R> cppFunction('std::vector<double> ex2(std::vector<double> x) { \
                 for (size_t i=0; i<x.size(); i++) x[i] = x[i] + 2; return x;}')
R> ex2(1:4)
[1] 3 4 5 6
R> 

Upvotes: 1

Related Questions