How to generate a matrix of combinations

佐手、 提交于 2019-12-17 05:04:17

问题


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.


回答1:


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



回答2:


To generalize Greg's answer:

N   <- 5
vec <- c(-1, 1)
lst <- lapply(numeric(N), function(x) vec)
as.matrix(expand.grid(lst))



回答3:


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))


来源:https://stackoverflow.com/questions/3993546/how-to-generate-a-matrix-of-combinations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!