如何在R中使用3x3窗口对光栅执行焦点操作(平均值)?我有lat / long值。

时间:2018-05-17 18:42:03

标签: r r-raster operation

我有光栅和纬度/长值,我想使用3x3窗口/内核对这些点执行焦点操作。我是R.的新手。

1 个答案:

答案 0 :(得分:1)

以下是计算以定义的纬度/经度坐标为中心的3x3区域中栅格平均值的工作流程。

栅格化点并扩展生成的栅格以创建3x3区域

library(mmand)
library(raster)

# rasterize points based on lat/lon coordinates
z <- rasterize(pts[,2:3], r, field = pts$id)

# dilate z using a 3x3 box
kern <- shapeKernel(c(3,3), type="box")
z[,] <- dilate(as.matrix(z), kern)

plot(z)

enter image description here

计算每个区域中r值的平均值

# raster::zonal function (zonal statistics) is used 
# -Inf correspond to NA values and should not be taken into account
# you can change "mean" by the stats you would like to compute
zonal(r, z, fun = "mean")

#     zone     mean
#[1,] -Inf 5.563607
#[2,]    1 5.000000
#[3,]    2 3.444444
#[4,]    3 5.222222

样本数据

library(raster)
set.seed(1)
# Generate raster of random values
r <- raster(crs = CRS("+proj=robin +datum=WGS84"), resolution = c(10, 10))
r[] <- round(runif(ncell(r), 1, 10))
# Generate data frame with lat/lon coordinates
pts <- data.frame(id = 1:3, lon = c(-100, 40, 120), lat = c(-45, 5, 35))

plot(r)
points(pts$lon, pts$lat, pch = 20, cex = 2)

enter image description here