【问题标题】:get all Combinations of length N out of M从 M 中取出所有长度为 N 的组合
【发布时间】:2014-06-05 14:34:03
【问题描述】:

我正在寻找一种简单的方法来从 M 中获取长度为 N 的所有可能的唯一组合。

这里是一个简单的例子:

M <- c( 1, 2, 3, 4, 5 )
N <- 2

预期输出:

1, 2
1, 3 
1, 4
1, 5
2, 3
2, 4
2, 5
3, 4
3, 5
4, 5

【问题讨论】:

  • 你在谷歌上搜索到什么combn 没有立即出现?
  • 请注意,combn 会返回所有“无替换”组合,这正是您所要求的。 expand.grid 返回所有“替换”组合:expand.grid(x1=c(1:5), x2=c(1:5))。我不知道combn 是否可以“替换”返回所有组合。

标签: r combinations


【解决方案1】:

使用combn函数

> n <- 1:5
> combn(n, 2)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    1    1    1    2    2    2    3    3     4
[2,]    2    3    4    5    3    4    5    4    5     5

【讨论】:

    【解决方案2】:

    这给出了与@jdharrison 的示例相同的结果。

    combnPrim 在快速移交给.C 时要快得多,尽管对于只需要一个小组合的示例来说,这显然是多余的。

    library(gRbase)
    ### the following dependencies may be necessary, install as follows:
    ### source("http://bioconductor.org/biocLite.R")
    ### biocLite("graph")
    ### biocLite("BiocGenerics")
    ### biocLite("RBGL")
    gRbase::combnPrim(seq(5), 2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 2021-02-22
      • 1970-01-01
      相关资源
      最近更新 更多