Rounding numbers
Problem
You want to round numbers.
Solution
There are many ways of rounding: to the nearest integer, up, down, or toward zero.
x <- seq(-2.5, 2.5, by=.5)
# Round to nearest, with .5 values rounded to even number.
round(x)
#> [1] -2 -2 -2 -1 0 0 0 1 2 2 2
# Round up
ceiling(x)
#> [1] -2 -2 -1 -1 0 0 1 1 2 2 3
# Round down
floor(x)
#> [1] -3 -2 -2 -1 -1 0 0 1 1 2 2
# Round toward zero
trunc(x)
#> [1] -2 -2 -1 -1 0 0 0 1 1 2 2
It is also possible to round to other decimal places:
x <- c(.001, .07, 1.2, 44.02, 738, 9927)
# Round to one decimal place
round(x, digits=1)
#> [1] 0.0 0.1 1.2 44.0 738.0 9927.0
# Round to tens place
round(x, digits=-1)
#> [1] 0 0 0 40 740 9930
# Round to nearest 5
round(x/5)*5
#> [1] 0 0 0 45 740 9925
# Round to nearest .02
round(x/.02)*.02
#> [1] 0.00 0.08 1.20 44.02 738.00 9927.00