[R] enty-wise closest element

Jason Smith devjason at gmail.com
Mon Jan 18 14:48:09 CET 2010


Here is one approach if I understand your requirements correctly.

ind1<-c(1,4,10)
ind2<-c(3,5,11)
m <- expand.grid(ind2=ind2,ind1=ind1)
m$diff <- (m$ind2 - m$ind1)
f <- function(x) {
	min_idx <- which.min(x$diff[x$diff > 0 & x$diff < x$ind2])
	list(c(elem=unique(x$ind2),min.value=x$ind1[min_idx],min.index=min_idx))
}
by(m, factor(m$ind2), f)


This yields the output:
     elem min.value min.index 
        3         1         1 
------------------------------------------------------------ 
     elem min.value min.index 
        5         4         2 
------------------------------------------------------------ 
     elem min.value min.index 
       11        10         3



More information about the R-help mailing list