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.

## 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.

## 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.

## 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 