Dynamically increase list size in Rcpp

I am trying to implement a "link to the past" algorithm in Rcpp. To do this, I need to save the random number matrix, and if the algorithm does not converge, create a new random number matrix and save it. This may be required 10 times or even before convergence.

I was hoping I could use List and dynamically update it, just like in R. I was very surprised that it worked a bit, but I get errors whenever the list size becomes large. This seems to make sense since I did not allocate the necessary memory for additional list items, although I am not familiar with C ++ and not sure if this is a problem.

Here is an example of what I have tried. however, keep in mind that this is likely to crash your R session :

 library("Rcpp") cppFunction( includes = ' NumericMatrix RandMat(int nrow, int ncol) { int N = nrow * ncol; NumericMatrix Res(nrow,ncol); NumericVector Rands = runif(N); for (int i = 0; i < N; i++) { Res[i] = Rands[i]; } return(Res); }', code = ' void foo() { // This is the relevant part, I create a list then update it and print the results: List x; for (int i=0; i<10; i++) { x[i] = RandMat(100,10); Rf_PrintValue(wrap(x[i])); } } ') foo() 

Does anyone know a way to do this without crashing R? I think I could initiate a list with a fixed number of elements here, but in my application the number of elements is random.

+4
source share
1 answer

You should β€œallocate” enough space for your list. Perhaps you can use something like the resize function:

 List resize( const List& x, int n ){ int oldsize = x.size() ; List y(n) ; for( int i=0; i<oldsize; i++) y[i] = x[i] ; return y ; } 

and whenever you want your list to be larger than now, you can do:

 x = resize( x, n ) ; 

Your start list is 0, so you are expected to get unpredictable behavior on the first iteration of your loop.

+5
source

Source: https://habr.com/ru/post/1494695/


All Articles