You can use the following basic syntax to find the closest value between elements of two vectors in R:
#define cut points
cuts #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
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 #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.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Calculate the Mean by Group in R
How to Average Across Columns in R
How to Sum Specific Columns in R