I have a raster made of values 1, 2, and NA
. I am wanting to use the focal function with a 3x3 window to reassign cells with a new value. The attached image shows an example of the dataset and 3x3 window. I want the new assigned value to be the count of neighboring cells in the window that do not equal the center cell, excluding NA
values. So, essentially, if the center cell = 1, I want it to count how many neighboring cells = 2, and vice versa. In this attached photo, the value would be 4, as the center value = 1, and there are four neighboring cells = 2.
I am using the code below, which works with the basic functions (mean
, min
, max
, etc.) but does not have any function to do what I am looking for, as far as I can find.
focal.statistic <- focal(raster, window=window, function=function)
I need to create a new function doing what I described above, that can then be called with "function=" code. I have been thinking about if, then statements but am struggling to write this function...
This is similar to this post from many years ago, but I still cannot figure it out.