【问题标题】:Subsetting geojson data with R用 R 子集 geojson 数据
【发布时间】:2017-11-06 20:39:48
【问题描述】:

我有一个州边界的 geojson 文件that I obtained from here。特别是我使用the 20m US States Data

我正在尝试对数据进行子集化,以便我可以使用传单仅映射某些状态。我可以使用以下方法对单个状态进行子集化:

states <- geojsonio::geojson_read("gz_2010_us_040_00_20m.json", what = "sp")
az <- subset(states, NAME == "Arizona")

这种方法似乎不适用于选择多个状态:

swStates <- subset(states, NAME == c("Arizona", "Nevada", "New Mexico"))

选择多个状态通常会导致只选择一个或两个状态,或者根本不选择。我可以使用其他方法来对这些数据进行子集化吗?

【问题讨论】:

    标签: r leaflet gis geojson ropensci


    【解决方案1】:

    您需要使用%in% 而不是==

    cities <- geojsonio::us_cities
    TwoCities <- subset(cities, name %in% c("Seattle WA", "San Francisco CA"))
    

    【讨论】:

    【解决方案2】:

    也没有放弃接受的答案,但这是另一种方法。

    我正在使用 library(geojsonsf) 将 GeoJSON 直接读入 sf 对象。从那里您可以按照任何data.frame 对其进行子集化(并使用library(sf) 对其进行其他空间操作)

    url <- "http://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_20m.json"
    
    ## use library(geojsonsf) to convert into an sf object
    sf <- geojsonsf::geojson_sf(url)
    
    library(dplyr)
    library(sf)
    
    sf %>%
        filter(NAME %in% c("Arizona", "Nevada", "New Mexico"))
    
    
    # Simple feature collection with 3 features and 5 fields
    # geometry type:  POLYGON
    # dimension:      XY
    # bbox:           xmin: -120.0057 ymin: 31.3323 xmax: -103.002 ymax: 42.00025
    # epsg (SRID):    4326
    # proj4string:    +proj=longlat +datum=WGS84 +no_defs
    # CENSUSAREA      GEO_ID LSAD       NAME STATE                       geometry
    # 1   113594.1 0400000US04         Arizona    04 POLYGON ((-112.5386 37.0006...
    # 2   121298.1 0400000US35      New Mexico    35 POLYGON ((-105.998 32.00233...
    # 3   109781.2 0400000US32          Nevada    32 POLYGON ((-114.0466 40.1169...
    

    【讨论】:

      【解决方案3】:

      不要放弃接受的答案,如果您想对 JSON 感到厌烦,就放弃一个选项。

      我在 dev 中有一个 pkg 尝试使用 jqr 包过滤原始 GeoJSON 本身(因此无需转换为 sp 对象并使用 subset

      devtools::install_github("ropenscilabs/geofilter")
      library(geofilter)
      library(leaflet)
      
      url <- "http://eric.clst.org/wupl/Stuff/gz_2010_us_040_00_20m.json"
      curl::curl_download(url, destfile = (f <- tempfile(fileext = ".json")))
      ariz <- sifter(readLines(f), NAME == Arizona)
      
      leaflet() %>%
        addTiles() %>%
        addGeoJSON(ariz) %>%
        setView(-112, 34, zoom = 7) 
      

      目前无法同时进行很多匹配(例如,NAME %in% c(Arizona, Nevada, New Mexico)

      【讨论】:

        猜你喜欢
        • 2015-01-20
        • 1970-01-01
        • 1970-01-01
        • 2014-11-21
        • 2018-04-13
        • 1970-01-01
        • 2018-07-28
        • 2018-11-24
        • 1970-01-01
        相关资源
        最近更新 更多