VOOZH about

URL: https://www.geeksforgeeks.org/r-language/how-to-use-a-for-loop-in-r/

⇱ How To Use A For Loop In R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How To Use A For Loop In R

Last Updated : 23 Jul, 2025

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.

Output:

[1] 1 4 9 16 25

Looping Over a Range of Numbers

For loops can also iterate over a specified range of numbers.

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:

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:

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:

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:

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.

Comment
Article Tags:

Explore