readOGR() cannot open file - r

wmap <- readOGR(dsn="~/R/funwithR/data/ne_110m_land", layer="ne_110m_land")
This code is not loading the shape file and error is generated as
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, :
Cannot open file
I am sure that the directory is correct one. At the end / is also not there and layer name is also correct.
Inside the ne_110m_land directory files I have are:
ne_110m_land.dbf
ne_110m_land.prj
ne_110m_land.shp
ne_110m_land.shx
ne_110m_land.VERSION.txt
ne_110m_land.README.html

You could have shown that you have the right path with:
list.files('~/R/funwithR/data/ne_110m_land', pattern='\\.shp$')
file.exists('~/R/funwithR/data/ne_110m_land/ne_110m_land.shp')
perhaps try:
readOGR(dsn=path.expand("~/R/funwithR/data/ne_110m_land"), layer="ne_110m_land")
or a simpler alternative that is wrapped around that:
library(raster)
s <- shapefile("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp")
Update:
rgdal has changed a bit and you do not need to separate the path and layer anymore (at least for some formats). So you can do
x <- readOGR("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp")
(perhaps still using path.expand)
Also, if you are still using readOGR you are a bit behind the times. It is better to use terra::vect or sf::st_read.

I had the same error. To read in a shapefile, you need to have three files in your folder: the .shp, .dbf and .shx files.

For me, the command returned the Cannot open layer error when I included the dsn and layer tags.
So when I included it all just as
readOGR('~/R/funwithR/data/ne_110m_land/ne_110m_land.shp')
it worked.
Note that my file was a gjson, so I've only seen this with
readOGR('~/R/funwithR/data/ne_110m_land/ne_110m_land.gjson')

the Mandatory files should be all in the same directory
.shp — shape format
.shx — shape index format;
.dbf — attribute format;
then we can just give the path as a parameter to the function it will work.
global_24h =readOGR( '/Users/m-store/Desktop/R_Programing/global_24h.shp')

Here's what worked for me (with a real example)
require(rgdal)
shape <- readOGR(dsn = "1259030001_ste11aaust_shape/STE11aAust.shp", layer = "STE11aAust")
The exact data is available here (download the .zip file called 'State and Territory ASGC Ed 2011 Digital Boundaries in MapInfo Interchange Format')

the syntax: library(raster)
s <- shapefile("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp") worked perfectly! todah rabah!

As I commented in other post (Error when opening shapefile), using file.choose() and selecting manually will help in the case one file selection is needed. Apparently is related with NaturalEarth shapefiles

it seems to me that this is the solution, at least before uploading it to the cloud
######################################
# Server
######################################
#I tell R where to extract the data from
#Le digo al R donde debe jalar la data
dirmapas <- "E:/Tu-carpeta/Tu-sub-carpeta/ESRI" #Depende donde tengas tú tus
#archivos de cartografía
setwd(dirmapas)
#The raw map
# El mapa de polígonos en blanco y negro
departamentos<-readOGR(dsn="BAS_LIM_DEPARTAMENTO.shp", layer="BAS_LIM_DEPARTAMENTO")

Related

How to edit cells Shapefile in R?

I downloaded a shapefile of the world map from gadm, however, there are typos that happen with importing the shape file. For example "Aland" shows up as "Ã…land" in the shapefile. There are handful of countries I want to make changes to.
world map shapefile, the one that says "You can also download this version as six separate layers (one for each level of subdivision/aggregation), as a geopackage database or as shapefiles" :https://gadm.org/download_world.html
I imported the shapefile using:
worldmap <- readOGR("file/gadm36_0.shp")
I tried using the following code:
levels(wordlmap$NAME_0)[5] <- "Aland"
However I got this message:
Error in `levels<-`(`*tmp*`, value = c(NA, NA, NA, NA, "Aland")) :
factor level [2] is duplicated
Could you suggest how this code can be made better or an alternative.Thanks in advance
Since you did not provide a shapefile, I just worked with a publicly-available shapefile of Indian states. The long and short of it is to use the sf package. It loads shapefiles as (quasi) dataframes--with the longitudes and latitudes stored in the geometry variable. Then, you should be in familiar territory. Here is some code to change a state name variable:
# clear environment
rm(list=ls(all=TRUE))
# let's take admin 1 (states)
# note: already in WGS84 format
library(sf)
india_shape <- st_read("india_shape/gadm36_IND_1.shp", stringsAsFactors=FALSE)
# Let's pick something to change (state name)
> india_shape$NAME_1[1]
[1] "Andaman and Nicobar"
# Now change it
> india_shape$NAME_1[1] <- "New State Name"
> india_shape$NAME_1[1]
[1] "New State Name"
I can tell you a few things about how I manage those shape files downloaded from, www.gadm.org site.
First, a shape file has several other related files that do not have the .shp extension. These files must remain together in the same folder. All these files are included in the shape zip file from the gadm website.
The rgdal package provides the, readOGR() function. This function is normally in the form: readOGR(dsn = " ", layer = " " )
The, dsn is "data source name". Use quotes.
The, layer is the name of shape file without the .shp extension. Use quotes.
Proper file management is required to make things work and to maintain good file management. I already have a USA folder within my dataset folder.
I just downloaded the gadm USA shape file. So first, I will add a new folder, named USA_map, in the USA folder. And also create a new folder named, data in this new USA_map folder.
C:/python/datasets/usa/usa_map/data # usa_map/data are new
Copy the downloaded gadm36_USA_shp.zip from the "download" folder and paste into the new "USA_map" folder. Then, open the GADM zip folder and extract the entire contents of the zip folder into the new "data" folder. Then the zip file can new be deleted because all the files have been copied into the "data" folder. All's done and ready.
Now use the readOGR() function to read the shape file and assign to new variable, called usmap
usmap <- readOGR(dsn = "c:/python/datasets/USA/USA_map/data", layer = "gadm36_USA_1")
The trick is to follow the correct file management so the readOGR() function works as designed.
Next, you need to learn how to navigate through this type of data.
If there is more than one polygon with the same wrong name, you can make like that :
w <- length(wordlmap)
for (i in 1:w){
if (wordlmap$NAME_0[i] == "Ã…land") {
wordlmap$NAME_0[i] <- "Aland"
}}

How to save a shapefile after transform the crs from the existing shapefile in R?

I am trying with this code but it is not working. Please help me with this issue. Thank you.
readshp <- readOGR(file.path(nhgisdir, “file1.shp”))`enter code here`
trshape <- spTransform(readshp, "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0”)
writeOGR(trshape, file.path(workdir,”file1_tr.shp"), driver="ESRI Shapefile”) # This one goes wrong!!
Make sure you specify all required arguments of the functions you are using to make them work. Also make sure you use only one type of quotation marks to open and close your strings. Your question uses two different types ” and ", which probably causes errors since r does not know where your commands start and end.
Now the functions to read shapefiles readOGR needs some arguments specified: That is dsn, the directory of your shapefiles and layer, the actual shapefile but without a file extension. The function writeOGR works similarly, but has different behaviour depending on the driver you use. For ESRI Shapefile, the argument dsn needs to be the filename you want to save your shapefile as including an extension. And layer will be the filename without an extension.
All of this info, and which type of arguments need to be specified for which driver, is in the documentation of rgdal. And there are numerous tutorials out there, e.g. this one by Dr. Emily Burchfield
Finally, here is some example code:
library(rgdal)
in_shape <- readOGR(dsn="/path/to/shape/", layer="shapefile")
transformed_shape <- spTransform(in_shape, CRS("+proj=longlat +ellps=GRS80"))
writeOGR(transformed_shape, dsn="/path/to/shape/exported_shapefile.shp", layer="exported_shapefile", driver="ESRI Shapefile")

SHP file reading getting error in R

Hi I am trying to read and plot on a custom shape file in R which is not a map.
This is the code I use and the error I get in return:
library(rgdal)
mySHP<- choose.files()
myFile<- readOGR(mySHP)
Error in ogrListLayers(dsn = dsn) : Cannot open data source
If your file is a shapefile, you need to specify the dsn which is the directory where is saved the shapefile and layer which is the name of the shapefile without the extension. You cannot really do it with choose.files. At least not that simply.
myFile <- readOGR(dsn='path.to.folder', layer='nameOfShapefile')

Using shapefile as an input to the user defined function using R

I have a script to create a randomly distributed square polygons in KML format which takes in shapefile with a single polygon as an input which works absolutely well. The problem arise when I tried to create the user defined function out of it. I used readShapePoly() function to read the shapefile and it works well when used out of the function. But when the function is created in which shapefile should be given as an input, it simply wont take. It shows this error message
Error in getinfo.shape(filen) : Error opening SHP file
I avoid writing extensions and I do have all the extension files to create the shapefile.
Part of the script to read the shapefile using it as the input file:
library(maptools)
library(sp)
library(ggplot2)
Polytokml <- function(shapefile_name){
###Input Files
file1 <- "shapefile_name"
Shape_file <- readShapePoly(file1) #requires maptools
return(Shape_file)
}
The function is created but it doesn't work if the function is called.
>Polytokml(HKH.shp)
Error in getinfo.shape(filen) : Error opening SHP file
This works well out of the function.
###Input Files
file1 <- "shapefile.shp"
Shape_file <- readShapePoly(file1) #requires maptools
This is just an example out of the whole script in which different arguments are taken as an input. So just to make things simple I have added script to read the shapefile which has been a problem now. Do let me know if it is not clear.
Thank you so much in advance :)

Creating Shapefiles in R

I'm trying to create a shapefile in R that I will later import to either Fusion Table or some other GIS application.
To start,I imported a blank shapefile containing all the census tracts in Canada. I have attached other data (in tabular format) to the shapefile based on the unique ID of the CTs, and I have mapped my results. At the moment, I only need the ones in Vancouver and I would like to export a shapefile that contains only the Vancouver CTs as well as my newly attached attribute data.
Here is my code (some parts omitted due to privacy reasons):
shape <- readShapePoly('C:/TEST/blank_ct.shp') #Load blank shapefile
shape#data = data.frame(shape#data, data2[match(shape#data$CTUID, data2$CTUID),]) #data2 is my created attributes that I'm attaching to blank file
shape1 <-shape[shape$CMAUID == 933,] #selecting the Vancouver CTs
I've seen other examples using this: writePolyShape to create the shapefile. I tried it, and it worked to an extent. It created the .shp, .dbf, and .shx files. I'm missing the .prj file and I'm not sure how to go about creating it. Are there better methods out there for creating shapefiles?
Any help on this matter would be greatly appreciated.
Use rgdal and writeOGR. rgdal will preserve the projection information
something like
library(rdgal)
shape <- readOGR(dsn = 'C:/TEST', layer = 'blank_ct')
# do your processing
shape#data = data.frame(shape#data, data2[match(shape#data$CTUID, data2$CTUID),]) #data2 is my created attributes that I'm attaching to blank file
shape1 <-shape[shape$CMAUID == 933,]
writeOGR(shape1, dsn = 'C:/TEST', layer ='newstuff', driver = 'ESRI Shapefile')
Note that the dsn is the folder containing the .shp file, and the layer is the name of the shapefile without the .shp extension. It will read (readOGR) and write (writeOGR) all the component files (.dbf, .shp, .prj etc)
Problem solved! Thank you again for those who help!
Here is what I ended up doing:
As Mnel wrote, this line will create the shapefile.
writeOGR(shape1, dsn = 'C:/TEST', layer ='newstuff', driver = 'ESRI Shapefile')
However, when I ran this line, it came back with this error:
Can't convert columns of class: AsIs; column names: ct2,mprop,mlot,mliv
This is because my attribute data was not numeric, but were characters. Luckily, my attribute data is all numbers so I ran transform() to fix this problem.
shape2 <-shape1
shape2#data <- transform(shape1#data, ct2 = as.numeric(ct2),
mprop = as.numeric(mprop),
mlot = as.numeric(mlot),
mliv = as.numeric(mliv))
I tried the writeOGR() command again, but I still didn't get the .prj file that I was looking for. The problem was I didn't specified the coordinate systems for the shapefile when I was importing the file. Since I already know what the coordinate system is, all I had to do was define it when importing.
readShapePoly('C:/TEST/blank_ct.shp',proj4string=CRS("+proj=longlat +datum=WGS84")
After that, I re-ran all the things I wanted to do with the shapefile, and the writeOGR line for exporting. And that's it!

Resources