Vectors are cool on their own, but the real magic happens when you start operating on them. R is built for vectorized operations โ instead of looping through each element, you can apply an operation to the whole vector at once. It's faster, cleaner, and way more readable.
Vectorized Arithmetic
Add, subtract, multiply, divide โ do it to a vector and R applies it to every element. Two vectors of the same length? R pairs them up element by element.
prices <- c(10, 20, 30)
# Add tax to every item at once
prices * 1.08
# Two vectors, element-wise
quantities <- c(2, 5, 3)
prices * quantities
Try it Yourself โ
Recycling โ When Lengths Don't Match
What if one vector is shorter than the other? R doesn't panic โ it "recycles" the shorter one, repeating it as many times as needed. You get a warning if the longer length isn't a multiple of the shorter length.
a <- c(1, 2, 3, 4, 5, 6)
b <- c(10, 20)
# b becomes c(10, 20, 10, 20, 10, 20)
a + b
Try it Yourself โ
Filtering with Conditions and which()
Want to find all scores above 80? Just write scores > 80 and R returns a logical vector. Use that to filter. The which() function gives you the indices where a condition is true. And %in% checks membership.
scores <- c(72, 88, 91, 65, 84)
# Logical comparison
scores > 80
# Filter directly
scores[scores > 80]
# Find positions
which(scores > 80)
# Check membership
"Alice" %in% c("Bob", "Charlie", "Alice")
Try it Yourself โ