我想逐步将
.geojson
转换为 tibble(或数据框)。
这是一个简约的 geojson 示例,我将其存储在名为
test.geojson
的文件中(请注意,geometry
字段是 null
,但这在这里并不重要):
{"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "VAR_1": 31,"VAR_2": "abc","VAR_3": 255 }, "geometry" : null },
{ "type": "Feature", "properties": { "VAR_1": 23,"VAR_2": "def","VAR_3": 876 }, "geometry" : null }
]}
期望的结果(这里假设
geometry
填充有两个坐标而不是null
)
# A tibble: 2 x 3
VAR_1 VAR_2 VAR_3 geometry
<dbl> <chr> <dbl> <list>
1 31 abc 255 <dbl [2]>
2 23 def 876 <dbl [2]>
我特别喜欢基于
{tidyverse}
的解决方案。我现在一直在尝试的是迭代每个 features
来尝试构建一个数据框,但我找不到一种方法来很好地添加 geometry
字段:
# Read geojson
js <- jsonlite::read_json("test.geojson")
# Iterate through each features ...
map_dfr(1:length(js$features), .f = function(i){
df <- js$features[[i]]$properties # this works but only importing VAR_1, VAR_2, VAR_3
df |> mutate(geometry = js$features[[i]]$geometry) # this does not work
})
注意:可以使用
{geojsonsf}
将其直接导入为 sf
对象,但我想一步一步地完成,最终得到一个小标题并理解我在做什么。非常感谢您的帮助!
sf <- geojsonsf::geojson_sf("test.geojson")
你可以这样做:
x <- '{"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "VAR_1": 31,"VAR_2": "abc","VAR_3": 255 }, "geometry" : [-74.0060, 40.7128]},
{ "type": "Feature", "properties": { "VAR_1": 23,"VAR_2": "def","VAR_3": 876 }, "geometry" : [-74.0060, 40.7128]}
]}'