how to read .shp files in R Tool - r

link for the .shp file dataset
I want to read a .shp file from R tool, am using the following script:
>scot_LL<-readOGR("C:/Documents and Settings/Admin/Desktop/scotlip/lip cancer/New Scot/scot.shp","scot"),
but when I run the script, am getting the below errors:
>Error in file(paste(DSN, .Platform$file.sep, layer, ".dbf", sep = ""), <br/>:
cannot open the connection<br/>:
In addition: Warning message:<br/>:
In file(paste(DSN, .Platform$file.sep, layer, ".dbf", sep = ""), :<br/>:
cannot open file 'C:/Documents and Settings/Admin/Desktop/scotlip/lip cancer/New Scot/scot.dbf': No such file or directory
Can you please help me.

Here is a solution using the maptools package:
library(maptools)
scot_mp <- readShapeSpatial('C:/Documents and Settings/Admin/Desktop/scotlip/lip cancer/New Scot/scot.shp')
proj4string(scot_mp) <- "+proj=longlat +datum=WGS84" # specify projection
plot(scot_mp)
and the result:
EDIT:
Solution using the rgdal package:
scot_mp <- readOGR('C:/Documents and Settings/Admin/Desktop/scotlip/lip cancer/New Scot', 'scot')
The first argument should not necessary contain the name of shape file, but the main problem seems to be that at least the dbf file is not in your folder, all of these are needed and should be in the same folder: scot.shp, scot.dbf, scot.shx. After that it proceeds as the other solution:
proj4string(scot_mp) <- "+proj=longlat +datum=WGS84"
plot(scot_mp)

Related

Error in reading shapefile in R

When I try to read shapefiles in a loop in R, it always reports
"Error in .local(x, ...) : file.exists(extension(x, ".shp")) is not
TRUE " .
The code that I use to read the shapefile is
"city.i=shapefile(citynames1[i]) "
where citynames1 is a vector of shapefile names with the extension of .shp.
Thanks very much for your help.
The problem is connected with locale setting on your PC. In my case sf package were able to write files with Chinese characters, please see the code below:
# simulation
library(sf)
file_name <- system.file("shape/nc.shp", package="sf")
nc <- st_read(file_name)
# write shape
st_write(nc, "你好.shp")
# clear & read
rm(list = ls())
nc <- st_read("你好.shp")
plot(nc)
Output:

Error opening .nc files in R

I am new to R and NetCDF files. I am trying to open data on surface sea temperatures that are in a .nc file from here. My code is as follows:
rm(list=ls())
#install.packages(c("netcdf", "chron", "RColorBrewer", "lattice"))
library(chron)
library(RColorBrewer)
library(lattice)
library(ncdf4)
# set path and filename
ncpath <- "C:/Users/Mihir Sharma/Dropbox/data/"
ncname <- "20140101023458-NCEI-L3C_GHRSST-SSTskin-AVHRR_Pathfinder-PFV5.3_NOAA19_G_2014001_night-v02.0-fv01.0"
ncfname <- paste(ncpath, ncname, ".nc", sep="")
dname <- "tmp" # note: tmp means temperature (not temporary)
# open a NetCDF file
ncin <- nc_open(ncfname)
But I am getting the following error:
Error in nc_open(ncfname) :
Error in nc_open trying to open file C:/Users/Mihir Sharma/Dropbox/1 EPIC/MPA/data/20140101023458-NCEI-L3C_GHRSST-SSTskin-AVHRR_Pathfinder-PFV5.3_NOAA19_G_2014001_night-v02.0-fv01.0.nc
I have followed the code from here and here. what am I doing wrong?
Many thanks,
Mihir
Path problems when using someone else's code:
# set path and filename
ncpath <- "C:/Users/Mihir Sharma/Dropbox/data/"
When you're following code on a blog or tutorial, if it's written well, they'll use a platform independent way to describe, but often they won't.
The platform independent way to write a path is:
file.path("Users", "Mihir Sharma", "Dropbox", "data"). This will always use the correct file separator for your Platform, a value stored in .Platform$file.sep

Reading geojson file in R

I have converted .shp file into geojson file using rgdal, httr, leafletR packages
file <- "province" # shp file name
arg_file <- readOGR(dsn = ".", "province") # destination require . to load from current directory
q.dat <- toGeoJSON(data = arg_file, name = "argentina")
Now I have an argentina.geojson file
How can I read the geojson file directly next time without converting the .shp file to geojson again as it is taking a lot of time.
Thanks in advance

Using R to download zipped data file, extract, and import .csv

I am trying to download and extract a .csv file from a webpage using R.
This question is a duplicate of Using R to download zipped data file, extract, and import data.
I cannot get the solution to work, but it may be due to the web address i am using.
I am trying to download the .csv files from http://data.worldbank.org/country/united-kingdom (under the download data drop down)
Using #Dirk's solution from the link above, i tried
temp <- tempfile()
download.file("http://api.worldbank.org/v2/en/country/gbr?downloadformat=csv",temp)
con <- unz(temp, "gbr_Country_en_csv_v2.csv")
dat <- read.table(con, header=T, skip=2)
unlink(temp)
I got the extended link by looking at the page source code, which I expect is causing the problems, although it works if i paste it into the address bar.
The file downloads with the correct Gb
download.file("http://api.worldbank.org/v2/en/country/gbr?downloadformat=csv",temp)
# trying URL 'http://api.worldbank.org/v2/en/country/gbr?downloadformat=csv'
# Content type 'application/zip' length 332358 bytes (324 Kb)
# opened URL
# downloaded 324 Kb
# also tried unzip but get this warning
con <- unzip(temp, "gbr_Country_en_csv_v2.csv")
# Warning message:
# In unzip(temp, "gbr_Country_en_csv_v2.csv") :
# requested file not found in the zip file
But these are the file names when i manually download them.
I'd appreciate some help with where i am going wrong , thanks
I am using Windows 8, R version 3.1.0
In order to get your data to download and uncompress, you need to set mode="wb"
download.file("...",temp, mode="wb")
unzip(temp, "gbr_Country_en_csv_v2.csv")
dd <- read.table("gbr_Country_en_csv_v2.csv", sep=",",skip=2, header=T)
It looks like the default is "w" which assumes a text files. If it was a plain csv file this would be fine. But since it's compressed, it's a binary file, hence the "wb". Without the "wb" part, you can't open the zip at all.
It's almost everything ok. In this case you only need to specify that it's a comma separated file, eg using sep="," in read.table:
temp <- tempfile()
download.file("http://api.worldbank.org/v2/en/country/gbr?downloadformat=csv",
temp)
con <- unz(temp, "gbr_Country_en_csv_v2.csv")
dat <- read.table(con, header=T, skip=2, sep=",")
unlink(temp)
With this little change i can import your csv smoothly.
HTH, Luca
The Word Bank Developmet Indictors can be obtained using the WDI package. For example,
library(WDI)
inds <- WDIsearch(field = "indicator")[, 1]
GB <- WDI("GB", indicator = inds)
See WDIsearch and WDI functions and the rerference manual for more info.

Read shape file with readOGR verses readShapePoly

I have read a shapefile using readShapePoly in the maptools package, but cannot read that same file with readOGR. I am hoping someone may be able to help me read the shapefile with readOGR.
I downloaded the file orcounty.shp from here: http://geography.uoregon.edu/geogr/topics/maps.htm
I also downloaded the associated files: orcounty.shx, orcounty.sbx, orcounty.sbn, and orcounty.dbf and put all five files in the folder: c:/users/mark w miller/gis_in_R/shapefile_example/
The following code reads the shapefile and displays some attributes:
library(maptools)
setwd('c:/users/mark w miller/gis_in_R/shapefile_example/')
# Oregon county census data (polygons)
orcounty.poly <- readShapePoly('orcounty.shp', proj4string=CRS("+proj=longlat"))
orcounty.line <- readShapeLines('orcounty.shp', proj4string=CRS("+proj=longlat"))
# see projection
summary(orcounty.poly)
Object of class SpatialPolygonsDataFrame
Coordinates:
min max
x -124.55840 -116.46944
y 41.98779 46.23626
Is projected: FALSE
proj4string : [+proj=longlat]
Data attributes:
However, when I try to read that same shapefile using the following code I receive an error:
library(rgdal)
# read shapefile
oregon.map <- readOGR(dsn="c:/users/mark w miller/gis_in_R/shapefile_example/", layer="orcounty")
# convert to dataframe
oregon.map_df <- fortify(oregon.map)
The error message says:
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv) :
Cannot open file
I can read Natural Earth http://www.naturalearthdata.com/ shapefiles using:
library(rgdal)
setwd("c:/users/mark w miller/gis_in_R/")
# read shapefile
wmap <- readOGR(dsn="ne_110m_physical", layer="ne_110m_land")
So, apparently there is a difference between the Natural Earth shapefiles and the Oregon shapefile orcounty.shp.
Thank you for any advice on how to read orcounty.shp with readOGR. My question is similar to the question here: rgdal / readOGR - unable to read shapefile from .zip
Try to remove your last '/' from file path.
readOGR(dsn = 'c:/users/mark w miller/gis_in_R/shapefile_example',
layer = 'orcounty')
For anyone ending up here with this error on a Linux box, I found the problem was using a home path shortcut. i.e.
# Works
readOGR(dsn="/home/user/dir", layer="file")
# Doesn't work
readOGR(dsn="~/dir", layer="file")
I have no idea why.
I used the file ne_110m_land
Try with this:
setwd('D:/JMSR/codes.R/mapas')
unzip("ne_110m_land.zip")
ogrInfo(".", "ne_110m_land")
wmap <- readOGR(".", "ne_110m_land")
raster::shapefile wraps around readOGR to take care of paths and tildes; just pass the full file name.
library(raster)
x <- shapefile("c:/users/orcounty.shp')
or
y <- shapefile("~/users/orcounty.shp")

Resources