Given is an initial raster
r <- raster(ncol=10, nrow=10)
values(r) <- c(1,1,2,1,1,1,1,1,3,3, 1,1,1,1,1,1,1,3,3,3, 1,1,1,1,1,3,3,3,3,3, 1,1,1,2,2,3,3,3,3,3, 1,2,2,2,2,3,3,2,3,3, 3,2,2,2,2,3,3,3,3,1, 2,2,2,2,2,2,3,2,3,1, 2,2,2,3,3,3,3,3,3,3, 2,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,1)
plot(r)
there are several "islands" within clumps. What I'm looking for is a way to add this isolated pixel to the dominant surrounding class. So that I'm receiving the following raster:
r1 <- raster(ncol=10, nrow=10)
values(r1) <- c(1,1,1,1,1,1,1,1,3,3, 1,1,1,1,1,1,1,3,3,3, 1,1,1,1,1,3,3,3,3,3, 1,1,1,2,2,3,3,3,3,3, 1,2,2,2,2,3,3,3,3,3, 2,2,2,2,2,3,3,3,3,3, 2,2,2,2,2,2,3,3,3,3, 2,2,2,3,3,3,3,3,3,3, 2,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3)
plot(r1)
isolated pixel were add to dominant surrounding class, but remained if at least one neighbouring cell had the same value.
How to achieve this result?
You can use focal
with a custom function argument. Something like the below.
f <- function(i) {
if (is.na(i[5])) return(NA)
s <- sum(i[5] == i, na.rm=TRUE)
if (s == 1) {
b <- table(i)
m <- max(b, na.rm=TRUE)
if (m > 1) {
b <- as.numeric( names(which.max(b)[1]) )
return(b)
}
}
i[5]
}
Your example data below, but note that I changed one value to make it match your plot (r[3,6]
), and that I set the extent to c(0,1,0,1)
to avoid having global lon/lat data -- that can be confusing because then the left and right-most cells are connected and you get a different result for one cell. You could also specify a planar CRS.
library(raster)
r <- raster(ncol=10, nrow=10, xmn=0, xmx=1, ymn=0, ymx=1)
values(r) <- c(1,1,2,1,1,1,1,1,3,3, 1,1,1,1,1,1,1,3,3,3, 1,1,1,1,1,2,3,3,3,3, 1,1,1,2,2,3,3,3,3,3, 1,2,2,2,2,3,3,2,3,3, 3,2,2,2,2,3,3,3,3,1, 2,2,2,2,2,2,3,2,3,1, 2,2,2,3,3,3,3,3,3,3, 2,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,1)
plot(r)
rr <- focal(r, matrix(1,3,3), f, pad=TRUE)
plot(rr)
This is different than what you show for the 2 gray cells in the lower right edge because what you show is not correct given the rule you specify. These cells both have a neighbor of the same value.