What is the closest value in vector?

The closest value in a vector is the one which has the shortest distance between it and the other elements of the vector. This distance is typically measured using the Euclidean distance, which is the straight line distance between two points in a vector space. The closest value can be found by comparing the distances between all the elements of the vector and finding the one with the shortest distance.


You can use the following basic syntax to find the closest value between elements of two vectors in R:

#define cut points
cuts <- c(-Inf, vector2[-1]-diff(vector2)/2, Inf)

#for each value in vector1, find closest value in vector2
cut(vector1, breaks=cuts, labels=vector2)

The following example shows how to use this syntax in practice.

Example: Find Closest Value in Vector in R

Suppose we have the following two vectors in R:

#define vectors
vector1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
vector2 <- c(3, 5, 8, 11)

Now suppose that for each value in the first vector, we would like to find the closest value in the second vector.

We can use the following syntax to do so:

#define cut points
cuts <- c(-Inf, vector2[-1]-diff(vector2)/2, Inf)

#for each value in vector1, find closest value in vector2
cut(vector1, breaks=cuts, labels=vector2)

 [1] 3  3  3  3  5  5  8  8  8  11

Here’s how to interpret the output:

  • For the first value in vector1 (1), the closest value in vector2 is 3.
  • For the second value in vector1 (2), the closest value in vector2 is 3.
  • For the third value in vector1 (3), the closest value in vector2 is 3.
  • For the fourth value in vector1 (4), the closest value in vector2 is 3.
  • For the fifth value in vector1 (5), the closest value in vector2 is 5.

And so on.

Note: This method assumes that the values in the second vector are strictly increasing. If they aren’t already, you may need to first sort the second vector.

The following tutorials explain how to perform other common tasks in R:

x