Reputation: 1121
Imagine a raster:
library(raster)
r = raster(nrow=3, ncol=3)
r[] = c(1,NA,1,1,NA,NA,1,NA,1)
plot(r)
How could I reclassify contiguous patches (not on the diagonal) in ascending order? In this example, the three-cell patch on the left hand side of the plot is reclassified as '1', the top right patch as '2' and the bottom right patch as '3'.
The actual reclassified values (and the order they appear across the raster) is unimportant. What is important is that each 'island' of connected (or individual cells) is represented by a new, unique, number.
Upvotes: 0
Views: 136
Reputation: 47706
You can use raster::clump
with argument directions=4
to not connect on the diagonal (with this example data it does not matter, as there no such case).
library(raster)
r <- raster(nrow=3, ncol=3, xmx=0)
values(r) <- c(1,NA,1,1,NA,NA,1,NA,1)
x <- clump(r, directions=4)
plot(x)
Note that I added xmx=0
to avoid a global raster. Without that, there is only one patch as longitudes -180 and 180 are the same and thus the cells of the first and last columns are, in fact, connected.
Upvotes: 1