r - 在 R 中将 SpatialPolygonsDataFrame 导出为 geojson 或 topojson

标签 r sf hexagonal-tiles geojsonio

我正在尝试将伦敦地方当局的 geojson 转换为六边形制图,其中每个六边形代表一个地方当局。它在 R 中工作,但是当我尝试将生成的 hexgrid 导出为 geojson 或 topojson 时,出现以下错误:

Error in sp::SpatialPolygonsDataFrame(polys, data = input@data) : 
  row.names of data and Polygons IDs do not match

这是代码。我正在使用 geogrid 生成网格,使用 geojsonio 将生成的数据框导出到 geojson 或 topojson:

library(geogrid)
library(geojsonio) # version 0.9.0

df <- read_polygons(system.file("extdata", "london_LA.json", package = "geogrid"))
# you can get the json file from here: https://github.com/jbaileyh/geogrid/blob/master/inst/extdata/london_LA.json

# Set arguments for plot
par(mfrow = c(2, 3), mar = c(0, 0, 2, 0))

# Hexagonal grid with 6 seeds
for (i in 1:3) {
  grid_hexagon <- calculate_grid(shape = df, learning_rate = 0.05, grid_type = "hexagonal", seed = i)
  plot(grid_hexagon, main = paste("Seed", i, sep = " "))
}

# Square grid
for (i in 1:3) {
  grid_square <- calculate_grid(shape = df, grid_type = "regular", seed = i)
  sp::plot(grid_square, main = paste("Seed", i, sep = " "))
}

# Get a SpatialDataFrame from our desired grid
tmp <- calculate_grid(shape = df, grid_type = "hexagonal", seed = 3)
df_hex <- assign_polygons(df, tmp)

# And export to TopoJSON
topojson_write(df_hex, object_name = "local_authorities", file = "output/london_hex.json")

关于如何解决这个问题有什么建议吗?此外,我有兴趣了解其他生成具有特定输入文件的十六进制制图的方法。

引用文献:https://github.com/jbaileyh/geogrid

最佳答案

您可以将 SpatialPolygonsDataFrame 转换为 sf,然后使用 st_write 写入 GeoJSON 文件:

library(sf)                                                                                                                               
df_hex = st_as_sf(df_hex)                                                                                                                 
st_write(df_hex, "df_hex.geojson") 

这是 QGIS 中的结果:

enter image description here

关于r - 在 R 中将 SpatialPolygonsDataFrame 导出为 geojson 或 topojson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64537922/

相关文章:

r - 将可编辑 DT 与 `add row` 功能相结合

r - 在中的两个SF POINT特征之间绘制线

读取/导入 .tpk 映射到 R 或 QGIS 并用作 shapefile

r - 将ggplot2中的十六进制垃圾箱设置为相同大小

以最小距离(3)为重复出现的颜色着色六边形瓦片 map 的算法

R - 条件递增

r - x 和 get ("x"之间的奇怪区别)?

r - 如何评估 R 中 data.frame 中组内先前值满足的条件

r - PROJ4 到 PROJ6 升级和 "Discarded datum"警告

瓷砖上的 C++ 连接六边形