# If Else Statements In R

If else statements are most used statements in any programming language. In R it is very simple to use if else.

## If condition in R

Let us start with If statement ist. Here is the syntax.

if (test_expression) {

R statement



}

Let us do an example. We would check if number 100 is even number or not.

In [7]:
if (100%%2==0)
paste(100, " is even")

'100 is even'

Note curly brackets are optional, if not followed by else condition in R.

100%%2==0 is a condition which is checking if the remainder is zero. If it does then paste(100, "is even ") statement is executed.

Let us extend our previous example and also R statement for condition if number is odd.

## If else statement in R

In [12]:
n <- 101
if (n%%2==0) {
paste(n, " is even")
} else {
paste(n, " is odd")
}

'101 is odd'

As we see above, we used curly braces since if statement is followed by else loop/condition.

## Multiple if else statements in R

OK, let us do an another example. Given a number we want find to out if the number is less than 100 or greater than 100 and less than 1000.

In [13]:
n <- 767
if (n <100) {
paste(n," is less than 100")
} else if (n > 100 && n < 1000) {
paste(n, " is greater than 100 but less than 1000")
} else {
paste(n, " is greater than 1000")
}

'767 is greater than 100 but less than 1000'

## Nested If else statements in R

Let us add one more scenario to above problem. If number is between 100 and 1000, check if number is even or odd.

In [18]:
n <- 767
if (n <100) {
print(paste(n," is less than 100"))
} else if (n > 100 && n < 1000) {
print(paste(n, " is greater than 100 but less than 1000"))
if (n%%2==0) {
print(paste(n, " is even."))
} else {
print(paste(n, " is odd."))
}
} else {
print(paste(n, " is greater than 1000"))
}

[1] "767  is greater than 100 but less than 1000"
[1] "767  is odd."


## Wrap Up!

I hope you would have now clear understanding of how to use if else statements in R. Also check out my tutorial on how to use for and if else loops in R Dataframe.