Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Rcpp::List to std::vector<double>

Tags:

c++

r

rcpp

I'm a newcomer in the field of R langauge, but I need to compute singular value decomposition via irlba in my C++ code. For this purpose I use RInside lib.

RInside R(argc, argv); 
std::string cmd = "S<-diag(3)";
R.parseEval(cmd);
R.parseEval("B<-svd(S,nu=dim(S)[1],nv=dim(S)[2])");
Rcpp::List V ((SEXP)R.parseEval("B$v"));

Now I need to convert my results from Rcpp::List with singular vectors to std::vector

Question: What is the best way to convert results of performing svd to the std::vector?

How can I transform my input matrix written as std::vector to the format appropriate for using it as an input parameter for svd function in irlba?

like image 768
Stepan Loginov Avatar asked Mar 13 '14 11:03

Stepan Loginov


1 Answers

To go from C++ types to R objects, you can use wrap. The way I usually construct NumericMatrixs from a std::vector<double> is like so:

// with x as a std::vector<double>
using namespace Rcpp;
NumericVector m = wrap(x); // wrap x into an R object
m.attr("dim") = Dimension(<num_rows>, <num_cols>); // set the dimensions

with <num_rows> and <num_cols> chosen based on your desired dimensions. m should then be usable as an R matrix.

In general, you can use as<T> to go from R types to C++ types, and wrap to go from C++ types to R types. See section 3 of the Rcpp-Introduction vignette for some more information.

like image 167
Kevin Ushey Avatar answered Oct 28 '22 04:10

Kevin Ushey