如何仅计算 getValuesFocal 中的一部分单元格?

How to compute only a subset of cells in getValuesFocal?

我想计算栅格上的焦点 windows,但我只想计算某些像元(下图中的黑色像元)的焦点 window。我知道,我可以计算所有单元格的焦点 window,然后过滤输出(参见下面的示例)。但是为了减少计算时间,有没有办法屏蔽计算的像元(例如使用第二个栅格)?

示例:

library(raster)
r <- raster(ncol=20, nrow=20, xmn=0, xmx=20, ymn=0, ymx=20)
r[]<-c(1:400)
r.compute.focal<-raster(ncol=20, nrow=20, xmn=0, xmx=20, ymn=0, ymx=20) # raster for which focal window shall be calculated
r.compute.focal[sample(r[],5)]<-1
plot(r)
plot(r.compute.focal,add=T,col="black",legend=F)

#focal computation
normal.output<-getValuesFocal(r,ngb=5) 

###filtered (desired) output####
normal.output[which(!is.na(r.compute.focal[])),]

您可以为此使用 adjacent 函数:

# example data
library(raster)
r <- raster(ncol=20, nrow=20, xmn=0, xmx=20, ymn=0, ymx=20)
r[] <- 1:400
set.seed(0)
cells <- sample(r[], 5)

# create 5 x 5 neighborhood matrix for use with adjacent
m <- matrix(1, 5, 5)
# central cell in matrix
m[3,3] <- 0
# find adjacent cells
a <- adjacent(r, cells, m)
# add the focal cells
a <- rbind(a, cbind(cells, cells))

#extract values
b <- extract(r, a[,2])

x <- cbind(a, value=b)

# first column is the focal cell, third column the values
head(x)
#     from  to value
#[1,]  359 317   317
#[2,]  359 337   337
#[3,]  359 357   357
#[4,]  359 377   377
#[5,]  359 397   397
#[6,]  359 318   318

tapply(x[,3], x[,1], mean)
#  106   149   228   359   360 
# 106.0 149.0 228.0 358.5 359.0