[R] check for nearest value in a vector

Petr PIKAL petr.pikal at precheza.cz
Wed Feb 8 14:05:32 CET 2012


Hi
> 
> Hi,
> 
> Is there a way to check which value in a vector is nearest to a given 
value?
> 
> so for example I have vector x:
> 
> x <- c(1, 6, 12, 28, 33)
> 
> and I would like to get the position of the element of x that is nearest 
to 14
> (in this case the third element).

Easy. Smallest difference between value and target.

which.min(abs(x-14))
[1] 3
which.min((x-14)^2)
[1] 3

Regards
Petr


> 
> 
> thanks!
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list