I have a matrix that is populated with discrete elements, and I need to cluster them (using R) into intact groups. So, for example, take this matrix:
[A B B C A] [A A B A A] [A B B C C] [A A A A A]
There would be two separate clusters for A, two separate clusters for C, and one cluster for B.
The output I'm looking for would ideally assign a unique ID to each cluster, something like this:
[1 2 2 3 4] [1 1 2 4 4] [1 2 2 5 5] [1 1 1 1 1]
Right now I wrote a code that does this recursively by just iteratively checking nearest neighbor, but it quickly overflows when the matrix gets large (i.e., 100x100).
Is there a built in function in R that can do this? I looked into raster and image processing, but no luck. I'm convinced it must be out there.