gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:34:23 30 4
gpt4 key购买 nike

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

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com