Table of Contents

    If...Else Ladder in R Programming Language: Syntax and Examples

    If...Else Ladder in R Programming Language: Syntax and Examples

    if…else Ladder

    The if…else ladder (if…else…if) statement allows you execute a block of code among more than 2 alternatives

    The syntax of if…else statement is:

    if ( test_expression1) {
    statement1
    } else if ( test_expression2) {
    statement2
    } else if ( test_expression3) {
    statement3
    } else {
    statement4
    }

    Only one statement will get executed depending upon the test_expressions.

    Example of nested if…else


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

    Output

    [1] "Zero"

    There is an easier way to use if…else statement specifically for vectors in R programming.

    You can use ifelse() function instead; the vector equivalent form of the if…else statement.


    Another Example of ifelse

    Code

    
    a <- c(1, 1, 0, 1)
    b <- c(2, 1, 0, 1)
    
    ifelse(a == 1 & b == 1, "Yes", "No")
    
    ifelse( b == 1 ,  "Hi", ifelse(b == 0, "Hello", "Goodbye"))
    
    

    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"
    > ifelse( b == 1 ,  "Hi", ifelse(b == 0, "Hello", "Goodbye"))
    [1] "Goodbye" "Hi"      "Hello"   "Hi"