Logical Operators in R Programming Language

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

Table of Content:


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 <- c(3,1,TRUE,2+3i)
b <- c(4,1,FALSE,2+3i)
print(a&b)

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 <- c(3,0,TRUE,2+2i)
b <- c(4,0,FALSE,2+3i)
print(a|b)

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 <- c(3,0,TRUE,2+2i)
print(!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 <- c(3,0,TRUE,2+2i)
b <- c(1,3,TRUE,2+3i)
print(a&&b)

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 <- c(0,0,TRUE,2+2i)
b <- c(0,3,TRUE,2+3i)
print(a||b)

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