Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R List of numeric vectors -> C++ 2d array with Rcpp

Tags:

c++

arrays

r

rcpp

I mainly use R, but eventually would like to use Rcpp to interface with some C++ functions that take in and return 2d numeric arrays. So to start out playing around with C++ and Rcpp, I thought I'd just make a little function that converts my R list of variable-length numeric vectors to the C++ equivalent and back again.

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 like I expect:

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

[[2]]
[1] 4 5 6

Admittedly I am only part way through the very thorough documentation, but is there a nicer (i.e. more Rcpp-like) way to do the R -> C++ conversion than with the for loop? I am thinking possibly not, since the documentation mentions that (at least with the built-in methods) as "offers less flexibility and currently handles conversion of R objects into primitive types", but I wanted to check because I'm very much a novice in this area.

like image 493
John Colby Avatar asked Nov 16 '11 22:11

John Colby


1 Answers

I will give you bonus points for a reproducible example, and of course for using Rcpp :) And then I will take those away for not asking on the rcpp-devel list...

As for converting STL types: you don't have to, but when you decide to do it, the as<>() idiom is correct. The only 'better way' I can think of is to do name lookup as you would 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 that helps. Otherwise, the list is always open...

PS As for the two-dim array, that is trickier as there is no native C++ two-dim array. If you actually want to do linear algebra, look at RcppArmadillo and RcppEigen.

like image 179
Dirk Eddelbuettel Avatar answered Oct 16 '22 23:10

Dirk Eddelbuettel