# [R] find closest value in a vector based on another vector values

Bert Gunter gunter.berton at gene.com
Tue Jun 18 16:07:04 CEST 2013

```Jorge: No.

> a <-c(1,5,8,15,32,33.5,69)
> b <-c(8.5,33)
> a[findInterval(b, a)]
[1]  8 32  ##should be  8   33.5

I believe it has to be done explicitly by finding all the differences
and choosing those n with minimum values, depending on what n you
want.

Note that the problem is incompletely specified. What if the same
value of a is closest to several values of b? -- do you want all the
values you choose to be different or not, in which case they may not
be minimum?

a <- c(1, 8, 9)
b <- c(2,3)

Then what are the 2 closest values of a to b?

-- Bert

On Tue, Jun 18, 2013 at 5:43 AM, Jorge I Velez <jorgeivanvelez at gmail.com> wrote:
> Dear Andras,
>
> Try
>
>> a[findInterval(b, a)]
> [1]  8 32
>
> HTH,
> Jorge.-
>
>
> On Tue, Jun 18, 2013 at 10:34 PM, Andras Farkas <motyocska at yahoo.com> wrote:
>
>> Dear All,
>>
>> 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
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.

--

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website: