How to Round Off Numbers in R - dummies

How to Round Off Numbers in R

By Andrie de Vries, Joris Meys

Although R can calculate accurately to up to 16 digits, you don’t always want to use that many digits. In this case, you can use a couple functions in R to round numbers. To round a number to two digits after the decimal point, for example, use the round() function as follows:

> round(123.456,digits=2)
[1] 123.46

You also can use the round() function to round numbers to multiples of 10, 100, and so on. For that, you just add a negative number as the digits argument:

> round(-123.456,digits=-2)
[1] -100

If you want to specify the number of significant digits to be retained, regardless of the size of the number, you use the signif() function instead:

> signif(-123.456,digits=4)
[1] -123.5

Both round() and signif() round numbers to the nearest possibility. So, if the first digit that’s dropped is smaller than 5, the number is rounded down. If it’s bigger than 5, the number is rounded up.

If the first digit that is dropped is exactly 5, R uses a rule that’s common in programming languages: Always round to the nearest even number. round(1.5) and round(2.5) both return 2, for example, and round(-4.5) returns -4.

Contrary to round(), three other functions always round in the same direction:

  • floor(x) rounds to the nearest integer that’s smaller than x. So floor(123.45) becomes 123 and floor(-123.45) becomes –124.

  • ceiling(x) rounds to the nearest integer that’s larger than x. This means ceiling (123.45) becomes 124 and ceiling(123.45) becomes –123.

  • trunc(x) rounds to the nearest integer in the direction of 0. So trunc(123.65) becomes 123 and trunc(-123.65) becomes –123.