# https://www.r-bloggers.com/2016/07/round-values-while-preserve-their-rounded-sum-in-r/ # E.G. # > 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 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 }