在 R 中将 SpatialPolygonsDataFrame 导出为 geojson 或 topojson

Export SpatialPolygonsDataFrame as geojson or topojson in R

我正在尝试将伦敦地方当局的 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 中的结果: