Skip to content
Prev 86177 / 398506 Next

expand.grid without expanding

I have made a few more improvements:

expand.grid.id  <- function(id, ...) {
 vars <- list(...)
 nv <- length(vars)
 lims <- sapply(vars,length)
 stopifnot(length(lims) > 0, id <= prod(lims), length(names(vars)) == nv)
 res <- structure(vector("list",nv), .Names = names(vars))
 if (nv > 1) for(i in nv:2) {
   f <- prod(lims[1:(i-1)])
   res[[i]] <- vars[[i]][(id - 1)%/%f + 1]
   id <- (id - 1)%%f + 1
 }
 res[[1]] <- vars[[1]][id]
 as.data.frame(res)
}

# test
expand.grid(A = 1:2, B = letters[1:3])
expand.grid.id(1:6, A = 1:2, B = letters[1:3])
On 2/8/06, Ray Brownrigg <ray at mcs.vuw.ac.nz> wrote: