Rounding percentages to 100% in R

霸气de小男生 提交于 2019-12-11 06:39:36

问题


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.

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.


回答1:


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.

Update: I implemented a version of this in the MESS package. Look at MESS::round_percent.



来源:https://stackoverflow.com/questions/40515869/rounding-percentages-to-100-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!