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.
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