R:从 GeoJson 到 DataFrame?

R: From GeoJson to DataFrame?

我有一个秘鲁的 GeoJson 文件及其状态(西班牙语为 Departamentos)。

我可以使用传单绘制秘鲁的州,但由于 GeoJson 文件没有我需要的所有数据,我正在考虑将其转换为 data.frame 然后添加我需要的数据列 return 将其转换为 GeoJson 格式进行绘图。

数据:您可以从这里下载秘鲁的GeoJson数据:

这是我正在使用的数据,我需要为它添加一个销售列,每个州都有一行("NOMBDEP" - 总共 24 个)

library(leaflet)
library(jsonlite)
library(dplyr)


states <- geojsonio::geojson_read("https://raw.githubusercontent.com/juaneladio/peru-geojson/master/peru_departamental_simple.geojson", what = "sp")

我想使用 "jsonlite" 包将 "GeoJson" 转换为数据框,但出现此错误:

library(jsonlite)

states <- fromJSON(states)

Error: Argument 'txt' must be a JSON string, URL or file.

我原以为在有了数据框之后我可以做类似的事情:

states$sales #sales is a vector with the sales for every department

states <- toJson(states)

不需要来回转换,只需在 states SPDF 中添加另一列即可:

states <- geojsonio::geojson_read("https://raw.githubusercontent.com/juaneladio/peru-geojson/master/peru_departamental_simple.geojson", what = "sp")
states$sales <- abs(rnorm(nrow(states), sd=1000))
plot(states, col=states$sales)

生成这张图片:

您可以使用library(geojsonsf)往返于GeoJSON和sf

library(geojsonsf)
library(sf)       ## for sf print methods

states <- geojsonsf::geojson_sf("https://raw.githubusercontent.com/juaneladio/peru-geojson/master/peru_departamental_simple.geojson")

states$myNewValue <- 1:nrow(states)

geo <- geojsonsf::sf_geojson(states)

substr(geo, 1, 200)
# [1] "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"properties\":{\"COUNT\":84,\"FIRST_IDDP\":\"01\",\"HECTARES\":3930646.567,\"NOMBDEP\":\"AMAZONAS\",\"myNewValue\":1},\"geometry\":{\"type\":\"Polygon\",\"coordinat"


.

可以看到myNewValue在GeoJSON