[R-sig-Geo] Create pixels neighborhood in a raster [solved]
Ege Rubak
rub@k @end|ng |rom m@th@@@u@dk
Wed Nov 11 00:14:55 CET 2020
A quick-and-dirty all spatstat solution:
library(spatstat)
eps <- 10
x <- pixellate(ants, eps = eps)
x[x>0] <- 1
y <- 0*x
s <- eps*c(-1,0,1)
for(i in s){
for(j in s){
y <- y + shift.im(x, vec = c(i,j))
}
}
z <- y
z[z>0] <- 1
plot(solist(x, y, z), main = "")
/Ege
On Tue, 2020-11-10 at 10:19 -0400, ASANTOS via R-sig-Geo wrote:
> Thanks Ben,
>
> Little things do matter, I changed cells<- xyFromCell(antscount,
> ants1)
> by cells <- unique(cellFromXY(antscount, geo.form)) and works!!
>
> Final solution:
>
> #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)
> # 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)
>
> # For 1 pixel neighborhood
> neigh1 <- matrix(1L, nrow=3, ncol=3); neigh1[2,2] <- 0L
> ants1<-which(values(antscount)> 0)
> cells <- unique(cellFromXY(antscount, geo.form))
> e1<-adjacent(antscount, cells, directions=neigh1, pairs=FALSE)
> ng_coords1 <- xyFromCell(antscount, e1)
> points(ng_coords1, col="red")
>
>
> #Rasterize for 1 pixel neighborhood
> ng_coords2<-rbind(ng_coords1,geo.form)
> antscount.9<- rasterize(ng_coords2, raster(ants.res), fun='count',
> background=0)
> values(antscount.9)[values(antscount.9) > 0] = 1
> plot(antscount.9)
>
More information about the R-sig-Geo
mailing list