无法取消嵌套 json 文件以在 r 中创建地图?

Unable to unnest json file to create map in r?

我不熟悉在 r 中使用 json,想使用其中的数据创建地图,但到目前为止我无法将其转换为可用的数据结构格式。

这是我试过的:

library(jsonlite)
library(tidyverse)
ind_waterways <- jsonlite::fromJSON( url("https://raw.githubusercontent.com/india-in-data/waterways/master/ind_waterways.json"))

ind_waterways
ind_waterways %>% 
  map_if(is.data.frame, list) %>% 
  as_tibble() %>% 
  unnest()

但是当我尝试 unnest 它时我得到错误:

ind_waterways$features %>% 
  map_if(is.data.frame, list) %>% 
  as_tibble() %>% 
  unnest(coordinates)

Error: Can't subset columns that don't exist. x Column coordinates doesn't exist. Run rlang::last_error() to see where the error occurred.

下面,代码使用 OP 的解决方案直到转换为 tibble,然后我们单独对列进行 unnesting,因为结构有点复杂,即涉及 matrix 作为列在嵌套的 list

library(dplyr)
library(jsonlite)
library(purrr)
out <- ind_waterways %>% 
  map_if(is.data.frame, list) %>% 
  as_tibble() %>%
  mutate(crs = unlist(crs)) %>% 
  unnest_wider(features, names_repair = "unique") %>%
  unnest_wider(geometry) %>%
  unnest(names(.)[3:6]) %>%
  mutate(coordinates = map(coordinates, as_tibble)) %>% 
  unnest_wider(coordinates) %>%
  unnest(c(V1, V2))  

-输出

out
# A tibble: 115,318 x 7
   type...1          crs   type...3    id type          V1    V2
   <chr>             <chr> <chr>    <int> <chr>      <dbl> <dbl>
 1 FeatureCollection name  Feature      0 LineString  77.6  34.6
 2 FeatureCollection name  Feature      0 LineString  77.5  34.6
 3 FeatureCollection name  Feature      0 LineString  77.4  34.7
 4 FeatureCollection name  Feature      0 LineString  77.2  34.7
 5 FeatureCollection name  Feature      0 LineString  77.2  34.8
 6 FeatureCollection name  Feature      0 LineString  77.1  34.8
 7 FeatureCollection name  Feature      0 LineString  77.1  34.8
 8 FeatureCollection name  Feature      0 LineString  77.0  34.8
 9 FeatureCollection name  Feature      0 LineString  77.0  34.8
10 FeatureCollection name  Feature      0 LineString  76.8  34.9
# … with 115,308 more rows