2012-09-24 31 views
6

我正嘗試使用提供的維度列表將一維數組映射到3D數組。在Rcpp中構建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()); 

我也沒弄明白什麼是我可以創造一個NumericVector,將有我的兩個數據和所需的尺寸。

+1

與* RcppArmadillo立方體*示例:http://markovjumps.blogspot.be/2011/12/r-array-to-rcpparmadillo-cube.html –

回答

5

這是可行的,但有點痛苦。我想爲新的構造函數或幫助函數提供一個體面的(和測試)貢獻將不勝感激。

與此同時,你可以做下面的例子。但要小心row-major和col-major等。另一個選項是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> 
+0

與新構造同意,將很有用。當我瞭解Rcpp中的工作情況時,我可以研究它。 – Datageek

+1

FWIW,爲已經膨脹的Vector矢量模板添加另一個構造函數似乎是一個糟糕的主意。您可以使用免費功能或專用Array類(如Rcpp11中的類)實現相同功能。 –

+2

感謝您更新一份爲期兩年的答案。 FWIW由於Armadillo有'Cube'作爲第一類對象,因此我在幾個場合一直使用RcppArmadillo。適用於我。 –

10

有一個簡短的解決方案。您可以使用.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