在Rcpp中构造3D数组

Dat*_*eek 10 r rcpp

我正在尝试使用提供的维度列表将1D阵列映射到3D阵列上.

这是我的组件:

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());
Run Code Online (Sandbox Code Playgroud)

我没想到的是如何创建一个既有我的数据又有所需尺寸的NumericVector.

Vyg*_*yga 15

有一个较短的解决方案.您可以使用重塑数据.attr.数据可以创建或作为输入提供 - 无关紧要.见下文:

library("Rcpp")

cppFunction(code='
NumericVector arrayC(NumericVector input, IntegerVector dim) { 
  input.attr("dim") = dim;
  return input;
}
')
x = 1:8
arrayC(x, c(2,2,2))
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
Run Code Online (Sandbox Code Playgroud)


Dir*_*tel 5

这是可行的,但有点痛苦.我想对新构造函数或辅助函数的一个体面的(和测试的)贡献将是值得赞赏的.

与此同时,您可以执行以下示例所做的操作.但要注意行主要和主要等.另一种选择是RcppArmadillo,它具有适当的'立方体'类型,可以将矩阵推广到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>
Run Code Online (Sandbox Code Playgroud)

  • 感谢您更新一份为期两年的答案.FWIW我曾经在几个场合使用过RcppArmadillo,因为Armadillo将`Cube`作为头等对象.适合我. (3认同)
  • FWIW,在已经肿的Vector模板上添加另一个构造函数似乎是个坏主意。您可以使用自由函数或专用Array类(例如Rcpp11中的类)来实现相同的目的。 (2认同)