I have a chunk of R code that used to work but does not work anymore and I cannot find the issue. The purpose of the code is to fill a shapefile with regularly spaced points.
My shapefile can be accessed here: https://drive.google.com/drive/folders/1SAbuyIQHevK4fz-0w3TTqpEhz0wKLEII?usp=sharing
If I begin with loading my shapefile:
GUA = raster::shapefile('Guam3BufferPoly.shp')
Then I set a variable for the coordinate reference system for this SpatialPolygonDataFrame:
projGUA = crs(GUA)
Transform to planar crs
putm <- spTransform(GUA, projGUA)
Create a raster (this is where it doesn't work)
ext = extent(putm)
r <- raster(ext, res=500)
Rasterize the polygon and transform to points
r2 <- rasterize(putm, r)
pts <- rasterToPoints(r2, spatial=TRUE)
Transform the points to lon/lat and plot the results
pts_lonlat <- spTransform(pts, "+proj=longlat +datum=WGS84")
plot(pts_lonlat,pch='*')
The raster, r, is empty (breaking all the code downstream).
Please let me know if you can help me. And please be kind (this is my first time posting here and I apologize if I have not formatted my question correctly). Thank you!
Welcome!
Basically, it seems like you're working in a coordinate reference system not appropriate for the steps you execute.
Seems like the crs provided
Guam3BufferPoly.prjis not quite up to standard, but I'm not 100 % sure here. However, you're working with lat/lon coordinates on WGS 84. Hence,spTransform(GUA, projGUA)has absolutely no effect, since you're reprojecting your feature to the same crs again.This leads to a follow-up issue: You're working in degrees as units and specify a raster of 500 units (here: degrees, not meters, as probably intended). And this is exactly what
raster()does, even if it makes no sense:To solve this, you should use a projected coordinate reference system suitable for Guam. Not sure how good of a fit this is, you'll probably know better, but let me try WGS 84 / UTM 55 S (EPSG: 32755):
Edit:
You can simplify the process using
sfinstead ofrasterandspIMHO. Individual steps include data import, reprojection to a metric crs, grid creation covering the whole extent of your dataset and "spatial filtering" by intersecting your buffer with the grid centroids.Created on 2022-08-18 by the reprex package (v2.0.1)