6  R as a calculator

Before we start

You must

6.1 Basic operations in R

6.1.1 Arithmetic operations

Performing arithmetic operations is no big deal in R. Simply write any operation using the usual arithmetic operators +, -, * and / and run your code. No need to type =.

5 + 3
[1] 8
9 * 2
[1] 18
14 / 3
[1] 4.666667

R allows you to add parentheses ( ) when you need to impose the order of operations. When it comes to raising a number to the power of another one, use the symbol ^ or **.

(24 + 3) ^ (1 / 3)
[1] 3
Exercise

In R, calculate:

  • 25 plus 49
  • 6 minus 19
  • 8 multiplied by 6
  • 7 divided by 2
  • 9 squared
  • multiply the sum of 9 and 2 by 3

6.1.2 Comparisons

You can compare 2 elements using the following operators:

  • > greater than,
  • >= greater than or equal to,
  • < less than,
  • <= less than or equal to,
  • == equal to,
  • != not equal to.

When comparing two elements, R returns either TRUE or FALSE.

9 == 3 * 3
[1] TRUE
5 > 4
[1] TRUE
9^2 != 9 * (3 + 6)
[1] FALSE
Exercise

In R,

  • Test whether 22/7 is larger than pi
  • Test if cats are greater than dogs. Why? (remember to use quote marks)
    Hint Prøv katter og hunder også

6.1.3 Operations with functions

More complex operations such as square root, logarithms and exponentiation shall be run using specific functions. These functions are sqrt(), log(), exp(), etc.

Exercise

In R, calculate

  • The square root of 29
  • The exponent of 29
  • The natural logarithm of 29
  • The base 10 logarithm of 29

You may need to look at the built-in help (Chapter 7) for some of these.

What’s next

How to get help (Chapter 7)

Contributors

  • Jonathan Soulé
  • Aud Halbritter
  • Richard Telford