How to generate a matrix of combinations

前端 未结 3 1292
刺人心
刺人心 2020-11-27 06:39

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 no

相关标签:
3条回答
  • 2020-11-27 06:45

    To generalize Greg's answer:

    N   <- 5
    vec <- c(-1, 1)
    lst <- lapply(numeric(N), function(x) vec)
    as.matrix(expand.grid(lst))
    
    0 讨论(0)
  • 2020-11-27 06:49

    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))
    
    0 讨论(0)
  • 2020-11-27 07:03
    expand.grid(c(-1,1), c(-1,1), c(-1,1), c(-1,1), c(-1,1))
    
    0 讨论(0)
提交回复
热议问题