round_preserve_sum: Round values while preserve their rounded sum in R

View source: R/round_preserve_sum.R

round_preserve_sumR Documentation

Round values while preserve their rounded sum in R

Description

In general, the sum of rounded numbers (e.g., using the base::round function) is not the same as their rounded sum. This 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

Usage

round_preserve_sum(x, digits = 0)

Arguments

x

vector to sum

digits

number of decimals for rounding

Source

https://www.r-bloggers.com/round-values-while-preserve-their-rounded-sum-in-r/ and http://stackoverflow.com/questions/32544646/round-vector-of-numerics-to-integer-while-preserving-their-sum

Examples

sum(c(0.333, 0.333, 0.334))
round(c(0.333, 0.333, 0.334), 2)
sum(round(c(0.333, 0.333, 0.334), 2))
round_preserve_sum(c(0.333, 0.333, 0.334), 2)
sum(round_preserve_sum(c(0.333, 0.333, 0.334), 2))

larmarange/JLutils documentation built on March 24, 2023, 6:39 a.m.