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.
source share