Skip to content
Prev 329917 / 398500 Next

Subtracting elements of a vector from each other stepwise

arun <smartpink111 <at> yahoo.com> writes:
x3<-x2[which.min(abs(x1-x2))];c(x1,x3)})
It's a little inefficient (because it constructs
the distances in both directions), but how about:

x = c(17,19,23,29)
d <- abs(outer(x,x,"-"))
diag(d) <- NA
d[lower.tri(d)] <- NA
which(d==min(d,na.rm=TRUE),arr.ind=TRUE)


?
[snip]