我在 R 中有一组百分比,我想让它们等于 100%。我需要单个百分比为最接近的整数。
我已经四舍五入百分比 [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。
这并不像看起来那么简单。在此线程中可以看到有关该问题的一些很好的讨论,这也是我得到解决方案的地方(与 OP 中的想法相同)。
这是一个可以为您完成的功能
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
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。请注意,上面的函数中根本没有错误检查。
更新:我在MESS包中实现了这个版本。看看MESS::round_percent。