I create hexagons within a polygon perimeter using either the sp
package or the newer sf
package. Page 134 6.4 of Bivand et al.'s (2008) "Applied Spatial Data Analysis with R" gives an example of creating hexagons with sp
that is repeated in form here:
StudyArea <- read_sf(paste0(here("Inputs"),"/StudyArea.shp"))
StudyArea_sp <- sf::as_Spatial(StudyArea $geometry)
HexPts <- spsample(StudyArea_sp, type = "hexagonal", cellsize = 21750)
HexPols <- HexPoints2SpatialPolygons(HexPts)
HexPols <- sf::st_as_sf(HexPols)
This creates the following output:
I get a similar, but not the exact same result with sf
style:
HexPols2 <- st_make_grid(StudyArea , cellsize = 21750, square = FALSE)
HexPols3 <- st_intersection(HexPols2,StudyArea)
plot(StudyArea)
plot(HexPols3, add=TRUE)
I have two interrelated questions:
There is a difference between the
sp
andsf
approach that results in a different fitting of the hexagons. Why would this occur and how should I best control this? For example, I would like to maximize the number of full hexagons that occur within the polygon and to minimize the number of hexagons that touch the perimeter.How do I get the hexagons to give complete coverage of the polygon? The
sp
approach has complete hexagons, but it does not always touch the perimeter. In contrast, thesf
approach touches the perimeter but does not finish drawing the hexagons that meet the perimeter. I would like hexagons that touch the perimeter to be completed and not cut off at the boundary. However, I have tried several options, such asst_overlaps
, and get the following type of error:Error in xy.coords(x, y, xlabel, ylabel, log) :
'x' is a list, but does not have components 'x' and 'y'