Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently create random sample from expand.grid output without using expand.grid

Let's suppose I have 3 vectors (just as an example). Now I want to obtain a random sample over all possible combinations of those 3. Usually, I'd do this:

x <- 1:3
y <- 10:12
z <- 15:18

N <- length(x) * length(y) * length(z) # Length of the resulting grid
idx <- sample(1:N, 10, replace = FALSE)
my_grid <- expand.grid(x, y, z)
result <- my_grid[idx, ]

That's fine for small vectors. But if those vectors grow in size, my_grid will get very big very fast. So the question is, how to create the result by only using idx and the three vectors?

like image 875
BerriJ Avatar asked Nov 15 '25 15:11

BerriJ


1 Answers

This should work:

X <- list(x, y, z)
X.len <- sapply(X, length)

# modify '%%' to return values 1..n instead of 0..(n-1)
mod2 <- function(x, y) (x-1) %% y + 1

result <- sapply(seq_along(X), function(i) 
  X[[i]][mod2(ceiling(idx / prod(X.len[seq_len(i-1)])),  
              X.len[i])]
)

Basically, the columns of the output of expand.grid for each vector are formed by blocks of values and the length of each block is a product of the lengths of the "preceding" vectors. So you just divide the index by this product and than take modulo from this number to find which value would be on that position.

like image 88
Robert Hacken Avatar answered Nov 18 '25 04:11

Robert Hacken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!