[英]How to perform focal operation (mean) on raster using 3x3 window in R? I have lat/long values
I have raster and lat/long values, I want to perform focal operation on these points using 3x3 window/kernel.我有栅格和纬度/经度值,我想使用 3x3 窗口/内核对这些点执行焦点操作。 I am new to R.
我是 R 的新手。
Here is a workflow to compute the mean of a raster in 3x3 zones centered at defined lat/lon coordinates.这是一个工作流程,用于计算以定义的纬度/经度坐标为中心的 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)
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.