如何在 R 中读取、绘制 WKT 并将其转换为 table?

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

我有一个包含几百个 POLYGON((...,...,...)) 条目的 WKT 文件。是否有 R 包来读取、绘制和转换此类数据?我没有发现任何明确的内容。当可能有更复杂的现有方法时,只想避免使用字符串。提前致谢。

好吧,我找到了两个包,可以让我找到一个简单的解决方案。这是从 POLYGON((...,...)) WKT 类型中提取坐标的代码。

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

编辑:上述内容适用于单个字符串/WKT 对象。以下代码可应用于 WKT 文件,创建矩阵列表:

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

一个选项是使用 wellknown,它有一个 fxn 可以使用 leaflet

查看数据
library(wellknown)
str <- "POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))"
wktview(str)

如果转换为 geojson,则可以提取坐标,例如

wkt2geojson(str)$geometry$coordinates

另一种选择是 sfmapview 包的组合:

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)