Learn R Programming

dtlg (version 0.0.2)

round_sum: Rounds numbers while preserving the total sum

Description

round_sum() rounds a numeric vector of non-negative values to a specified number of decimal places while ensuring that the sum of the rounded value remains as close as possible to the original total.

Usage

round_sum(x, digits = 0L)

Value

A numeric vector of the same length as x, with values rounded in such a way that the total sum is preserved.

Arguments

x

A numeric vector of non-negative values that you want to round. Missing values (NA) are ignored.

digits

The number of decimal places to round to. Default is 0 (integer rounding).

Examples

Run this code
# Rounds to integers, preserving the sum of 100.
x <- c(33.3333, 33.3333, 33.3334)
(y <- round_sum(x))
identical(sum(x), sum(y))

# Rounds to integers, preserving the sum of 1002.
x <- c(100.5, 200.25, 300.75, 400.5)
(y <- round_sum(x))
identical(sum(x), sum(y))

# Rounds to one decimal place, preserving the total sum.
x <- c(12.345, 67.890, 19.765)
(y <- round_sum(x))
identical(sum(x), sum(y))

Run the code above in your browser using DataLab