Passing `data.table` in a C ++ function using` Rcpp` and / or `RcppArmadillo`

Is there a way to pass data.table objects for C ++ functions using Rcpp and / or RcppArmadillo without manually converting to data.table in data.frame ? In the example below, test_rcpp(X2) and test_arma(X2) both parameters work 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); } 
+7
source share
4 answers

Based on other answers, here is a sample 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 refers to 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 internal data.table elements.

+11
source

Try passing data.table as a DataFrame , not a NumericMatrix . In any case, it is data.frame , with the same structure, so you do not need to convert it.

+9
source

Rcpp sits on top of the built-in R types encoded as SEXP. This includes, for example, data.frame or matrix .

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

+3
source

For reference, I think it's good to list out rcpp as data.table to allow updating through lists.

Here is an example of a mannequin:

 cCode <- ' DataFrame DT(DTi); NumericVector x = DT["x"]; int N = x.size(); LogicalVector b(N); NumericVector d(N); for(int i=0; i<N; i++){ b[i] = x[i]<=4; d[i] = x[i]+1.; } return Rcpp::List::create(Rcpp::Named("b") = b, Rcpp::Named("d") = d); '; require("data.table"); require("rcpp"); require("inline"); DT <- data.table(x=1:9,y=sample(letters,9)) #declare a data.table modDataTable <- cxxfunction(signature(DTi="data.frame"), plugin="Rcpp", body=cCode) DT_add <- modDataTable(DT) #here we get the list DT[, names(DT_add):=DT_add] #here we update by reference the data.table 
+2
source

All Articles