Looping in R

R Tutorial 17.0

In the series of R tutorials, we earlier covered "must know" part of data management of R in depth and then we switched to statistical procedures part. We left few chunks in the data management part, which we will try to cover now with stats part, in parallel. There is no need to get confused, as the all the blogs would be enlisted in the "R" tab thatwould act as your guide.
Just focus on learning, as you need to evolve, everyday!

We are covering three basic ways used for looping in R:

Method 1 : Repeat - increase - Break

#Initialize a counter
n = 1
repeat {
# Write here, what you want to do in code
______________________________________
______________________________________
# Increase the counter
n = n+1
# Come out of counter using logical condition
if(n > 5) { break } }

Let's look at an example :

text = c("print it with Method 1 - Loop")
n = 1
repeat {

print(paste(text, n))
print (n**2)
n = n+1 if(n > 5) { break } }

Method 2 : While - Increase - Auto Break
#Initialize a counter
n = 1
#Restric the loop execution with logical condition using a while statement
while ( n< 7) {
# Write here, what you want to do in code
______________________________________
______________________________________
# Increase the counter
n = n +1
}

Let's look at an example :

text = c("print it with Method 2- Loop") n = 1 while (n < 6){ print(paste(text, n)) print (n**2) n = n+1 }

Method 3 : Excel style for loop - the simplest one 


#Initialize a counters
for( n in 1:10) {

# Write here, what you want to do in code
______________________________________
______________________________________

}

Let's look at an example :

text = c("print it with Method 3- Loop") for (n in 1:10){ print(paste(text, n)) print (n**2) }


Enjoy reading our other articles and stay tuned with us. Kindly do provide your feedback in the 'Comments' Section and share as much as possible.