使用`Rcpp`和/或`RcppArmadillo`将`data.table`传递给c ++函数 [英] Passing a `data.table` to c++ functions using `Rcpp` and/or `RcppArmadillo`
问题描述
是否有办法使用 Rcpp
和/或<$>将 data.table
对象传递给c ++函数无需将 data.table
手动转换为 data.frame
,即可使用 test_rcpp(X2)
和 test_arma(X2)
(未知原因)。
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代码
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 ++函数
NumericMatrix test_rcpp(NumericMatrix X) {
return(X);
}
mat test_arma(mat X) {
return(X);
}
推荐答案
,这里是一些示例代码:
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 ;
}
因此,正如Matthew所说, .table 作为 data.frame
(aka a Rcpp :: DataFrame
in Rcpp
)。
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
这完全忽略了 data.table
。
这篇关于使用`Rcpp`和/或`RcppArmadillo`将`data.table`传递给c ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!