In Today’s post we will be exploring different For loop operations in R Language:

As we know there are three List of Loops

  1. While Loop  ( I have posted on this in my previous post, please refer this below link if not explored)

2.For Loop: we will be discussing in this Post

3.Repeat Loop : we will discuss  on this in next Post

There are two Loop control statements:

1.Break statement

2. Next statement

Before we dive into the examples, let’s start with a quick theoretical introduction to for-loops…

The for loop in R is very valuable when we need to iterate over a list of elements (vectors, Matrix, List & data frame) or a range of numbers.

It is an entry-controlled loop, in this loop the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.

For Loop starts with keyword For and Just Like while Loop, it also has a Simple braces and then Curly braces, The curly Braces are indeed for the body of the loop and the Open Braces doesn’t specify the  Condition/Expression, Instead it specifies the iterations of the loop.

In the following, I’ll show you 7 examples for the application of for-loops in R. So keep on reading!

Now don’t get afraid, don’t get worried

we won’t be digging too much into vectors, Lists, Matrix in this specific tutorial but this is our first encounter of the elements  and it’s natural because R is all about vectors and vector as operations, matrix  and Lists we’ll drill into those topics  in a lot and in detail in the next posts, but for now let me show you a quick intro or show you how we’re using those elements in For Loop.

1.For Loop Through Vector in R (Basics) :

Syntax Written in Source Pane:

# 1. working on For Loop Through Vectors

# Head of for Loop

for (i in  1 : 10) {

#code Block

  val1 <- i ** 2

#Prints the  val1 variable  value in console

  print(val1 )

         }

In the above  R code, we are specifying within the head of the for-loop that we want to run through a vector containing ten elements from the first element (i.e. 1) to the last element (i.e. 10).

Within the body of the for-loop we are then creating an output called var1, which contains the  I value from the  for Loop (1 to 10) to the power of 2. We are printing the result of our code block in each iteration to the R Studio console.

2.For Loop   Through character vectors

Syntax written in R Pane :

#For Loop  through Character vectors

# First Declaring a Variable name var2

#Iam adding Five person Names as a List to var2 Variable

var2 <- c(“Subha”,”Reshma”, “sri”, “Jo”, “Hareesh”)

#The above var2 Variable creates Character vector

for (i in var2){

#loop the character vectors stored in variable var2

print (paste(“The Name”,i, “consists of”, nchar(i),”characters”)) 

}

From the above code  Variable var2 is assigned to a List of five person Names

And in the body of the loop,  we are trying to print the every  name of the Person. Number of Characters the name consists.

Note:  1. Paste function is used to concatenate or add the multiple String Values

            2. From the above example, nchar(i)  represents number of characters in a string

3.For Loop through vector by Appending the Data ( this example will help you to append the data)

Syntax written in R pane:

#For Loop through vector by Appending the Data 

#Let us create an empty data Object

var1 <- numeric ()

#Now will use  For statement to create a vector of output Values

#Head of For Loop  Block

for(i in 1: 10){

#Execute Code Block

  var1 <- c(var1,i**2)

  print (var1)

4. Nested For Loop:

Code written in console pane :

#Nested Loop

#Create Empty Data Object

var1 <- character()

for(i in 1:5){

#Nested For loop

  for(j in  1:3){

   var1 <- c(var1,paste(LETTERS[i],letters[j],sep = “_”))

  }

}

print(var1)

Here paste Function  is used to combine the strings, LETTERS is also a function to display the alphabet in Capitals , letters is also a function to display alphabets  in Lower letters, sep is a separator between the Upper case string  and lower case string, and separator used here is underscore to separate the strings.

5. Let’s use Break statement in For loop

Break: When the break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop.

6.Next statement in for Loop :

The next statement in R programming language is useful when we want to skip the current iteration of a loop without terminating it. On encountering next, the R parser skips further evaluation and starts next iteration of the loop.

7. Create Multiple Plots within For Loop

Code written  in Source Pane :

#          Create multiple plots within For Loop

#ncol represents no.of colums in iris dataset

for(i in 1:(ncol(iris)- 1)){

#plot is a function to display the rows & colums in Plot

#nrow represents no.of rows in iris dataset

plot(1:nrow(iris),iris[,i])

#sys.sleep function will suspend the  execution of R expressions

#for specified Time Interval, here Time interval is 1

Sys.sleep(1)

}

Please Click on zoom button in the plot pane to see the detailed image.

Note : iris dataset is a  famous data set  & in built dataset which gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively.

0 0 votes
Article Rating
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments