Dimension swap from cube to matrix in rcpp

Viewed 188

I encountered an interesting problem today. In one of my postprocessing functions of my code, I do some where I have 3dimensional cubes out of an MCMC algorithm. When accessing the cube, I assumed that anything I extract will result in a Matris, as I also tried to save it. Nevertheless, if one of the dimensions is just 1 weird stuff happens. I'll give you a small example:

library(Rcpp)
library(RcppArmadillo)

cppFunction("arma::mat test(arma::cube Rarray) {
arma::mat test = Rarray.row(0);
return test;
}", depends="RcppArmadillo")

Rarray1 <- array(NA, dim=c(100,1,2))
Rarray2 <- array(NA, dim=c(100,2,1))

When letting run the function and looking at the dimensions, I get

dim(test(Rarray1))
> 1 2
dim(test(Rarray2))
> 1 2

So extracting the first row of the array/cube and saving it in a matrix swaps the dimensions. My guess is that internally Rcpp takes out the first row of Rarray, which is a 1x2 or 2x1 matrix. Regardless of that, whenever one of dimensions is just one it transforms it to a column vector (the default in Armadillo) and then saves it to the matrix. Therefore, I always will get back a column vector saved in a matrix, which results in a 1x2 matrix. But that's just a guess.

Is there any way to prevent this behavior? Similar to drop=FALSEin R.

0 Answers
Related