Extended Operators

Now that you’re comfortable with the four basic arithmetic operators and how R decides which operation to do first, we can extend your toolkit with a few more operators and functions that come up often in real analyses. You don’t need to memorize all of these today, treat this page as a reference you can come back to.

Powers & Roots

We use the caret character, ^, to specify exponents. The following code will square and cube the value of y.

y^2
[1] 49
y^3
[1] 343

Do: run the code, then predict the output of the next chunk before revealing it.

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.

sqrt(y)
[1] 2.645751

For other roots, we can use fractional exponents.

y^(1/3) # cube root of y
[1] 1.912931
y^(1/4) # quartic root of y
[1] 1.626577

Other Common Operators

R also includes many special functions for the most common mathematical operations. Rather than trying to memorize every one of these right now, skim the code and its comments once, then use it as a reference whenever you need one of these operations later.

log(y)   # natural logarithm of y
[1] 1.94591
log10(y) # log base 10 of y
[1] 0.845098
log2(y)  # log base 2 of y
[1] 2.807355
exp(x) # exponentiate x
[1] 12.18249
y %% x # modulo: remainder after dividing y by x
[1] 2
foo <- -3.14159

round(foo, 3) # round 'foo' to 3 decimal places
[1] -3.142
floor(foo)    # round 'foo' down to the nearest whole number
[1] -4
ceiling(foo)  # round 'foo' up to the nearest whole number
[1] -3
abs(foo) # absolute value of 'foo'
[1] 3.14159
Note

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.

Practice
  1. Create an object called age that takes the value of your age in whole years.
  2. Use the age object you created above to create a second object called weeks that 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 age contains 52 whole weeks).
  3. Print the value of weeks.
  4. Use the modulo operator, %%, to check whether weeks is 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 38 years old. So, these would be my age and weeks objects.

age   <- 38
weeks <- 38 * 52
weeks
[1] 1976
weeks %% 4
[1] 0

Quick Check

Which function would you use to…

  • …find the remainder after division? (round() / %% / abs())
  • …always round a number up? (floor() / ceiling() / round())
  • …remove the negative sign from a number? (sqrt() / abs() / exp())

Try each candidate function in the editor to verify your answer if you’re unsure.

Back to top