Programmer1
Programmer1

Reputation: 23

Rounding percentages to 100% in R

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.

Upvotes: 2

Views: 2781

Answers (1)

ekstroem
ekstroem

Reputation: 6181

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.

Upvotes: 9

Related Questions