【问题标题】:unordered combination and store the result in a matrix in r无序组合并将结果存储在 r 中的矩阵中
【发布时间】:2018-12-04 09:21:31
【问题描述】:

假设我有一个列表 (a, b, c),我想找出它们的所有可能组合并存储在一个矩阵中,例如:

      a b c
 [1,] 1 0 0
 [2,] 0 1 0
 [3,] 0 0 1
 [4,] 1 1 0
 [5,] 1 0 1
 [6,] 0 1 1
 [7,] 1 1 1`

我不知道怎么做。感谢您的帮助!

【问题讨论】:

  • 使用expand.grid(list(a,b,c))
  • @YOLO 谢谢!这正是我正在寻找的。​​span>
  • @YOLO 实际上不是。不过还是谢谢你。
  • @vincent - 实际上是,只需删除第一行 - 例如expand.grid(0:1,0:1,0:1)[-1,]

标签: r


【解决方案1】:

要完全按照您的意愿行事,请使用 gtools 包中的 permutations。其工作原理如下:

m <- permutations(2, 3, v=c(0,1), repeats.allowed=T)
colnames(m) <- c('a','b','c')
# delete [0,0,0]
m <- m[-1,]

产量:

     a b c
[1,] 0 0 1
[2,] 0 1 0
[3,] 0 1 1
[4,] 1 0 0
[5,] 1 0 1
[6,] 1 1 0
[7,] 1 1 1 

【讨论】:

    【解决方案2】:

    想法来自这个问题下的评论部分: Generate all combinations of length 2 using 3 letters

    我的改编不是很优雅……但它似乎能胜任。

    output <- expand.grid(rep(list(c('a', 'b', 'c')), 3))
    colnames(output) <- c('a', 'b', 'c')
    for (col in colnames(output)) { 
      output[, col] <- as.character(output[,col])
      output[, col] <- ifelse(output[, col]==col, 1, 0)
    }
    output <- output[!duplicated(output), ]
    rownames(output) <- NULL
    print(output)
    # a b c
    # 1 1 0 0
    # 2 0 0 0
    # 3 1 1 0
    # 4 0 1 0
    # 5 1 0 1
    # 6 0 0 1
    # 7 1 1 1
    # 8 0 1 1
    

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      相关资源
      最近更新 更多