Gomal Amin
Gomal Amin

Reputation: 31

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. I am new to R.

Upvotes: 3

Views: 988

Answers (1)

DJack
DJack

Reputation: 4940

Here is a workflow to compute the mean of a raster in 3x3 zones centered at defined lat/lon coordinates.

Rasterize the points and dilate the resulting raster to create the 3x3 zones

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

Compute the mean of r values in each zone

# 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

Sample data

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

Upvotes: 2

Related Questions