1---2name: r3description: Avoid common R mistakes — vectorization traps, NA propagation, factor surprises, and indexing gotchas.4---5
6## Vectorization
7- Loops are slow — use `apply()`, `lapply()`, `sapply()`, or `purrr::map()`
8- Vectorized functions operate on whole vectors — `sum(x)` not `for (i in x) total <- total + i`
9- `ifelse()` is vectorized — `if` is not, use `ifelse()` for vector conditions
10- Column operations faster than row — R is column-major
11
12## Indexing Gotchas
13- R is 1-indexed — first element is `x[1]`, not `x[0]`
14- `x[0]` returns empty vector — not error, silent bug
15- Negative index excludes — `x[-1]` removes first element
16- `[[` extracts single element — `[` returns subset (list stays list)
17- `df[, 1]` drops to vector — use `df[, 1, drop = FALSE]` to keep data frame
18
19## NA Handling
20- NA propagates — `1 + NA` is `NA`, `NA == NA` is `NA`
21- Use `is.na()` to check — not `x == NA`
22- Most functions need `na.rm = TRUE` — `mean(x)` returns NA if any NA present
23- `na.omit()` removes rows with any NA — may lose data unexpectedly
24- `complete.cases()` returns logical vector — rows without NA
25
26## Factor Traps
27- Old R converted strings to factors by default — use `stringsAsFactors = FALSE` or modern R
28- `levels()` shows categories — but factor values are integers internally
29- Adding new value not in levels gives NA — use `factor(x, levels = c(old, new))`
30- `as.numeric(factor)` gives level indices — use `as.numeric(as.character(factor))` for values
31- Dropping unused levels: `droplevels()` — or `factor()` again
32
33## Recycling
34- Shorter vector recycled to match longer — `c(1,2,3) + c(10,20)` gives `11, 22, 13`
35- No error if lengths aren't multiples — just warning, easy to miss
36- Single values recycle intentionally — `x + 1` adds 1 to all elements
37
38## Data Frames vs Tibbles
39- Tibble never converts strings to factors — safer defaults
40- Tibble never drops dimensions — `df[, 1]` stays tibble
41- Tibble prints better — shows type, doesn't flood console
42- `as_tibble()` to convert — from `tibble` or `dplyr` package
43
44## Assignment
45- `<-` is idiomatic R — `=` works but avoided in style guides
46- `<<-` assigns to parent environment — global assignment, usually a mistake
47- `->` right assignment exists — rarely used, confusing
48
49## Scope
50- Functions look up in parent environment — can accidentally use global variable
51- Local variable shadows global — same name hides outer variable
52- `local()` creates isolated scope — variables don't leak out
53
54## Common Mistakes
55- `T` and `F` can be overwritten — use `TRUE` and `FALSE` always
56- `1:length(x)` fails on empty x — gives `c(1, 0)`, use `seq_along(x)`
57- `sample(5)` vs `sample(c(5))` — different! first gives 1:5 permutation
58- String splitting: `strsplit()` returns list — even for single string