if...else statement in R Programming Language

Rumman Ansari   Software Engineer   2023-03-24   6260 Share
☰ Table of Contents

Table of Content:


if…else statement

The syntax of if…else statement is:

if (test_expression) {
statement1
} else {
statement2
}

The else part is optional and is only evaluated if test_expression is FALSE.

It is important to note that else must be in the same line as the closing braces of the if statement.

Flowchart of if…else statement


Flowchart of if...else in R Programming

Example of if…else statement


x <- -5
if(x > 0){
print("Non-negative number")
} else {
print("Negative number")
}

Output

[1] "Negative number"

The above conditional can also be written in a single line as follows.

if(x > 0) print("Non-negative number") else print("Negative number")

This feature of R allows us to write construct as shown below.

> x <- -5
> y <- if(x > 0) 5 else 6
> y
[1] 6

This ia a another example of ifelse

Program


 
ifelse( 1 == 1, "Yes", "No")
ifelse( 1 == 0, "Yes", "No")

toTest <- c(1, 1,0, 1, 0, 0, 1)
ifelse( toTest == 1, "Yes", "No")

ifelse( toTest == 1, toTest*3, "Zero")

toTest[2] <- NA
toTest
ifelse( toTest == 1, toTest*3, "Zero")


Output

If you will run the above code it will produce following result


> ifelse( 1 == 1, "Yes", "No")
[1] "Yes"
> ifelse( 1 == 0, "Yes", "No")
[1] "No"
> toTest <- c(1, 1,0, 1, 0, 0, 1)
> ifelse( toTest == 1, "Yes", "No")
[1] "Yes" "Yes" "No"  "Yes" "No"  "No"  "Yes"
> ifelse( toTest == 1, toTest*3, "Zero")
[1] "3"    "3"    "Zero" "3"    "Zero" "Zero" "3"   
> toTest[2] <- NA
> toTest
[1]  1 NA  0  1  0  0  1
> ifelse( toTest == 1, toTest*3, "Zero")
[1] "3"    NA     "Zero" "3"    "Zero" "Zero" "3"

Another Example of ifelse

Program


a <- c(1, 1, 0, 1)
b <- c(2, 1, 0, 1)

ifelse(a == 1 & b == 1, "Yes", "No")

Output


> a <- c(1, 1, 0, 1)
> b <- c(2, 1, 0, 1)
> ifelse(a == 1 & b == 1, "Yes", "No")
[1] "No"  "Yes" "No"  "Yes"