R Arithmetic Operators
Arithmetic Operators
Arithmetic operators are used with numeric values to do common math, like the calculations you know from school:
| Operator | Name | Description | Example | Try it |
|---|---|---|---|---|
| + | Addition | Adds together two values | x + y | Try it » |
| - | Subtraction | Subtracts one value from another | x - y | Try it » |
| * | Multiplication | Multiplies two values | x * y | Try it » |
| / | Division | Divides one value by another | x / y | Try it » |
| ^ | Exponent | Raises a value to the power of another | x ^ y | Try it » |
| %% | Modulus | Returns the remainder of a division | x %% y | Try it » |
| %/% | Integer Division | Divides, and removes the decimals | x %/% y | Try it » |
Here is an example that uses all the arithmetic operators:
Example
x <- 10
y <- 3
x + y
x - y
x * y
x / y
x ^ y
x %% y
x %/% y
Try it Yourself »
Note: The / operator always gives the exact answer, also when it has decimals: 10 / 3 is 3.333333. If you only want the whole number, use %/% instead.
Integer Division and Modulus
The %/% and %% operators are often used together.
Imagine that you share 14 candies with 4 friends. %/% tells you how many candies each friend gets, and %% tells you how many candies are left over:
Example
candies <- 14
friends <- 4
candies %/% friends
candies %% friends
Try it Yourself »
Each friend gets 3 candies (4 * 3 = 12), and 2 candies are left over.
Real-Life Example: Even or Odd
The %% operator is useful to check if a number is even or odd. An even number has no remainder when you divide it by 2:
Example
number <- 7
number %% 2
Try it Yourself »
The result is 1, so 7 is an odd number. For an even number, like 8, the result would be 0.