在 Rcpp 中构建 3D 数组 [英] Constructing 3D array in Rcpp
问题描述
我正在尝试使用提供的维度列表将一维数组映射到 3D 数组.
I am trying to map a 1D array onto 3D array using provided list of dimensions.
这是我的组件:
SEXP data; // my 1D array
// I can initialise new 3D vector in the following way:
NumericVector vector(Dimension(2, 2, 2);
// or the following:
NumericVector vector(data.begin(), data.end());
我没有弄清楚如何创建一个同时包含我的数据和所需维度的 NumericVector.
What I didn't figure out is how can I create a NumericVector that would have both my data and the desired dimensions.
推荐答案
这是可行的,但有点痛苦.我想为新的构造函数或辅助函数做出体面(并经过测试)的贡献将不胜感激.
It is doable, but a little painful. I guess a decent (and tested) contribution for new constructor or helper function would be appreciated.
同时,您可以执行以下示例的操作.但要注意 row-major 和 col-major 等.另一种选择是 RcppArmadillo它具有适当的立方体"类型,可将矩阵泛化为 3-d.
In the meantime, you can do what the example below does. But be careful about row-major and col-major etc. Another option is RcppArmadillo which has a proper 'Cube' type generalizing matrices to 3-d.
R> library(inline)
R> fx <- cxxfunction(signature(vs="numeric", ds="integer"), plugin="Rcpp", body='
+ Rcpp::NumericVector v(vs); // get the data
+ Rcpp::Dimension d(ds); // get the dim object
+ Rcpp::NumericVector r(d); // create vec. with correct dims
+ std::copy(v.begin(), v.end(), r.begin()); // and copy
+ return Rcpp::List::create(v, d, r);
+ ')
R> fx(1:8, c(2,2,2))
[[1]]
[1] 1 2 3 4 5 6 7 8
[[2]]
[1] 2 2 2
[[3]]
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
R>
这篇关于在 Rcpp 中构建 3D 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!