简体   繁体   English

如何生成组合矩阵

[英]How to generate a matrix of combinations

I have 5 items each of which can take on the value of 1 or -1. 我有5个项目,每个项目可以取值1或-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. 如果这与其他问题类似,我很抱歉,但我发现的解决方案都不能用我的编程技巧应用于这个特定问题。

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

To generalize Greg's answer: 概括格雷格的答案:

N   <- 5
vec <- 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 : data.table相比, expand.grid包的替代方案略快expand.grid

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM