### If-else condition in R

#### if Statement in R:

The if-else combination is probably the most commonly used control structure not only in R but also for other programming languages. This structure allows you to test a condition and act on it depending on whether it’s true or false.
if statement in R:

`if (condition) {#R Code}`

`x<-200if(x > 100){print("X is greater than 100")}`

Output:

` "X is greater than 100"`

If the condition is TRUE, the statement gets executed. But if it’s FALSE, nothing happens. Here, condition can be a logical or numeric vector, but only the first element is taken into consideration.

You could have a series of if clauses that always get executed if their respective conditions are true.

if(condition1) {
R Code
}
if(condition2) {
R Code
}

#### if…else statement in R:

In R, the if/else syntax is:

if (condition) {

R code

} else {

R code

}

#### if-else: `x <- readline(prompt="Enter a number: ") #Take input from user. Then run the next line.`

`y <- if(x > 10){print("Value is greater than 10")} else {print("Value is less than or equal to 10")}`

Output:

`> x <- readline(prompt="Enter a number: ")Enter a number: 11`

` "Value is more than 10"`

Example:

`x = 4y = 6if (x > y) {print("x is larger than y")} else {print("x is less than or equal to y")}`

Output:

` "x is less than or equal to y"`

#### ifelse() Function in R:

This is called Vectorization with ifelse. The ifelse() function is a vector equivalent form of the if…else statement in R. This vectorization of code, will be much faster than applying the same function to each element of the vector individually.

So, you can use if-else like this also `ifelse(4 > 3, "greater","less")`

Output:

` "greater"`

This is how we use ifelse() to a vector.

`x<- 1:20ifelse(x> 10, "greater", "less")`

Output:

` "less" "less" "less" "less" "less" "less" "less" "less" "less" "less" "greater" "greater" "greater" "greater" "greater" "greater" "greater" "greater" "greater" "greater"`

#### Nested if…else statement in R: `x <- 0if (x < 0) {print("Negative number")} else if (x > 0) {print("Positive number")} elseprint("Zero")`

Output:

` "Zero"`