# Creates a sequence from 1 to 5
1:5 # Results in: 1 2 3 4 5
[1] 1 2 3 4 5
Steven P. Sanderson II, MPH
March 17, 2025
Programming, For-Loop with Range in R, R for-loop examples, R programming loops, Range in R programming, For-loop in R, R for-loop syntax, R loop iteration, R sequence iteration, For-loops in data analysis, R control structures, How to create a for-loop with range in R programming, Pre-allocating memory for R for-loops best practice, Nested for-loops with ranges in R examples, Using seq() function in R for-loops with custom steps, Differences between for-loops and vectorized operations in R
For-loops are fundamental programming structures that help automate repetitive tasks by executing code multiple times. If you’re learning R or looking to enhance your R programming skills, understanding how to use for-loops with ranges is important. This guide breaks down the concept of for-loops with ranges in R, providing clear explanations and practical examples to help you implement them in your own projects.
No matter where you are with your R programming, this article will walk you through everything you need to know about using for-loops with ranges in R.
A for-loop is a control flow statement that allows code to be executed repeatedly. In R, for-loops follow this basic syntax:
Let’s break this down:
variable
is a placeholder that takes on each value in the sequence, one at a timesequence
is a vector of values (like numbers, characters, or other data types){}
runs once for each value in the sequenceIn R, creating a range of numbers is typically done using the colon operator (:
). This creates a sequence of consecutive integers.
For more complex ranges, you can use the seq()
function:
Let’s start with a simple example to print numbers from 1 to 5:
In this example:
i
is our variable that takes on each value in the sequence1:5
creates a range of numbers from 1 to 5print(i)
outputs the current value of i
during each iteration# Calculate sum of numbers from 1 to 10
sum <- 0
for (i in 1:10) {
sum <- sum + i
print(paste("After adding", i, "the sum is:", sum))
}
[1] "After adding 1 the sum is: 1"
[1] "After adding 2 the sum is: 3"
[1] "After adding 3 the sum is: 6"
[1] "After adding 4 the sum is: 10"
[1] "After adding 5 the sum is: 15"
[1] "After adding 6 the sum is: 21"
[1] "After adding 7 the sum is: 28"
[1] "After adding 8 the sum is: 36"
[1] "After adding 9 the sum is: 45"
[1] "After adding 10 the sum is: 55"
[1] "Final sum: 55"
# Creating a multiplication table for the number 7
number <- 7
for (i in 1:10) {
result <- number * i
print(paste(number, "×", i, "=", result))
}
[1] "7 × 1 = 7"
[1] "7 × 2 = 14"
[1] "7 × 3 = 21"
[1] "7 × 4 = 28"
[1] "7 × 5 = 35"
[1] "7 × 6 = 42"
[1] "7 × 7 = 49"
[1] "7 × 8 = 56"
[1] "7 × 9 = 63"
[1] "7 × 10 = 70"
# Creating a vector
fruits <- c("Apple", "Banana", "Cherry", "Date", "Fig")
# Using a for-loop to access elements by index
for (i in 1:length(fruits)) {
print(paste("Fruit at position", i, "is", fruits[i]))
}
[1] "Fruit at position 1 is Apple"
[1] "Fruit at position 2 is Banana"
[1] "Fruit at position 3 is Cherry"
[1] "Fruit at position 4 is Date"
[1] "Fruit at position 5 is Fig"
Nested for-loops involve placing one for-loop inside another. This is useful for working with multi-dimensional data structures.
You can also create reverse ranges to count backward:
Using the seq()
function lets you skip elements in your range:
# Print only even numbers from 2 to 20
for (i in seq(2, 20, by = 2)) {
print(paste(i, "is an even number"))
}
[1] "2 is an even number"
[1] "4 is an even number"
[1] "6 is an even number"
[1] "8 is an even number"
[1] "10 is an even number"
[1] "12 is an even number"
[1] "14 is an even number"
[1] "16 is an even number"
[1] "18 is an even number"
[1] "20 is an even number"
For-loops can be used to process data frames row by row:
# Create a simple data frame
students <- data.frame(
name = c("Alice", "Bob", "Charlie", "David"),
score = c(85, 92, 78, 95)
)
# Calculate letter grades based on scores
for (i in 1:nrow(students)) {
score <- students$score[i]
if (score >= 90) {
grade <- "A"
} else if (score >= 80) {
grade <- "B"
} else if (score >= 70) {
grade <- "C"
} else {
grade <- "D"
}
print(paste(students$name[i], "scored", score, "and received a grade", grade))
}
[1] "Alice scored 85 and received a grade B"
[1] "Bob scored 92 and received a grade A"
[1] "Charlie scored 78 and received a grade C"
[1] "David scored 95 and received a grade A"
In R, it’s more efficient to pre-allocate memory for your results rather than growing objects incrementally:
R is optimized for vector operations. When possible, use vectorized functions instead of for-loops:
For long-running loops, it’s helpful to print progress messages:
n <- 100
step <- 10
for (i in 1:n) {
# Do some calculation
result <- i^2
# Print progress every 'step' iterations
if (i %% step == 0) {
print(paste("Processed", i, "of", n, "iterations -", (i/n)*100, "%"))
}
}
[1] "Processed 10 of 100 iterations - 10 %"
[1] "Processed 20 of 100 iterations - 20 %"
[1] "Processed 30 of 100 iterations - 30 %"
[1] "Processed 40 of 100 iterations - 40 %"
[1] "Processed 50 of 100 iterations - 50 %"
[1] "Processed 60 of 100 iterations - 60 %"
[1] "Processed 70 of 100 iterations - 70 %"
[1] "Processed 80 of 100 iterations - 80 %"
[1] "Processed 90 of 100 iterations - 90 %"
[1] "Processed 100 of 100 iterations - 100 %"
Let’s practice creating a for-loop with range in R. Try this exercise:
Exercise: Write a for-loop that calculates the cube of each number from 1 to 5 and stores the results in a vector.
for (variable in sequence) { code }
.1:5
or the seq()
function.seq()
function provides flexibility in creating custom ranges with specific steps.For-loops with ranges are important tools in R programming that help automate repetitive tasks. While R offers vectorized alternatives that are often faster, for-loops remain valuable for their readability and flexibility, especially when dealing with complex logic or when you need to access elements by their position.
By mastering for-loops with ranges in R, you’ve added a powerful technique to your programming toolkit. Whether you’re analyzing data, building models, or creating visualizations, you’ll find numerous applications for these fundamental programming structures.
Remember to consider performance implications when working with large datasets, and always look for opportunities to use R’s vectorized operations when appropriate.
A for-loop iterates over a predetermined sequence of values, while a while-loop continues until a specified condition becomes false. For-loops are better when you know the exact number of iterations in advance.
No, R is optimized for vectorized operations, which are typically faster than for-loops. However, for-loops are often more readable and sometimes necessary for certain types of iterative algorithms.
You can use the break
statement to exit a for-loop prematurely when a certain condition is met.
Yes, you can use the next
statement to skip the current iteration and proceed to the next one.
You can use the seq_along()
function to iterate over indices and then access multiple vectors using the same index.
I hope you found this guide helpful for understanding and implementing for-loops with ranges in R! Feel free to experiment with the examples and adapt them to your specific needs.
Happy Coding! 🚀
You can connect with me at any one of the below:
Telegram Channel here: https://t.me/steveondata
LinkedIn Network here: https://www.linkedin.com/in/spsanderson/
Mastadon Social here: https://mstdn.social/@stevensanderson
RStats Network here: https://rstats.me/@spsanderson
GitHub Network here: https://github.com/spsanderson
Bluesky Network here: https://bsky.app/profile/spsanderson.com
My Book: Extending Excel with Python and R here: https://packt.link/oTyZJ
You.com Referral Link: https://you.com/join/EHSLDTL6