How to generate a matrix of combinations
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))