Table of Contents

    Logical Operators in R Programming Language: Explanation and Examples

    Logical Operators in R Programming Language: Explanation and Examples

    Logical Operators

    Following table shows the logical operators supported by R language. It is applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical value TRUE.

    Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value.

    Operator Description Example
    & It is called Element-wise Logical AND operator. It combines each element of the first vector with the corresponding element of the second vector and gives a output TRUE if both the elements are TRUE.
    a

    it produces the following result −

    [1]  TRUE  TRUE FALSE  TRUE
    | It is called Element-wise Logical OR operator. It combines each element of the first vector with the corresponding element of the second vector and gives a output TRUE if one the elements is TRUE.
    a

    it produces the following result −

    [1]  TRUE FALSE  TRUE  TRUE
    ! It is called Logical NOT operator. Takes each element of the vector and gives the opposite logical value.
    a

    it produces the following result −

    [1] FALSE  TRUE FALSE FALSE

    The logical operator && and || considers only the first element of the vectors and give a vector of single element as output.

    Operator Description Example
    && Called Logical AND operator. Takes first element of both the vectors and gives the TRUE only if both are TRUE.
    a

    it produces the following result −

    [1] TRUE
    || Called Logical OR operator. Takes first element of both the vectors and gives the TRUE if one of them is TRUE.
    a

    it produces the following result −

    [1] FALSE

     

    More Examples

    Operators & and | perform element-wise operation producing result having length of the longer operand.

    But && and || examines only the first element of the operands resulting into a single length logical vector.

    Zero is considered FALSE and non-zero numbers are taken as TRUE. An example run.

    > x <- c(TRUE,FALSE,0,6)
    > y <- c(FALSE,TRUE,FALSE,TRUE)
    > !x
    [1] FALSE  TRUE  TRUE FALSE
    > x&y
    [1] FALSE FALSE FALSE  TRUE
    > x&&y
    [1] FALSE
    > x|y
    [1]  TRUE  TRUE FALSE  TRUE
    > x||y
    [1] TRUE