Search code examples
rrasterr-raster

raster in R: Create pixels in a target surronding neighborhood


In my example:

#Packages
library(spatstat)
library(raster)

#Selection of ants data set
data(ants)
geo.form<-cbind(x=ants$x,y=ants$y)

#Definition of raster resolution - 10 units
ants.w<-as.owin(ants)
ext <- as(extent(c(ants.w$xrange,ants.w$yrange)), "SpatialPolygons")
ants.res<-rasterToPoints(raster(ext, resolution = 10), spatial = TRUE)
coordinates(ants.res) <- ~ x + y
# coerce to SpatialPixelsDataFrame
gridded(ants.res) <- TRUE

#Rasterize
antscount<- rasterize(geo.form, raster(ants.res), fun='count', background=0)
values(antscount)[values(antscount) > 0] = 1

#Vizualize
plot(antscount)

ex1

Now, I'd like to find any way to create 1 (total 9 pixels) and 2 pixels (total 25 pixels) surrounding the neigourhood of each pixel (ant) in the plot image. I need that's this new create pixels has 1 as value too.

The selection of neighborhood pixels sounds easy, something like:

# For 1 pixel neighborhood
neigh1 <- matrix(1L, nrow=3, ncol=3); neigh1[2,2] <- 0L
ants1<-which(values(antscount)> 0)
cells<- xyFromCell(antscount, ants1)
e1<-adjacent(antscount, cells, directions=neigh1, pairs=FALSE)
ng_coords1 <- xyFromCell(antscount, e1)

# For 2 pixel neighborhood
neigh2 <- matrix(1L, nrow=5, ncol=5); neigh1[3,3] <- 0L
e2<-adjacent(antscount, cells , directions=neigh2, pairs=FALSE)
ng_coords5 <- xyFromCell(antscount, e2)

The problem is my ng_coords1/ng_coords5 coordinates is wrong and just only in the top of the antscount raster, despite xyFromCell(antscount, ants1) condition. My goal is a new ant presence raster with 8 and 24 pixels surrounding the neigourhood of each pixel (ant) in the original antscount raster. Please, any ideas?


Solution

  • This is best done with focal

    Example data (note the simpler code)

    library(spatstat)
    library(raster)
    data(ants)
    geo.form <- cbind(x=ants$x, y=ants$y)
    ants.w <- as.owin(ants)
    ext <- extent(c(ants.w$xrange, ants.w$yrange))
    r <- raster(ext, resolution=10)
    antscount<- rasterize(geo.form, r, field=1, background=0)
    

    Solution

    # direct neighbors
    x <- focal(antscount, w=matrix(1, ncol=3, nrow=3), fun=max, pad=TRUE, padValue=0)
    # 2 cell neighborhood    
    y <- focal(antscount, w=matrix(1, ncol=5, nrow=5), fun=max, pad=TRUE, padValue=0)