How to generate a matrix of combinations How to generate a matrix of combinations r r

How to generate a matrix of combinations


expand.grid(c(-1,1), c(-1,1), c(-1,1), c(-1,1), c(-1,1))


To generalize Greg's answer:

N   <- 5vec <- c(-1, 1)lst <- lapply(numeric(N), function(x) vec)as.matrix(expand.grid(lst))


Alternative from data.table package is slightly faster compared to expand.grid:

library(data.table)  CJ(c(-1,1), c(-1,1), c(-1,1), c(-1,1), c(-1,1))