【问题标题】:Rounding percentages to 100% in R在 R 中将百分比四舍五入到 100%
【发布时间】:2016-11-09 20:55:38
【问题描述】:

我在 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。

【问题讨论】:

  • 可重现的示例以准确说明您的意思?
  • 请添加示例数据集以及到目前为止您尝试过的代码
  • 我添加了一个示例数据集,现在可能更清楚了

标签: r rounding percentage


【解决方案1】:

这并不是一个看起来那么简单的问题。关于这个问题的一些很好的讨论可以看到in this thread,这也是我得到解决方案的地方(这与 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 
}

希望这会有所帮助。请注意,上面的函数中根本没有错误检查。

更新:我在MESS 包中实现了这个版本。看MESS::round_percent

【讨论】:

    猜你喜欢
    • 2021-02-18
    • 1970-01-01
    • 2013-11-19
    • 2015-12-05
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多