I have 5 elements, each of which can take the value 1 or -1. I want to create a matrix consisting of rows of possible combinations. The order of the items does not matter, and the order of the combinations does not matter. I know that I can do this mechanically, but I thought that someone should know a shortcut to create this matrix. I apologize if this looks like other questions, but none of the solutions we found can be applied to this particular problem with my programming skills.
expand.grid(c(-1,1), c(-1,1), c(-1,1), c(-1,1), c(-1,1))
To summarize Greg's answer:
N <- 5 vec <- c(-1, 1) lst <- lapply(numeric(N), function(x) vec) as.matrix(expand.grid(lst))
The alternative to the data.table package data.table slightly faster than expand.grid :
data.table
expand.grid
library(data.table) CJ(c(-1,1), c(-1,1), c(-1,1), c(-1,1), c(-1,1))