Rounding - Cghlewis/data-wrangling-functions GitHub Wiki

Because R has unexpected behavior when rounding, I thought it was worth covering a few rounding options and the differences between those options.

First, it is important for everyone to know that, when rounding to whole numbers, base R does not round in the normal way many of us think of rounding, like this:

1.5 -> 2
2.5 -> 3
3.6 -> 4
4.2 -> 4

Instead it uses banker's rounding, and rounds like this

1.5 -> 2
2.5 -> 2
3.6 -> 4
4.2 -> 4

So you'll notice, everything looks as expected except at 2.5. And this is because at .5, R rounds to the even number, rather than always rounding up.

If you are rounding to 1 or more decimal places, I believe rounding will be your typical rounding behavior, where we round up at 5 or higher and down at 4 or lower. However, since decimal places are not represented exactly, you may get different results depending on your OS. See documentation on round for more information.

In the examples below we explore the way R rounds, and show an alternative way to round using the janitor package.

Round values


Main functions used in examples

Package Functions
base round()
janitor round_half_up()

Other functions used in examples

Package Functions
dplyr mutate(); across()
base ceiling(); floor(); trunc()

Resources