Vector Arithmetic
In this page:
Vector Arithmetic
Arithmetic operators on vectors work element-wise automatically -- c(1,2,3) + c(10,20,30) adds corresponding elements without a loop. If the vectors are different lengths, R recycles the shorter one, repeating its values to match the longer vector's length. This vectorized behavior is central to writing efficient, idiomatic R code.
Note: Vectorized operations are almost always faster than writing an explicit loop over each element in R.
Example: Vector Arithmetic
a <- c(1, 2, 3)
b <- c(10, 20, 30)
print(a + b)
print(a * 2)
# Recycling: shorter vector repeats to match length
print(c(1, 2, 3, 4) + c(10, 20))
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: