[GIS] How to plot polygon in R from coordinates string

coordinatesrspatial statisticsspatial-database

So I extracted the boundaries from DBSCAN in python and am now working on R to create visualization in GGPLOT and LEAFLET but I can't get the polygons to plot. This is a sample of the data:

[1,] "[(-98.898765, 19.455622), (-98.90185646, 19.44840652),
(-98.91575986, 19.45534196), (-98.91887031, 19.46230492),
(-98.91900371, 19.46275993), (-98.89589915, 19.46653405),
(-98.89548853, 19.46623211), (-98.89525595, 19.46604594), (-98.897175,
19.45978824), (-98.898765, 19.455622)]"

[2,] "[(-98.84953814, 19.55776871), (-98.86278253, 19.55505466),
(-98.86600973, 19.56443923), (-98.86597848, 19.56479789),
(-98.86202303, 19.57997289), (-98.85983876, 19.58694556),
(-98.84350132, 19.59316276), (-98.84325275, 19.59280415),
(-98.83970199, 19.58690075), (-98.83834813, 19.58301972),
(-98.84953814, 19.55776871)]"

I'm guessing I have to extract each number to create separate columns for latitude and longitude and be able to run the ggplot?
I've tried to split it, extract it, and many more methods but getting various errors for example:

Error in UseMethod("extract_") :
no applicable method for 'extract_' applied to an object of class "factor"

I've tried to do it on one cell only to get grips first but negative results always.

Any suggestions?

Best Answer

To plot your coordinate string on Leaflet in R:

Include the leaflet library:

install.packages('leaflet') library('leaflet')

Assign original string to a variable:

s1 <- "[(-98.898765, 19.455622), (-98.90185646, 19.44840652), (-98.91575986, 19.45534196), (-98.91887031, 19.46230492), (-98.91900371, 19.46275993), (-98.89589915, 19.46653405), (-98.89548853, 19.46623211), (-98.89525595, 19.46604594), (-98.897175, 19.45978824), (-98.898765, 19.455622)]"

Strip out unwanted characters:

c1 <- chartr('()[]',' ', s1)

Turn the cleaned string into a two column matix (Like @Spacedman said):

m1 <- matrix(as.numeric(strsplit(c1,",")[[1]]),ncol=2,byrow=TRUE)

make the Leaflet map and plot it:

map <- leaflet() map <- addTiles(map) map <- addPolygons(map, data = m1, color = "blue", weight = 4, smoothFactor = 0.5,opacity = 1.0, fillOpacity = 0.5,fillColor = 'red') map

You could also use SpatialPolygons like this past answer to a similar question.