Reverse coordinates for (multi-) polygon - r

I'm working with shapefiles of subdivisions of a number of countries, and for one country (Iceland), the X and Y coordinates appear to be swapped around in the shapefile.
The data can be downloaded here: shapefile data; IS_50V:mork_kjordaemi is the relevant dataset, select the "shape-zip" option in the download dropdown menu.
I've been using the "sf" package in R for all the shapefile work, and it has worked flawlessly with all the other shapefile data I have.
library(sf)
ic_2003 <- downloaded_data
st_crs(ic_2003) gives me
Coordinate Reference System:
User input: ISN2016
wkt:
GEOGCRS["ISN2016",
DATUM["Islands Net 2016",
ELLIPSOID["GRS 1980",6378137,298.257222101,
LENGTHUNIT["metre",1]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433]],
CS[ellipsoidal,2],
AXIS["geodetic latitude (Lat)",north,
ORDER[1],
ANGLEUNIT["degree",0.0174532925199433]],
AXIS["geodetic longitude (Lon)",east,
ORDER[2],
ANGLEUNIT["degree",0.0174532925199433]],
USAGE[
SCOPE["unknown"],
AREA["Iceland"],
BBOX[59.96,-30.87,69.59,-5.55]],
ID["EPSG",8086]]
head(ic_2003) gives me
Simple feature collection with 6 features and 15 fields
Geometry type: MULTIPOLYGON
Dimension: XY
Bounding box: xmin: 63.29577 ymin: -24.53268 xmax: 66.56644 ymax: -13.49462
Geodetic CRS: ISN2016
I've tried ic_2003 <- st_transform(ic_2003, 4326) but this doesn't fix the problem.
I've also tried ic_2003 <- st_transform(ic_2003, pipeline = "+proj=pipeline +step +proj=axisswap +order=2,1"), as done here , but this also does not solve the issue.
If I plot the data
ggplot(ic_2003) +
geom_sf() +
coord_sf()
I get the right shape, but rotated 90 degrees and in the wrong place on a world map.
Any help you could give me would be greatly appreciated.

There must be a sf way of doing this easily, but you can also use purrr::modify (which works like map) to swap all of the geometry lat/lon columns (a matrix within a list within a list within a list) without changing the sf attributes...
library(sf)
library(tidyverse)
ic_2003 <- st_read("mork_kjordaemiPolygon.shp") #from link above
ic_2003 <- ic_2003 %>%
mutate(geometry = modify(geometry, modify, ~list(.[[1]][,c(2,1)])))
ggplot(ic_2003) +
geom_sf() +
coord_sf()

Related

Spatial join longitude and latitude points to multipolygon shapefile

I have a spatial data frame of the longitude and latitude of wildfire origins that I am trying to perform a spatial join on to a US Census TIGER/Line shapefile (places) to see if/where there is spatial intersection of fire origins and places.
I am converting the longitude and latitude to coordinate geometry using st_as_sf then attempting to st_join this to the places file, but am encountering an error as the CRS are different. The shapefile is in NAD83 projection, so I am attempting to match that.
library(tidyverse)
library(sf)
> head(fires)
# Longitude Latitude FireName
#1 -106.46667 34.66000 TRIGO
#2 -81.92972 35.87111 SUNRISE
#3 -103.76944 37.52694 BRIDGER
#4 -122.97556 39.37500 BACK
#5 -121.15611 39.62778 FREY
#6 -106.38306 34.77056 BIG SPRING
#convert df to sf
fires_sf <- st_as_sf(fires, coords = c("Longitude", "Latitude"), crs = 4269, agr = "constant")
head(fires_sf$geometry)
#Geometry set for 6 features
#Geometry type: POINT
#Dimension: XY
#Bounding box: xmin: -122.9756 ymin: 34.66 xmax: -81.92972 ymax: 39.62778
#Geodetic CRS: NAD83
#POINT (-106.4667 34.66)
#POINT (-81.92972 35.87111)
#POINT (-103.7694 37.52694)
#POINT (-122.9756 39.375)
#POINT (-121.1561 39.62778)
head(places$geometry)
#Geometry set for 6 features
#Geometry type: MULTIPOLYGON
#Dimension: XY
#Bounding box: xmin: -1746916 ymin: -395761.6 xmax: -1655669 ymax: -212934.8
#Projected CRS: USA_Contiguous_Albers_Equal_Area_Conic
#First 5 geometries:
#MULTIPOLYGON (((-1657066 -233757.7, -1657192 -2...
#MULTIPOLYGON (((-1668181 -273428.5, -1669420 -2...
#MULTIPOLYGON (((-1735046 -389578.2, -1735146 -3...
#MULTIPOLYGON (((-1732841 -376703.9, -1732642 -3...
#MULTIPOLYGON (((-1693749 -377716, -1693286 -377..
joined <- st_join(places, fires_sf)
Error in st_geos_binop("intersects", x, y, sparse = sparse, prepared = prepared, :
st_crs(x) == st_crs(y) is not TRUE
To work around this, I have tried st_transform to change the projection to longitude and latitude coordinates, as the places shapefile may be using UTM coordinates, and the datum to NAD83 in both spatial frames. I am getting an error for this as well.
#transform CRS projections
places_transform <- st_transform(places, "+proj=longlat +datum=NAD83")
fires_sf_transform <- st_transform(fires_sf, "+proj=longlat +datum=NAD83")
joined_new <- st_join(places_transform, fires_sf_transform)
Error in s2_geography_from_wkb(x, oriented = oriented, check = check) :
Evaluation error: Found 1045 features with invalid spherical geometry.
[3] Loop 0 is not valid: Edge 280 has duplicate vertex with edge 306
I have attempted to convert the geometry from longitude and latitude coordinates in the fires dataset to UTM coordinates to match the places shapefile, but this was also unsuccessful.
Any advice on how I can properly perform the spatial join of these points and multipolygons would be greatly appreciated.

How do I get gCentroid to work at the pole?

I am struggling with gCentroid, because it doesn't seem -- to me -- to give the 'right' answer near a pole of the Earth.
For instance:
library(rgeos)
gCentroid(SpatialPoints(coords=data.frame(longitude=c(-135,-45,45,135),latitute=c(80,80,80,80)),proj4string = CRS('EPSG:4326')))
does not give me the North Pole, it gives:
> SpatialPoints:
> x y
> 1 0 80
> Coordinate Reference System (CRS) arguments: +proj=longlat +datum=WGS84 +no_defs
How do I get gCentroid to work on the surface of the Earth?
The GEOS library is limited to planar geometry operations; this can bring issues in edge cases / the poles being a notorious example.
For the centroid via GEOS to work as intended you need to transform your coordinates from WGS84 to a coordinate reference system appropriate to polar regions; for Arctic regions I suggest EPSG:3995.
library(sp)
library(dplyr)
library(rgeos)
points_sp <- SpatialPoints(coords=data.frame(longitude=c(-135,-45,45,135),latitute=c(80,80,80,80)),proj4string = CRS('EPSG:4326'))
points_updated <- points_sp %>%
spTransform(CRS("EPSG:3995")) # a projected CRS apropriate for Arctic regions
centroid <- gCentroid(points_updated) %>%
spTransform(CRS("EPSG:4326")) # back to safety of WGS84!
centroid # looks better now...
# SpatialPoints:
# x y
# 1 0 90
# Coordinate Reference System (CRS) arguments: +proj=longlat +datum=WGS84 +no_defs
Also note that your workflow - while not wrong in principle - is a bit dated, and the {rgeos} package is approaching its end of life.
It may be good time to give a strong consideration to {sf} package, which is newer, actively developed and can, via interface to s2 library from Google, handle spherical geometry operations.
For an example of {sf} based workflow consider this code; the result (centroid = North Pole) is equivalent to the sp / rgeos one.
library(sf)
points_sf <- points_sp %>% # declared earlier
st_as_sf()
centroid_sf <- points_sf %>%
st_union() %>% # unite featrues / from 4 points >> 1 multipoint
st_centroid()
centroid_sf # the North Pole in a slightly different (sf vs sp) format
# Geometry set for 1 feature
# Geometry type: POINT
# Dimension: XY
# Bounding box: xmin: 0 ymin: 90 xmax: 0 ymax: 90
# Geodetic CRS: WGS 84 (with axis order normalized for visualization)
# POINT (0 90)

How to read & plot from .shp files using sf package in r?

I am new to geospatial data & trying to plot using .shp file but getting an error.
The geometry type in this .shp file is LINESTRING which seems to be different from MULTIPOLYGON which I have plotted before using sf
shape file source: https://github.com/johnsnow09/covid19-df_stack-code/blob/main/in_country_boundaries.shp
original source of shapefile: https://github.com/wri/wri-bounds/blob/master/dist/in_countries.zip
Expecting result:
code attempt:
library(tidyverse)
library(sf)
ind_global <- sf::read_sf("path/in_country_boundaries.shp")
ind_global
output
Simple feature collection with 412 features and 9 fields
Geometry type: LINESTRING
Dimension: XY
Bounding box: xmin: -141.0056 ymin: -54.88624 xmax: 140.9776 ymax: 70.07531
Geodetic CRS: WGS 84
ind_global %>%
st_as_sf() %>%
ggplot() +
geom_sf()
Error in st_cast.POINT(X[[i]], ...) : cannot create MULTILINESTRING
from POINT
Do I need to handle LINESTRING geometry .shp file in some other way?
The code is running fine after removing st_as_sf() %>%. I have downloaded the shapefile from https://github.com/wri/wri-bounds/blob/master/dist/in_countries.zip and it is MULTIPOLYGON only.
library(tidyverse)
library(sf)
ind_global <- sf::read_sf("...\\in_countries.shp")
ind_global
ind_global %>%
ggplot() +
geom_sf()

How to manipulate the geometry of a shapefile polygon using sf in R

I have two shapefile polygons, one with a defined CRS (shapefile A) and another with an undefined CRS (shapefile B). I have lat/long coordinates with geometries similar to that of shapefile A. However, I want to count these points in the polygons of shapefile B. I realize that simply setting the CRS in shapefile B to that of shapefile A does not solve the problem as the geometries are different.
How do I go about modifying the geometry of shapefile B so that it matches with shapefile A? The closest help I found was to apply an affine transformation on the polygons, but I'm not sure how to go about doing so, if that is the correct method.
Here are some descriptions of the two shapefiles (note the bbox and CRS fields in particular):
Shapefile A
Simple feature collection with 61 features and 29 fields
geometry type: MULTIPOLYGON
dimension: XY
bbox: xmin: -61.93033 ymin: 10.04404 xmax: -60.90916 ymax: 10.84451
geographic CRS: WGS 84
Shapefile B
Simple feature collection with 534 features and 13 fields
geometry type: POLYGON
dimension: XY
bbox: xmin: 617063.2 ymin: 1110279 xmax: 728431.5 ymax: 1199347
CRS: NA
I imagine that I would need to multiply the geometries of shapefile B by -10^-4 for the x coordinates and 10^-5 for the y coordinates but I'm not sure if the negative will reflect the shapefile as well. If so, is it still possible to apply another viable transformation?

Plotting sfc_POLYGON in leaflet

I have a sfc_POLYGON, IHS obtained as a union of a few shapes using the sf package.
Geometry set for 1 feature
geometry type: POLYGON
dimension: XY
bbox: xmin: 270194.7 ymin: 2255850 xmax: 279225 ymax: 2265469
epsg (SRID): 32643
proj4string: +proj=utm +zone=43 +datum=WGS84 +units=m +no_defs
POLYGON((279224.998943279 2261084.1514869, 2792...
While I am able to plot this in mapview, I am facing some problems while plotting the same in leaflet. When I plot this is leaflet, I get a warning sf layer is not long-lat data which it isn't, and I get the base world map. This is the code I used for plotting in leaflet.
IHS%>%leaflet()%>%addTiles()%>%
addProviderTiles(providers$Esri.WorldImagery, group ="ESRI")%>%
addPolygons()
I suspect this has to do something with the CRS. I have tried st_set_crs(IHS, 4326)which changes my projection of IHS from utm to longlat:
Geometry set for 1 feature
geometry type: POLYGON
dimension: XY
bbox: xmin: 270194.7 ymin: 2255850 xmax: 279225 ymax: 2265469
epsg (SRID): 4326
proj4string: +proj=longlat +datum=WGS84 +no_defs
However there is no change in the leaflet warning and output. I am not sure here, but has it got something to do with changing the dimension and bbox (which appears to be in meters)?
"Converting" into Lon/Lat is to change its spatial projection. Once you know that, you can play with spatial data and find in library help the correct way of projecting spatial features.
In your case, using st_set_crs(IHS, 4326) only says that the projection is Lon/lat, without projecting it.
You need to use st_transform:
IHS_wgs84 <- st_transform(IHS, "+init=epsg:4326")

Resources