【问题标题】:How to filter a large geojson file in R如何在 R 中过滤大型 geojson 文件
【发布时间】:2020-03-25 05:11:47
【问题描述】:

我在使用 R 过滤大型 geojson 文件时遇到问题。如果我只想显示一个国家/地区的地图,我不希望加载整个欧洲地图,因为它很大。所以我想过滤这个数据集,例如保加利亚——CNTR_CODE == "BG",但我无法管理。 请在下面找到要下载的代码以及未产生预期结果的初步努力

link <- 'https://ec.europa.eu/eurostat/cache/GISCO/distribution/v2/nuts/download/ref-nuts-2013-01m.geojson.zip'
temp <- tempfile()
download.file(link,temp)
mapdata <- readLines(unzip(temp, "NUTS_RG_01M_2013_4326_LEVL_3.geojson"))
mapdata <- jsonlite::fromJSON(mapdata, simplifyVector = FALSE)
#glimpse(mapdata)
mapdata$features[[100]]$properties$CNTR_CODE
[1] "BG"


  library(sf)
  mapdata2 <- copy(mapdata)
  mapdata2 %>% 
    filter(CNTR_CODE %in% c('BG'))

谢谢。

【问题讨论】:

    标签: r json geojson r-highcharter


    【解决方案1】:

    如果您使用正确的工具,文件不会那么大。

    1. library(geojsonsf) 可以将 geojson 直接读取到 sf 对象中
    2. library(mapdeck) 可以绘制所有的多边形
    link <- 'https://ec.europa.eu/eurostat/cache/GISCO/distribution/v2/nuts/download/ref-nuts-2013-01m.geojson.zip'
    temp <- tempfile()
    download.file(link,temp)
    
    library(geojsonsf)
    library(sf)
    
    sf <- geojsonsf::geojson_sf(unzip(temp, "NUTS_RG_01M_2013_4326_LEVL_3.geojson"))
    

    然后你可以过滤sf对象并绘图

    library(mapdeck)
    set_token( "YOUR_MAPBOX_API_TOKEN" )
    
    mapdeck(
        style = mapdeck_style("dark")
    ) %>%
        add_polygon(
            data = sf[ sf$CNTR_CODE %in% c("BG"), ]
            , fill_colour = "NUTS_NAME"
            , legend = T
        )
    
    

    或绘制整个地段

    mapdeck(
        style = mapdeck_style("dark")
    ) %>%
        add_polygon(
            data = sf
            , fill_colour = "NUTS_NAME"
            , legend = T
        )
    

    【讨论】:

      【解决方案2】:

      如果你想要一个列表,那么Filter 可以工作:

      path = "NUTS_RG_01M_2013_4326_LEVL_3.geojson"
      x <- jsonlite::fromJSON(path, simplifyVector = FALSE)
      x$features <- Filter(function(z) z$properties$CNTR_CODE == "BG", x$features)
      vapply(x$features, function(x) x$properties$CNTR_CODE, "")
      

      如果你想保持geojson字符格式的数据,你可以使用jqr

      path = "NUTS_RG_01M_2013_4326_LEVL_3.geojson"
      x <- paste0(readLines(path), collapse = "")
      xx <- jqr::jq(x, '.features |= map(select(.properties.CNTR_CODE == "BG"))')
      jqr::jq(xx, '.features[].properties.CNTR_CODE')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-05
        • 1970-01-01
        • 2022-08-19
        • 1970-01-01
        • 2021-03-15
        • 2019-03-24
        • 1970-01-01
        相关资源
        最近更新 更多