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

时间:2015-12-15 11:26:16

标签: r r-raster

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

示例:

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)

black cells indicate cells for which the focal window shall be computet

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用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