Round values while preserve their rounded sum in R

July 27, 2016
By

(This article was first published on R – BioStatMatt, and kindly contributed to R-bloggers)

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

    1. Round down to the specified number of decimal places
    2. Order numbers by their remainder values
    3. 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

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...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)