问题
I am not sure why but I cant read shapefiles at all in r!
On a MacOS Mojave,
I have tried:
afg <- readOGR("afg.shp")
afg <- readOGR(dsn = ".", layer = "afg")
The shapefiles are from this website: http://www.diva-gis.org/gdata, Afghanistan roads.
This same error keeps occuring:
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, :
Cannot open layer
However, this code works:
countries <- readOGR("countries.geojson")
Can someone figure out why?
回答1:
I'm on Mojave and this works fine:
httr::GET(
url = "http://biogeo.ucdavis.edu/data/diva/rds/AFG_rds.zip",
httr::write_disk("AFG_rds.zip"),
httr::progress()
) -> res
fils <- unzip("AFG_rds.zip", exdir = "afg-roads")
fils
## [1] "afg-roads/AFG_roads.dbf" "afg-roads/AFG_roads.prj"
## [3] "afg-roads/AFG_roads.shp" "afg-roads/AFG_roads.shx"
rgdal::readOGR("afg-roads/AFG_roads.shp")
## OGR data source with driver: ESRI Shapefile
## Source: "/Users/bob/Development/afg-roads/AFG_roads.shp", layer: "AFG_roads"
## with 1409 features
## It has 5 fields
## class : SpatialLinesDataFrame
## features : 1409
## extent : 60.6075, 74.67168, 29.38582, 38.48983 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
## variables : 5
## names : MED_DESCRI, RTT_DESCRI, F_CODE_DES, ISO, ISOCOUNTRY
## min values : Unknown, Primary Route, Road, AFG, AFGHANISTAN
## max values : Without Median, Unknown, Trail, AFG, AFGHANISTAN
回答2:
I faced the same problem too. Don't try renaming the file. After unzipping, you will get a number of files, one of which will be a shapefile. In my case, all those files had the same name but different extensions. Then just do what you were already doing:
afg <- readOGR(dsn = ".", layer = "AFG_roads")
Hopefully this will work.
来源:https://stackoverflow.com/questions/53472453/cannot-open-shapefile-in-r