I want to process my data (classified single-band raster) according to a specific idea. Pixels that do have less than 2 neighbors of the same class (eg. with the value 1) shall be removed and classified as NA. It seems a lot trickier than I expected this part to be. I imagined it might be similar to the GameOfLife (Cellular Automata). But I could not implement it with a similar methodology of GameOfLife (I tried it like in the examples of the R package 'focal'). I also tried to use focal in general, which seems not to work good as well, as there are restrictions to the function that can be used (several number as input, one number as output) and I also did not manage to think through how to fix the problem with the outer cells of the moving window. Now I tried to use the function adjacend in which I can get the cell-index of 4 or 8 neighbor-cells. This makes it very inefficient though and can not stop thinking that there must be a better alternative.
Has anyone a good idea how I could tackle the problem to change the value of a cell of a specific class in my raster to NA, if it has less then 2 cells with the same classification that it is connected to?
I also tried to work with the mean function in the focal-package, but that approach is way too coarse for my needs.
I want to get rid of the single pixels of only one class, lets say class one which is shown in red in my plot. I don't want the function to delete any values of other classes though, like class 0 (green) or class 2 (blue).
After trying several methods (game of life, adjacent of the raster package, focal of the raster package, clump of the raster package) I figured out that the clump command was the easiest to implement. I came quite far with a function that could be called in focal (from @Spacedman), but it did not work without problems. Clump seems to be an easy way and the calculation is fast. If you want to perform the command only on special classes, like me, you have to define them as a band first and you can later use raster calculations to get the result you want to achieve.
The difference might look small, but it's important for my computation.