Vector Arithmetic
Vector arithmetic does math on every item in a list at once, like telling a whole class to add two to their scores. You do not need to touch each one separately.
In this page:
Syntax
result <- vector1 + vector2
result <- vector * number
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Adding vectors of different lengths that do not divide evenly, such as
c(1,2,3) + c(1,2), which recycles with only a warning. - Expecting
*to be a matrix product, when it multiplies element by element; use%*%for matrices. - Assuming recycling gives an error, when R silently repeats the shorter vector.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: