Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically increase size of list in Rcpp

Tags:

list

r

rcpp

I am trying to implement a "coupling to the past" algorithm in Rcpp. For this I need to store a matrix of random numbers, and if the algorithm did not converge create a new matrix of random numbers and store that as well. This might have to be done 10+ times or something until convergence.

I was hoping I could use a List and dynamically update it, similar as I would in R. I was actually very surprised it worked a bit but I got errors whenever the list size becomes large. This seems to make sense as I did not allocate the needed memory for the additional list elements, although I am not that familiar with C++ and not sure if that is the problem.

Here is an example of what I tried. however be aware that this will probably 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 guess I could initiate the list at a fixed amount of elements here, but in my application the amount of elements is random.

like image 346
Sacha Epskamp Avatar asked Aug 01 '13 10:08

Sacha Epskamp


1 Answers

You have to "allocate" enough space for your list. Maybe you can use something like a resizefunction:

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 bigger than it is now, you can do:

x = resize( x, n ) ;

Your initial list is of size 0, so it expected that you get unpredictable behavior at the first iteration of your loop.

like image 187
Romain Francois Avatar answered Sep 29 '22 06:09

Romain Francois