How to match values of one vector tp values of another vector with tolerance?

I have a vector

c(0.399999999999977, 0.000399999999899592, 0, 0, 1.00239999999985)

I expect the values to be equal to integers: 0, 1, 2, 3, 4. However, this equality is subject to a tolerance of let’s say 0.1. I would like to receive a new vector of matched integer values. In cases where a values of input vector does not correspond to the values it is matched against I would like to get an NA (e.g. 0.3999 does not correspond to to the 0, 1, 2, 3, 4 integers with tolerance of < 0.1)

c(NA, 0, 0, 0, 1)

>Solution :

You can try something like this:

vec <- c(0.399999999999977, 0.000399999999899592, 0, 0, 1.00239999999985)
ifelse( abs(vec - round(vec)) <= 0.1, round(vec), NA)

Leave a Reply