Extracting list of coordinates of all pixels in neighborhood of given pixel in R

I have a Raster layer. I want to get coordinates of all pixels in neighborhood (for example 7*7) of given pixel. Is there any function available to do this in R?

1 Answer

`raster::adjacent` does this, you need to call it successively to get wider margins

Consider one cell at index 1500

``````library(raster)
r <- setExtent(raster(volcano), extent(0, nrow(volcano), 0, ncol(volcano)))
plot(r)
points(xyFromCell(r, 1500))

adj1 <- raster::adjacent(r, 1500, directions = 8)
adj2 <- raster::adjacent(r, adj1[, "to"], directions = 8)
neighbours <- unique(c(adj1[, "to"], adj2[, "to"]))
adj3 <- raster::adjacent(r, neighbours, directions = 8)
neighbours <- unique(c(adj1[, "to"], adj2[, "to"], adj3[, "to"]))

points(xyFromCell(r, neighbours))
length(neighbours)
[1] 49
``````

• It worked well but in your code you set an extent to volcano raster. I don't find any need to set extent because setExtent function removed the projection of volcano raster. Commented Dec 10, 2018 at 13:05
• @RiteshPorwal, you kind of missed the point in the use of setExtent. It is a quite clever, for examples sake, making the coordinate space row/column based. Commented Dec 10, 2018 at 16:09
• That's right, it's just a reprex - I can't stand example rasters crushed into [0, 1, 0, 1] - I should have caveated that code by saying "just a dummy example, replace with your own raster". The extent has no bearing on the adjacent() function with respect to a cell number. Commented Dec 11, 2018 at 11:17