Table of Contents

    If Statement in R Programming Language: Syntax and Examples

    If Statement in R Programming Language: Syntax and Examples

    R if statement

    The syntax of if statement is:

    if (test_expression) {
    statement
    }
    

    If the test_expression is TRUE, the statement gets executed. But if it’s FALSE, nothing happens.

    Here, test_expression can be a logical or numeric vector, but only the first element is taken into consideration.

    In the case of numeric vector, zero is taken as FALSE, rest as TRUE.

    Flowchart of if statement


    Flowchart of if in R Programming

    Example: if statement


    x <- 5
    if(x > 0){
    print("Positive number")
    }
    

    Output

    [1] "Positive number"