R – Check if Two Objects are Equal

There are two ways to check if two Objects are equal or not in R programming.

  1. Using identical()
  2. Using all.equal() in conjunction with isTrue()

identical() – Check if two objects are exactly equal

identical() function takes two objects (along with some optional parameters) and checks for their exact equality.

identical() returns TRUE if both the objects are exactly equal and FALSE if they are not equal.

</>
Copy
> x = c(14, 25, 96, 75)
> y = c(14, 25, 96, 75)
> z = c(58, 5, 526, 75)
> 
> xy = identical(x,y)
> print(xy)
[1] TRUE
> 
> xz = identical(x,z)
> print(xz)
[1] FALSE

In the above code snippet, x and y are exactly equal while z is different from x or y.

identical(x,y) returns TRUE as the objects x and y are equal or exactly identical.

identical(x,z) returns FALSE as the objects x and z are not identical.

isTrue(all.equal()) – Check if Two Objects are Equal

all.equal() returns TRUE if the two objects are equal or the Mean relative difference between the two objects if the objects are not equal.

</>
Copy
> x = c(14, 25, 96, 75)
> y = c(14, 54, 96, 75)
> 
> xy = all.equal(x,y)
> print(xy)
[1] "Mean relative difference: 1.16"
> x = c(14, 25, 96, 75)
> y = c(14, 25, 96, 75)
> 
> xy = all.equal(x,y)
> print(xy)
[1] TRUE

And isTrue() checks if all.equal() returns TRUE or not.

</>
Copy
> x = c(14, 25, 96, 75)
> y = c(14, 25, 96, 75)
> z = c(58, 5, 526, 75)
> xy = isTRUE(all.equal(x,y))
> print(xy)
[1] TRUE
> xz = isTRUE(all.equal(x,z))
> print(xz)
[1] FALSE

Conclusion

In this R Tutorial, we learned how to check if two objects are equal or not with the help of examples.