How to use for loop in R

base-r
for loop
Learn how to perform use for loop in R. Step-by-step statistical tutorial with examples.
Published

February 21, 2026

Introduction

A for loop is a control structure in R that allows you to repeatedly execute a block of code for each element in a sequence or vector. It’s one of the most fundamental programming constructs for automating repetitive tasks. You would use for loops when you need to perform the same operation multiple times, iterate through data structures, or when you need precise control over the iteration process.

Syntax

The basic syntax of a for loop in R follows this pattern:

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

The key components are:

  • variable: A placeholder that takes on each value from the sequence during iteration
  • sequence: A vector, list, or range of values to iterate over
  • code block: The operations to perform in each iteration, enclosed in curly braces

Common sequences include numeric ranges like 1:10, vectors like c("a", "b", "c"), or existing data structures.

Example 1: Basic Usage

Looping through numbers

The simplest use case is iterating through a sequence of numbers. Here we loop through 1 to 5 and calculate the square of each number:

for (i in 1:5) {
  square <- i^2
  print(paste("Number:", i, "Square:", square))
}

The variable i takes values 1, 2, 3, 4, 5 in each iteration. Inside the loop, we calculate the square and print the result.

Looping through a character vector

For loops work with any vector type, not just numbers. Here we iterate through a vector of fruit names:

fruits <- c("apple", "banana", "orange")

for (fruit in fruits) {
  print(paste("I like", fruit))
}

The variable fruit takes each string value in sequence: “apple”, then “banana”, then “orange”.

Combining loops with conditional logic

You can add if statements inside loops to perform actions only when certain conditions are met:

numbers <- c(2, 7, 4, 9, 1, 6)

for (num in numbers) {
  if (num > 5) {
    print(paste(num, "is greater than 5"))
  }
}

This loop checks each number and only prints those greater than 5 (7, 9, and 6).

Example 2: Practical Application

The Problem

Imagine you’re a teacher with 4 students and their grades across 3 subjects. You need to:

  1. Calculate each student’s average grade
  2. Find each student’s best subject
  3. Generate a report for each student

Doing this manually would be tedious. A for loop automates this perfectly.

Setting up the data

First, let’s create our student data as a matrix where rows are students and columns are subjects:

students <- c("Alice", "Bob", "Charlie", "Diana")
subjects <- c("Math", "Science", "English")

grades <- matrix(
  c(85, 92, 78,
    76, 88, 82,
    90, 85, 95,
    88, 79, 87),
  nrow = 4,
  byrow = TRUE,
  dimnames = list(students, subjects)
)

Creating a results storage

Before looping, we need a place to store our calculated results. Always initialize storage objects before the loop:

results <- data.frame(
  Student = students,
  Average = numeric(4),
  Highest_Subject = character(4),
  stringsAsFactors = FALSE
)

The main analysis loop

Now we loop through each student, calculate their statistics, and store the results:

for (i in 1:length(students)) {
  # Get this student's grades
  student_grades <- grades[i, ]

  # Calculate average and store it
  avg_grade <- mean(student_grades)
  results$Average[i] <- round(avg_grade, 1)

  # Find best subject and store it
  best_subject <- names(student_grades)[which.max(student_grades)]
  results$Highest_Subject[i] <- best_subject
}

The loop runs 4 times (once per student). In each iteration, i is the row number, so grades[i, ] extracts that student’s grades.

Adding a detailed report with nested loops

We can use a nested loop (a loop inside a loop) to print each subject’s grade:

for (i in 1:length(students)) {
  print(paste("=== Report for", students[i], "==="))

  # Inner loop: iterate through each subject
  for (subject in subjects) {
    grade <- grades[i, subject]
    print(paste(subject, "grade:", grade))
  }

  print(paste("Average:", results$Average[i]))
  print(paste("Best subject:", results$Highest_Subject[i]))
  print("")
}

The outer loop iterates through students. For each student, the inner loop iterates through all subjects to print individual grades.

Summary

  • Use for (variable in sequence) syntax for basic iteration through vectors, lists, or ranges
  • Split complex operations into separate code blocks with explanations for readability
  • Always initialize storage objects (vectors, data frames) before loops when collecting results
  • Use nested loops when working with multi-dimensional data (rows and columns)
  • Combine loops with if statements for conditional processing
  • While R’s vectorized operations are often more efficient, for loops provide explicit control for complex algorithms