Chapter 17: R Operators
R Operators — the symbols and keywords that let you do calculations, comparisons, assignments, logical decisions, and more. Operators are the “verbs” and “connectors” of the language.
I’ll explain this like we’re sitting together in RStudio: slowly, category by category, with lots of real examples (many Hyderabad-flavored), tables for quick reference, common pitfalls, and 2026 best-practice tips.
1. Assignment Operators (The Most Important First)
These are how you create / update variables.
| Operator | Meaning | Example | Recommended? | Notes |
|---|---|---|---|---|
| <- | Left assignment (classic R style) | temperature <- 29.5 | ★ Yes ★ | Most common in modern R, very clear |
| = | Left assignment (alternative) | temperature = 29.5 | Sometimes | Works, but can be confusing in function arguments |
| -> | Right assignment | 29.5 -> temperature | Rarely | Looks backward, avoid in normal code |
| ->> | Right global assignment | 29.5 ->> global_temp | Very rare | Assigns to global environment from inside functions |
| <<- | Left super-assignment | <<- inside functions | Advanced | Modifies variable in parent environment |
Modern recommendation (2026): Always use <- for normal assignments — it’s clearer and avoids confusion.
|
0 1 2 3 4 5 6 7 8 9 10 |
# Good style avg_temp_hyd <- mean(c(28.5, 29.8, 30.2)) # Confusing (avoid) lm(mpg ~ wt, data = mtcars = new_data) # syntax error or surprise! |
2. Arithmetic Operators (Calculator Stuff)
These work element-wise on vectors — R’s superpower.
| Operator | Meaning | Example | Result (when vectorized) |
|---|---|---|---|
| + | Addition | temps + 2 | every element +2 |
| – | Subtraction | revenue – cost | element-wise |
| * | Multiplication | prices * quantities | element-wise |
| / | Division | total / n_students | element-wise |
| ^ or ** | Exponentiation | 2 ^ 3 or 1.1 ** 12 | same |
| %% | Modulo (remainder) | 17 %% 5 → 2 | very useful in indexing |
| %/% | Integer division | 17 %/% 5 → 3 | floor division |
|
0 1 2 3 4 5 6 7 8 9 |
celsius <- c(28.5, 29.8, 30.2, 27.9) fahrenheit <- celsius * 9/5 + 32 print(round(fahrenheit, 1)) # 83.3 85.6 86.4 82.2 |
3. Comparison / Relational Operators (Create Logicals)
These return TRUE / FALSE vectors — used everywhere for filtering.
| Operator | Meaning | Example | Typical use |
|---|---|---|---|
| == | Equal | city == “Hyderabad” | exact match |
| != | Not equal | marks != 0 | exclude |
| > | Greater than | temp > 30 | hot days |
| >= | Greater or equal | score >= 40 | passing |
| < | Less than | age < 18 | minors |
| <= | Less or equal | price <= 500 | budget |
|
0 1 2 3 4 5 6 7 8 9 |
marks <- c(92, 68, 85, 45, 78) passed <- marks >= 50 print(passed) # TRUE FALSE TRUE FALSE TRUE sum(passed) # 3 passed |
Very common mistake: = instead of == inside conditions → syntax error or wrong logic.
4. Logical Operators (Combine Conditions)
| Operator | Meaning | Vectorized? | Example code | When to use |
|---|---|---|---|---|
| & | AND | Yes | (temp > 30) & (humid > 60) | filtering |
|
OR | Yes | (marks < 40) |
|
| ! | NOT | Yes | !is_weekend | negation |
| && | AND (scalar) | No | if (x > 0 && y > 0) {...} | if / while |
|
OR (scalar) | No | ||
| xor() | Exclusive OR | Yes | xor(a, b) → true if exactly one is true | rare |
Key difference:
- & / → work element-by-element → perfect for vector filtering
- && / || → stop at first FALSE / TRUE → used only in control flow (if, while)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
hot_days <- temps >= 30 humid_days <- humid >= 60 uncomfortable <- hot_days & humid_days print(uncomfortable) # Inside if (scalar only) if (length(temps) > 0 && mean(temps) > 28) { cat("It's been warm this week!\n") } |
5. Other Very Useful Special Operators
| Operator | What it does | Example | Very common in … |
|---|---|---|---|
| %in% | Membership test | "Hyd" %in% c("Hyd", "Bng", "Del") → TRUE | filtering |
| : | Sequence operator | 1:10, seq_dates <- date1:date2 | loops, indices |
| $ | Extract by name (list / data.frame) | students$marks, df$city | data frames |
| [[ ]] | Extract single element (list) | my_list[[1]], results[["model"]] | lists |
| [ ] | Extract subset | marks[passed], df[ , c("name","marks")] | subsetting |
| %>% / | > |
Pipe (magrittr / native) | df |
| %like% | SQL-like pattern matching (in some pkgs) | — | — |
%in% example — very frequent:
|
0 1 2 3 4 5 6 7 |
major_cities <- c("Hyd", "Bng", "Del", "Mum", "Kol") students$city %in% major_cities |
6. Operator Precedence (Quick Order – What Happens First)
Highest to lowest (you can always use parentheses to be safe):
- ::::: (namespaces)
- $@
- [[[
- ^**
- -+ (unary)
- */
- +- (binary)
- <<=>>===!=
- !
- &&&
- ||
- ~
- <-=->
- %…% (user-defined)
- (
Tip: When in doubt → use ( ) — makes code much clearer.
Your Mini Practice (Copy → Run!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Mock Hyderabad student data names <- c("Aarav", "Priya", "Rahul", "Sneha") marks <- c(92, 68, 85, 45) city <- c("Hyd", "Bng", "Hyd", "Mum") temp <- c(29.8, 28.5, 31.2, 30.1) # Combine operators passed_hyd_high_temp <- (marks >= 70) & (city == "Hyd") & (temp > 30) # See who qualifies data.frame( Name = names[passed_hyd_high_temp], Marks = marks[passed_hyd_high_temp], Temp = temp[passed_hyd_high_temp] ) |
Summary – Quick Operator Families
- Assignment → <- (best), =, ->
- Arithmetic → + – * / ^ %% %/%
- Comparison → == != > >= < <=
- Logical → & | ! (vector) vs && || (control flow)
- Membership → %in%
- Sequence → :
- Pipe → |> (base since R 4.1) or %>% (magrittr/tidyverse)
Feeling good with operators now?
Next step?
- Want to practice complex filtering with many operators?
- Go into subsetting ([ ], $, [[ ]]) in detail?
- Or jump to vectors / data frames?
Just tell me — next whiteboard section is ready! ☕🚀
