# Focal, result is a raster as well.
## Use s2 NIR band as an example
fname <- 'your_class_note_folder/S2A_MSIL2A_20201014T154231_N0214_R011_T19TBG_20201014T200156_20m.tif'
nir_band <- rast(fname, lyrs = 9)
# weight matrix could not the square,
# but ncol and nrow must be uneven numbers
## Reproduce Sobel edge detection
wx <- matrix(c(-1, -2, -1, 0, 0, 0, 1, 2, 1), nrow = 3, byrow = TRUE)
wy <- matrix(c(1, 0, -1, 2, 0, -2, 1, 0, -1), nrow = 3, byrow = TRUE)
# Apply focal calculation
nir_x <- focal(nir_band, w = wx)
nir_y <- focal(nir_band, w = wy)
# Simply band calculation
nir_edge <- sqrt(nir_x^2 + nir_y^2)
writeRaster(nir_edge, 'your_class_note_folder/edge.tif')