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). thanks!
How about this: x <- c(1, 6, 12, 28, 33) which.min(abs(x - 14)) I hope it helps. Best, Dimitris On 2/8/2012 1:56 PM, Martin Batholdy wrote:> 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). > > > 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. >-- Dimitris Rizopoulos Assistant Professor Department of Biostatistics Erasmus University Medical Center Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands Tel: +31/(0)10/7043478 Fax: +31/(0)10/7043014 Web: http://www.erasmusmc.nl/biostatistiek/
Hi> > Hi, > > Is there a way to check which value in a vector is nearest to a givenvalue?> > 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 nearestto 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 guidehttp://www.R-project.org/posting-guide.html> and provide commented, minimal, self-contained, reproducible code.
great, thanks! On 08.02.2012, at 14:00, Dimitris Rizopoulos wrote:> How about this: > > x <- c(1, 6, 12, 28, 33) > > which.min(abs(x - 14)) > > > I hope it helps. > > Best, > Dimitris > > > On 2/8/2012 1:56 PM, Martin Batholdy wrote: >> 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). >> >> >> 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. >> > > -- > Dimitris Rizopoulos > Assistant Professor > Department of Biostatistics > Erasmus University Medical Center > > Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands > Tel: +31/(0)10/7043478 > Fax: +31/(0)10/7043014 > Web: http://www.erasmusmc.nl/biostatistiek/