I have 5 items each of which can take on the value of 1 or -1. I want to generate a matrix that consists of rows of the possible combinations. The order of the items does not matter and the order of the combinations does not matter. I know I could do this mechanically, but I thought that someone must know a shortcut to generating this matrix. I apologize if this is similar to other questions but none of the solutions I have found can be applied to this particular problem with my programming skills.
Asked
Active
Viewed 2.2k times
3 Answers
23
To generalize Greg's answer:
N <- 5
vec <- c(-1, 1)
lst <- lapply(numeric(N), function(x) vec)
as.matrix(expand.grid(lst))

caracal
- 2,690
- 19
- 22
7
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))

Bulat
- 6,869
- 1
- 29
- 52
-
2I think a more general solution would be `do.call(CJ, rep(list(c(-1, 1)), 5))` – David Arenburg Jun 10 '18 at 08:52