Writing Your Own Functions With Vectors
Everything from vectorized-operations onward has been building toward one habit: when you write your own function, there's usually no reason for its body to loop over its input either. If x is a vector, (x - min(x)) / (max(x) - min(x)) is a single vectorized expression that, when called once with the whole vector, produces a whole vector of normalized results — not one number computed per call.
normalize <- function(x) {
(x - min(x)) / (max(x) - min(x))
}
print(normalize(c(10, 20, 30, 40, 50)))
[1] 0.00 0.25 0.50 0.75 1.00
normalize() was called exactly once, with the entire five-element vector as its single argument — min(x) and max(x) each ran once over the whole vector, and the final subtraction and division ran element-wise automatically, the same way x + y did all the way back in the vectorized-operations lesson. The result is a five-element vector where the smallest input became 0, the largest became 1, and everything else scaled proportionally in between — all without ever writing for or a loop index. Next: closing thoughts — a recap, and where to go next.
Practice exercise
Write a function cube <- function(x) that returns x^3 for a whole vector at once, with no loop inside it. Call it with c(1, 2, 3) and print the result.