【问题标题】:Creating a matrix with all combinations within a budget在预算内创建包含所有组合的矩阵
【发布时间】:2013-12-16 19:02:27
【问题描述】:

我正在尝试创建一个矩阵,该矩阵包含一个范围内的所有数字组合,以便该行总和为特定值。我不确定是否有此功能,或者我是否需要手动创建该功能。我已经尝试过 combn 函数,但它不限制总和,因此矩阵很快就会变大。

示例:总和为 5 的 3 行

5,0,0
4,1,0
4,0,1
3,2,0
3,0,2
3,1,1
2,3,0
2,0,3
2,2,1
2,1,2
etc..

【问题讨论】:

    标签: r


    【解决方案1】:

    这些组合对象称为partitions(另见here 甚至here),它们的计算由partitions 包实现。

    根据您真正想要的,使用以下方法之一:

    library(partitions)
    
    ## The first argument says you want to enumerate all partitions in which the 
    ## second argument (5) is broken into three summands, each of which can take a
    ## maximum value of 5.
    blockparts(rep(5,3),5)  ## Equiv: blockparts(c(5,5,5), 5)
    #                                              
    # [1,] 5 4 3 2 1 0 4 3 2 1 0 3 2 1 0 2 1 0 1 0 0
    # [2,] 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0
    # [3,] 0 0 0 0 0 0 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5
    
    restrictedparts(5,3)
    #              
    # [1,] 5 4 3 3 2
    # [2,] 0 1 2 1 2
    # [3,] 0 0 0 1 1
    

    【讨论】:

    • +1。我最初也在考虑分区包,但我几乎从不使用该包,所以仍在阅读文档:-)
    • 非常感谢您的洞察力。
    【解决方案2】:

    也许这就是你想要的:

    x <- expand.grid(replicate(3, list(0:5)))
    x[rowSums(x) == 5, ]
    #     Var1 Var2 Var3
    # 6      5    0    0
    # 11     4    1    0
    # 16     3    2    0
    # 21     2    3    0
    # 26     1    4    0
    # 31     0    5    0
    # 41     4    0    1
    # 46     3    1    1
    # 51     2    2    1
    # 56     1    3    1
    # 61     0    4    1
    # 76     3    0    2
    # 81     2    1    2
    # 86     1    2    2
    # 91     0    3    2
    # 111    2    0    3
    # 116    1    1    3
    # 121    0    2    3
    # 146    1    0    4
    # 151    0    1    4
    # 181    0    0    5
    

    expand.gridcombn 有点相关,但我发现expand.grid 更适用于这类问题。


    还有来自“gtools”包的permutations函数:

    library(gtools)
    x <- permutations(6, 3, v = 0:5, set = FALSE, repeats.allowed=TRUE)
    x[rowSums(x) == 5, ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2019-10-11
      • 2021-09-22
      相关资源
      最近更新 更多