2015-07-28 47 views
8

您是否知道生成矩陣的更有效方法,該矩陣包含所有「權重」的唯一組合(讓權重爲w和0 < = w < = 1,並且w的值以0.1的步長分隔),使得權重總和爲1,第一個是最高權重,最後一個是最低權重。生成總計爲1的值的組合,按降序排列

這裏是代碼,沒有工作,但似乎沒有效率的刪除行:

# generate combinations of weights such that w1 >= w2 >= w3 ... 
w = seq(0, 1, 0.1) #weights 0, 0.1, ..., 0.9, 1 
w = expand.grid(w, w, w, KEEP.OUT.ATTRS = FALSE) #all combinations of 3 weights 
w = w[rowSums(w) == 1, ] #make sure the weights sum to one 
w = w[!(w[, 1] < w[, 2] | w[, 2] < w[, 3]),] #make sure w1 >= w2 >= w3 ... 

w  
#  Var1 Var2 Var3 
# 11 1.0 0.0 0.0 
# 21 0.9 0.1 0.0 
# 31 0.8 0.2 0.0 
# 41 0.7 0.3 0.0 
# 51 0.6 0.4 0.0 
# 61 0.5 0.5 0.0 
# 141 0.8 0.1 0.1 
# 151 0.7 0.2 0.1 
# 171 0.5 0.4 0.1 
# 271 0.6 0.2 0.2 
# 281 0.5 0.3 0.2 
# 291 0.4 0.4 0.2 
# 401 0.4 0.3 0.3 

讓我補充一些基本信息: 在這個問題(3個權重按上述順序)的上限用於第一,第二,第三值如下:

  • 所述第一數目可以最低限度地是1所述的組合(1,0,0)
  • 第二數量可以最大程度地是1/2的組合(1/2,1/2,0)
  • 第三數量可以最大程度地是1/3的組合(1/3,1/3,1/3)
+0

在示例輸出中,您顯示權重不等於一個......從您的代碼中我假設它們應該總和爲'<= 1'。如果是這種情況,你應該編輯你的問題。 –

+0

最後的三點也是多餘的,因爲它們遵循每行中第一個元素必須是最大的要求。 – slabofguinness

+0

@ user2706569編輯了這個問題,是一個錯字。 – JBJ

回答

4

甲非base可能性:

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 
1

通用功能使用標準包:

# 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) 
+1

運行之前需要進行相當多的調整... –

+1

「行」和「列」在哪裏定義?爲什麼「noWeights」和「noRows」未被使用? 「gen」應該等於「generateWeights」嗎? – mra68

+0

對不起。固定。 – Yester