Cause of warning when trying to simplify polygons? - r

I've got a leaflet map and I'm plotting some polygons on top of it. I'm trying to use rmapshaper::ms_simplify() to decrease the loading time for the map.
polygons_ll <- (
spTransform(polygons, CRS("+proj=longlat +datum=WGS84"))
)
polygons_ll <- ms_simplify(polygons_ll)
This is all within a R shiny application, which doesn't run after encountering the warning:
Warning in sp::proj4string(sp) :
CRS object has comment, which is lost in output
The app was functioning before the addition of the ms_simplify().
any advice is appreciated. Thanks

After doing some research and trial and error:
rgdal::set_rgdal_show_exportToProj4_warnings(FALSE)
will suppress the warning.
I ended up using:
crs <- CRS("+proj=longlat +datum=WGS84")
polygons_ll <- polygons %>%
rgeos::gSimplify(tol=25, topologyPreserve=TRUE) %>%
spTransform(crs)
# overwrite untransformed polygons with transformed polygons
polygons#polygons <- polygons#polygons
Maps are much faster to load now.

Related

SF: How can I get all the points that lay within a polygon? [duplicate]

I have a shapefile (with several polygons) and a dataframe with coordinates. I want to assign each coordinate in a dataframe to a polygon in a shapefile. So to add a column in a data frame with a polygon name or id
Here is the link to the data
library(sf)
library(readr)
shape <- read_sf("data/Provinces_v1_2017.shp")
data<- read_csv("data/data.csv")
But when I try to join them, I always get the error
pts = st_as_sf(data, coords = c("dec_lon", "dec_lat"), crs= 4326)
st_join(pts, shape)
i tried over() functions, and other tricks like st_make_valid() but I always get this error:
Error in s2_geography_from_wkb(x, oriented = oriented, check = check) : Evaluation error: Found 30 features with invalid spherical geometry.
It is a recent issue (before my code worked), but now I am unable to use sf package to do this task, I always end up with this error. I updated the libraries to see whether it would help, but I could not make it work.
I would really appreciate your help on this matter
You have two options:
turn off the s2 processing via sf::sf_use_s2(FALSE) in your script; in theory the behaviour should revert to the one before release 1.0
repair the spherical geometry of your polygons object; this will depend on the actual nature of your errors.
I can't access your file & make certain, but this piece of code has helped me in the past:
yer_object$geometry <- yer_object$geometry %>%
s2::s2_rebuild() %>%
sf::st_as_sfc()
I find that this 'invalid spherical geometry' does keep on popping up. If the s2::s2_rebuild() solution above doesn't work, a solution which usually works for me involves projecting and simplifying (reducing the map resolution a little). If your application can work with less resolution try this.
library(tidyverse)
library(sf)
crs_N = 3995 #northern polar projection
# example of FAILING map - with bad spherical geometry.
m_RU <- rnaturalearthdata::countries50 %>%
st_as_sf() %>%
filter((admin %in% c("Russia") )) |>
st_as_s2()
In the example, I chose Russia because it crosses the dateline, which can be one of the challenges. I switch to an Arctic polar projection, and reduce the map to 10km resolution (5km is not enough in this case!).
# with 2 extra lines the problem is gone
m_RU <- rnaturalearthdata::countries50 %>%
st_as_sf() %>%
filter((admin %in% c("Russia") )) |>
st_transform(crs = crs_N) |>
st_simplify(dTolerance = 10000) |> # to get rid of duplicate vertex (reduce to 10km steps)
st_as_s2()

How to resolve spherical geometry failures when joining spatial data

I have a shapefile (with several polygons) and a dataframe with coordinates. I want to assign each coordinate in a dataframe to a polygon in a shapefile. So to add a column in a data frame with a polygon name or id
Here is the link to the data
library(sf)
library(readr)
shape <- read_sf("data/Provinces_v1_2017.shp")
data<- read_csv("data/data.csv")
But when I try to join them, I always get the error
pts = st_as_sf(data, coords = c("dec_lon", "dec_lat"), crs= 4326)
st_join(pts, shape)
i tried over() functions, and other tricks like st_make_valid() but I always get this error:
Error in s2_geography_from_wkb(x, oriented = oriented, check = check) : Evaluation error: Found 30 features with invalid spherical geometry.
It is a recent issue (before my code worked), but now I am unable to use sf package to do this task, I always end up with this error. I updated the libraries to see whether it would help, but I could not make it work.
I would really appreciate your help on this matter
You have two options:
turn off the s2 processing via sf::sf_use_s2(FALSE) in your script; in theory the behaviour should revert to the one before release 1.0
repair the spherical geometry of your polygons object; this will depend on the actual nature of your errors.
I can't access your file & make certain, but this piece of code has helped me in the past:
yer_object$geometry <- yer_object$geometry %>%
s2::s2_rebuild() %>%
sf::st_as_sfc()
I find that this 'invalid spherical geometry' does keep on popping up. If the s2::s2_rebuild() solution above doesn't work, a solution which usually works for me involves projecting and simplifying (reducing the map resolution a little). If your application can work with less resolution try this.
library(tidyverse)
library(sf)
crs_N = 3995 #northern polar projection
# example of FAILING map - with bad spherical geometry.
m_RU <- rnaturalearthdata::countries50 %>%
st_as_sf() %>%
filter((admin %in% c("Russia") )) |>
st_as_s2()
In the example, I chose Russia because it crosses the dateline, which can be one of the challenges. I switch to an Arctic polar projection, and reduce the map to 10km resolution (5km is not enough in this case!).
# with 2 extra lines the problem is gone
m_RU <- rnaturalearthdata::countries50 %>%
st_as_sf() %>%
filter((admin %in% c("Russia") )) |>
st_transform(crs = crs_N) |>
st_simplify(dTolerance = 10000) |> # to get rid of duplicate vertex (reduce to 10km steps)
st_as_s2()

Unable to properly use autokrige from automap package (R cannot read the prediction locations well)

I'm trying to use R to perform a map of interpolated frequencies of data collected from Iberian Peninsula. (something like this https://gis.stackexchange.com/questions/147660/strange-spatial-interpolation-results-from-ordinary-kriging )
My problem is that the plot is not showing the interpolated data, due to some kind of error in the atributte new_data of the autokrige function.
https://cran.r-project.org/web/packages/automap/automap.pdf
new_data:
A sp object containing the prediction locations. new_data can be a points set, a
grid or a polygon. Must not contain NA’s. If this object is not provided a default is calculated. This is done by taking the convex hull of input_data and placing around 5000 gridcells in that convex hull.
I think the problem is that R is not reading well the map transformed to poligons because if I avoid this new_data attribute I get a propper plot of the krigging values. but I do not obtain a good shape of the iberian peninsula.
Can someone help me please? I would be truly grateful
here you can see my data: http://pastebin.com/QHjn4qjP
Actual code:
now since I transform my data coordinates to UTM projection i do not get error messages but the last plot is not interpolated, the whole map appear of one single color :(
setwd("C:/Users/Ruth/Dropbox/R/pruebas")
#Libraries
library(maps)
library(mapdata)
library(automap)
library(sp)
library(maptools)
library(raster)
library(rgdal)
####################MAPA#############
#obtain the grid of the desired country
map<-getData('GADM', country='ESP', level=0)
#convert the grid to projected data
mapa.utm<-spTransform(mapa3,CRSobj =CRS(" +proj=utm +zone=29 +zone=30 +zone=31 +ellps=WGS84"))
###############################Datos#######################
#submit the data
data1<-read.table("FRECUENCIASH.txt",header=T)
head(data1)
attach(data1)
#convert longlat coordinates to UTM
coordinates(data1)<-c("X","Y")
proj4string(data1) = CRS("+proj=longlat +datum=WGS84")
data1.utm=spTransform(data1, CRS("+proj=utm +zone=29 +zone=30 +zone=31 +ellps=WGS84 "))
######################Kriging interpolation #####################
#Performs an automatic interpolation
kriging_result<-autoKrige(Z~1,data1.utm,mapa.utm,data_variogram = data1.utm)
#Plot the kriging
result1<-automapPlot(kriging_result$krige_output,"var1.pred",sp.layout = list("sp.points", data1.utm));result1
result2<-plot(kriging_result);result2
The error you get is related to the fact you are using unprojected data as input for automap. Automap can only deal with projected data. Googling for map projections should give you some background information. To project your data to a suitable projection, you can use spTransform from the sp package.
The fact that it works without newdata is because in that object the projection is not set, so automap cannot warn you. However, the results of automap with latlon input data is not reliable.

How to properly project and plot raster in R

I have a raster in an equal area Behrmann projection and I would like to project it to the Mollweide projection and plot.
When I do this with the following code, however, the plotting doesn't seem right, as the map extends to the sides, and there are outlines of various landmasses where I wouldn't expect them.Also, the map extends beyond the plot window.
Can anyone please help me get this to plot nicely?
Thanks!
The data file used can be downloaded from this link.
Here is the code I have so far:
require(rgdal)
require(maptools)
require(raster)
data(wrld_simpl)
mollCRS <- CRS('+proj=moll')
behrmannCRS <- CRS('+proj=cea +lat_ts=30')
sst <- raster("~/Dropbox/Public/sst.tif", crs=behrmannCRS)
sst_moll <- projectRaster(sst, crs=mollCRS)
wrld <- spTransform(wrld_simpl, mollCRS)
plot(sst_moll)
plot(wrld, add=TRUE)
Alright, since the example at this page seems to work, I tried to mimic it as much as possible. I think problems arise because the far left and far right side of the raster image overlap. Cropping and an intermediate reprojection to Lat-Lon as in the example seem to solve your problem.
Perhaps this workaround can be a basis for a more elegant solution that directly addresses the problem, as it is not benificial to reproject a raster twice.
# packages
library(rgdal)
library(maptools)
library(raster)
# define projections
mollCRS <- CRS('+proj=moll')
behrmannCRS <- CRS('+proj=cea +lat_ts=30')
# read data
data(wrld_simpl)
sst <- raster("~/Downloads/sst.tif", crs=behrmannCRS)
# crop sst to extent of world to avoid overlap on the seam
world_ext = projectExtent(wrld_simpl, crs = behrmannCRS)
sst_crop = crop(x = sst, y=world_ext, snap='in')
# convert sst to longlat (similar to test file)
# somehow this gets rid of the unwanted pixels outside the ellipse
sst_longlat = projectRaster(sst_crop, crs = ('+proj=longlat'))
# then convert to mollweide
sst_moll <- projectRaster(sst_longlat, crs=mollCRS, over=T)
wrld <- spTransform(wrld_simpl, mollCRS)
# plot results
plot(sst_moll)
plot(wrld, add=TRUE)

How to create a KML file using R

I have written a R script to get some map point data (Latitude and Longitude values). I am able to plot them in R and visualize them. But now I want to generate a KML file from this data and view using Google Earth. So that I can share it with colleagues and they can see it on Google Earth too.
What is the best method / package to do this ?
Check the writeOGR function in the rgdal package. Here is a simple example:
library("sp")
library("rgdal")
data(meuse)
coordinates(meuse) <- c("x", "y")
proj4string(meuse) <- CRS("+init=epsg:28992")
meuse_ll <- spTransform(meuse, CRS("+proj=longlat +datum=WGS84"))
writeOGR(meuse_ll["zinc"], "meuse.kml", layer="zinc", driver="KML")
The objects exported are SpatialPointsDataFrame, SpatialLinesDataFrame, or SpatialPolygonsDataFrame objects as defined in the sp package.
R> class(meuse)
[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"
For writing with the KML driver, note that the geometries should be in geographical coordinates with datum WGS84.
I think is worth mentioning the plotKML package as well.
Edit 2022-05-16: Seems that plotKML is no longer on CRAN, but you can use an older package version from the CRAN archive. See Installing a Package Removed from CRAN.
However, for easy sharing among colleagues I found interesting the mapview package based on leaflet package. One can save a map as HTML document with various options for a background map; no need of Google Earth and the HTML map will run on your browser.
Some examples:
library(sp)
library(rgdal)
library(raster)
library(plotKML)
library(mapview)
# A SpatialPointsDataFrame example
data(meuse)
coordinates(meuse) <- ~x+y
proj4string(meuse) <- CRS("+init=epsg:28992") # CRS Amersfoort (Netherlands)
# make a KML file from SpatialPointsDataFrame object
# will get a warning like "Reprojecting to +proj=longlat +datum=WGS84 ..."
# as it is expected to work with geographical coordinates with datum=WGS84,
# but seems that it takes care of the reprojecting.
plotKML::kml(meuse,
file.name = "meuse_cadium.kml",
points_names = meuse$cadmium,
colour = "#FF0000",
alpha = 0.6,
size = 1,
shape = "http://maps.google.com/mapfiles/kml/pal2/icon18.png")
# Or, an easy to make interactive map with mapView()
mapView(meuse)
# A RasterLayer example
data(meuse.grid)
gridded(meuse.grid) <- ~x+y
proj4string(meuse.grid) <- CRS("+init=epsg:28992")
dist_rst <- raster(meuse.grid["dist"])
# make a KML file from RasterLayer object
plotKML::kml(dist_rst,
file.name = "dist_rst.kml",
colour_scale = SAGA_pal[[1]])
# Or, easy to make interactive map with mapView() - display raster and add the points
mapView(dist_rst, legend=TRUE) + meuse
# However, note that for bigger raster datasets mapView() might reduce from resolution
More examples with plotKML here.
For mapview, an intro can be found here.
If you're willing to step outside R, there is a free program called DNRGarmin can take a comma separated file as a .txt and convert it to .kml for import into google earth.
You can find it here:
http://www.dnr.state.mn.us/mis/gis/tools/arcview/extensions/DNRGarmin/DNRGarmin.html
so in R:
my.geo.data <- all.my.data[ c("unique.id", "lats", "longs")]
write.csv( my.geo.data, file = "myGeoData.txt")
open DNRGarmin,
File -> Load From -> File -> myGeoData.txt Then,
File -> Save to -> File -> myGeoData.kml
#rcs's advice re: WGS84 applies for this answer too.
Good luck
If you/your collegues know QGIS, this is a very good way to display data in Google Earth. QGIS has the feature of showing Google Earth as a base map and then you can open your spatial data and it will be displayed on the base map. Of course it requires your data to be correctly projected as rcs says.
Here you need to export your points as a shape file using the maptools package and Spatial Points package:
library(maptools)
library(sp)
## define projection
myProjection <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
## your points in format dataframe
coordinates.df <- as.data.frame(MyCoordinates)
## the number of points you have as dataframe
number <- as.data.frame(NumberOfPoints)
## convert points to Spatial Points Dataframe
myPoints.spdf <- SpatialPointsDataFrame(coordinates.df, number, proj4string = CRS(myProjection))
## save shapefile
writeSpatialShape(myPoints.spdf, "MyPointsName")
Your points can now be opened in QGIS and be displayed in Google Earth. In QGIS your data can also easily be saved as kmz file if necessary.

Resources