在 R 中将百分比四舍五入为 100% [英] Rounding percentages to 100% in R
问题描述
我在 R 中有一组百分比,我想让它们等于 100%.我需要单个百分比为最接近的整数.
I have a set of percentages in R which I want to make equal to 100%. I need the individual percentages to be to the nearest integer.
我已经四舍五入百分比 [20.5, 50.6, 25.8 , 3.1].然后我四舍五入到最接近的整数 [20,50,25,3].然后计算出各个小数位 [0.5,0.6,0.8.0.1]].然后将小数位按降序排序,但输出为[3,2,1,4].我需要将最高小数位的整数加1,直到达到100.
I have rounded percentages [20.5, 50.6, 25.8 , 3.1].Then I am rounding to the nearest integer [ 20,50,25,3].Then working out the individual decimal places [0.5,0.6,0.8.0.1].Then sorting the decimal places in descending order but output are [ 3,2,1,4].And I need to add 1 to the integer of the highest decimal place until I reach 100.
推荐答案
这并不是一个看起来那么简单的问题.关于这个问题的一些很好的讨论可以在在这个线程中看到 这也是我得到解决方案的地方(与 OP 中的想法相同).
It is not really as trivial a problem as it may seem. Some good discussions about the problem can be seen in this thread and that is also where I got the solution (which is identical to the idea in the OP).
这是一个可以为您完成的功能
Here's a function that might do it for you
round_percent <- function(x) {
x <- x/sum(x)*100 # Standardize result
res <- floor(x) # Find integer bits
rsum <- sum(res) # Find out how much we are missing
if(rsum<100) {
# Distribute points based on remainders and a random tie breaker
o <- order(x%%1, sample(length(x)), decreasing=TRUE)
res[o[1:(100-rsum)]] <- res[o[1:(100-rsum)]]+1
}
res
}
希望这会有所帮助.请注意,上面的函数中根本没有错误检查.
Hope this helps. Note that there is no error checking at all in the function above.
更新:我在 MESS
包中实现了这个版本.看看MESS::round_percent
.
Update: I implemented a version of this in the MESS
package. Look at MESS::round_percent
.
这篇关于在 R 中将百分比四舍五入为 100%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!