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

```
if (100%%2==0)
paste(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

```
n <- 101
if (n%%2==0) {
paste(n, " is even")
} else {
paste(n, " 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.

```
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")
}
```

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

```
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"))
}
```

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

## Related Notebooks

- How To Plot Histogram In R
- Boxplots In R
- How To Run Logistic Regression In R
- For Loop In R
- How To Iterate Over Rows In A Dataframe In Pandas
- How To Replace na Values with Zeros In R Dataframe
- 3 Ways to Rename Columns in Pandas DataFrame
- How to Generate Random Numbers in Python
- How To Write DataFrame To CSV In R