R Programming Loops Explained with Examples
R Programming: Loops
Hello students! So far,
we’ve learned how R can perform calculations with operators and make decisions
with if statements. Now, imagine you need to repeat a certain task many, many
times – like printing the numbers from 1 to 100, or performing the same
calculation for every student in a class of thousands. Doing this manually
would be tedious and error-prone!
This is where loops
come to our rescue. A loop is a programming construct that allows you to
execute a block of code repeatedly as long as a certain condition is met, or
for each item in a sequence. Loops are incredibly powerful because they
automate repetitive tasks, making your code more efficient, concise, and less
prone to mistakes.
Think of it like this:
●
Without loops:
If you want to take 10 steps, you individually instruct: "Step 1, Step 2,
Step 3, …, Step 10."
●
With loops:
You instruct: "Repeat ‘take one step’ 10 times."
R provides several
types of loops, but for beginners, the for loop and the while loop are the most
important to understand.
1. The for Loop
The for loop is used
when you know in advance how many times you want the loop to run, or when you
want to iterate over each item in a sequence (like a vector). It’s great for
going through lists, numbers, or elements one by one.
Syntax:
for (variable in sequence) {
# Code to execute for each item in the
sequence
}
●
variable: This is a temporary variable
that takes on the value of each item in the sequence during each iteration of
the loop.
●
sequence: This is a collection of items
(e.g., a vector of numbers, characters, or a range created with :). The loop
will run once for each item in this sequence.
●
{ }: These curly braces define the block
of code that will be repeated.
Simple Example:
Let’s print each fruit
name from a list:
# A vector of fruits
fruits
<- c("apple", "banana", "cherry")
#
Loop through each fruit in the ‘fruits’ vector
for
(fruit_name in fruits) {
print(paste("I love", fruit_name))
}
#
——————————————–
#
Example with numbers
#
The sequence 1:5 means 1, 2, 3, 4, 5
for
(i in 1:5) {
print(paste("Counting:", i))
}
Explanation:
In the first example, fruit_name will first be
"apple", then "banana", then "cherry". For each
of these, the print line inside the curly braces will run.
In the second example, i will take values 1, 2, 3, 4,
5 in consecutive turns.
2. The while Loop
The while loop is used
when you want to repeat a block of code as long as a certain condition
remains TRUE. You don’t necessarily know in advance how many times it will run;
it just keeps going until the condition becomes FALSE.
Syntax:
while (condition) {
# Code to execute as long as the condition is
TRUE
# IMPORTANT: Make sure something inside the
loop changes the condition
# so it eventually becomes FALSE; otherwise,
the loop will run infinitely.
}
●
condition: This is an expression that
evaluates to TRUE or FALSE. The loop continues to run as long as this condition
is TRUE.
●
{ }: The block of code to be repeated.
●
Crucial Point:
You must include code inside the loop that will eventually make the
condition FALSE. If the condition never becomes FALSE, your loop will run
forever, which is called an infinite loop, and your program will get
stuck.
Simple Example:
Let’s count from 1 up
to 5 using a while loop:
# Initialize a counter variable
count
<- 1
#
Loop as long as ‘count’ is less than or equal to 5
while
(count <= 5) {
print(paste("Current count:",
count))
# Increment the counter
# (This makes the condition eventually FALSE)
count <- count + 1
}
Explanation:
⒈
count starts at 1.
⒉
1 <= 5 is TRUE, so the loop runs.
"Current count: 1" is printed. count becomes 2.
⒊
2 <= 5 is TRUE, loop runs.
"Current count: 2" is printed. count becomes 3.
⒋
…
⒌
5 <= 5 is TRUE, loop runs.
"Current count: 5" is printed. count becomes 6.
⒍
6 <= 5 is FALSE, so the loop stops.
3. Loop Control Statements: break and next
Sometimes, you might
want more control over how a loop executes:
●
break: Immediately exits the current loop,
even if the loop’s condition is still TRUE or there are more items in the
sequence.
●
next: Skips the current iteration of the
loop and moves to the next one. The rest of the code in the current loop
iteration is ignored.
These are more advanced
but good to be aware of for future reference.
4. Simple Programs Demonstrating Loops
Here are two
straightforward R programs to demonstrate the use of for and while loops.
Students should enter these into an R script in RStudio, run them, and observe
the output carefully.
Program 1: Calculating Squares using a for
loop
This program uses a for
loop to iterate through a range of numbers and calculate the square of each
number.
# Program 1: Calculating Squares using a ‘for’
loop
cat("—
Calculating Squares —\n")
#
Define a vector of numbers
numbers_to_square
<- c(2, 4, 6, 8, 10)
#
Create an empty vector to store the results
squared_numbers
<- c()
#
Loop through each number in the ‘numbers_to_square’ vector
for
(num in numbers_to_square) {
# Calculate the square
square_result <- num * num
# Print the result for the current number
cat(paste("The square of", num,
"is", square_result, "\n"))
# Add the result to the ‘squared_numbers’
vector
squared_numbers <- c(squared_numbers,
square_result)
}
cat("\nAll
squared numbers collected:\n")
print(squared_numbers)
Program 2: Simple Guessing Game using a
while loop
This program uses a
while loop to simulate a very simple guessing game. The loop continues until
the correct number is "guessed."
# Program 2: Simple Guessing Game using a
‘while’ loop
cat("—
Simple Guessing Game —\n")
#
The secret number to guess
secret_number
<- 7
#
Initialize the guess variable
#
It is set to a value different from the secret number
user_guess
<- 0
#
Loop until the correct number is guessed
while
(user_guess != secret_number) {
cat("Guess the number (between 1 and
10): ")
# Simulating user guesses for demonstration
# First guess: 5, Second guess: 9, Third
guess: 7
if (user_guess == 0) {
user_guess <- 5
} else if (user_guess == 5) {
user_guess <- 9
} else {
user_guess <- secret_number
}
# Display the guessed number
cat(user_guess, "\n")
# Check if the guess is correct
if (user_guess != secret_number) {
print("Wrong guess! Try again.")
}
}
#
Correct guess message
print("Congratulations!
You guessed the secret number!")
Concluding Thought:
Loops are fundamental tools for any programmer. They
empower you to handle large datasets, automate repetitive calculations, and
build more sophisticated programs. The for loop is excellent when you know your
iteration range, while the while loop is perfect for repeating actions until a
specific condition is met. Practice with these examples, and you’ll soon
appreciate the power and efficiency that loops bring to your R coding!