Generate combinations of values which sum to one, sorted in descending order

后端 未结 2 971
天涯浪人
天涯浪人 2021-01-18 01:34

Do you know a more efficient way to generate a matrix holding all unique combinations of \"weights\" (let weights be w and 0 <= w <= 1, and values of w are separated b

相关标签:
2条回答
  • 2021-01-18 01:38

    General purpose function with standard packages:

    # Generate weights matrix with noWeights columns and noRows rows.
    # Each row of this matrix contains sorted decremental weights summing up to 1.0.
    generateWeights = function(noWeights,
                               noRows,
                               distribution = runif,
                               rounding = function(x){ round(x, 1) })
    {
      generator = function()
      {
        x = distribution (noWeights);
        x = x/sum(x);
        sort(rounding(x), decreasing = T)
      } 
      t(replicate(noRows, generator()))
    }
    
    # example of use
    generateWeights(3, 10)
    
    0 讨论(0)
  • 2021-01-18 02:03

    A non-base possibility:

    library(partitions)
    
    step <- 0.1
    n_weights <- 3
    
    t(restrictedparts(n = 1/step, m = n_weights) * step)
    #  [1,] 1.0 0.0 0.0
    #  [2,] 0.9 0.1 0.0
    #  [3,] 0.8 0.2 0.0
    #  [4,] 0.7 0.3 0.0
    #  [5,] 0.6 0.4 0.0
    #  [6,] 0.5 0.5 0.0
    #  [7,] 0.8 0.1 0.1
    #  [8,] 0.7 0.2 0.1
    #  [9,] 0.6 0.3 0.1
    # [10,] 0.5 0.4 0.1
    # [11,] 0.6 0.2 0.2
    # [12,] 0.5 0.3 0.2
    # [13,] 0.4 0.4 0.2
    # [14,] 0.4 0.3 0.3
    
    0 讨论(0)
提交回复
热议问题