If you understand correctly, you want to calculate the smallest value between a member of a vector and its neighbors.
First we sort the data.
x= sort(c(1,23,4,15,8,17,21))
Then we calculate the difference with the left neighbor (which is missing for item 1) and the difference with the right neighbor (which is missing for item 2)
diffs <- cbind(c(NA,diff(x)),c(diff(x),NA))
So, now we have a difference with left and right for each element, now all that remains is to find the smallest:
res <- apply(diffs,MARGIN=1, min, na.rm=T)
Note that although this solution contains an explanation, the other solutions provided (in particular the pmin approach by @Julius) are probably faster when performance is a problem.
source share