Errors working through plotting shapefiles in the ggplot wiki - r

I'm trying to learn how to plot shapefiles with ggplot2 and I found a wiki at:
https://github.com/hadley/ggplot2/wiki/plotting-polygon-shapefiles
I downloaded and extracted the zip file provided into new directory on my desktop ( http://www.epa.gov/nheerl/arm/documents/design_doc/ecoregion_design.zip ).
I started reading through the article, going line by line but I'm running into a problem with fortify.
require("rgdal")
require("maptools")
require("ggplot2")
require("plyr")
> my_dsn <- "directory here"
>
> utah = readOGR(dsn=my_dsn, layer="eco_l3_ut")
OGR data source with driver: ESRI Shapefile
Source: "directory here", layer: "eco_l3_ut"
with 10 features and 7 fields
Feature type: wkbPolygon with 2 dimensions
> utah#data$id = rownames(utah#data)
> utah.points = fortify(utah, region="id")
Error: isTRUE(gpclibPermitStatus()) is not TRUE
I looked at the ?fortify help page and get the jist of how it should be used. I think its being used correctly. I also found another question with the same error on SO,
Getting error while using fortify function in R (ggplot)
but I can't figure out how to apply what is being said for my solution. I might help if I had access to dropbox right now but I don't.

The short answer is to install the rgeos package and include it at the top.
A longer answer can be found here (and elsewhere): https://stat.ethz.ch/pipermail/r-sig-geo/2012-July/015685.html

Related

R read and plot gdbtable

I'm very new to gbd table and today at work I was asked to use R to read the data available on https://frap.fire.ca.gov/media/9792/fthrt14_2.zip and plot it using R tools like ggplot and plot_ly.
My problem is that I don't even understand how to read this data with R.
These are the stackoverflow questions I read so far:
- rgdal - read a table within a ESRI geodatabase (gdb)
- How to read a table from an ESRI file geodatabase (.gdb) using R
- How do I get rgdal to open a geodatabase (.gdb) file?
however none of them seems to be working.
These are my steps:
- I unzipped the file in my C:\temp folder. This means I have an R variable file_gdb = "C:/temp/fthrt14_2.gdb"
- then, I have fc_list = ogrListLayers(file_gdb ) and if I print its content I see:
character(0)
attr(,"driver")
[1] "OpenFileGDB"
attr(,"nlayers")
[1] 0
at this point I try fc = readOGR(dsn=fgdb,layer="OpenFileGDB") but I get the following error:
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv
Cannot open layer
and from here I'm quite lost.
Any help would be much appreciated. Many thanks from a complete newbie.

Cannot load a shapefile in R "Error: no features found"

I'm trying to read the shapefile that you can download with this url.
I have a code similar to the next one to download automatically the files:
library("raster")}
url<-"http://www6.gipuzkoa.eus/CATASTRO/Planos/ZIP-A098.zip"
downloader::download(url, dest=paste0(getwd(),"/","my_file.zip"), mode="wb",quiet=T)
zipped_shape_names<-c("098_HELBIDE_SHP/ATRIBUTOAK-A098.cpg","098_HELBIDE_SHP/ATRIBUTOAK-A098.dbf","098_HELBIDE_SHP/ATRIBUTOAK-A098.shp","098_HELBIDE_SHP/ATRIBUTOAK-A098.shx")
unzip("my_file.zip", files=zipped_shape_names)
my_shape<-raster::shapefile("098_HELBIDE_SHP/ATRIBUTOAK-A098.shp")
But what I obtain is the following error:
Error in rgdal::readOGR(dirname(x), fn, stringsAsFactors = stringsAsFactors, :
no features found
In addition: Warning messages:
1: In .local(x, ...) : .prj file is missing
2: In ogrFIDs(dsn = dsn, layer = layer) : no features found
You can access to the original web page by this link and pressing "Descargar planos"
I don't have this problem with others areas, just with this and another one, but I don't know what is happening with this specific area.
Any help will be appreciated.
The error message is quite clear. no features found means that your shapefile is empty. You can check this in multiple ways.
One is to add your shapefile in Q-Gis or any other GIS-software tool. In the case of Q-GIS your shapefile will pop-up in the layers pane, but you won't see any features.
It is also possible to check the .dbf file in R:
library(foreign)
read.dbf("098_HELBIDE_SHP/ATRIBUTOAK-A098.dbf")
The .dbf should contain as many rows as there are features. In your case None.
Simpler code would be
library(raster)
url<-"http://www6.gipuzkoa.eus/CATASTRO/Planos/ZIP-A098.zip"
download.file(url, dest="my_file.zip")
unzip("my_file.zip")
s <- raster::shapefile("098_HELBIDE_SHP/ATRIBUTOAK-A098.shp")
Clearly that file is empty. However, it works for this file:
s <-raster::shapefile("098_LANDALUR_SHP/LANDALUR-PARTZELAK-A098.shp")

"Error opening SHP file" when loading from package data

I want to shift some of my most commonly used shapefiles to github. I have a new package in development. It worked when built in RStudio, but when I pull the package from github and run it I get the error "Error in getinfo.shape(filen) : Error opening SHP file". When I look inside the package the shapefiles are in place in the data folder. They're being called by individual functions, e.g.
load_lon = function(){
require(maptools)
lon <<- readShapePoly('data/london_outline_simple.shp', proj4string=CRS('+init=epsg:27700'))
}
Presumably this method means R is wrongly looking for subfolder 'data' in the working directory. But I can't think how else to call them, as data() doesn't support shp. Grateful for advice how to load them in.
In line with #josh-obrien's comment, the answer is to put data files in a subfolder of inst, whereupon they'll be compiled with the code when the package is built. I've put the shapefiles in:
$SOURCEDIR/inst/external/
These are installed via functions such as:
load_lon = function(){
require(maptools)
path = system.file("external/london_outline_simple.shp", package="londonShapefiles")
lon <<- readShapePoly(path, proj4string=CRS('+init=epsg:27700'))
}
Check out the working github package for full working example.

I am trying to make an interactive map using leafletR package according to a ZevRoss blog. But there is an error in the code

The ZevRoss blog is as follow:
http://zevross.com/blog/2014/04/11/using-r-to-quickly-create-an-interactive-online-map-using-the-leafletr-package/
The code with error is:
# ----- Write data to GeoJSON
leafdat<-paste(downloaddir, "/", filename, ".geojson", sep="")
writeOGR(subdat, leafdat, layer="", driver="GeoJSON")
And the error is:
Error in writeOGR(subdat, leafdat, layer = "", driver = "GeoJSON") :
GDAL Error 3: Cannot open file 'd:/Leaflet/County_2010Census_DP1.geojson'
Because I am a freshman in R, I searched for this problem a lot and didn't get any good answer.
I am using Rstudio R version 3.1.1(2014-07-10) on windows 7 32bit.
My rgdal version is 0.9-1.
The other code in the blog runs successfully, this sentence seems to be the only difficult point.
You could create GeoJSON using leafletR package:
library('leafletR')
Your_GeoJSON <- toGeoJSON(data=YourData, dest=getwd())
I've tried to find a solution for this mysterious error for some time.
Eventually I found this post on the Gdal package errors' tickets site that clarified the problem and gave a solution.
Basically the problem is in the interface between rgdal and Gdal (Gdal changed their way to work and the latest version of rgdal hasn't watched up yet):
writeOGR() calls ogrCheckExists("foo.geojson") to check first if the file exists before creating a new dataset.
In the 1.11 version the OGR GeoJSON driver will emit an error message that this file doesn't exists, whereas previous version didn't emit an error message.
rgdal catches this error as a fatal one and doesn't go to the writing step. This should be fixed in rgdal.
Meanwhile you have an easy workaround : add check_exists = FALSE as a parameter to writeOGR()
Therefore the following code will work:
writeOGR(spDf,'foo.geojson','spDf', driver='GeoJSON',check_exists = FALSE)
Of course if there is already a geojson file with the chosen name at the location writeOGR still fails.
Even though you already have a 'd:' drive on your computer and you have permission to write to that drive, try the following:
--------------------------------
leafdat<-paste(downloaddir, "/", ".geojson", sep="")
> leafdat
> "d:/Leaflet/.geojson"
writeOGR(subdat, leafdat, layer="", driver="GeoJSON")
--------------------------------
Then you may get ".geojson" file on "d:/Leaflet". Change the file name ".geojson" to "County_2010Census_DP1.geojson".

Using SRTM tif file in R

I'm trying to import a SRTM dataset into R. I've downloaded the data in a tif file however am having trouble reading it in "R".
Ive tried using the following code:
t = readTIFF("srtm_56_06/srtm_56_06.tif", as.is=TRUE)
load('srtm_56_06/srtm_56_06.tif')
read_file<-as.matrix(raster("srtm_56_06/srtm_56_06.tif")
However I am still getting error messages:
load('srtm_56_06/srtm_56_06.tif')
# Error: bad restore file magic number (file may be corrupted) -- no data loaded
# In addition: Warning message:
# file ‘srtm_56_06.tif’ has magic number 'II*'
# Use of save versions prior to 2 is deprecated
library(raster)
t = readTIFF("srtm_56_06/srtm_56_06.tif", as.is=TRUE)
# Error: could not find function "readTIFF"
read_file<-as.matrix(raster("srtm_56_06/srtm_56_06.tif") + min(read_file)
# Error: unexpected symbol in:
# "read_file<-as.matrix(raster("srtm_56_06/srtm_56_06.tif")
# min"
Can anyone help me with the commands to import this data. I'm a novice at "R" and a little lost.
Just read it with raster, but note you depend on rgdal being installed as well to read a .tif.
library(raster)
library(rgdal)
r <- raster("srtm_56_06/srtm_56_06.tif")
If that works, try
plot(r)
r
If it's really a "TIFF" then that should be fine, if it's really a GeoTIFF then you'll have a sensible map as well. (If it's something else that GDAL can read you might get a good result anyway, remember the extension of a file is not a reliable indicator of its contents).
The SRTM clue suggests that this is a single band DEM file from the tiled global SRTM data set. If it's somehow a "multi-band image" then you could read that with brick and plot with plotRGB (but I really doubt that is the case here). Note that there is a native binary format for SRTM that raster/rgdal could read as well but either they distributed .tif as well or someone else converted it.
There are a number of misconceptions in your code:
load is for a particular file type created from R (not these .tifs)
readTIFF is not in package raster
read_file would be a sensible matrix, if you have rgdal installed (which raster must use to load a .tif), but why throw away the spatial metadata?

Resources