How To Use A For Loop In R
Last Updated :
24 Apr, 2024
For loops in R is a fundamental programming construct that allows you to repeat a block of code a specified number of times or for a given range of elements. They are essential for automating repetitive tasks, manipulating data, and performing various computational operations.
The basic syntax of a for loop in R Programming Language is:
for (variable in sequence)
{
# Code to be repeated
}
- variable: A variable that represents the current element in the loop.
- sequence: A vector or range that provides the elements to iterate over.
Let's explore different scenarios and examples of using for loops in R.
Looping Over a Vector
A common use case for for loops is iterating over a vector to perform operations on each element.
R
# Create a vector
numbers <- c(1, 2, 3, 4, 5)
# Initialize an empty vector to store results
squared_numbers <- c()
# Loop over each element in the vector and square it
for (num in numbers) {
squared_numbers <- c(squared_numbers, num^2)
}
print(squared_numbers)
Output:
[1] 1 4 9 16 25
Looping Over a Range of Numbers
For loops can also iterate over a specified range of numbers.
R
# Loop from 1 to 10 and print each number
for (i in 1:10) {
print(i)
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
Looping Over a List
For loops can iterate over lists, allowing you to perform operations on each item:
R
# Create a list with different elements
my_list <- list(name = "Ali", age = 25, city = "New York")
# Loop over each item in the list and print the key-value pair
for (item in names(my_list)) {
cat(item, ":", my_list[[item]], "\n")
}
Output:
name : Ali
age : 25
city : New York
Looping Over a Data Frame
When working with data frames, for loops can iterate over rows or columns:
R
# Create a data frame
df <- data.frame(
Name = c("Ali", "Boby", "Charles"),
Age = c(25, 30, 35)
)
# Loop over each row and print the information
for (i in 1:nrow(df)) {
cat("Row", i, ": Name =", df$Name[i], ", Age =", df$Age[i], "\n")
}
Output:
Row 1 : Name = Ali , Age = 25
Row 2 : Name = Boby , Age = 30
Row 3 : Name = Charles , Age = 35
Looping with Conditional Statements
You can use for loops with conditional statements to perform specific actions based on conditions:
R
# Loop from 1 to 10 and print only even numbers
for (i in 1:10) {
if (i %% 2 == 0) { # Check if the number is even
print(i)
}
}
Output:
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
Nested For Loops
Nested for loops allow you to perform complex operations by looping within a loop:
R
# Loop through a 3x3 matrix and multiply each element by 2
matrix <- matrix(1:9, nrow = 3)
# Nested loop to iterate over rows and columns
for (i in 1:nrow(matrix)) {
for (j in 1:ncol(matrix)) {
matrix[i, j] <- matrix[i, j] * 2
}
}
print(matrix)
Output:
[,1] [,2] [,3]
[1,] 2 8 14
[2,] 4 10 16
[3,] 6 12 18
Conclusion
For loops in R are a powerful tool for automating repetitive tasks, manipulating data, and performing complex operations with nested loops. By understanding their syntax and different use cases, you can use for loops effectively to solve a wide range of programming problems.
Similar Reads
How to Use do.call in R In R Programming language the do.call() function is used to execute a function call using a list of arguments. This can be particularly useful when we have a function and its arguments stored in separate objects (e.g., in a list) and we want to apply the function to these arguments. Syntax do.call(f
4 min read
How to Create a Nested For Loop in R? A loop in a programming language is a sequence of instructions executed one after the other unless a final condition is met. Using loops is quite frequent in a program. Need of a loop Let us consider a scenario where we want to print natural numbers from 1 to 3. We can simply print them one by one.
6 min read
Print to PDF in a For Loop Using R When working with R, it's often necessary to automatically create multiple plots or reports and save each one as a PDF file. This task is usually part of data analysis and reporting, where it's important to be efficient and ensure that results can be reproduced easily. Using a `for` loop along with
2 min read
For loop in R For loop in R Programming Language is useful to iterate over the elements of a list, data frame, vector, matrix, or any other object. It means the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object. It is an entry-controlled loop, in
5 min read
How to create a list in R In this article, we will discuss What is a list and various methods to create a list using R Programming Language. What is a list?A list is the one-dimensional heterogeneous data i.e., which stores the data of various types such as integers, float, strings, logical values, and characters. These list
2 min read