MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Setup
  • 1A: Fundamental Building Blocks
  • 1B: Compound Statements
  • 2: Ordered Collection
  • 3: Key-Value Map and Structures
  • 4: More Data types
  • 5: Iteration Constructs
    • Loops
    • Vectorization vs Loops
  • 6: Other constructs
  • 7. Regex
  • 8. Date and Time
  • Revision
  • Practice Exercise

Iteration Constructs: Loops

Why Learn Loops in Data Analytics?

Imagine you are monitoring website traffic logs. You have a vector of hourly visitor counts: c(120, 95, 150, 80, 200, 110). You want to:

  1. Scan each hourly count.
  2. If the count is below 100, print an alert message.
  3. Keep a running tally of how many hours had low traffic.

To look at each hour one-by-one and make decisions, you need Loops. Loops allow you to repeat a block of code for every item in a dataset, automating repetitive inspection tasks.


1. The for Loop

The for loop is used to iterate over a sequence (like a vector or a list) a pre-determined number of times.

Syntax

for (variable in sequence) {
  # code to repeat
}

Example: Iterating over a Vector

visitor_counts <- c(120, 95, 150, 80, 200)

for (count in visitor_counts) {
  if (count < 100) {
    print(paste("Alert: Low traffic hour with only", count, "visitors!"))
  }
}

2. The while Loop

The while loop repeats a block of code as long as a specified condition remains TRUE.

attempts <- 1

while (attempts <= 3) {
  print(paste("Attempt number:", attempts))
  attempts <- attempts + 1 # Increment to avoid infinite loop
}
Simulation Best Practice: Setting a `maxIter` limit

When using while() loops to simulate random walks or other statistical behaviors where the termination condition relies on chance, always enforce a maximum iteration limit. This prevents your code from running infinitely if the condition is never met:

max_iterations <- 1000
step <- 1
current_value <- 0

# Run until threshold is exceeded OR limit is hit
while (abs(current_value) < 10 && step <= max_iterations) {
  current_value <- current_value + rnorm(1)
  step <- step + 1
}

3. The repeat Loop (Unique to R)

R features a third loop type called repeat. It has no condition check at the start; it simply repeats a block of code indefinitely until it encounters a break statement inside.

counter <- 1

repeat {
  print(counter)
  counter <- counter + 1
  
  if (counter > 3) {
    break # Exit the loop
  }
}

4. break vs. next

To control loop execution dynamically, R provides two keywords:

  • break: Exits the entire loop immediately.
  • next: Skips the rest of the current iteration and jumps directly to the start of the next iteration (equivalent to Python's continue keyword!).
numbers <- 1:5

for (num in numbers) {
  if (num == 3) {
    next # Skip printing 3
  }
  print(num) # Outputs: 1, 2, 4, 5
}

Hands-on Exercises

Exercise 1: Finding High-Temperature Alerts

You have a vector of temperature readings: c(32, 35, 41, 38, 43, 30). Write R code to:

  1. Loop through the vector using a for loop.
  2. If a temperature is greater than 40, print the temperature and stop the loop immediately using a break statement.
  3. If the temperature is 40 or below, print "Normal".
# Write your code below and click Run Code
Click to view Answer
temps <- c(32, 35, 41, 38, 43, 30)

for (temp in temps) {
  if (temp > 40) {
    print(paste("Critical Heatwave Alert:", temp))
    break
  }
  print("Normal")
}
# Output should show "Normal", "Normal", then the Alert, then stop.

Exercise 2: Even Number Tally

You want to count the number of even integers in a sequence from 1 to 15 using a loop. Write R code to:

  1. Create a variable even_count <- 0.
  2. Write a for loop that iterates through 1:15.
  3. If a number is odd, skip to the next iteration using next.
  4. If it is even, increment even_count by 1.
  5. Print the final even_count value after the loop exits.
# Write your code below and click Run Code
Click to view Answer
even_count <- 0

for (num in 1:15) {
  if (num %% 2 != 0) {
    next # Skip odd numbers
  }
  even_count <- even_count + 1
}

print(paste("Total even numbers:", even_count)) # Output: 7
Privacy Policy | Terms & Conditions