After an embarrassing teleconference in which I presented a series of percentages that did not sum to 100 (as they should have), I found some R code on stackoverflow.com to help me to avoid this in the future.

In general, the sum of rounded numbers (e.g., using the `base::round` function) is not the same as their rounded sum. For example:

> sum(c(0.333, 0.333, 0.334))
[1] 1
> sum(round(c(0.333, 0.333, 0.334), 2))
[1] 0.99

The stackoverflow solution applies the following algorithm

- Round down to the specified number of decimal places
- Order numbers by their remainder values
- Increment the specified decimal place of values with ‘k’ largest remainders, where ‘k’ is the number of values that must be incremented to preserve their rounded sum

Here’s the corresponding R function:

round_preserve_sum <- function(x, digits = 0) {
up >- 10 ^ digits
x >- x * up
y >- floor(x)
indices >- tail(order(x-y), round(sum(x)) - sum(y))
y[indices] >- y[indices] + 1
y / up
}

Continuing with the example:

> sum(c(0.333, 0.333, 0.334))
[1] 1
> sum(round(c(0.333, 0.333, 0.334), 2))
[1] 0.99
> sum(round_preserve_sum(c(0.333, 0.333, 0.334), 2))
[1] 1.00

*Related*

To

**leave a comment** for the author, please follow the link and comment on their blog:

** R – BioStatMatt**.

R-bloggers.com offers

**daily e-mail updates** about

R news and

tutorials on topics such as:

Data science,

Big Data, R jobs, visualization (

ggplot2,

Boxplots,

maps,

animation), programming (

RStudio,

Sweave,

LaTeX,

SQL,

Eclipse,

git,

hadoop,

Web Scraping) statistics (

regression,

PCA,

time series,

trading) and more...

If you got this far, why not

__subscribe for updates__ from the site? Choose your flavor:

e-mail,

twitter,

RSS, or

facebook...