9

I just started to use R a day ago and I'm trying to read a geojson file using the SF library, but I'm not sure what the correct way is.

library(dplyr)
library(sf)
geo <- system.file('/my/path/zones.geojson', package = 'sf')
st_read(geo)

When I run these lines of code, I get the error message:

Cannot open data source
Error in CPL_read_ogr(dsn, layer, as.character(options), quiet, type,  :
  Open failed.

Please let me know how I change it, thank you all!

code_learner93
  • 571
  • 5
  • 12

1 Answers1

5

The sf package cannot read geojson natively. However, there is a package called geojsonsf that reads geojson into data that you can work with in sf.

Obviously I don't have your geojson file to work with, but the package itself comes with some sample data so that I can show you the principle:

install.packages("geojsonsf")
library(geojsonsf)
library(ggplot2)

geo <- geojson_sf("C:/R/R-3.6.2/library/geojsonsf/examples/geo_melbourne.geojson")

ggplot(geo) + geom_sf(aes(fill = SA2_NAME)) + guides(fill = guide_none())

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • 6
    I don't know if this has changed since you wrote your answer, but `sf` can read geojson directly: `sf::st_read( geojsonsf::geo_melbourne )` (but `geojsonsf` still benchmarks faster) – SymbolixAU Mar 09 '21 at 04:52