Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconHow To Use If-Else Statements And Loops In R

How To Use If-Else Statements And Loops In R

Last updated:
19th Jan, 2023
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
How To Use If-Else Statements And Loops In R

If you are not sure how to use if-else statements and loops in r, this article will help a lot. Whether you are programming in any other language, including R, you want to take control of how and when each part of the code is executed. This can be very easily done if you choose to use control structures such as if-else statements. In simpler terms, control structures are code blocks that help to manage the execution of the other code sections depending on stated parameters. These can be considered as instructions that parents give to their children before they go out of the house. For instance, “If I do not come home by 10 pm, go off to sleep.” A condition is set where the control structures instruct R about what should be done if the condition is not met or met. At all times, R will strictly follow the instructions given.

Comparison Operators in R 

If you want to use control structures, the first thing that has to be done is creating statements that will either result in ‘False’ or ‘True’. In the aforementioned example of kids, the statement “It is 10 pm. Have my parents returned home?” yields False (No) or True (Yes). The best way to assess something as False or True in R is with the help of comparison operators. Mentioned below are a few comparison operators that are essential to work with control structures in R: 

Here ‘==’ means equality. If the declaration x == a is outlined as a question, it means, “Is the value of x the same as the value of a?” 

  • ‘!=’ signifies “not equal to”. If the statement x != b is outlined as a question, it means, “Is the value of x not the same as the value of b?” 
  • ‘<’ signifies “less than”. If the statement x < c is outlined as a question, it symbolizes “Is x’s value less than c’s value?” 
  • ‘<=’ signifies “less than or equals to”. If the statement x <= d is outlined as a question, it symbolizes “Is x’s value less or the same as the value of d?” 
  • ‘>’ signifies “greater than”. If the declaration x > e is outlined as a question, it symbolizes “Is x’s value bigger than the value of e?” 
  • ‘>=’ signifies “greater than or equals to”. If the statement x >= f is outlined as a question, it means, “Is x’s value more than or equals to f’s value?” 

Everything you need to know about If-Else in R 

Explore our Popular Data Science Courses

Suppose you are watching a match of cricket that determines the team that will make it to the playoffs. All possible outcomes can easily be visualized with the help of a tree chart: 

Source Image: Google 

With the help of the aforementioned tree chart, you can easily see that there are only 2 possible outcomes. In case Team A wins the match, they will reach the playoffs. On the other hand, Team B will reach the playoffs if it wins the match. 

You can try representing this situation in R as well. An if statement can be used so that the program can be written that determines the winning team. R is instructed by if statements to run a code line if one of the conditions returns True. Considering an if statement in this situation is a better choice here. Depending on the outcome occurs, an if statement allows control of the statement that is printed. 

Read our popular Data Science Articles

The basic syntax and conditional flow chart for an if statement is shown in the figure given below: 

Source Image: Google

The condition in if statement has to be in a manner that it results in ‘False’ or ‘True’. In case the expression returns ‘True’, all code within the brackets { } will be executed by the program. On the other hand, code is executed by the program if the expression reverts ‘False’. Now, given below is an illustration of an if statement that will print the winner team’s name: 

Source Image: Google 

The program worked! As ‘Team A’ scored more goals compared to Team B, the conditional statement [team_A > team_B] results in ‘True’. Hence, the broadcast that Team A has won the game is printed. 

Check Out upGrad’s Data Science Courses 

Adding the else Statement in R 

Previously, based on the expression, the team’s name that will make it to the playoffs was printed. Now, take a look at a different score matchup. What happens when Team B scores 3 goals and Team A scores 1 goal. The team_A > team_B conditional will result in ‘False’. Hence, nothing will be printed when the code runs. The is because when the if statement results in ‘False’, the block of code within the if statement will not be executed: 

Source Image: Google 

If you check the original flow chart, for one of the two probabilities, only one branch is coded: 

Source Image: Google 

The program should be designed in a manner that accounts for both likelihoods. When the expression will evaluate to ‘False’, ‘Team B makes the playoffs’. To put it in another way, the aim is to be able to manage both conditional branches: 

Source Image: Google 

For this, it will be turned to an if-else statement by adding an else statement. An if-else statement instructs the program to run a code block when the conditional statement evaluates to ‘True’ in R. Similarly, a different code block runs when the conditional statement evaluates to ‘False’. Given below is an image in the form of a flowchart and with respect to R syntax of how it works.

Source Image: Google 

Three arguments are required by the if-else in R: 

A statement that either evaluates to False or True. 

In case the comparison operator executes to ‘True’, the value that should be returned by R. 

In case the comparison operator accesses to ‘False’, the value that should be returned by R. 

Hence, a code block has to be added that will run when team_A > team_B, the conditional expression, returns ‘False’. With the addition of an else statement in R, this can be done. In case the comparison operator computes to ‘False’, then “Team B will make the playoffs” is printed.

Source Image: Google 

If you are curious to learn about tableau, data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Explore Free Courses

Suggested Blogs

Data Mining Techniques &#038; Tools: Types of Data, Methods, Applications [With Examples]
101463
Why data mining techniques are important like never before? Businesses these days are collecting data at a very striking rate. The sources of this eno
Read More

by Rohit Sharma

07 Jul 2024

An Overview of Association Rule Mining &#038; its Applications
142207
Association Rule Mining in data mining, as the name suggests, involves discovering relationships between seemingly independent relational databases or
Read More

by Abhinav Rai

07 Jul 2024

What is Decision Tree in Data Mining? Types, Real World Examples &#038; Applications
16859
Introduction to Data Mining In its raw form, data requires efficient processing to transform into valuable information. Predicting outcomes hinges on
Read More

by Rohit Sharma

04 Jul 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
82582
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

04 Jul 2024

Most Common Binary Tree Interview Questions &#038; Answers [For Freshers &#038; Experienced]
9998
Introduction Data structures are one of the most fundamental concepts in object-oriented programming. To explain it simply, a data structure is a par
Read More

by Rohit Sharma

03 Jul 2024

Data Science Vs Data Analytics: Difference Between Data Science and Data Analytics
70136
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right
Read More

by Rohit Sharma

02 Jul 2024

Graphs in Data Structure: Types, Storing &#038; Traversal
51846
In my experience with Data Science, I’ve found that choosing the right data structure is crucial for organizing information effectively. Graphs
Read More

by Rohit Sharma

01 Jul 2024

Python Banking Project [With Source Code] in 2024
14852
The banking sector has many applications for programming and IT solutions. If you’re interested in working on a project for the banking sector,
Read More

by Rohit Sharma

25 Jun 2024

Linear Search vs Binary Search: Difference Between Linear Search &#038; Binary Search
66256
In my journey through data structures, I’ve navigated the nuances of linear search vs binary search in data structure, especially when dealing w
Read More

by Rohit Sharma

23 Jun 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon