← Back to R Course | Chapter 3: Vectors | Lesson 3 of 7

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:

  1. Vector Arithmetic
Syntax
r
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

markup
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))
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
  1. 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.
  2. Expecting * to be a matrix product, when it multiplies element by element; use %*% for matrices.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.