Function that uses the largest remainder method to ensure that a set of percentages sum to 100% even in the presence of rounding error.

percent_that_sums_to_100(x, digits = 1, freq = FALSE)

Arguments

x

A vector of proportions or frequencies that are suppose to sum to 100%.

digits

The number of digits to round to.

freq

Logical; if TRUE assumes x is a vector of frequencies, otherwise assumes x is a vector of proportions.

Value

A vector of percentages that sum to 100%.

Examples

x <- c( 9990, 5, 5 )
# Convert to percentage and round
p <- round( 100*x/sum(x), 1 )
# No longer sums to 100% due to rounding error
print( sum(p) )
#> [1] 99.9
# Adjust percentages using the
# largest remainder method so
# they sum to 100%
print( percent_that_sums_to_100( p/100 ) )
#> [1] 100   0   0
# Works with frequencies as well
print( percent_that_sums_to_100( x, freq = TRUE ) )
#> [1] 100   0   0