Search code examples
rgeojsonterra

save geojson as shapefile in R


I read the file from this link in R (Microsoft Office building footprint)

https://minedbuildings.blob.core.windows.net/global-buildings/2023-06-27/global-buildings.geojsonl/RegionName%3DNetherlands/quadkey%3D120200313/part-00138-7b73ad6b-e7c8-4e22-9fa2-01d140ca911d.c000.csv.gz

After unzipping the file, I get a csv which I convert into geojson. How do I save it as a shapefile either using sf or terra

library(R.utils)
library(terra)
library(sf)
library(geojson)


file_name <- "part-00138-7b73ad6b-e7c8-4e22-9fa2-01d140ca911d.c000.csv.gz"
R.utils::gunzip(file_name))

readLines(file_name) %>% 
 paste(collapse = ", ") %>%
 {paste0('{"type": "FeatureCollection",
         "features": [', ., "]}")} -> j

x <- to_geojson(j)
class(x)

"geofeaturecollection" "geojson"

sf::st_write(x, dsn = getwd(), "temp.shp")
Error in UseMethod("st_write") : 
 no applicable method for 'st_write' applied to an object of class "c('geofeaturecollection', 'geojson')"

terra::writeVector(x, 'temp.shp')
unable to find an inherited method for function ‘writeVector’ for signature ‘"geofeaturecollection", "character"’

Solution

  • The first argument for sf::st_read() is dsn (data source name). The docs state:

    interpretation varies by driver - for some drivers dsn is a file name, but may also be a folder, or contain the name and access credentials of a database); in case of GeoJSON, dsn may be the character string holding the geojson data.

    So you can just provide your character string. Here's a simpler, complete example with no unzipping:

    # Read some sample geojson data
    x <- readLines("https://dataworks.calderdale.gov.uk/download/24mx6/94l/VenuesNov2022.geojson")
    
    dat <- sf::st_read(x)
    #   using driver `GeoJSON'
    # Simple feature collection with 13 features and 9 fields
    # Geometry type: POINT
    # Dimension:     XY
    # Bounding box:  xmin: -2.098113 ymin: 53.70398 xmax: -1.786043 ymax: 53.74124
    # Geodetic CRS:  WGS 84
    
    sf::st_write(dat, "tmp.shp", append = FALSE)
    

    Or in your case:

    dat  <- sf::st_read(j)
    sf::st_write(dat, "tmp.shp", append = FALSE)