3D arrays
Seemlessly pass three dimensional arrays between between R and Rcpp. I found a function called threeDIndex on a forum written for Rcpp but it did not convert from R to Rcpp smoothly. I needed to be passing these 3D arrays back and forth not just using them in Rcpp. I re-wrote the threeDIndex code (mythreeDIndex code) that works seemlessly with the R coverterts c() and array().
library(Rcpp)
library(inline)
fx <- cxxfunction(,"",includes=
' int threeDIndex(int jf, int kf, int lf, int Jf, int Kf, int Lf)
{ return lf*Kf*Jf + kf*Jf + jf;
}
Rcpp::NumericVector myfunc( int j, int k, int l, int J, int K, int L, Rcpp::NumericVector myvector )
{ myvector(threeDIndex(j-1,k-1,l-1,J,K,L))= myvector(threeDIndex(j-1,k-1,l-1,J,K,L))+1;
return myvector;
}
RCPP_MODULE(foo)
{ function( "threeDIndex", &threeDIndex);
function( "myfunc", &myfunc);
}
', plugin="Rcpp")
foo <- Module("foo",getDynLib(fx))
The example shows how you can use threeDIndex within R. I wrote a quick example function called myfunc that adds one to any element of a matrix. The first three input numbers are the indexes in the 3D array to find and add one to, the next three numbers are the dimensions of A. Here the Rcpp code is made to seemlessly work with c() to read in arrays for easy passing between R and Rcpp. Then foo$myfunc Rcpp code returns a vector that can quickly be converted to an R array with the array() function.
### EXAMPLE 1:
A=array(1:24,dim=c(2,3,4)) #make an R array (A)
D=foo$myfunc(1,1,1,2,3,4,c(A)) #add one to the first entry spot of A
array(D,dim=c(2,3,4)) #convert Rcpp vector to an R 3D array (same as A)
#### EXAMPLE 2
A=array(1:24,dim=c(2,3,4)) #make an R array (A)
D=foo$myfunc(1,2,3,2,3,4,c(A)) #add one to A[1,2,3]
array(D,dim=c(2,3,4)) #convert Rcpp vector to an R 3D array (same as A)