How to create a combination matrix

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.

+15
r cross-join
Oct 22 2018-10-22T00:
source share
3 answers
expand.grid(c(-1,1), c(-1,1), c(-1,1), c(-1,1), c(-1,1)) 
+27
Oct 22 2018-10-10T00:
source share

To summarize Greg's answer:

 N <- 5 vec <- c(-1, 1) lst <- lapply(numeric(N), function(x) vec) as.matrix(expand.grid(lst)) 
+20
Oct 22 '10 at 11:32
source share

The alternative to the data.table package data.table slightly faster than expand.grid :

 library(data.table) CJ(c(-1,1), c(-1,1), c(-1,1), c(-1,1), c(-1,1)) 
+5
May 17 '16 at 12:09
source share



All Articles