R Math Functions
A math function does a fixed calculation on a number. R ships with built-in math functions for common jobs.
Size and square root
abs drops the sign from a negative number. sqrt gives the square root of 25.
print(abs(-9))
print(sqrt(25))Rounding numbers
round keeps two digits after the point. ceiling rounds up and floor rounds down.
print(round(3.567, 2))
print(ceiling(4.2))
print(floor(4.8))Sign and exp
sign reports a value for each of the three numbers. The final print shows the result of calling exp with 1.
print(sign(-12))
print(sign(7))
print(sign(0))
print(exp(1))Example
change <- -2.75
print(abs(change))
print(round(change, 1))
print(floor(change))
print(sqrt(16))Key points
- A function call writes the function name first.
- The values for a call sit inside parentheses after the name.
- abs gives the size of a number with no sign.
- sqrt gives the square root of a number.
- round rounds a number to a chosen count of digits.
- The second value in a round call says how many digits to keep.
- ceiling rounds a number up and floor rounds a number down.
- sign gives 1 for a positive number, 0 for zero and -1 for a negative number.
In this example, abs drops the sign from the change value. round keeps one digit and floor rounds the value down. sqrt then gives the square root of 16.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does print(round(3.567, 2)) show?