To calculate Hamming distance in R, you can use the sum() function along with the inequality operator !=. Hamming distance measures the number of positions at which the corresponding elements of two vectors are different.

In this article, we will explore how to calculate Hamming distance in R with examples.

Method: Use sum() Function and Inequality Operator

The sum() function in R, combined with the inequality operator !=, can be used to calculate the Hamming distance between two vectors. Here’s the syntax:

sum(vector1 != vector2)

The following example shows how to calculate Hamming distance in R.

Calculate Hamming Distance Between Two Vectors

Let’s see how we can calculate Hamming distance between two vectors:

# Define binary vectors
x <- c(0, 1, 1, 0, 1, 0)
y <- c(0, 0, 1, 1, 1, 0)

# Calculate Hamming distance
hamming_distance <- sum(x != y)

# Display Hamming distance
print(hamming_distance)

Output: 👇️

[1] 2

In this example, the sum() function calculates the Hamming distance between the vectors x and y.

The output shows the number of positions at which the corresponding elements of the two vectors are different.