Exploring Medical Data Science with R

Exploring Medical Data Science with R

Basic

Sec.B-Ch.1-Subsec.5: A Complete Analysis of Loops and Iteration Functions in R

Understanding for, while, apply-family functions, and control structures for efficient data processing and analysis in R

Dr. Xie YJ's avatar
Dr. Xie YJ
Mar 09, 2026
∙ Paid

Loops and iteration functions in R play a crucial role in data processing and executing complex tasks. A deep understanding of how these functions work and when to use them is essential for improving programming skills and enhancing data analysis efficiency. This article provides a comprehensive analysis of loops and iteration functions in R, offering strong support for learners and users of the R language.


I. Loops

1. For Loop

In R, a fundamental control flow construct is the for loop, which allows you to iterate over a collection of objects such as vectors, lists, matrices, or data frames, and apply the same set of operations to each element in the given data structure. In addition, the for loop helps keep code clean by avoiding unnecessary repetition of code blocks. It enables efficient execution of repetitive tasks and can be applied to various data structures, making it a universal and essential part of R programming.

The basic syntax of a for loop in R is as follows:

for (variable in sequence) {
  expression
}

Here, variable takes each value in sequence, and expression represents the set of operations to be executed for each value.

Iterating over an integer vector

for (i in 1:3) {
  print("I Love Apple")
}

Result:

[1] "I Love Apple"
[1] "I Love Apple"
[1] "I Love Apple"

Iterating over a character vector

for (word in c("hello", "nice", "world")) {
  cat("Now, the word is", word, "\n")
}

Result:

Now, the word is hello
Now, the word is nice
Now, the word is world

Using a For Loop to Traverse a Numeric Vector and Print Squared Values

numbers <- c(1, 2, 3, 4, 5)

for (num in numbers) {
  print(num^2)
}

Result:

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

This code first creates a vector numbers containing the numbers 1 to 5. Then, through a for loop, it traverses each element of the vector. For each element num, it calculates the square and prints the result.


2. While Loop

The while loop is used to repeatedly execute a block of code as long as a condition remains true. The syntax is as follows:

while (condition) {
  statements
}

condition is a logical expression. When it is TRUE, the code inside the loop will execute repeatedly until the condition becomes FALSE.

User's avatar

Continue reading this post for free, courtesy of Dr. Xie YJ.

Or purchase a paid subscription.
© 2026 Xie Yaojue · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for great culture