Andras Farkas
2013-Jun-18 12:34 UTC
[R] find closest value in a vector based on another vector values
Dear All, would you please provide your thoughts on the following: let us say I have: a <-c(1,5,8,15,32,69) b <-c(8.5,33) and I would like to extract from "a" the two values that are closest to the values in "b", where the length of this vectors may change but b will allways be shorter than "a". So at the end based on this example I should have the result "f" as f <-c(8,32) appreciate the help, Andras
Jorge I Velez
2013-Jun-18 12:43 UTC
[R] find closest value in a vector based on another vector values
Dear Andras, Try> a[findInterval(b, a)][1] 8 32 HTH, Jorge.- On Tue, Jun 18, 2013 at 10:34 PM, Andras Farkas <motyocska@yahoo.com> wrote:> Dear All, > > would you please provide your thoughts on the following: > let us say I have: > > a <-c(1,5,8,15,32,69) > b <-c(8.5,33) > > and I would like to extract from "a" the two values that are closest to > the values in "b", where the length of this vectors may change but b will > allways be shorter than "a". So at the end based on this example I should > have the result "f" as > > f <-c(8,32) > > appreciate the help, > > Andras > > ______________________________________________ > R-help@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. >[[alternative HTML version deleted]]
arun
2013-Jun-18 13:12 UTC
[R] find closest value in a vector based on another vector values
Hi, Perhaps this works: a[sapply(b,function(x) which.min(abs(x-a)))] #[1]? 8 32 A.K. ----- Original Message ----- From: Andras Farkas <motyocska at yahoo.com> To: r-help at r-project.org Cc: Sent: Tuesday, June 18, 2013 8:34 AM Subject: [R] find closest value in a vector based on another vector values Dear All, would you please provide your thoughts on the following: let us say I have: a <-c(1,5,8,15,32,69) b <-c(8.5,33) and I would like to extract from "a" the two values that are closest to the values in "b", where the length of this vectors may change but b will allways be shorter than "a". So at the end based on this example I should have the result "f" as f <-c(8,32) appreciate the help, Andras ______________________________________________ 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.