```
<- 5
a <- 5
b identical(a, b)
```

`[1] TRUE`

rtip

Author

Steven P. Sanderson II, MPH

Published

July 11, 2023

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.

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.

- Comparing Numeric Values: Let’s start with a simple example comparing two numeric values:

In this case, the `identical()`

function will return `TRUE`

since both `a`

and `b`

have the same numeric value of 5.

- Comparing Character Strings: Now, let’s consider an example with character strings:

In this case, the `identical()`

function will return `TRUE`

as both `name1`

and `name2`

contain the same string “John”.

- Comparing Vectors: The
`identical()`

function can also compare vectors. Let’s see an example:

Here, the `identical()`

function will return `TRUE`

since `vec1`

and `vec2`

have the same values in the same order.

- 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.

- 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:

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.

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!