分数として表され、降順にソートされた、さまざまなイベントの頻度のベクトルを計算しました。合計すると正確に 100 になる正の整数パーセンテージを必要とするツールに接続する必要があります。入力分布を最もよく表す方法でパーセンテージを生成したいと考えています。つまり、パーセンテージ間の関係 (比率) が入力分数の関係 (比率) に最もよく一致するようにしたいと考えています。
これらのパーセンテージを生成する関数がありますが、最適またはエレガントではないと思います。特に、「愚かな整数のトリック」に頼る前に、数値空間でより多くの作業を行いたいと考えています。
周波数ベクトルの例を次に示します。
fractionals <- 1 / (2 ^ c(2, 5:6, 8, rep(9,358)))
そして、ここに私の機能があります:
# Convert vector of fractions to integer percents summing to 100
percentize <- function(fractionals) {
# fractionals is sorted descending and adds up to 1
# drop elements that wouldn't round up to 1% vs. running total
pctOfCum <- fractionals / cumsum(fractionals)
fractionals <- fractionals[pctOfCum > 0.005]
# calculate initial percentages
percentages <- round((fractionals / sum(fractionals)) * 100)
# if sum of percentages exceeds 100, remove proportionally
i <- 1
while (sum(percentages) > 100) {
excess <- sum(percentages) - 100
if (i > length(percentages)) {
i <- 1
}
partialExcess <- max(1, round((excess * percentages[i]) / 100))
percentages[i] <- percentages[i] - min(partialExcess,
percentages[i] - 1)
i <- i + 1
}
# if sum of percentages shorts 100, add proportionally
i <- 1
while (sum(percentages) < 100) {
shortage <- 100 - sum(percentages)
if (i > length(percentages)) {
i <- 1
}
partialShortage <- max(1, round((shortage * percentages[i]) / 100))
percentages[i] <- percentages[i] + partialShortage
i <- i + 1
}
return(percentages)
}
何か案は?