[R] R recursion depth and stack size
Pascal A. Niklaus
Pascal.Niklaus at unibas.ch
Tue Nov 25 16:10:56 CET 2003
I am playing around with latin squares, and wrote a recursive function
that searches for valid combinations.
Apart from the fact that there are very many, I run into troubles
beginning with size 10x10 because the recursion depth becomes too large
(max of 10x9-1=89 in this case).
Why is this a problem? Isn't there enough space allocated to the stack?
Can this be increased? The memory demand shouldn't be terrible, with
only minimal local variables (only set and the function params r,c,t - s
is local to a block called only once when a solution is found). Even if
variables aren't stored efficiently, a recursion depth of 100 shouldn't
consume more than a couple of kilobytes.
Is this a fundamental misunderstanding of the way R works?
BTW: Is there a way to pass variables "by reference" in function calls?
The function stripped-down to the essential looks like this:
latin.square <- function(t = 4)
latinCheck <- function(r,c,t)
set <- setdiff(LETTERS[1:t],c(m[r,],m[,c]));
for(i in set)
m[r,c] <<- i;
else # found a solution
s <- paste(m[1,],collapse="",sep="");;
for(i in 2:t)
s <- paste(c(s,"-",m[i,]),collapse="",sep="");
m[r,c] <<- NA;
latinSolutions <<- character(0);
fullset <<- LETTERS[1:t];
m <<- matrix(nrow=t,ncol=t);
m[1,] <<- LETTERS[1:t];
More information about the R-help