Rounding

Various sorts of rounding (rounding up, rounding down, rounding to the nearest integer) can be done easily. Take 5.7 as an example. The ‘greatest integer less than’ function is floor

floor(5.7)

[ 1 ]  5

and the ‘next integer’ function is ceiling

ceiling(5.7)

[1] 6

You can round to the nearest integer by adding 0.5 to the number then using floor. There is a built-in function for this, but we can easily write one of our own to introduce the notion of function writing. Call it rounded, then define it as a function like this:

rounded<-function(x) floor(x+0.5)

Now we can use the new function:

rounded(5.7)

[1] 6

rounded(5.4)

[1] 5

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.