For a two-variable problem, outer
is most likely the best solution for this and if the space to loop over is small enough then we can have expand.grid
do our legwork. However, those are ruled out if we have more than two variables and a large space to loop over. outer
can't handle more than two variables and expand.grid
eats up more memory than I've ever seen a machine be able to take.
I've recently found myself writing code like this:
n<-1000
for(c in 1:n){
for(b in 1:c){
for(a in 1:b){
if(foo(a,b,c))
{
bar(a,b,c)
}
}
}
}
In these cases it does seem like a nested loop is the natural solution (e.g. mapply
won't do and there's no nice factors for tapply
to use), but is there a better way? It seems like a path to bad code.
I suspect that combn
might be able to do it somehow, but in my experience it doesn't take long for that to either fall in to the same memory trap as expand.grid
. If memory serves, I've also known it to take the ill-advised step of telling me to make changes to my global settings for recursion limits.