Operators — Arithmetic, Comparison and Logic
R's arithmetic, comparison and logical operators work element by element across whole vectors, producing numbers or TRUE and FALSE values you can count and combine.
Compare vectorized calculations, comparisons and logical operations on example inputs.
The garden coordinator asks: "How many plots gave more than 7 kg, and how many of those were watered?" In many languages you would write a loop. In R, a few operators applied to whole vectors answer it in one line.
The rule
Every operator runs element by element across whole vectors.
Line two vectors up and R applies the operator to each pair of positions. A single number is a vector of length one, so it is simply reused for every position.
kg <- c(12.5, 8, 15, 3.5, 6)
watered <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
kg * 1000 # 12500 8000 15000 3500 6000
kg > 7 # TRUE TRUE TRUE FALSE FALSE
kg > 7 & watered # TRUE FALSE TRUE FALSE FALSE
sum(kg > 7) # 3, since each TRUE counts as 1Arithmetic: +, -, *, /, and ^ for powers (2^3 is 8). Two you will use for grouping and remainders:
%/%is integer division:17 %/% 5is 3.%%is the remainder:17 %% 5is 2.
Comparison: ==, !=, <, >, <=, >=. Each gives a logical vector of TRUE and FALSE. Remember the double equals: one = assigns, two compare.
Logic: ! (not), & (and), and a single vertical bar for "or". These three work element by element too. Their doubled forms, && and a double bar, compare exactly one TRUE or FALSE and stop early once the answer is known. Use the doubled forms inside if (), where you need one answer, and the single forms on vectors. Since R 4.3, giving && a vector longer than one is an error.
Membership: %in% asks whether each value on the left appears anywhere on the right: "chilli" %in% c("tomato", "bean", "chilli") is TRUE.
Precedence follows maths, with one surprise: ^ binds tighter than a leading minus, so -2^2 is -4, not 4. When in doubt, add brackets.