For Loop in R

ByHariharan Rajendran

For Loop in R

In a real time, we will be in a position to handle the logic using loops. Loop concept is available in all programming language and also in R.

For example, if we want to generate first 200 prime numbers, we have to use loop to get the result.

In R, “for loop” is used to iterate over a vector.

Syntax

for (val in sequence) {

statement

}

In the above syntax, sequence is a vector which we can define and assign into an object and can use the object or we can directly place the vector with the expression. “val” will take the value of sequence and process in a loop. The statement will be triggered until the length of the sequence is completed.

Example,

x <- c(1,2,3,4,5,6,7,8,9,10)

count <- 0

for (val in x) {

if(val %% 2 == 0) count = count+1

}

print(count)

image

Using Next

We can use the word next inside the for loop and it will change the flow of the process. Check the below example,

for (i in 1:10) {

if (!i %% 2){

}

print(i)

}

image

If you run above script, I will get the result as 1,2,3,4,5,6,7,8,9,10 (All the values from the 1:10 sequence).

If you want to display only the odd number for the same sequence input then I can just add a “next” keyword inside if loop.

for (i in 1:10) {

if (!i %% 2){

next

}

print(i)

}

image

First “i” value 1 will go to if condition once the value reaches the keyword “next”. It will redirect to for loop again and it will come again for the second number i.e. 2 and it will continue up to 10.

About the Author

Hariharan Rajendran author

Hariharan Rajendran is a Microsoft Certified Trainer and Lead BI Solutions Consultant with 8+ years of experience in Database, BI and Azure platforms. Hariharan is also an active community leader, speaker & organizer and leads the Microsoft PUG (Power BI User Group – Chennai), SQLPASS Power BI Local Group – Chennai and an active speaker in SQL Server Chennai User Group and also a leader in Data Awareness Program worldwide events. Hariharan also frequently blogs (www.dataap.org/blog), provides virtual training (on ad-hoc basis) on Microsoft Azure, Database Administration, Power BI and database development to worldwide clients/audience.

Comments Are Closed!!!