c++ - R 数值 vector 列表 -> C++ 2d array with Rcpp

标签 c++ arrays r rcpp

我主要使用 R,但最终想使用 Rcpp 与一些接收和返回二维数值数组的 C++ 函数交互。因此,为了开始使用 C++ 和 Rcpp,我想我只需要编写一个小函数,将我的可变长度数字 vector 的 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

不可否认,我只是完成了非常详尽的文档的一部分,但是是否有比使用 for 循环更好(即更像 Rcpp)的方法来进行 R -> C++ 转换?我我想可能不是,因为文档提到(至少使用内置方法)as“提供较少的灵 active ,目前处理 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++ 二维数组。如果你真的想做线性代数,看看RcppArmadilloRcppEigen .

关于c++ - R 数值 vector 列表 -> C++ 2d array with Rcpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8159872/

相关文章:

java - 查找数组中最小元素的索引 (Java)

Javascript:console.log(arr.length) 表示长度为 n,console.log(arr) 表示长度为 n-1。第二种情况不会显示最后一个元素

arrays - 如何在 Matlab 中创建指向对象的指针数组?

r - 时间序列数据为月度时如何均匀间隔geom_bar

c++ - clang : error: invalid use of non-static data member

c++ - 如何将打印从屏幕(或任何 FILE*)重定向到 C++ 中的字符串/字符*

r - ggplot2 移动构面布局

r - 如何定义维恩图中相交的颜色?

c++ - OpenGL:纹理渲染卡住

c++ - 可移植到 OpenMP 和 MPI 的 C++ 程序中的复杂循环?