Round values preserving their sum. Often used to round percentages such that their totals still add to 100

round_preserve_sum(x, digits = 0)

Arguments

x

numeric vector to round

digits

integer indicating the number of decimal places to be used

Value

a numeric value

Examples

x <- c(10.3, 20.3, 69.4) # These three values add to 100 sum(x)
#> [1] 100
# But when rounded they do not add to 100 sum(round(x))
#> [1] 99
# Using round_preserve_sum ensures the rounded values add to 100 round_preserve_sum(x)
#> [1] 10 20 70
sum(round_preserve_sum(x))
#> [1] 100