How can I create a SpatialPolygons object from SpatialPolygonsDataFrame object in R? - r

I am working on creating a species distribution model using R-INLA, and I want to use a shapefile(.shp) that I have created in ArcPro as a barrier in the spatial mesh. In order to do so, I think the shapefile must be in the 'SpatialPolygons' format.
When I read in the shapefile (which is made up of 6 polygons), using st_read(), it is imported as a SpatialPolygonsDataFrame (see attached pictures).
Additionally, i tried to get shapefiles using worldhire, thinned them and tried to remove all the extra wee islands, but the mesh wouldn't run on INLA.
Long story short, is there:
a) A way I can import the .shp file as a SpatialPolygons object (would it need to be a separate shapefile for each polygon, or a different function)?
b) A way I can convert the SpatialPolygonsDataFrame object to a SpatialPolygons object?
c) Use a SpatialPolygonsDataFrame object when constructing a spatial autocorrelation mesh in R-INLA?
I appreciate any advice you can provide, please let me know if I can provide any more information
Link to image of shapefile plotted using plot() function
Link to image of the SpatialPolygonsDataFrame

I'm not sure this will help regarding your underlying problem, but to create a Spatial* object from a Spatial*DataFrame, you use the geometry() function:
library(sp)
library(rgdal)
seas = readOGR("il_seas.shp")
class(seas)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
> seas_geom = geometry(seas)
> class(seas_geom)
[1] "SpatialPolygons"
attr(,"package")
[1] "sp"
That simply strips off all attribute columns from the SPDF.

Related

Project SpatialLinesDataFrame for spNetwork

I am trying to use the nkde function of spNetworks to create a KDE of crashes in DC along its roadnetwork. In preparation for the function I am creating lixels for nkde, but running lines_center(lixels) always gives me an error.
lixels <- lixelize_lines(dc_lines,1000,mindist = 250)
samples <- lines_center(lixels)
Whenever I am trying to run lines_center(lixels) I get the following error:
Error in maptools::SpatialLinesMidPoints(with_length) :
is.projected(sldf) is not TRUE
In addition: Warning message:
In RGEOSMiscFunc(spgeom, byid, "rgeos_length") :
Spatial object is not projected; GEOS expects planar coordinates
I tried looking up various techniques, such as turning the SpatialLinesDataFrame into a normal Dataframe, st_as_sf, and then projecting it, but nothing worked out thus far and I always get the same error.
I am loading the data like this:
dc <- readOGR("assessment/test/Roads_2013", "Roads_2013")
Since the uploaded file is a Large SpatialPolygonsDataFrame, I am transforming it into SpatialLines using this code:
dc_lines <- as(dc, "SpatialLinesDataFrame")
Any idea what I am doing wrong or how I can properly project the lines?
The shapefile used is here:
https://opendata.dc.gov/datasets/roads
I am the spNetwork developer. Please, consider posting your issue on the github for faster response. The problem here is that your dataset does not use a planar (X/Y coordinates in meters) CRS, but a geographical one (Lon/Lat in degrees). You need to reproject your data in an appropriate CRS with the function spTransform from sp package. Here is the link with some examples (https://www.rdocumentation.org/packages/rgdal/versions/1.5-28/topics/spTransform-methods).
Maybe the EPSG:2927 could be the CRS to use (I am not familiar with EPSG used in USA).
dc <- readOGR("assessment/test/Roads_2013", "Roads_2013")
dc_proj <- spTransform(dc, CRS("+init=epsg:2927"))

Easy way to convert sfc_POINT into RasterLayer?

I am using the library sf for spatial data in R. I want to use the SpaDES::splitRaster() method to split up a grid made with sf::st_make_grid() into many tiles. As far as I know, neither the sf or the raster library support such an operation.
However, st_make_grid() returns an object of sfc_POINT, but splitRaster() requires an object of type RasterLayer (for example).
Is there a method in sf (or raster, but I'd prefer to stay within sf) that I can use to quickly convert sfc_POINT into a RasterLayer, ideally without loading rgdal and rgeos?

Convert Spatial Lines to Spatial Polygons

Is there an easy way to convert a Spatial Lines into a Spatial Polygon object within R?
Reproducible Example
I have put together a reusable dataset here, which is downloaded from OpenStreetMaps through the overpass package. This extracts the locations of a few airports in South England:
devtools::install_github("hrbrmstr/overpass")
library(overpass)
library(raster)
library(sp)
# Write Query
query_airport <- '
(node["aeroway"="aerodrome"](50.8, -1.6,51.1, -1.1);
way["aeroway"="aerodrome"](50.8, -1.6,51.1, -1.1);
relation["aeroway"="aerodrome"](50.8, -1.6,51.1, -1.1);
);
out body;
>;
out skel qt;
'
# Run query
shp_airports <- overpass::overpass_query(query_airport, quiet = TRUE)
crs(shp_airports) <- CRS("+init=epsg:4326") # Add coordinates
shp_airports <- shp_airports[,1]
# Plot Results
plot(shp_airports, axes = T)
However, the data is of the class "SpatialLinesDataFrame". This really messes things up if you want to do any form of spatial joins or intersections, as it only acknowledges the edge of the region.
Potential Leads
I was exploring the use of SpatialLines2PolySet within the maptools package, but in my time exploring I produced nothing but error codes, so I didn't think there would be any worth including these within the question. There is some guidance about these functions here: https://rdrr.io/rforge/maptools/man/SpatialLines2PolySet.html
Notes
I have searched the web and SO to see find similar questions and struggled to find any questions directly referring to this. A lot seem to reference converting SpatialPoints -> SpatialLineDataFrames , but not SpatialLineDataFrames -> SpatialPolygonDataFrames. This question is similar but lacks any answers (or a reproducible dataset): Close a spatial line into a polygon using a shapefile
In addition, it seems strange that this would be difficult as it is something which can be done so easily in ArcGIS using the "Feature to Polygon" tool. This function requires no additional arguments specified and it works perfectly.
A way to solve the problem would be to use the library sf. After your query
library(sp)
library(raster)
library(sf)
sf_airports <- st_as_sf(shp_airports)
sf_airports_polygons <- st_polygonize(sf_airports)
shp_airports <- as(sf_airports_polygons, "Spatial") # If you want sp
class(shp_airports)

How to convert from shape into polygon in R? There was shape2poly(shapefiles) but this function have been removed

How to convert from shape into polygon in R? There was shape2poly(shapefiles) but this function have been removed, are shapefiles, maptools, spdep still packages for handling maps in R?
I tend to use the OGR stuff, as it lets me work with data from a range of sources (geodatabases, kml, etc).
library(rgdal)
mylayer <- readOGR(dsn="/path/to/folder/containing/shapefile",
layer="shapefilename-minus-dot-shp")

Overlaying SpatialLines by SpatialPolygons in R

I have a SpatialLines object representing roads and a SpatialPolygons object
containing cities.
I'd like to know how to overlay a SpatialLines object by a SpatialPolygons
object in R.
I'd like to know the Lines that passes over the two cities and which cities in?
Is it possible?
You need the rgeos package which wraps the GEOS library of geometry operations.
Then probably gIntersection or gIntersects will do what you want.
In general, overlays of spatial objects are handled by the over function from the sp package. In the Methods section of the documentation of over (?over) there is a list of methods for over, which does not include the combination of Lines and Polygons. Luckily, the documentation of over says that by installing the rgeos package these kind of methods are made available.

Resources