我主要使用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')
Run Code Online (Sandbox Code Playgroud)
这就像我期望的那样:
> test1(list(1:2, 4:6))
[[1]]
[1] 1 2
[[2]]
[1] 4 5 6
Run Code Online (Sandbox Code Playgroud)
不可否认,我只是通过非常详尽的文档的一部分,但有没有更好的(即更像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);
')
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.否则,列表总是打开...
PS至于双暗阵列,由于没有原生C++双暗阵列,因此比较棘手.如果你真的想做线性代数,看看RcppArmadillo和RcppEigen.
| 归档时间: |
|
| 查看次数: |
2787 次 |
| 最近记录: |