R List of number vectors & # 8594; C ++ 2d array with Rcpp

I mainly use R, but would eventually like to use Rcpp to interact with some C ++ functions that accept and return 2d numeric arrays. Therefore, to start playing with C ++ and Rcpp, I thought that I would just make a small function that converts my R-list of variable-length number vectors into the C ++ equivalent and vice versa.

require(inline) require(Rcpp) test1 = cxxfunction(signature(x='List'), body = ' using namespace std; List xlist(x); int xlen = xlist.size(); vector< vector<int> > xx; for(int i=0; i<xlen; i++) { vector<int> test = as<vector<int> > (xlist[i]); xx.push_back(test); } return(wrap(xx)); ' , plugin='Rcpp') 

This works as I expect:

 > test1(list(1:2, 4:6)) [[1]] [1] 1 2 [[2]] [1] 4 5 6 

Admittedly, I only partially understand very thorough documentation, but is there a more convenient (i.e. more Rcpp-like) way to do an R → C ++ conversion than with a for loop? I think not, because the documentation mentions that (at least with built-in methods) as "offers less flexibility and currently handles the conversion of R objects to primitive types", but I wanted to check because I'm very new to this area.

+4
source share
1 answer

I will give you bonus points for the reproduced example and, of course, for using Rcpp :) And then I will remove them so as not to ask rcpp-devel on the list ...

As for the conversion of STL types: you don't need it, but when you decide to do it, the id as<>() true. The only "best way" I can come up with is to look for names, as in R itself:

 require(inline) require(Rcpp) set.seed(42) xl <- list(U=runif(4), N=rnorm(4), T2df=rt(4,2)) fun <- cxxfunction(signature(x="list"), plugin="Rcpp", body = ' Rcpp::List xl(x); std::vector<double> u = Rcpp::as<std::vector<double> >(xl["U"]); std::vector<double> n = Rcpp::as<std::vector<double> >(xl["N"]); std::vector<double> t2 = Rcpp::as<std::vector<double> >(xl["T2df"]); // do something clever here return(R_NilValue); ') 

Hope this helps. Otherwise, the list is always open ...

PS As for the two-dimensional array, this is more complicated, since there is no built-in C ++ two-dimensional array. If you really want to do linear algebra, check out RcppArmadillo and RcppEigen .

+6
source

Source: https://habr.com/ru/post/1381586/


All Articles