r gis: find borders between polygons - r

Having a polygon shapefile, I need to produce a polyline shapefile containing only the common borders between polygons (see the picture).
My question is similar to 1 and 2, only I need to do this in R. The latter similar question refers to a solution with the use of Shapely package for python. The analogue of Shapely for R is rgeos. Though, I couldn't find the solution with rgeos on my own.
Note: the shapefile with borders used for illustration was produced in ArcGIS using the solution from similar question 1. Now I need to do the same in R.

What you want is the lines that are the difference between the set of lines from the dissolved regions and the lines of the regions themselves. IN the rgeos package, gUnaryUnion will dissolve the polygons, and gDifference will subtract.
For my small EU subset eusub, I can do this with:
library(rgeos); library(sp)
borders = gDifference(
as(eusub,"SpatialLines"),
as(gUnaryUnion(eusub),"SpatialLines"),
byid=TRUE)
Note the need to convert polygons to lines because the output will be lines.
Then see this:
plot(eusub)
plot(borders, col="red",lwd=2,add=TRUE)

Related

Unable to create a multilinestring using st_intersection that is good enough to use border_segment from the SpatialRDD package

I’ve been following the following tutorial https://axlehner.github.io/SpatialRDD/articles/spatialrdd_vignette.html#assign-treatment for SpatialRDD using my own dataset and maps. I’ve run into a problem when attempting to use border_segment. In the tutorial the author has a cut off line he uses which describes a spatial discontinuity. In my own project I am trying to create such a cut off line using historical boundaries and by taking the intersection. I’ve been using two neighboring polygons and taking the intersection of their boundaries using st_intersection to create this cut off. However, once I reach the point where I need to use border_segment it does not work as intended.
If for instance I want 2 border segments to be created using my region, points in that region, and my cut off line, it appears border_segment creates 2 segments for each line segment of my cut off line (the cut off line I created using the intersection of boundaries). Furthermore, comparing the cut off line from the tutorial (can be loaded into R using SpatialRDD::data("cut_off.sf")) to the one I create, the one in the tutorial has one big matrix describing the geometry, while the one I create is described by many 2x2 matrices. I think this is where the problem might be stemming from, but I have no idea how to fix it. I think by finding a solution it would help to understand how to create better geographical objects using just R.
I’ve created a reproducible example to illustrate the issue:
library(SpatialRDD)
library(sf)
library(tmap)
library(spData) #loading various maps
#getting worldmap
data("world")
#changing to a localised projection system
world <- st_transform(world, "EPSG:3035")
#getting just Germany
germany <- world[world$name_long == "Germany",]
#getting just Poland
poland <- world[world$name_long == "Poland",]
#taking the union of Germany and Poland to later distribute random points in them
union <- st_union(germany, poland)
#taking the intersection of their borders, which will act as a cut off line
cut_off <- st_intersection(germany, poland)
#creating random points for exercise to work (similar code to what is done in tutorial)
set.seed(1088) # set a seed
points_samp <- sf::st_sample(union, 1000)
points_samp <- sf::st_sf(points_samp) # make it an sf object
#using border_segment to sort points into 2 border regions
points_samp$segment2 <- border_segment(points_samp, cut_off, 2)
#mapping the points in their respective border segments
tm_shape(points_samp) + tm_dots("segment2", size = 0.1) + tm_shape(cut_off) + tm_lines()
As you will see when plotting the points after creating the border segments, that there will be many border segments even though I indicated for border_segment to create only two.
I’m fairly new to R and geospatial manipulation, so maybe there is a simple solution, but I’ve searched everywhere and haven’t been able to find one. This is the first time after using stack overflow for years that I’ve had to actually post. Please let me know if you need any other information or if I was not clear enough at some point!

How to stop fortify from merging overlapping polygons

I have a SpatialPolygonsDataFrame containing multiple polygons that I want to plot in ggplot2. However, when I try converting my SpatialPolygonsDataFrame to a dataframe (required by ggplot2) via the fortify {ggplot2} function, polygons that overlap are merged. I know this is where the problem is because View(as.data.frame(data_pre_fortify)) and View(data_post_fortify) tell me the number of polygons before & after fortifying.
Currently my fortify function simply calls fortify(data_post_fortify, region = "id").
Can this merging of polygons be avoided, and if so, how?
Whilst this is by no means a perfect solution, I have managed to work around the issue by creating three SpatialPolygonsDataFrames, each containing only polygons that don't overlap (so overlapping polygons are split between different SpatialPolygonsDataFrames, and then fortifying these on their own. When it came to plotting I therefore had three geom_polygon layers, each calling one of the dataframes containing a subset of polygons.
I realise this isn't a great solution — colour/fill aesthetics cannot be added for all polygons together, plus this manual sorting of overlapping polygons may not be very time effective for larger/more overlapping datasets — so any further answers are very welcome!

Adding Boundaries to Spatial Polygons Object

I have the following SpatialPolygonsDataFrame.
require(raster)
usa <- getData('GADM', country='USA', level=2)
metro <- subset(usa, NAME_1=="Nebraska" & NAME_2 %in% c("Dodge","Douglas","Sarpy","Washington"))
plot(metro)
I would like to be able to replicate the following map boundaries (defined by the colors):
Does anyone know a good plan of attack? I realize this is a somewhat manual process. I have already downloaded all US Census files that are of a more detailed geography. I was hoping that a more detailed level of geography could be aggregated to answer the above question, but unfortunately the districts do not line up the same.
Is there a R function already out there that would be helpful in assisting this manual process? At the very minimum, I would like to be able to leverage the perimeter of the 4-county area.
Use writeOGR from the rgdal package to create a shapefile of your metro object. Then install QGIS (http://www.qgis.org/), a free and open-source GIS, and load the shapefile as a new layer.
Then you can edit the layer, add new polygons, edit lines etc, then save as a shapefile to read back into R.
Additionally, you may be able to "georeference" your image (by identifying known lat-long points on the image) and load that into QGIS as a raster layer. That makes it easier to digitise your new areas. All you need for that is a few lat-long coordinates of specific points, such as the corners of polygons or line intersections, and then QGIS has a georeferencing plugin that can do it.
I don't think you'll find any R code as suitable for digitising new geometries over an image as good as QGIS.
After half an hour (and twenty years experience, not all of which you'll need) I've got this:
I didn't precisely digitise your new boundaries though, just roughly for speed. That QGIS screen cap shows the five coloured areas under the four metro areas.
Step one was georeferencing. This screengrab shows how the PNG has been georeferenced - the red line is the metro area shapefile drawn with transparency over the PNG after the PNG has been converted to a GeoTIFF by matching control points.
Step two was then using QGIS editing tools to split, join, and create new polygons. Then I just coloured them and added labelling to pretty it up.
I could probably bundle these files all up for you to neaten, but it really doesn't take that long and you'll learn a lot from doing it. Also, this is probably a gis.stackexchange.com question...

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")

Autokriging spatial data

I'm trying to use a kriging function to create vertical maps of chemical parameters in an ocean transect, and I'm having a hard time getting started.
My data look like this:
horiz=rep(1:5, 5)
depth=runif(25)
value = horiz+runif(25)/5
df <- data.frame(horiz, depth, value)
The autoKrige function in the automap package looks like it should do the job for me but it takes an object of class SpatialPointsDataFrame. As far as I can tell, the function spTransform in package rgdal creates SpatialPointsDataFrame objects, but there are two problems:
OSX binaries of this aren't available from CRAN, and my copy of RStudio running on OXS 10.7 doesn't seem to be able to install it, and
This function seems to work on lat/long data and correct distance values for the curvature of the Earth. Since I'm dealing with a vertical plane (and short distances, scale of hundreds of meters) I don't want to correct my distances.
There's an excellent discussion of kriging in R here, but due to the issues listed above I don't quite understand how to apply it to my specific problem.
I want a matrix or dataframe describing a grid of points with interpolated values for my chemical parameters, which I can then plot (ideally using ggplot2). I suspect that the solution to my problem is considerably easier than I'm making it out to be.
So there a a few question you want answered:
The spTransform function does not create SPDF's, but transforms between projections. To create a SPDF you can use a simple data.frame as a start. To transform df to a SPDF:
coordinates(df) = c("horiz", "depth")
OS X binaries of rgdal can be found at http://www.kyngchaos.com. But I doubt if you need rgdal.
spTransform can operate on latlong data, but also on projected data. But I do not think you need rgdal, or spTransform, see also point 1.
After you create the SPDF using point 1, you can use the info at the post you mentioned to go on.

Resources