Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing 3D array in Rcpp

Tags:

r

rcpp

I am trying to map a 1D array onto 3D array using provided list of dimensions.

Here are my components:

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());

What I didn't figure out is how can I create a NumericVector that would have both my data and the desired dimensions.

like image 441
Datageek Avatar asked Sep 24 '12 17:09

Datageek


1 Answers

There is a shorter solution. You can reshape your data using .attr. The data can be created or given as an input - it does not matter. See below:

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
like image 84
Vyga Avatar answered Sep 23 '22 16:09

Vyga