Fiveable

💻Advanced R Programming Unit 3 Review

QR code for Advanced R Programming practice questions

3.2 Loops (for, while, repeat)

3.2 Loops (for, while, repeat)

Written by the Fiveable Content Team • Last updated August 2025
Written by the Fiveable Content Team • Last updated August 2025
💻Advanced R Programming
Unit & Topic Study Guides

Loops are the backbone of repetitive tasks in R programming. They allow you to execute code multiple times, saving time and effort. This section covers three types of loops: for, while, and repeat, each serving different purposes in your code.

Understanding loops is crucial for efficient programming. You'll learn how to iterate over sequences, perform condition-based execution, and control loop behavior. These skills will help you tackle complex problems and automate repetitive tasks in your R projects.

For Loops for Iteration

Iterating Over Sequences

  • for loops are used to iterate over a sequence of elements, executing a block of code for each element in the sequence
  • The sequence can be a vector, list, or any other iterable object, and the variable takes on each value of the sequence in each iteration
  • for loops are particularly useful when you need to apply a function or perform an operation on each element of a vector, list, or other iterable objects (data frames, matrices)
  • Example: Iterating over a vector of numbers to calculate their square roots
    </>R
    numbers <- c(4, 9, 16, 25)
    for (num in numbers) {
        sqrt_num <- sqrt(num)
        print(sqrt_num)
    }

Fixed Number of Repetitions

  • for loops can also be used to perform a fixed number of repetitions by using a sequence of integers, such as 1:n or seq_along(vector)
  • The basic syntax of a for loop in R is: for (variable in sequence) { code block }
  • The code block inside the for loop is executed for each iteration, allowing for repetitive tasks or computations
  • It is important to properly initialize any variables used to store results before the loop and update them within the loop as needed
  • Example: Repeating a task a fixed number of times
    </>R
    n <- 5
    for (i in 1:n) {
        print(paste("Iteration", i))
    }

While Loops for Condition-Based Execution

Iterating Over Sequences, Data Analysis with R

Repeating Code Until Condition is Met

  • while loops repeatedly execute a block of code as long as a specified condition evaluates to TRUE
  • The basic syntax of a while loop in R is: while (condition) { code block }
  • The condition is evaluated at the beginning of each iteration, and if it is TRUE, the code block is executed; this process continues until the condition becomes FALSE
  • It is crucial to ensure that the condition eventually becomes FALSE to avoid an infinite loop; this is usually achieved by modifying the variables involved in the condition within the code block
  • Example: Iterating until a specific condition is met
    </>R
    count <- 0
    while (count < 5) {
        print(count)
        count <- count + 1
    }

Condition-Based Iteration

  • The condition in a while loop typically involves comparing variables or expressions using logical operators such as <, >, ==, !=, &, or |
  • while loops are useful when the number of iterations is not known in advance and depends on a certain condition being met
  • Common use cases for while loops include iterating until convergence is reached, processing input until a specific value is encountered, or repeating an operation until a desired result is obtained
  • Example: Reading input until a specific value is entered
    </>R
    user_input <- ""
    while (user_input != "quit") {
        user_input <- readline("Enter a value (or 'quit' to exit): ")
        print(user_input)
    }

Repeat Loops for At Least Once Execution

Iterating Over Sequences, Data Analysis with R

Executing Code at Least Once

  • repeat loops execute a block of code repeatedly until a specific condition is met, which is checked at the end of each iteration
  • The basic syntax of a repeat loop in R is: repeat { code block }
  • Unlike while loops, repeat loops do not have a condition specified in the loop construct itself; the code block is always executed at least once
  • To exit a repeat loop, an explicit break statement must be used within the code block; the break statement is typically placed inside an if statement that checks for the desired condition
  • Example: Implementing a menu-driven program
    </>R
    repeat {
        print("Menu:")
        print("1. Option 1")
        print("2. Option 2")
        print("3. Exit")
        choice <- readline("Enter your choice: ")
    
        if (choice == "1") {
            print("You selected Option 1")
        } else if (choice == "2") {
            print("You selected Option 2")
        } else if (choice == "3") {
            print("Exiting...")
            break
        } else {
            print("Invalid choice. Please try again.")
        }
    }

Ensuring Condition for Exit

  • repeat loops are useful when you want to ensure that the code block is executed at least once, regardless of the initial condition
  • It is important to ensure that the break statement is reachable and that the condition for breaking the loop will eventually be satisfied to prevent an infinite loop
  • Common use cases for repeat loops include implementing menu-driven programs, where the menu is displayed and processed repeatedly until the user chooses to exit
  • Example: Validating user input
    </>R
    valid_input <- FALSE
    repeat {
        user_input <- readline("Enter a positive number: ")
        if (user_input > 0) {
            valid_input <- TRUE
            break
        }
        print("Invalid input. Please enter a positive number.")
    }
    print(paste("You entered:", user_input))

Loop Control with Break and Next

Exiting Loops Prematurely with Break

  • The break statement is used to exit a loop prematurely, immediately terminating the loop's execution and moving the program flow to the next statement after the loop
  • When encountered inside a loop, the break statement causes the loop to terminate, regardless of the remaining iterations or the loop condition
  • The break statement is commonly used in combination with conditional statements (e.g., if) to exit a loop when a specific condition is met
  • Example: Searching for a specific element in a vector
    </>R
    numbers <- c(3, 7, 2, 9, 4)
    target <- 9
    for (num in numbers) {
        if (num == target) {
            print("Target found!")
            break
        }
    }

Skipping Iterations with Next

  • The next statement is used to skip the remainder of the current iteration and move to the next iteration of the loop
  • When encountered inside a loop, the next statement immediately moves the program flow to the next iteration, skipping any remaining code in the current iteration
  • The next statement is often used to handle special cases or to avoid unnecessary computations for certain elements within a loop
  • Both break and next statements provide control over the loop execution and allow for more flexible and efficient processing of elements within loops
  • It is important to use break and next statements judiciously and ensure that they are placed in the appropriate locations within the loop to achieve the desired behavior
  • Example: Skipping even numbers in a loop
    </>R
    numbers <- c(1, 2, 3, 4, 5)
    for (num in numbers) {
        if (num %% 2 == 0) {
            next
        }
        print(num)
    }
Pep mascot
Upgrade your Fiveable account to print any study guide

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Click below to go to billing portal → update your plan → choose Yearly → and select "Fiveable Share Plan". Only pay the difference

Plan is open to all students, teachers, parents, etc
Pep mascot
Upgrade your Fiveable account to export vocabulary

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Plan is open to all students, teachers, parents, etc
report an error
description

screenshots help us find and fix the issue faster (optional)

add screenshot

2,589 studying →