我想一步一步地把.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}
的解决方案.我现在一直在try 迭代每个features
,以try 构建数据帧,但我找不到一种方法来很好地添加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 <- geojsonsf::geojson_sf("test.geojson")
的sf
对象,但我想一步一步地这样做,最终在Tibble上结束并了解我正在做什么.
非常感谢你的帮助!