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:

The syntax of if statement is:

 

if (condition) {
#R Code
}

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

Output:

[1] "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

[1] "Value is more than 10"

Example:

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

Output:

[1] "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:

[1] "greater"

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

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

Output:

[1] "less" "less" "less" "less" "less" "less" "less" "less" "less" "less" "greater" "greater"
[13] "greater" "greater" "greater" "greater" "greater" "greater" "greater" "greater"

Nested if…else statement in R:

 

x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")

Output:

[1] "Zero"

Control Structure

For Loops