6

I have a geojson file of state boundaries that I obtained from here. In particular I'm using the 20m US States Data

I'm trying to subset the data so that I can use leaflet to map only certain states. I can subset a single state using:

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

This method does not seem to work for selecting multiple states though:

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

Selecting multiple states usually results in only one or two states being selected, or none at all. Is there a different method I can use to subset this data?

3 Answers 3

7

You need to use %in% rather than ==

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

Not to take away from the accepted answer, just throwing out an option if you want to get nerdy with JSON.

I have a pkg in dev that tries to help filter raw GeoJSON itself using jqr package (so no need to convert to a sp object and use 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) 

can't currently do many matches at the time (e.g., NAME %in% c(Arizona, Nevada, New Mexico))

3

Also not taking away from the accepted answer, but here is an alternative approach.

I'm using library(geojsonsf) to read the GeoJSON directly into an sf object. From there you can subset it as per any data.frame (and do other spatial operations on it using 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...

Not the answer you're looking for? Browse other questions tagged or ask your own question.