Daily Archives: August 28, 2009

1 post

Accessing an array created in R from C++

Assume that you have created a 3-dim array in R containing vectors of various size: > a<-array(list(),c(2,2,2))   # array where each element contain a numeric vector > a[[1,1,1]]<-rnorm(1) > a[[1,1,2]]<-rnorm(3) > a[[2,1,1]]<-rnorm(2) > a[[2,1,2]]<-rnorm(3) > a[[1,2,1]]<-rnorm(4) > a[[1,2,2]]<-rnorm(3) > a[[2,2,1]]<-rnorm(5) > a[[2,2,2]]<-rnorm(1) > d = dim(a) > d [1] 2 2 2 > i<-1; j<-1; k<-2 > q<-i + j*d[1] + k*(d[1]*d[2]) – (d[1] + d[1]*d[2]) > a[[i,j,k]]      # access an element [1] -0.2370040 -0.6009635  3.0550405 > a[[q]]          # access the same element using a single index [1] -0.2370040 -0.6009635  3.0550405 Note you can access the array in two ways. Next you want to copy the array to a vector on the C++ side. For instance in a package you may need to do some operations in C++ to speed up time. On the C++ side you can create a function: