我需要创建一个函数:
- 在包含最小值的光栅中搜索像素
- 在第一次迭代中,为等于栅格单元大小(2.5km)的半径内的所有像素分配值1(包括值最小的像素)
- 在第二次迭代中,选择具有下一个最小值的像素(不包括在步骤ii中选择的像素),并搜索相同的半径,并为其指定值2。这种情况一直持续到没有剩余像素为止(如果半径内没有可用像素,则选择停止)
听起来很复杂,但希望有可能?以下是我的光栅示例:
xy <- matrix(pnorm(900,40, 200),30,30)image(xy)
rast <- raster(xy)
# Give it lat/lon coords for 36-37°E, 3-2°S
extent(rast) <- c(36,37,-3,-2)
也许您可以使用以下内容。我不会在很大的光栅上尝试这个(这需要很长时间)。但以你为例,如果你不必做太多次,它也很好用。
library(raster)
set.seed(0)
xy <- matrix(rnorm(900, 40, 200),30 , 30)
r <- raster(xy)
extent(r) <- c(36,37,-3,-2)
rorig <- r
x <- r
i <- 1
while (TRUE) {
# cell with min value
m <- which.min(x)
## are there, and do you care about ties? Do they have the same level?
## If not, you can do
## m[1]
## or sample
## m <- sample(m, 1)
# focal and four adjacent cells
a <- adjacent(r, m, 4, FALSE, include=TRUE)
# exclude those that have already been affected
w <- which(!is.na(x[a]))
a <- a[w]
# assign the value
r[a] <- i
# set assigned cells to NA
x[a] <- NA
# stop when done
if (is.na(maxValue(x))) break
i <- i + 1
}
plot(r)
plot(rorig, r)