Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top