How to read, plot and convert WKT to table in R?

3.9k views Asked by At

I have a WKT file with a few hundred POLYGON((...,...,...)) entries. Is there an R package to read, plot and convert such data? I did not find anything explicit. Just want to avoid working with strings when there might be a more elaborate existing approach. Thanks in advance.

3

There are 3 answers

0
AudioBubble On BEST ANSWER

Okay, I found two packages that bring me to a straightforward solution. Here's the code to extract the coordinates from a POLYGON((...,...)) WKT type.

str="POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))"

library(rgeos)
# For this library you need to `sudo apt-get install libgeos++-dev` in Linux
test <-readWKT(str)
library(sp)
plot(test)
coords <- as.data.frame(coordinates(test@polygons[[1]]@Polygons[[1]])) # Extracts coordinates of the polygon

EDIT: the aforementioned applies to a single string / WKT object. The following code can be applied to a WKT file, creating a list of matrices:

df <- read.table("yourfile.wkt",header = F, sep = "\t")
wow <- apply(df, 1, function(x) readWKT(as.character(x))) # Applies readWKT to every row of your df, i.e. to each WKT object
works = list()
for (i in 1:length(wow)) { 
  works[[i]] <- as.data.frame(coordinates(wow[[i]]@polygons[[1]]@Polygons[[1]]))
} # Loop populates a list with the coordinate matrices of each object of type polygon
0
sckott On

one option is using wellknown which has a fxn to view the data with leaflet

library(wellknown)
str <- "POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))"
wktview(str)

enter image description here

and you can extract coordinates if you convert to geojson, e.g.,

wkt2geojson(str)$geometry$coordinates
0
jsta On

Another alternative is a combination of the sf and mapview packages:

library(sf)
library(mapview)
str <- "POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))"
pnt <- st_as_sfc(str, crs = 4326)
mapview(pnt)

map of results