R Tutorial R Charts & Graphs R Statistics R References

R - Logical NOT operator



In R, element-wise Logical NOT operator ! takes each elements of a vector and returns opposite logical value. It can be applied on vectors of type logical, numeric or complex. All numbers other than 0 are considered as logical value TRUE.

Example: using with a vector

Consider the example below, where ! operators is used with a vector.

v1 <- c(10, 0, TRUE, 1+2i)

#Applying ! operator
print(!v1)

The output of the above code will be:

[1] FALSE  TRUE FALSE FALSE

Example: using with a matrix

Similarly, the ! operators can be used with a matrix.

m1 <- matrix(c(10, 0, TRUE, 1+2i), nrow=2)

#Applying ! operator
print(!m1)

The output of the above code will be:

      [,1]  [,2]
[1,] FALSE FALSE
[2,]  TRUE FALSE

Example: Reversing boolean

Consider the example below, where ! operators is used to reverse a boolean condition.

i <- 16

if (!(i > 100)) {
  sprintf("%d is less than 100.", i)
} else {
  sprintf("%d is not less than 100.", i)
}

The output of the above code will be:

[1] "16 is less than 100."

❮ R - Operators