If I have a raster like this:
library(raster)
r1 <- raster(ncol=10, nrow=10)
r1[] <- runif(ncell(r1))
r1[] = 1:ncell(r1)
x=c(-6)
y=c(-67)
I can extract values that correspond to this point as:
values = extract(r1, SpatialPoints(cbind(y,x),CRS("+init=EPSG:4326")))
However, this extracts the closest pixel to the coordinates of this point. I need to extract the 9 closest pixels (8 neighbors to the pixel extracted)to this point. Any idea?
You can use the adjacent
method for that.
Example data
library(raster)
r <- raster(ncol=10, nrow=10)
values(r) = 1:ncell(r)
xy <- cbind(-67, -6)
Solution
cells <- cellFromXY(r, xy)
adj <- adjacent(r, cells, 8, include=TRUE)
r[adj[,2]]
# [1] 54 43 53 63 45 55 65 44 64
This returns the value for the cells (because include=TRUE
) and their 8 neighbors