# Define three objects to use in the following examples
x <- 2.5
y <- 7
z <- 5Additional Mathematical Operators
Now that you’re comfortable with the four basic arithmetic operators, we can extend your toolkit with a few additional, commonly encountered mathematical operators. You don’t need to memorize all of these today, treat this page as a reference to which you can return.
Powers & Roots
We use the caret character, ^, to specify exponents. For example, the following code will square and cube the value of y.
y^2[1] 49
y^3[1] 343
The sqrt() function returns the square root of its argument (i.e., the value we specify inside the parentheses). The following code calculates the square root of y.
Don’t worry about exactly what we mean by a function, just yet. You’ll learn all about those in the R Functions module.
sqrt(y)[1] 2.645751
For other roots, we can use fractional exponents.
# Cute root of y
y^(1 / 3)[1] 1.912931
# Quartic root of y
y^(1 / 4)[1] 1.626577
Other Common Operators
R also includes many special functions for the most common mathematical operations.
# Natural logarithm of 'y'
log(y)[1] 1.94591
# Base-10 logarithm of 'y'
log10(y)[1] 0.845098
# Base-2 logarithm of 'y'
log2(y)[1] 2.807355
# Exponentiate 'x'
exp(x)[1] 12.18249
# Modulo: Remainder after dividing 'y' by 'x'
y %% x[1] 2
foo <- -3.14159
# Round 'foo' to 3 decimal places
round(foo, 3)[1] -3.142
# Round 'foo' down to the nearest whole number
floor(foo)[1] -4
# Round 'foo' up to the nearest whole number
ceiling(foo)[1] -3
# Absolute value of 'foo'
abs(foo)[1] 3.14159
Note that log(y) calculates the natural logarithm of y, \(\ln(y)\). If you want the “ordinary” base-10 log, you need to use the log10() function.
- Create an object called
agethat takes the value of your age in whole years. - Use the
ageobject you created above to create a second object calledweeksthat takes the value of your age in whole weeks.- Assume 52 weeks in each year.
- Disregard partial years (i.e., assume every year counted in
agecontains 52 whole weeks).
- Print the value of
weeks. - Use the modulo operator,
%%, to check whetherweeksis evenly divisible by 4.
For step 4, remember that a %% b returns the remainder after dividing a by b. A value is evenly divisible by b whenever that remainder is 0.
At time-of-writing, I’m 40 years old. So, these would be my age and weeks objects.
age <- 40
weeks <- 40 * 52
weeks[1] 2080
To see if my weeks value is evenly divisible by 4, I’ll apply the modulo operator.
weeks %% 4[1] 0
Since the remainder after dividing my weeks value by 4 is equal to 0, we conclude that my weeks value is evenly divisible by 4.
Which function would you use to find the remainder after division?
round()%%abs()
Which function would you use to always round a number up?
floor()ceiling()round()
Which function would you use to remove the negative sign from a number, without changing its magnitude?
sqrt()abs()exp()
Try each candidate function in the editor to verify your answer.