Open In App

How To Use A For Loop In R

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads