← Back to R Course | Chapter 12: Best Practices | Lesson 2 of 6

Vectorization over Loops

In this page:

  1. Vectorization over Loops

Vectorization over Loops

R is optimized for vectorized operations -- applying a function to an entire vector at once -- which run much faster than an equivalent element-by-element for loop, since vectorized operations are implemented in optimized C code under the hood. Prefer v * 2, sum(v), or sapply() over manually looping and appending to a result vector. This is one of the most important performance habits in R.

Warning: Growing a vector inside a loop with result <- c(result, new_value) is a classic R performance trap -- it reallocates memory on every iteration.

Example: Vectorization over Loops

markup
numbers <- 1:1000000

# Vectorized (fast, idiomatic)
squared_vectorized <- numbers^2

# A loop would work but be far slower for this size of data
cat("First 5 squared values:", head(squared_vectorized, 5), "\n")
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.