Not equal to in R: The Inequality Operator in R

R language has many types of operators to carry out logical, comparative, and mathematical operations. For example, relational operators are used to compare between values.

Not equal to in R

The not equal operator in R is one of the relational operators, and it is the opposite of the equality operator. The not equal to operator written as an exclamation mark followed by an equals sign ( != ).

To check if an object is equal to another object in R, use either equality operator(=) or inequality operator(!=).

The not equal to operator can also be applied for logicals, numerical, and other R objects.

Syntax

!=

Example

19 != 21
TRUE != FALSE
TRUE != TRUE
FALSE != FALSE
FALSE != TRUE

Output

[1] TRUE
[1] TRUE
[1] FALSE
[1] FALSE
[1] TRUE

The first statement is 19 != 21, which is TRUE. So both are different values, and 19 is less than 21.

Furthermore, TRUE is not equal to FALSE. That’s why it returns TRUE.

In the next statement, it returns FALSE because TRUE is equal to TRUE.

Then, it returns FALSE because FALSE is equal to FALSE.

At last, it returns TRUE because FALSE is not equal to TRUE.

Example 2

Let’s define two numerical vectors and compare them using various relational operations.

rv <- 11
ra <- 21

rv < ra
rv > ra
rv <= 12
rv >= 21
ra == 21
ra != rv

Output

[1] TRUE
[1] FALSE
[1] TRUE
[1] FALSE
[1] TRUE
[1] TRUE

Compare two vectors using not equal to operator

To compare the equality of two vectors in R, use either equality or inequality operator.

rv <- c(11, 21)
ra <- c(18, 19)

rv != ra

Output

[1] TRUE  TRUE

Combining equal to and not equal to operators in R

The equal to and not equal to operators can be combined with &, meaning “and“, and |, meaning or operator.

19 != 18 | 21 == 21
19 != 18 & 21 != 21
19 == 18 | 21 != 21

Output

[1] TRUE
[1] FALSE
[1] FALSE

The or operator(|) is used to check more than one comparison where any comparison returns TRUE.

The and operator(&) is used to check each comparison returns TRUE; if one comparison returns FALSE, the output becomes FALSE. We have combined the equality and inequality operators with & and | operators.

That’s it for this tutorial.

See also

Not in R

%in% in R

Leave a Comment