I have raster images and I want to apply a function that will give a value based of adjacent cells values. In a 3x3 window centered in that cell I want to give a cell a value between 0 and 8/8(=1) depending on how many cells (from the other 8 cells in that window). For example if 5 other cells have different values than the center cell, the function must assign 5/8 in that cell. I am trying to do that using focal from raster package.
Firstly, I wrote a function that process a 3x3 window:
mix<-function(a, na.rm=TRUE){
v==0
b=a[2:2]
if (!(a[1:1]=b)) {
if (!is.na(a[1:1])){v=v+1}else v=v
}
if(!(a[1:2]=b)){if (!is.na(a[1:2])){v=v+1}else v=v}
if(!(a[1:3]=b)){if (!is.na(a[1:3])){v=v+1}else v=v}
if(!(a[2:1]=b)){if (!is.na(a[2:1])){v=v+1}else v=v}
if(!(a[2:3]=b)){if (!is.na(a[2:3])){v=v+1}else v=v}
if(!(a[3:1]=b)){if (!is.na(a[3:1])){v=v+1}else v=v}
if(!(a[3:2]=b)){if (!is.na(a[3:2])){v=v+1}else v=v}
if(!(a[3:1]=b)){if (!is.na(a[3:3])){v=v+1}else v=v}
v
}
Then I tried to use focal like this:
r2<-focal(r, w=matrix(1,3,3), fun=mix(w))
but: "Error in mix(w) : object 'v' not found"
I think that I am missing something and maybe the method is not correct.
Any help will be appreciated.
Thanks In advance John