R 生成总和为1的值的组合,按降序排序
你知道一种更有效的方法来生成一个包含所有唯一“权重”组合的矩阵吗(让权重为w,0=w3。。。 w=序列(0,1,0.1)#权重0,0.1,…,0.9,1 w=展开.grid(w,w,w,KEEP.OUT.ATTRS=FALSE)#3个权重的所有组合 w=w[rowSums(w)==1,]#确保权重总和为1 w=w[!(w[,1]R 生成总和为1的值的组合,按降序排序,r,R,你知道一种更有效的方法来生成一个包含所有唯一“权重”组合的矩阵吗(让权重为w,0=w3。。。 w=序列(0,1,0.1)#权重0,0.1,…,0.9,1 w=展开.grid(w,w,w,KEEP.OUT.ATTRS=FALSE)#3个权重的所有组合 w=w[rowSums(w)==1,]#确保权重总和为1 w=w[!(w[,1]=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
- 对于组合(1,0,0),第一个数字至少可以是1
- 对于组合(1/2,1/2,0),第二个数字可以最大为1/2
- 对于组合(1/3、1/3、1/3),第三个数字最多可为1/3
- 一种非
基础
可能性:
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
库(分区)
步骤带有标准软件包的通用功能:
# 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)
在示例输出中,您显示的权重总和不是一……根据您的代码,我假设它们的总和应该是,并且末尾的三个点是多余的,因为它们符合每行的第一个元素必须是最大的要求。@user2706569编辑了这个问题,是一个打字错误。@Seamus O'Baired:您的注释I当然,这在逻辑上是正确的!但是一个好的问题不一定是冗余最少的问题,对吗?它是最清楚的问题。因此,我认为,解释事物比冗余最少更重要。你期望这些变量的分布是什么?在运行之前需要进行大量调整……行和列在哪里定义?为什么不使用“noWeights”和“noRows”?是“gen”应该等于“generateWeights”?很抱歉。修正了。在这种情况下,“genarateWeights(3,10)只产生13个三元组中的10个。我想我没有得到你最后的评论。
# 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)