Not equal (!=) Operator in R

In R, the not equal (!=) operator is used to test inequality between two objects. It checks whether its left-hand and right-hand operands are not equal and returns a logical value (TRUE or FALSE) for each comparison.

Syntax

operand1 != operand2

operand1 and operand2 can be numbers, variables, vectors, or comparable objects.

Visual Representation

Pictorial representation of not equal operator in R

Example 1: Usage of inequality(!=) operator

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

Output

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

Example 2: Comparing numerical vectors

Comparing numerical vectors in R

rv <- 11
ra <- 21

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

Output

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

Example 3: Comparing two string values

Diagram of comparing two string values using inequality(!=) operator

a <- "volvo"
b <- "bmw"
output <- a != b
cat(a, "!=", b, " is ", output, "\n")

a <- "audi"
b <- "audi"
output <- a != b
cat(a, "!=", b, " is ", output, "\n")

Output

volvo != bmw is TRUE
audi != audi is FALSE

Example 4: Combining equal to and not equal to operators

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

Output

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

Example 5: Conditional statements

x <- 19
y <- 21

if (x != y) {
  cat("Both are different", "\n")
}

Output

Both are different

Example 6: Subsetting Data

vec <- c(1, 2, 3, 4, 5)

subset_vec <- vec[vec != 3]

print(subset_vec)

Output

[1] 1  2  4  5

That’s all!

Leave a Comment