Search code examples
rshapefileqgis

error reading shapefile in R that works fine in QGIS


I'm getting an error reading this shape file in R using both readOGR and read_sf:

http://45.56.98.26/madrid-divisiones/Termino_1612.shp

readOGR error:

Warning in ogrFIDs(dsn = dsn, layer = layer) : no features found
Error in readOGR(dsn = "http://45.56.98.26/madrid-divisiones/Termino_1612.shp") : 
  no features found

read_sf error:

Warning in CPL_read_ogr(dsn, layer, query, as.character(options), quiet,  :
  GDAL Error 1: JSON parsing error: continue (at offset 0)

It opens fine in QGIS. I'm able to read other shapefiles fine with my R setup fine (generally using read_sf) and I've never seen this error before. This is the code I'm using:

madrid1612 <- read_sf("http://45.56.98.26/madrid-divisiones/Termino_1612.shp",quiet=TRUE,as_tibble = FALSE,stringsAsFactors = TRUE)

madrid1612 <- readOGR(dsn="http://45.56.98.26/madrid-divisiones/Termino_1612.shp")

I've looked at all the "error reading a shapefile in R" questions, but can't find anything that sorts my issue out. I tried opening it up in QGIS and exporting as a geojson file and I got this error:

madrid1612<-fromJSON(txt ="http://45.56.98.26/madrid-divisiones/Termino_1612.geojson")

Warning: Error in polygonData.default: Don't know how to get path data from object of class list


EDIT WITH SOLUTION: The problem turned out to be an issue with inconsistent projection data in the file. QGIS could handle it, but R couldn't. I was able to fix this by using st_transform to make it consistent:

madrid1970 <- read_sf("./Termino_1970.shp") %>% st_transform(4326)

Solution

  • With your code directly linking to the single .shp file, R {sf} cannot tell where the required files (.shx, .dbf, .prj) are located.

    You can download these files to local disk:

    library(sf)
    
    library(downloader)
    
    loc = "http://45.56.98.26/madrid-divisiones/"
    shape_name = "Termino_1612"
    ext_name = c(".shp", ".shx", ".dbf", ".prj")
    
    i=1
    for (i in 1:4){
      download(paste0(loc, shape_name, ext_name[i]), 
               destfile= paste0("./", shape_name, ext_name[i]), mode = "wb")
      i = i +1
    } 
    
    madrid1612 <- read_sf("./Termino_1612.shp")
    plot(madrid1612) 
    

    If you need to download it directly, choose geojson.

    madrid1612 <- read_sf("http://45.56.98.26/madrid-divisiones/Termino_1612.geojson")
    plot(madrid1612)