June 2007
Beginner to intermediate
950 pages
27h 8m
English
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
Read now
Unlock full access