How do I generate a Hexagonal grid in R
Asked Answered
K

1

15

I would like to be able to create a SpatialPolygons object (which is a Hexagonal grid) that covers another SpatialPolygon.

I would like all the Hexagons to have a diameter of 1km (ideally i can vary this) and for all the hexagons together to cover the whole object. The method below only seems to cover a small amount of it...

Below is my attempt using the sp package:

require(sp)
data(meuse.riv)
meuse.sr = SpatialPolygons(list(Polygons(list(Polygon(meuse.riv)), "x")))
plot(meuse.sr)

HexPts <-spsample(meuse.sr,type="hexagonal",cellsize=1000)
HexPols <- HexPoints2SpatialPolygons(HexPts)
plot(HexPols, add=TRUE)

Any help as always is greatly appreciated...

Kannry answered 31/3, 2015 at 16:45 Comment(0)
L
20

replace meuse.sr with some buffered version, like rgeos::gBuffer(meuse.sr, width = 2000) in the call to spsample. Here is a full example that selects only the intersecting hexagons:

require(sp)
data(meuse.riv)
meuse.sr = SpatialPolygons(list(Polygons(list(Polygon(meuse.riv)), "x")))
plot(meuse.sr)

library(rgeos)
meuse.large = gBuffer(meuse.sr, width = 2000)
HexPts <-spsample(meuse.large, type="hexagonal", cellsize=1000)
HexPols <- HexPoints2SpatialPolygons(HexPts)
plot(HexPols[meuse.sr,], add=TRUE)

enter image description here

Lune answered 31/3, 2015 at 17:29 Comment(6)
I get this error: > HexPts <-spsample(rgeos::gBuffer(meuse.sr, 2000),type="hexagonal",cellsize=1000) Error in spsample(rgeos::gBuffer(meuse.sr, 2000), type = "hexagonal", : error in evaluating the argument 'x' in selecting a method for function 'spsample': Error: is.logical(byid) is not TRUEKannry
Thank you! That's very good...but How do I get it so that I only get polygons that intersect with the underlying spatial polygon, because at the moment with width=2000, there are some polygons that do not intersect with the underlying object at all...Kannry
added the full example to the answer.Lune
Is there a way to do this with sf without converting from and to sp?Quinlan
There is also a nice post on the topic here by the way.Quinlan
With sf, you can use st_make_grid(x, square=FALSE)[x] with x = st_as_sf(meuse.sr)Lune

© 2022 - 2024 — McMap. All rights reserved.