2
votes

I'm trying to calculate the majority value in a categorical raster data set in R, for example using land cover data. This would be similar to the focal statistics tool in ArcGIS using the majority statistic. I am able to calculate the majority land cover type using a rectangular moving window and the modal function:

library(raster)

# create data
r <- raster(nrows = 120, ncol = 120, xmn=0)
r[] <- sample(3, ncell(r), replace=TRUE)

a<-focal(r, w=matrix(1,3,3), fun=modal)    # 3x3 moving window
plot(a)

However, when I apply a focal weight to define my circular moving window, the output values appear to be treated as continuous numbers and not discrete values, even if I convert the raster to a factor:

#convert to a factor factor
r.f<-as.factor(r)
#set up window
fw <- focalWeight(r.f, 4.5, type='circle')
#apply focal fxn
r.f.focal<-focal(r.f, w=fw, fun=modal, na.rm=TRUE) 

It appears zeros might be added into the analysis and that is creating the problem. Can anyone steer me in the right direction?

1
Your rasters crs is currently in "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0". If you reduce d in focalWeight to something like "0.001" the result looks kind of okay.Philipp Gärtner
Thanks @PhilippGärtner. I did not pay attention to the crs - it was just what I worked up for a reproducible example. I still have the problem when I perform the focal function on my projected land cover data.Tim Assal

1 Answers

3
votes

I think it will be fixed if d (which is now 4.5) is an integer. Your defined radius should be based on cell counts (1,2,3,...,n). However, still, the output will be in floating format as each xij in the kernel is a floating point with sum of 1. To achieve an integer output there is also a third option.

library(raster)

set.seed(070319)
# create data
r <- raster(nrows = 120, ncol = 120, xmn=0)
r[] <- sample(3, ncell(r), replace=TRUE)
a<-focal(r, w=matrix(1,3,3), fun=modal)    # 3x3 moving window

par(mfrow=c(1,2)) 
plot(r)
plot(a)

enter image description here

#set up window
fw <- focalWeight(r, 4, type='circle')
#apply focal fxn
r.f.focal<-focal(r, w=fw, fun=modal, na.rm=TRUE)

par(mfrow=c(1,2)) 
plot(r)
plot(r.f.focal)

enter image description here

for integer output you can also do this:

#set up window
fw <- ceiling(focalWeight(r, 4, type='circle'))#for integer output
#apply focal fxn
r.f.focal<-focal(r, w=fw, fun=modal, na.rm=TRUE)

par(mfrow=c(1,2), oma=c(0,0,0,1)) 
plot(r)
plot(r.f.focal)

enter image description here