Programs

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

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)

Top Data Science Skills You Should Learn

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

Read our popular Data Science Articles

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.

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.

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.

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

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Data Science Course

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks