Skip to Content
Course content

8: Vectorized Operations

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a PR from a developer who had spent most of his career in Java. He was writing a script to process a dataset of about two million weather station readings. He had written a massive for loop that iterated through every single row, extracted the temperature in Fahrenheit, converted it to Celsius, and saved it to a new vector. It worked, but it was painfully slow—it took nearly three minutes to run on his machine. I told him to delete the loop and replace it with a single line of math. He thought I was joking, but when the execution time dropped from 180 seconds to about 0.02 seconds, he actually sat in silence for a minute. That's the power of vectorization.

Thinking in Vectors, Not Loops

Coming from other languages, your instinct is to think about "the current element" of a list. In R, that mindset is actually a liability. R is built on top of vectorized primitives; the language is designed to apply an operation to an entire vector at once rather than stepping through it one by one. When you write x + 2 and x is a vector of a thousand numbers, R doesn't just add 2 to the first element—it broadcasts that addition across the entire vector using highly optimized C and Fortran code under the hood.

This isn't just about typing fewer lines of code (though that's a nice perk). It's about performance. Loops in R are notoriously slow because the interpreter has to check the type of the data and the operation for every single iteration. Vectorized operations bypass that overhead. If you find yourself writing for (i in 1:length(x)), stop and ask yourself: "Is there a vectorized way to do this?" Nine times out of ten, the answer is yes.

# The slow way (Avoid this)
temps_f <- c(32, 68, 100, 150)
temps_c <- numeric(length(temps_f))
for (i in 1:length(temps_f)) {
  temps_c[i] <- (temps_f[i] - 32) * 5/9
}

# The R way (Vectorized)
temps_c <- (temps_f - 32) * 5/9

The Logic of Recycling

One of the most powerful (and occasionally confusing) parts of vectorization is "recycling." When you perform an operation on two vectors of unequal length, R doesn't just throw an error. Instead, it repeats the shorter vector until it matches the length of the longer one. I've seen this save people hours of manual data alignment, but it can also lead to subtle bugs if you aren't paying attention.

For example, if you have a vector of prices and you want to apply a 5% tax, you don't need a vector of 0.05s the same length as your prices. You just multiply by 1.05. R "recycles" that single value for every element in the price vector. This also works for longer vectors; if you have a vector of 10 items and you add a vector of 2 items to it, R will reuse those 2 items five times over.

# Simple recycling
prices <- c(10, 20, 30, 40)
tax <- 1.05
final_price <- prices * tax 

# Complex recycling: alternating multipliers
# This multiplies the first by 1, second by 2, third by 1, fourth by 2...
values <- c(10, 10, 10, 10)
multipliers <- c(1, 2)
result <- values * multipliers 
# result is now c(10, 20, 10, 20)

Just a heads-up: if the longer vector's length isn't a perfect multiple of the shorter one, R will still do the calculation, but it'll throw a warning. I usually treat those warnings as red flags—it usually means there's a logic error in how the data is aligned.




📋 Practical Task

Exercise: Calculating Net Profit for Regional Stores

You have been given two vectors: one containing the total gross revenue for five different store locations, and another containing the operating costs for those same stores. Additionally, there is a flat corporate tax rate that applies to the profit of every store.

Your Goal: Calculate the net profit for each store (Gross Revenue minus Operating Costs, then multiplied by the remaining percentage after tax) using only vectorized operations. Do not use any loops.

# Given Data
gross_revenue <- c(120000, 85000, 210000, 150000, 95000)
operating_costs <- c(40000, 30000, 80000, 50000, 35000)
tax_rate <- 0.25 # 25% tax

# Your code here:
# 1. Calculate the profit (revenue - costs)
# 2. Apply the tax (profit * (1 - tax_rate))
# 3. Store the result in a vector called 'net_profit'
Rating
0 0

There are no comments for now.

to be the first to leave a comment.