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

Vector Arithmetic

In this page:

  1. Vector Arithmetic

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))
🔒

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.