[R] find closest match between two vectors

Phil Spector spector at stat.berkeley.edu
Thu Dec 16 19:13:51 CET 2010


Jannis -
    One approach is as follows:

> one = c(1,2,6)
> two = c(0,0.5,1,2,3,8)
> findit = function(x,vec){
+   y = vec - x
+   y[y<=0] = NA
+   if(all(is.na(y)))NA else which.min(y)
+ }
> > sapply(two,findit,one)
[1]  1  1  1  2  3 NA

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu



On Thu, 16 Dec 2010, Jannis wrote:

> Dear list,
>
>
> I hope I can define my problem in an understandable manner. I seek some 
> funktion that finds me the index of the value in a vector 1 that is the least 
> bigger then the value in another vector 2. And this for all values in vector 
> 2.
>
> For example:
>
>
> vector 1 : c(1,2,6)
>
> vector 2 : c(0,0.5,1,2,3,8)
>
>
> the result should be as long as vector 2 and give the indices of the 
> corresponding elements in vector 1:
>
> result: c(1,1,2,3,3,NA)
>
> Any suggestions how to do this without doing complicated loops through vector 
> 2?
>
>
> Cheers
> Jannis
>
> ______________________________________________
> 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