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"
Iteration, Flow Control, and Result Storage
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.
for (i in x): Repeats code for each item in the object x.break / next: Commands used to control the flow of the loop.numeric(), character()).cat(): Used to print custom, formatted messages.Let’s start by printing the names of the first 5 characters in the starwars dataset.
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.”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.
# 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
Printing values is useful for checking data, but often we want to save the results of a calculation into a new variable.
# 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
Sometimes you need to stop a loop early or skip specific items based on a condition.
break - Stop EarlyWe will stop the loop as soon as we reach “Darth Vader.”
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 ItemsWe will print names but skip “C-3PO” entirely.
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"
cat()**The cat() function allows you to combine text and variables into a single, clean message. The \n symbol creates a new line.
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.
for (i in 1:length(x))results[i] <- calculationif (condition) nextif (condition) breakcat("Text", variable, "\n")Great job! You have mastered the logic of iteration.