A Closer Look at the R Function identical()

rtip
Author

Steven P. Sanderson II, MPH

Published

July 11, 2023

Introduction

In the realm of programming, R is a widely-used language for statistical computing and data analysis. Within R, there exists a powerful function called identical() that allows programmers to compare objects for exact equality. In this blog post, we will delve into the syntax and usage of the identical() function, providing clear explanations and practical examples along the way.

Syntax of identical()

The identical() function in R has the following simple syntax:

identical(x, y)

Here, x and y are the objects that we want to compare. The function returns a logical value of either TRUE or FALSE, indicating whether x and y are exactly identical.

Examples

  1. Comparing Numeric Values: Let’s start with a simple example comparing two numeric values:
a <- 5
b <- 5
identical(a, b)
[1] TRUE

In this case, the identical() function will return TRUE since both a and b have the same numeric value of 5.

  1. Comparing Character Strings: Now, let’s consider an example with character strings:
name1 <- "John"
name2 <- "John"
identical(name1, name2)
[1] TRUE

In this case, the identical() function will return TRUE as both name1 and name2 contain the same string “John”.

  1. Comparing Vectors: The identical() function can also compare vectors. Let’s see an example:
vec1 <- c(1, 2, 3)
vec2 <- c(1, 2, 3)
identical(vec1, vec2)
[1] TRUE

Here, the identical() function will return TRUE since vec1 and vec2 have the same values in the same order.

  1. Comparing Data Frames: Data frames are a fundamental data structure in R. Let’s compare two data frames using identical():
df1 <- data.frame(a = 1:3, b = c("A", "B", "C"))
df2 <- data.frame(a = 1:3, b = c("A", "B", "C"))
identical(df1, df2)
[1] TRUE

In this case, the identical() function will return TRUE as both df1 and df2 have the same column names, column types, and corresponding values.

  1. Handling Inexact Equality: The identical() function is particularly useful when we want to ensure that two objects are precisely the same. However, it does not handle cases where inexact equality is expected. For example:
x <- sqrt(2) * sqrt(2)
y <- 2
identical(x, y)
[1] FALSE

Surprisingly, the identical() function will return FALSE in this case. This occurs because sqrt(2) introduces a slight rounding error, resulting in x and y being slightly different despite representing the same mathematical value.

Conclusion

In this blog post, we explored the syntax and various use cases of the identical() function in R. By leveraging this function, you can determine whether two objects are exactly identical, whether they are numbers, strings, vectors, or even complex data structures like data frames. Remember that identical() is designed for exact equality, so if you require inexact comparisons, you may need to explore alternative approaches. Happy coding with R!