55 floor(), ceiling(), round(), and abs()
Written by José Casas and last updated on 7 October 2021.
55.1 Introduction
In this lesson, you will learn how to:
- Use
floor()
andceiling()
to get the floor and ceiling of a number, respectively. - Use
round()
to round a number to a specified number of decimal places. - Use
abs()
to compute the absolute value of a number.
Prerequisites:
- Basic knowledge of R.
All of the following functions can only take numeric or logical (TRUE and FALSE) objects, and NA. These functions also work with vectors of those types.
55.2 floor()
and ceiling()
The floor and ceiling of a number are defined as the nearest integer less than and greater than that number, respectively. The floor and ceiling of an integer number are the same number.
Here, we will use floor()
and ceiling()
to get the floor and ceiling of a single number. For this, simply put a number as the function argument:
floor()
and ceiling()
can also take a vector as an argument:
55.3 round()
round()
lets you round up a number to however many decimal places you want. It takes two arguments: the value to be rounded, and the number of decimal places (called digits
in the function).
For example:
round()
can also take a vector as an argument:
numbers <- c(6.2345, 24.545611, 5, 8.29, 0.00003)
round(numbers, digits = 3)
#> [1] 6.234 24.546 5.000 8.290 0.000
Notice that round()
does “round up” after decimals greater than 5, for example:
round()
can also be used to round to a power of ten, by giving a negative number for the second argument. This negative number \(n\) represents the nearest \(n\)-th power of ten. For example, using -2 will round to the nearest hundred.
More examples:
55.4 abs()
The absolute value is defined as the distance of a number from the origin of a number line.
With abs()
you can calculate the absolute value of a number. For example:
abs()
can also take a vector as an argument:
55.5 Exercises
55.6 Common Errors
-
non-numeric argument to mathematical function
. Remember, all of the functions can only take numeric values, logical objects (TRUE and FALSE), or NA, so if you input something else you will get this error. Make sure that your input doesn’t have some text hiding in there!