Subsetting geojson data with R

Viewed 1570

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

You need to use %in% rather than ==

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

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))

Related