Home Â» How to Calculate Euclidean Distance in R (With Examples)

# How to Calculate Euclidean Distance in R (With Examples)

The Euclidean distance between two vectors, A and B, is calculated as:

Euclidean distance = âˆšÎ£(Ai-Bi)2

To calculate the Euclidean distance between two vectors in R, we can define the following function:

```euclidean function(a, b) sqrt(sum((a - b)^2))
```

We can then use this function to find the Euclidean distance between any two vectors:

```#define two vectors
a #calculate Euclidean distance between vectors
euclidean(a, b)

[1] 12.40967
```

The Euclidean distance between the two vectors turns out to beÂ 12.40967.

Note that we can also use this function to calculate the Euclidean distance between two columns of a data frame:

```#define data frame
df #calculate Euclidean distance between columns a and d
euclidean(df\$a, df\$d)

[1] 7.937254
```

Note that this function will produce a warning message if the two vectors are not of equal length:

```#define two vectors of unequal length
a #attempt to calculate Euclidean distance between vectors
euclidean(a, b)

[1] 23.93742
Warning message:
In a - b : longer object length is not a multiple of shorter object length```