Mastering Loops in R

Iteration, Flow Control, and Result Storage

Author

Abdullah Al Shamim

Published

February 14, 2026

What is a Loop?

A loop repeats a block of code multiple times. In R, the most common and simplest loop is the for loop. It allows you to automate repetitive tasks efficiently.


🎓 Key Takeaways

  1. for (i in x): Repeats code for each item in the object x.
  2. break / next: Commands used to control the flow of the loop.
  3. Storing Results: Best practice is to initialize empty vectors (e.g., numeric(), character()).
  4. cat(): Used to print custom, formatted messages.

1. Basic Loop Structure

Let’s start by printing the names of the first 5 characters in the starwars dataset.

Code
library(tidyverse)

# Print the first 5 character names
for(i in 1:5) {
  print(starwars$name[i])
}
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
[1] "Leia Organa"

Explanation: - i acts as a counter (taking values 1, 2, 3, 4, 5).

  • 1:5 defines the range, telling R to “run this code exactly 5 times.”

2. Looping Through All Data

Instead of hardcoding a specific number, we use length() to ensure the loop runs for every row in the dataset, regardless of how large it is.

Code
# Loop through ALL heights in the dataset
# Note: We wrap it in head() or limit it for the output display
for(i in 1:length(starwars$height[1:10])) {
  print(starwars$height[i])
}
[1] 172
[1] 167
[1] 96
[1] 202
[1] 150
[1] 178
[1] 165
[1] 97
[1] 183
[1] 182

3. Storing Loop Results

Printing values is useful for checking data, but often we want to save the results of a calculation into a new variable.

Example: Converting CM to Meters

Code
# 1. Create an empty vector to store 5 numbers
tallness <- numeric(length = 5) 

# 2. Fill the vector using a loop
for(i in 1:5) {
  tallness[i] <- starwars$height[i] / 100
}

# 3. Check the result
tallness 
[1] 1.72 1.67 0.96 2.02 1.50

4. Controlling Loops

Sometimes you need to stop a loop early or skip specific items based on a condition.

break - Stop Early

We will stop the loop as soon as we reach “Darth Vader.”

Code
for(name in starwars$name) {
  print(name)
  if(name == "Darth Vader") {
    break  # Exit the loop entirely
  }
}
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"

next - Skip Items

We will print names but skip “C-3PO” entirely.

Code
for(name in starwars$name[1:10]) {
  if(name == "C-3PO") {
    next  # Skip this iteration and go to the next name
  }
  print(name)
}
[1] "Luke Skywalker"
[1] "R2-D2"
[1] "Darth Vader"
[1] "Leia Organa"
[1] "Owen Lars"
[1] "Beru Whitesun Lars"
[1] "R5-D4"
[1] "Biggs Darklighter"
[1] "Obi-Wan Kenobi"

**5. Fancy Output with cat()**

The cat() function allows you to combine text and variables into a single, clean message. The \n symbol creates a new line.

Code
for(i in 1:5) {
  cat("✨", starwars$name[i], "is", 
      tallness[i], "meters tall.\n")
}
✨ Luke Skywalker is 1.72 meters tall.
✨ C-3PO is 1.67 meters tall.
✨ R2-D2 is 0.96 meters tall.
✨ Darth Vader is 2.02 meters tall.
✨ Leia Organa is 1.5 meters tall.

Systematic Checklist (Cheat Sheet):

  • To start: for (i in 1:length(x))
  • To store: results[i] <- calculation
  • To skip: if (condition) next
  • To stop: if (condition) break
  • To print: cat("Text", variable, "\n")

Great job! You have mastered the logic of iteration.