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

后端 未结 2 974
天涯浪人
天涯浪人 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)
    

提交回复
热议问题