---
description: Master the for loop in R with our comprehensive guide, helping you to iterate through sequences efficiently and enhance your data analysis skills.
title: For Loop in R with Examples for List and Matrix
image: https://www.guru99.com/images/r_programming/032818_1243_ForLoopinRw1.png
---

 

[Skip to content](#main) 

A for loop is very valuable when we need to iterate over a list of elements or a range of numbers. Loop can be used to iterate over a list, data frame, vector, matrix or any other object. The braces and square bracket are compulsory.

In this tutorial, we will learn,

* [For Loop Syntax and Examples](#for-loop-syntax-and-examples)
* [For Loop over a list](#for-loop-over-a-list)
* [For Loop over a matrix](#for-loop-over-a-matrix)

## For Loop Syntax and Examples

For (i in vector) {
    Exp	
}

Here,

[R](https://www.guru99.com/r-tutorial.html) will loop over all the variables in vector and do the computation written inside the exp.

[![For Loop in R](https://www.guru99.com/images/r_programming/032818_1243_ForLoopinRw1.png)](https://www.guru99.com/images/r%5Fprogramming/032818%5F1243%5FForLoopinRw1.png)

For Loop in R

Let’s see a few examples.

**For Loop in R Example 1**: We iterate over all the elements of a vector and print the current value.

# Create fruit vector
fruit <- c('Apple', 'Orange', 'Passion fruit', 'Banana')
# Create the for statement
for ( i in fruit){ 
 print(i)
}

**Output:** 

## [1] "Apple"
## [1] "Orange"
## [1] "Passion fruit"
## [1] "Banana"

**For Loop in R Example 2**: creates a non-linear function by using the polynomial of x between 1 and 4 and we store it in a list

# Create an empty list
list <- c()
# Create a for statement to populate the list
for (i in seq(1, 4, by=1)) {
  list[[i]] <- i*i
}
print(list)

**Output:** 

## [1]   1  4 9 16

The for loop is very valuable for machine learning tasks. After we have trained a model, we need to regularize the model to avoid over-fitting. Regularization is a very tedious task because we need to find the value that minimizes the loss function. To help us detect those values, we can make use of a for loop to iterate over a range of values and define the best candidate.

## For Loop over a list

Looping over a list is just as easy and convenient as looping over a vector. Let’s see an example

# Create a list with three vectors
fruit <- list(Basket = c('Apple', 'Orange', 'Passion fruit', 'Banana'), 
Money = c(10, 12, 15), purchase = FALSE)
for (p  in fruit) 
{ 
	print(p)
}

**Output:** 

## [1] "Apple" "Orange" "Passion fruit" "Banana"       
## [1] 10 12 15
## [1] FALSE

## For Loop over a matrix

A matrix has 2-dimension, rows and columns. To iterate over a matrix, we have to define two for loop, namely one for the rows and another for the column.

# Create a matrix
mat <- matrix(data = seq(10, 20, by=1), nrow = 6, ncol =2)
# Create the loop with r and c to iterate over the matrix
for (r in 1:nrow(mat))   
    for (c in 1:ncol(mat))  
         print(paste("Row", r, "and column",c, "have values of", mat[r,c]))  

**Output:** 

## [1] "Row 1 and column 1 have values of 10"
## [1] "Row 1 and column 2 have values of 16"
## [1] "Row 2 and column 1 have values of 11"
## [1] "Row 2 and column 2 have values of 17"
## [1] "Row 3 and column 1 have values of 12"
## [1] "Row 3 and column 2 have values of 18"
## [1] "Row 4 and column 1 have values of 13"
## [1] "Row 4 and column 2 have values of 19"
## [1] "Row 5 and column 1 have values of 14"
## [1] "Row 5 and column 2 have values of 20"
## [1] "Row 6 and column 1 have values of 15"
## [1] "Row 6 and column 2 have values of 10" 

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter](https://www.guru99.com/images/footer-email-avatar-imges-1.png) Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/r-for-loop.png","url":"https://www.guru99.com/images/r-for-loop.png","width":"306","height":"190","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/r-for-loop.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/r-programming","name":"R Programming"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/r-for-loop.html","name":"For Loop in R with Examples for List and Matrix"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/r-for-loop.html#webpage","url":"https://www.guru99.com/r-for-loop.html","name":"For Loop in R with Examples for List and Matrix","dateModified":"2024-06-12T19:22:18+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/r-for-loop.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/r-for-loop.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/evelyn","name":"Evelyn Clarke","description":"I'm Evelyn Clarke, an AI Research Scientist specializing in machine learning and natural language processing, dedicated to advancing the field responsibly.","url":"https://www.guru99.com/author/evelyn","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/evelyn-clarke-author-120x120.png","url":"https://www.guru99.com/images/evelyn-clarke-author-120x120.png","caption":"Evelyn Clarke","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"@type":"NewsArticle","headline":"For Loop in R with Examples for List and Matrix","keywords":"R, Programming","dateModified":"2024-06-12T19:22:18+05:30","articleSection":"R Programming","author":{"@id":"https://www.guru99.com/author/evelyn","name":"Evelyn Clarke"},"publisher":{"@id":"https://www.guru99.com/#organization"},"description":"Master the for loop in R with our comprehensive guide, helping you to iterate through sequences efficiently and enhance your data analysis skills.","copyrightYear":"2024","copyrightHolder":{"@id":"https://www.guru99.com/#organization"},"name":"For Loop in R with Examples for List and Matrix","@id":"https://www.guru99.com/r-for-loop.html#richSnippet","isPartOf":{"@id":"https://www.guru99.com/r-for-loop.html#webpage"},"image":{"@id":"https://www.guru99.com/images/r-for-loop.png"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/r-for-loop.html#webpage"}}]}
```
