3
votes

I´m trying to calculate moving majority values over an raster in R. The focal function in the raster package just provides mean, min and max. I have a raster with 3 values (1, 2 and 3) and I would like to have the value most abundant in a 3x3 window set in the center.

How can I do that most efficient in R? Thank you!

library(raster)

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

2 Answers

4
votes

You could do:

f <- function(x){
 tab <- table(x)
 # I am using the first value here, maybe you want to use the mean, 
 # if 2 or more values occur equally often.
 names(tab)[which.max(tab)][1]
}

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

r <- focal(r, w=3, f)
4
votes

Maybe I am little bit late, but it could be useful for futurs readers:

Now in R you can find focal function for majority (mode), so:

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)

(NOTE: make attention whenusing NA values - it worth better to convert them to integer number)

result:

result from focal analysis