I have a list of numbers I need to group by similarity (differences being 1 between each). For example, in a list of [198, 202, 207, 218, 219, 220], 190 would be put into a list, 202 would be put into another list, 207, into a list, and 218 219 220 into another list.
Although some clustering algorithms will do this, there's a simpler way: sort the input, create a binary vector indicating whether each neighboring pair is dissimilar or not, prefix that with a
The last line isn't really needed in
The groups are 1 --> (198), 2 --> (202), 3 --> (207), 4 --> (218, 219, 220, 220).
If you don't want duplicates to appear, clean the input first using
On my system this code groups an input of four million integers in one second. Most of that is spent in the sorting step.
The same algorithm is readily applied on other platforms such as Stata, Matlab, Mathematica, Python, etc.
This can be accomplished with hierarchical clustering using the