【问题标题】:How to make an efficient combination of numbers R?如何有效地组合数字 R?
【发布时间】:2015-04-11 04:52:02
【问题描述】:

我正在尝试制作一个由 1 到 100(整数)之间的 5 个数字的所有组合组成的矩阵,总和为 100。如果我可以为每 5 个数字设置最小值和最大值,那将会更大。 我做的最简单的方法是做 5 个嵌套循环。

for (a in min:max ) 
{
  for (b in min:max ) 
  { 
  for (c in min:max)
  {
   for(d in min:max)
    {
      for (e in min:max)
  {
        for (f in min:max)
    {
      for (g in min:max)
          {
        for (h in min:max)
        {
    port <- c (a,b,c,d,e,f,g,h)
    if(a+b+c+d+e+f+g+h==100) {portif <- rbind(port,portif)}
}}}}}}}}

但我很确定在 R 中有比这些漂亮的慢循环更好的方法。

编辑: - 是的,顺序很重要

如果我可以为每个 a,b,c 设置不同的最小值和最大值 ...

非常感谢您的帮助

【问题讨论】:

标签: r loops combinations


【解决方案1】:

获取所有(choose(100, 5) 导致 75287520)组合:

x <- combn(1L:100L, 5)

计算列总和并检查等于100

x[, colSums(x) == 100]

导致25337组合,例如:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4   90
[2,]    1    2    3    5   89
[3,]    1    2    3    6   88
[4,]    1    2    3    7   87
[5,]    1    2    3    8   86
...

【讨论】:

    【解决方案2】:

    动态编程对您来说可能更快,但更难实现。这是一个递归解决方案:

    f <- function(min, max, cnt) {                                                   
      if(max < min) return(NULL)                                                     
      if(cnt == 1) return(max)                                                       
    
      do.call(rbind, lapply(min:max,                                                 
                            function(i){                                             
                              X <- f(min, max-i, cnt-1)                              
                              if(!is.null(X)) cbind(i, X)                            
                            })                                                       
      )                                                                              
    
    }     
    

    要不包括同一集合的排列,您可以将递归更改为

    X <- f(i+1, max-i, cnt-1)
    

    //编辑:要为每个层设置不同的最小值和最大值,您可以制作最小值和最大值向量,然后将用法更改为例如min[cnt];您可能还想将订单交换为 cbind(X,i) 以保持理智。

    【讨论】:

      【解决方案3】:

      比你,你的两个代码都快得多 我又找到了一段代码,看起来也不错

      library("partitions")
      numparts <- 8  
      sumparts <- 20
      weights <- compositions(n=sumparts, m=numparts, include.zero=TRUE)/sumparts
      

      【讨论】:

        猜你喜欢
        • 2020-01-25
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 2017-11-23
        • 1970-01-01
        • 2014-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多