Reputation: 358
I am trying to crate a grid inside a shapefile, something like this. However, I am unable to generate such grid. I was wondering if anyone has an idea on how to accomplish this.
Here is my code -
WWWL.Shape<- readOGR("E:/Juan Arango", "WWL_Commerce_OK")
WWWL.Shape
plot(WWWL.Shape)
proj4string(WWWL.Shape)
bb <- bbox(WWWL.Shape)
cs <- c(3.28084, 3.28084)*6000 # cell size
cc <- bb[, 1] + (cs/2) # cell offset
cd <- ceiling(diff(t(bb))/cs) # number of cells per direction
grd <- GridTopology(cellcentre.offset=cc, cellsize=cs, cells.dim=cd)
grd
sp_grd <- SpatialGridDataFrame(grd,
data=data.frame(id=1:prod(cd)),
proj4string=CRS(proj4string(WWWL.Shape)))
plot(sp_grd)
Output of WWL.Shape
class : SpatialPolygonsDataFrame
features : 1
extent : 334367, 334498.7, 4088915, 4089057 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=15 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
variables : 1
names : Id
min values : 0
max values : 0
Upvotes: 5
Views: 7772
Reputation: 10340
sf
versionsee rgdal
version below
First, we start of with a shapefile. You might probably load it from any geospatial file using st_read
.
library(sf)
library(raster)
library(ggplot2)
# load some spatial data. Administrative Boundary
shp <- getData('GADM', country = 'aut', level = 0)
shp <- st_as_sf(shp)
# ggplot() +
# geom_sf(data = shp)
Now the only thing you need is a combination of st_make_grid
and st_intersection
:
grid <- shp %>%
st_make_grid(cellsize = 0.1, what = "centers") %>% # grid of points
st_intersection(shp) # only within the polygon
# ggplot() +
# geom_sf(data = shp) +
# geom_sf(data = grid)
rgdal
and versionTo create a grid of pixels you can use the sp::makegrid
function.
Let's start with a reproducible example:
library(raster)
shp <- getData(country = "FRA", level = 0)
So now we have a (multi)polygon. Let's transform it to a metric coordinate system (since your data and cell sizes were also metric):
shp <- spTransform(shp, CRSobj = "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")
plot(shp)
Afterwards, we create a grid within this polygon with your specified cell size.
cs <- c(3.28084, 3.28084)*6000
grdpts <- makegrid(shp, cellsize = cs)
Then, we convert this grid (which basically is a matrix of center points) to a SpatialPoints
object:
spgrd <- SpatialPoints(grdpts, proj4string = CRS(proj4string(shp)))
This can then be converted into a SpatialPixels object. (Note: adding the subset [shp, ]
only selects points within the original polygons)
spgrdWithin <- SpatialPixels(spgrd[shp,])
plot(spgrdWithin, add = T)
If you need the grid as Polygons or Grid you can use
spgrdWithin <- as(spgrdWithin, "SpatialPolygons")
# or
spgrdWithin <- as(spgrdWithin, "SpatialGrid")
Upvotes: 19