Rounding Numbers in R

Rounding numbers in R

This tutorial explains several different ways to round numbers in R.

Rounding Numbers

Suppose we have the following vector that contains 5 elements:

#create a vector x of 5 elements
x <- c(1.7, 12.5, 134, 7.3, -8.2)

The following code demonstrates several different methods of rounding the elements in this vector:

#round to the nearest integer
round(x)

#[1] 2 12 134 7 -8

#round up
ceiling(x)

#[1] 2 13 134 8 -8

#round down
floor(x)

#[1] 1 12 134 7 -9

#round toward zero
trunc(x)

#[1] 1 12 134 7 -8

#round to one decimal place
round(x, 1)

#[1] 1.7 12.5 134.0 7.3 -8.2

#round to the nearest tens place
round(x, -1)

#[1] 0 10 130 10 -10

#round to the nearest hundreds place
round(x, -2)

#[1] 0 0 100 0 0

#round to the nearest 5
round(x/5)*5

#[1] 0 10 135 5 -10

#round to the nearest .05
round(x/.05)*.05

#[1] 1.7 12.5 134.0 7.3 -8.2

Leave a Reply

Your email address will not be published. Required fields are marked *