Hi, everybody,

I am trying to calculate the minimum of differences between all observations by group.

For example, I have this data,
obs var group
1 1 1
2 3 1
3 6 1
4 2 2
5 1 2
6 2 2
7 3 2
and I want,
obs var group Want
1 1 1 2
2 3 1 2
3 6 1 3
4 2 2 0
5 1 2 1
6 2 2 0
7 3 2 1
For observation 1, it belongs to group 1. So the difference between obs 1 and obs 2 is 2, between obs 1 and obs 3 is 5. So the min diff for obs 1 is 2. I am thinking of using a loop, the logic is within each group, for observation i, calculate the diff between i and all but i, and return the min of the diffs. And move to the next i until it is the last observation in that group. But I am not sure how to put it in Stata code. Please help, thank you so much!

Kevin