I am trying to take a polygon and add grid lines over top, then divide the polygon into many polygons based on the grids. I've accomplished this through st_make_grid() and raster::intersect().
The outcome is correct:
But I would like to later reference each cell (now individual polygons in a SpatialPolygonsDataFrame) with alphanumeric labels, in which the letter references the row the cell is in and the number references the column the cell is in. I can't find any way to do this via st_make_grid() or anything else.
library(spatialEco)
library(raster)
library(dplyr)
library(sp)
library(maptools)
library(sf)
library(rgdal)
library(rgeos)
#owin2Polygons is just for conversion
owin2Polygons <- function(x, id="1") {
stopifnot(is.owin(x))
x <- as.polygonal(x)
closering <- function(df) { df[c(seq(nrow(df)), 1), ] }
pieces <- lapply(x$bdry,
function(p) {
Polygon(coords=closering(cbind(p$x,p$y)),
hole=is.hole.xypolygon(p)) })
z <- Polygons(pieces, id)
return(z)
}
tess2SP <- function(x) {
stopifnot(is.tess(x))
y <- tiles(x)
nam <- names(y)
z <- list()
for(i in seq(y))
z[[i]] <- owin2Polygons(y[[i]], nam[i])
return(SpatialPolygons(z))
}
owin2SP <- function(x) {
stopifnot(is.owin(x))
y <- owin2Polygons(x)
z <- SpatialPolygons(list(y))
return(z)
}
w3 <- owin(xrange=c(55,562), yrange=c(137,1436)) #dummy window
spatpoly3 <- owin2SP(w3)
grid<-st_make_grid(spatpoly3, cellsize = 100, square = TRUE)
grid
gr_t2 <- as_Spatial(grid, cast = TRUE, IDs = paste0("ID", 1:length(grid)))
gr_t2 <- gBuffer(gr_t2, byid=TRUE, width=0)
spatpoly3 <- gBuffer(spatpoly3, byid=TRUE, width=0)
newLines <- raster::intersect(gr_t2, spatpoly3)
plot(newLines)
getSpatialPolygonsLabelPoints(newLines)
class(newLines)
numb3 <- data.frame(number = 1:length(newLines))
( pid <- sapply(slot(newLines, "polygons"), function(x) slot(x, "ID")) )
( p.df <- data.frame( ID=1:length(newLines), row.names = pid) )
polygrid_numbered3 <- SpatialPolygonsDataFrame(newLines, p.df)
With help from @obrl_soil I'm very close, but for some reason, setting cell size in st_make_grid throws the labeling off:
If I remove cellsize but leave "square = TRUE", the labeling is correct but the cells are not squares:
Any ideas?
w3
, and you should probably also show which packages you are using (looks like a mix ofsf
,sp
,rgeos
and whereverowin2SP
comes from (spatstat
?).