Operators
“Data is the new oil.” — Clive Humby
Before you start: R objects; indexing.
Setup: No data files are needed. Run setup and code blocks from the top of this page.
Your check: Choose comparison and logical operators for the intended decision. Practise in the unit summary.
Operators perform calculations, compare values, or combine logical values. Control structures use logical conditions to decide which code to run. Common examples include arithmetic operations such as addition (+), comparisons such as greater than (>), and Boolean operations such as AND (& or && in R).
| Operator | Description | Example |
|---|---|---|
| Arithmetic operators | ||
| + | Addition | x + y |
| - | Subtraction | x - y |
| * | Multiplication | x * y |
| / | Division | x / y |
| ^ or ** | Exponentiation | x^y |
| x %% y | Modulus (x mod y) | x %% y |
| Relational operators | ||
| < | Test whether x is smaller than y | x < y |
| > | Test whether x is greater than y | x > y |
| == | Test whether x equals y | x == y |
| >= | Test whether x is greater than or equal to y | x >= y |
| <= | Test whether x is less than or equal to y | x <= y |
| != | Test whether x differs from y | x != y |
| Logical operators | ||
| ! | logical NOT | !x |
| & | element-wise logical AND | x & y |
| && | logical AND | x && y |
| | | element-wise logical OR | x | y |
| || | logical OR | x || y |
Information
- Modulo gives the remainder after division.
Example: 10 %% 3 = 1 (i.e. "ten modulo three equals one")
because 10 / 3 = 3, remainder 1 (3 * 3 + 1 = 10) - Relational operators compare values.
- Logical operators carry out Boolean operations such as AND, OR, and NOT on logical values.
- Operators & and | perform element-wise operations. Their result has the length of the longer operand.
Operators && and || use a single logical value from each operand and return a single logical value. Use length-one operands; supplying a vector with more than one element causes an error in current R versions.