# Simulate a doubly-nested loop with a single while loop
it <- igrid(a=1:3, b=1:2)
repeat {
x <- nextOr(it, break)
cat(sprintf('a = %d, b = %d\n', x$a, x$b))
}
it <- igrid(x=1:3, y=4:5)
nextOr(it, NA) # list(x=1, y=4)
nextOr(it, NA) # list(x=1, y=5)
nextOr(it, NA) # list(x=2, y=4)
nextOr(it, NA) # list(x=2, y=5)
nextOr(it, NA) # list(x=3, y=4)
nextOr(it, NA) # list(x=3, y=5)
# Second Cartesian product
nextOr(it, NA) # list(x=1, y=4)
nextOr(it, NA) # list(x=1, y=5)
nextOr(it, NA) # list(x=2, y=4)
nextOr(it, NA) # list(x=2, y=5)
nextOr(it, NA) # list(x=3, y=4)
nextOr(it, NA) # list(x=3, y=5)
# igrid is an iterator equivalent to base::expand.grid()
# Large data.frames are not created unless the iterator is manually consumed
a <- 1:2
b <- 3:4
c <- 5:6
it3 <- igrid(a=a, b=b, c=c)
df_igrid <- do.call(rbind, as.list(it3))
df_igrid <- data.frame(df_igrid)
# Compare df_igrid with the results from base::expand.grid()
base::expand.grid(a=a, b=b, c=c)
Run the code above in your browser using DataLab