Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a `data.table` to c++ functions using `Rcpp` and/or `RcppArmadillo`

Tags:

r

data.table

rcpp

Is there a way to pass a data.table objects to c++ functions using Rcpp and/or RcppArmadillo without manually transforming to data.table to a data.frame? In the example below test_rcpp(X2) and test_arma(X2) both fail with c++ exception (unknown reason).

R code

X=data.frame(c(1:100),c(1:100))
X2=data.table(X)
test_rcpp(X)
test_rcpp(X2)
test_arma(X)
test_arma(X2)

c++ functions

NumericMatrix test_rcpp(NumericMatrix X) {
    return(X);
}

mat test_arma(mat X) {
    return(X);
}
like image 945
user2503795 Avatar asked Dec 08 '12 01:12

user2503795


3 Answers

Rcpp sits on top of native R types encoded as SEXP. This includes eg data.frame or matrix.

data.table is not native, it is an add-on. So someone who wants this (you?) has to write a converter, or provide funding for someone else to write one.

like image 64
Dirk Eddelbuettel Avatar answered Sep 24 '22 17:09

Dirk Eddelbuettel


Building on top of other answers, here is some example code:

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
double do_stuff_with_a_data_table(DataFrame df){
    CharacterVector x = df["x"] ;
    NumericVector   y = df["y"] ;
    IntegerVector   z = df["v"] ;

    /* do whatever with x, y, v */
    double res = sum(y) ;
    return res ;
}

So, as Matthew says, this treats the data.table as a data.frame (aka a Rcpp::DataFrame in Rcpp).

require(data.table)
DT <- data.table(
    x=rep(c("a","b","c"),each=3), 
    y=c(1,3,6), 
    v=1:9)
do_stuff_with_a_data_table( DT ) 
# [1] 30

This completely ignores the internals of the data.table.

like image 13
Romain Francois Avatar answered Oct 15 '22 14:10

Romain Francois


Try passing the data.table as a DataFrame rather than NumericMatrix. It is a data.frame anyway, with the same structure, so you shouldn't need to convert it.

like image 10
Matt Dowle Avatar answered Oct 15 '22 14:10

Matt Dowle