[英]R List of numeric vectors -> C++ 2d array with Rcpp
我主要使用R,但最终想使用Rcpp与一些C ++函数接口,这些函数接收并返回2d数字数组。 因此,为了开始使用C ++和Rcpp,我想我只是做了一个小函数,将我的可变长度数字向量的R列表转换为C ++等价物并再次返回。
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')
这就像我期望的那样:
> test1(list(1:2, 4:6))
[[1]]
[1] 1 2
[[2]]
[1] 4 5 6
不可否认,我只是通过非常详尽的文档的一部分,但有没有更好的(即更像Rcpp)方式进行R - > C ++转换而不是for循环? 我想可能不会,因为文档中提到的(至少与内置的方法) as
“提供了较少的灵活性,目前处理的R转换对象转换成原始类型”,但我想检查,因为我这人非常这方面的新手。
我会给你一个可重复的例子的奖励积分,当然还有使用Rcpp :)然后我会把它们带走,因为没有询问rcpp-devel列表......
至于转换STL类型:你不必,但是当你决定这样做时, as<>()
成语是正确的。 我能想到的唯一“更好的方法”就是像R本身一样进行名称查找:
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);
')
希望有所帮助。 否则,列表总是打开...
PS至于双暗阵列,由于没有原生C ++双暗阵列,因此比较棘手。 如果你真的想做线性代数,看看RcppArmadillo和RcppEigen 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.