R Arithmetic Operators
R's arithmetic operators let you perform calculations on numbers and vectors, including two division-related operators — %% and %/% — that many other languages don't offer as built-ins.
The Basic Arithmetic Operators
R supports the operators you'd expect from a calculator, plus two extras for working with whole-number division. Every one of them also works directly on vectors, applying the calculation to each element in turn.
Basic Calculations
10 + 3
10 - 3
10 * 3
10 / 3
10 ^ 2Vectorized Arithmetic
When you apply an arithmetic operator to a vector, R calculates element by element. If the two vectors are different lengths, R recycles the shorter one — repeating it from the start — as long as the longer length is a multiple of the shorter one.
Working with Vectors
prices <- c(10, 20, 30, 40)
discount <- c(1, 2)
prices - discount
prices * 1.1Modulo and Integer Division
%% returns the remainder of a division, and %/% returns the whole-number quotient, discarding any remainder. Together they're the standard way to check divisibility, convert a total count into groups, or split minutes into hours and leftover minutes.
Practical Uses
2024 %% 4 == 0
total_minutes <- 137
hours <- total_minutes %/% 60
minutes <- total_minutes %% 60
c(hours, minutes)