I'm having issues filtering a large geojson file with R. If I just want to show the map for one country, I don't want the entire map of europe to be loaded which is huge. So I want to filter this dataset for example for Bulgaria -- CNTR_CODE == "BG"
but I can't manage.
Please find code to download below and an initial effort which doesn't result in the desired outcome
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'))
Thanks.
If you want a list, then Filter
could work:
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, "")
If you want to keep the data in geojson character format, you could use 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')