Vectorization (R)
Vectorization is R's practice of applying operations to entire vectors at once, element by element, instead of writing explicit loops. It makes code shorter, clearer, and much faster.
R
In R, arithmetic and most functions work on whole vectors automatically: v * 2 doubles every element, and sqrt(v) takes the square root of each. There's no need for a for loop because the looping happens in fast, compiled C code under the hood — so vectorized code is both concise and far quicker than an equivalent R-level loop.
Vectorized thinking is the idiomatic R mindset. Many built-in functions (sum, mean, ifelse, pmax) are vectorized, and the apply family extends the idea to rows, columns, and list elements. Combined with recycling, a scalar applied to a vector touches every element.
When an operation genuinely can't be vectorized, R loops or the apply family fill the gap, but reaching for vectorized solutions first is the single biggest performance and readability win in R. ifelse(cond, a, b) is the vectorized form of an if/else.
Syntax
result <- vector1 + vector2 # element-wise, no loopExamples
R
prices <- c(10, 20, 30)
tax <- prices * 0.1
print(prices + tax)
print(ifelse(prices > 15, "high", "low"))Output:
[1] 11 22 33
[1] "low" "high" "high"