在R中将SpatialPolygonsDataFrame导出为geojson或topojson。

4

我正在尝试将伦敦地方政府的GeoJSON转换为六边形卡托图,其中每个六边形代表一个地方政府。 在R中可以工作,但是当我尝试将生成的六边形网格导出为GeoJSON或TopoJSON时,会出现以下错误:

原始答案:Original Answer

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
1个回答

7
你可以将 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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接