Operators — Arithmetic, Comparison and Logic
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.
The shortcut
Write the vectors as columns and apply the operator row by row. Then, if you need a count, remember that sum() of a logical vector counts its TRUEs and mean() gives the proportion.
Compare
kg > 7checks each weight: TRUE TRUE TRUE FALSE FALSE.
The shortcut also catches the && mistake: if the thing on either side is a column of several values, you want the single &.
Drills
Answer fast — trust the rule.
What is 17 %% 5?
What is 17 %/% 5?
What is -2^2 in R?
How many TRUE values does kg < 10 & !watered produce?
What does "bean" %in% c("tomato", "bean", "chilli") return?
Remember
- Every operator runs element by element across whole vectors.
- Shortcut: write the vectors as columns, apply row by row, then
sum()the TRUEs to count. - Trap:
=versus==,-2^2being -4, and&&on vectors.
