Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

If Statement in R: How to use if Statements in R?

Updated on 03 July, 2023

5.56K+ views
9 min read

Programming languages are the backbone of the software industry. Everything from Computer games to Websites to Machine Learning models is designed using programming languages. One such awesome language is R, and it is used for statistical computing and graphics. It provided a plethora of statistical power such as classical statistical tests, classification and clustering, time-series analysis, and linear/non-linear modelling. 

R also includes effective data handling, robust storage handling, operators for all those calculations on arrays, a large collection of data analysis tools, conditions for loops, and user-defined functions.

In this article, we will cover the conditional aspect of R programming and focus mainly on the if statement in R.

IF statements are essential in R programming for directing the flow of execution depending on specIFied criteria. Along with IF statements, IF-else statements in R allow for more complex decision-making. An IF statement in R has a straightforward structure. It enables you to run a code block IF a certain condition statement in R is fulfilled. The following flow diagram depicts the logic and flow of an IF statement in R:

For instance, an IF statement has the following basic syntax:

IF (condition) {

  # executed IF the condition is true

}

Control Structures

To control certain specific parts of code, we use control structures such as if-else statements, for or while loops. Control structures are the chunks of code that used to execute sections of code based on a set of specific conditions and parameters. 

Let us visualise it using an example of a common page shifter 

“If the button is clicked, shift to the next page.”

If the condition of clicking on the button is met, it would tell the program to shift to the next page but would not work if you don’t click on the button. 

Operators and Their Application

These operators are used whenever the answer is either True or False. The statements for these operations are crafted in a way such that you have two or more choices on each step and the solution of that operation depends on that choice. So, now you need to know how to compare these choices, and here comes the use of comparison operators. There are several kinds of comparison operators in R, and we will discuss all of them before proceeding ahead on the if conditional operator in R.

Here are the six essential comparison operators that can be used for working with ‘if’ statements present in R.

  1. Less than ‘<’: This comparison operator uses the < symbol that is x < y, which means “the value of x is always less than y”.
  2. Greater than ‘>’: This comparison operator uses the > symbol that is x > y which means “the value of x is always greater than y”.
  3. Less than or equal to ‘<=’: This comparison operator uses the <= symbol that is x<=y which means “the value of x is less than or equal to y”.
  4. Greater than or equal to ‘>=’: This comparison operator uses the >= symbol that is x>=y, which means “ the value of x is greater than or equal to y”.
  5. Equality ‘==’: This comparison operator used the == symbol that is x==y which means “x is equal to y”.
  6. Not Equal ‘!=’: This comparison operator uses the != symbol that is x!=y where x is not equal to y.

Else IF  in R Statements

We frequently meet situations in which many conditions must be assessed. This is where IF statements come into play again. The else IF statement checks extra criteria, allowing other pathways of execution. An else IF  in R statement has the following structure:

IF (condition1) {

  # executed IF condition1 is true

} else IF (condition2) {

  # executed IF condition1 is false and condition2 is true

} else {

  # executed IF both condition1 and condition2 are false

}

You may handle numerous scenarios and run dIFferent code blocks using else-IF expressions based on the circumstances fulfilled.

Combining IF and Else IF Statements

In increasingly complicated scenarios, numerous conditions may need to be assessed sequentially. This is possible by mixing IF and else-IF expressions. Here’s an illustration of the concept:

IF (condition1) {

  # executed IF condition1 is true

} else IF (condition2) {

  # executed IF condition1 is false and condition2 is true

} else IF (condition3) {

  # executed IF condition1 and condition2 are false, but condition 3 is true

} else {

  #executed IF none of the conditions is true

}

You can create a decision-making structure that accommodates various conditions by chaining together multiple else-IF statements.

Understanding the If-Else Operator in R

We can understand this situation using a basic example of two students who compete to get more marks than the other. If anyone of them gets greater marks than the other counterpart, he/she gets Rank 1, and the other one gets Rank 2.

So if (marks student 1> marks student 2), the A grade goes to Student 1, and grade B goes to Student 2.

And if(marks student 1< marks student 2), the A grade goes to Student 2, and grade B goes to Student 1.

We can use a common statement using If-Else

if (Student 1 > Student 2)

{

      print(“Rank 1: Student 1, Rank 2: Student 2”);

}

else

{

      print(“Rank 1: Student 2, Rank 2: Student 1”);

}

Here Student 1 gets Grade A if his marks are greater than Student 2. Else, if his marks are less than Student 2, it is pushed to Grade B. 

But if you notice what if both the students have the same marks and then you want to compare who got more marks in math and give that student the higher grade. To do so, you can use what’s called a Nested if-else statement.

Nested If-Else Statement

So now you want to base the result upon the marks in mathematics if the students have the same marks. Implementing it in R will look like this:

if(Student 1 > Student 2)

{
        print(“Rank 1: Student 1, Rank 2: Student 2”);

}

else if(Student 1 == Student 2)

{

        if(MathsStudent1 > MathsStudent2){

print(“Rank 1: Student 1”);

        }

        else{

print(“Rank 1: Student 2, Rank 2: Student 1”);

        }

}

else

{
      print(“Rank 1: Student 2, Rank 2: Student 1”);

}

As you can see we have used a term called else if which gets executed when the if statement is not satisfied. We can use a series of such if…else if…else statements which is called an if-else ladder. An if-else ladder might look something like this:

if ( condition 1) {

statement1

} else if (condition 2) {

statement2

} else if (condition 3) {

statement3

} else {

statement4

}

So using such a ladder, you can use multiple decision-making statements. As you also saw, you can use other if-else statements inside one another. This makes the whole thing very flexible to use, but at the same time, it might look a lot more cluttered. Let’s say you are writing a function that needs a lot of if-else statements in it.

A lot of if and else statements will make your code look more complex and wordy. To tackle such situations, you can use if-else present in R. 

The syntax for ifelse is:

ifelse(test expression, x, y)

In the above condition, we give the statement, and x represents the value that will return if the statement is true, and y represents the value that will return if the statement is false. Suppose you are familiar with other programming languages. In that case, you might notice that this is very similar to the ternary operator in certain languages like C++, and it helps us shrink down our code to a single line that is way less wordy and makes our code look clean.

While Loops in R

Apart from conditional statements, R also provides a while loop that allows you to execute a block of code repeatedly IF a specIFic condition holds. The structure of a while loop in R is as follows:

while (condition) {

}

The condition statement in R is checked before each loop iteration. The code block within the loop is run IF the condition is TRUE. The loop ends when the condition becomes FALSE, and the program proceeds with the following code.

Combining IF Statements and While Loops

IF statements and while loops can be combined to create dynamic and powerful control flow structures. You may incorporate extra criteria to influence the loop’s execution by utilizing an IF statement within a while loop. Here’s an illustration:

while (condition1) {

  IF (condition2) {

  }

  # Additional code within the loop

}

In this case, the code block within the while loop is executed repeatedly as long as condition 1 holds. An IF statement is used within the loop to examine condition 2, providing more precise control over the loop’s behavior.

Our learners also read: Learn Python Online for Free

upGrad’s Exclusive Data Science Webinar for you –

Watch our Webinar on How to Build Digital & Data Mindset?

Conclusion

If statement in R is an integral part of R language and definitely a must to master if you want to succeed as a programmer, we explained various ways in which you can use these statements to have the desired result when a specific condition is specified. You can use various other statements like loops inside of an if statement as well. It all depends upon what you want to accomplish. Now that you know what if-else statements, you can practice them and learn further concepts and apply them according to your needs.

If you are curious to learn about R, data science, check out our 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.

Learn data science courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Frequently Asked Questions (FAQs)

1. Which is better among R and Python?

Although both of the languages R and Python are apt for Data Science, there are some shortcomings in both of them in certain aspects.
1. Python can be used for general purposes whereas R is more dedicated to the statistical arena.
2. Python is widely used for developing scalable applications incorporating ML algorithms such as image recognition. On the other hand, R is used for generating powerful visualizations for data analysis.
3. In Python, data can be imported from various file formats including JSON. R being an analysis-oriented language supports only CSV, Excel, and .txt files.
4. Python is used by programmers and developers, whereas R is preferred by researchers and scientists. Those who have less experience in programming can also use R as a tool for analysis purposes.

2. What are the conditional statements in R?

The conditional statements or the flow control statements are the statements that affect the flow of the program depending on whether their conditions are satisfied or not. The R language provides three conditional statements that are mentioned below:
1. If - The if statement comes with a condition. If this condition is satisfied, the R code in the if block will be executed otherwise it will be ignored.
2. Else - The else block works alongside the if statement. If the if statement is not satisfied, the else block will be executed.
3. Else if - When we have multiple conditions to check, for instance, if condition 1 is false then check condition 2. In that case, we use the “else if” statement.

3. What are the operators in R?

The operators in the R programming language are the symbols that direct the compiler on how to operate two operands. There are 4 kinds of operators classified on the basis of their work. These operators are as follows:
1. Arithmetic Operators
2. Logical Operators
3. Relational Operators
4. Assignment Operators