Shapefiles in R - r

I'm relatively new to using Shapefiles in R. I want to create visualizations of country and district level data for India for which I'm using maptools in R. For the shapefiles, I got the data from gadm.org which includes state/district/subdistrict level data for India.
However, I'm trying to load the file in R and it's just not happening.This is my code :
library(maptools)
dist <- readShapePoly("IND_adm2.shp")
Here IND_adm2.shp is the district level shape file for India.
R is unable to read the file, giving me this error:
"Error in getinfo.shape(filen) : Error opening SHP file"
I'm not really sure what the problem is.I have R 3.0.1, have the files in the appropriate directory but something's just not right. I'm also new to making maps in R so it's been a bit annoying. Any ideas on how to fix this?

You could use the package rgdal
library(rgdal)
library(sp)
shp <- readOGR("path/to/shpfiles", "IND_adm2")
plot(shp)

Related

Unable to read shapefiles with st_read() in R

I am trying to read a shapefile
library(sf)
wards <- read_sf("Shape_files/benguluru_ward_boundaries_reprojected.shp")
and I am getting this error
Error in CPL_get_z_range(obj, 3) : z error - expecting three columns;
I googled it and it seems it has to do with z-dimension but I couldn't find a solution. How to solve this? Thanks in advance.
Edit:
This is what I am getting when I load the sf package
> library(sf)
Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
you can get the files here
Edit2: I was able to solve this by running extract z values as mentioned here and there dropping it while exporting the layer. I am able to read that new layer without any issues.

tract_choropleth in Choroplethr v3.6.0 for R

I'm trying to replicate the maps shown in this short example (Choroplethr v3.6.0 is now on CRAN) for California, but I'm having trouble with the tract_choropleth function for areas that are not in NY. I get the error message below. I'm able to import the underlying tract data for all areas, but I'm having trouble mapping the non-NY ones. Thanks in advance.
# Load all packages (DONE)
# Install api key (DONE)
# Get Tract-Level Demographics
ca_stats = get_tract_demographics("california")
# Create choropleth map with the function tract_choropleth
ca_stats$value = ca_stats$per_capita_income
tract_choropleth(ca_stats, "california", title = "2013 Per Capita Income\nCensus Tracts", legend="Dollars")
Error message returned:
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding,
use_iconv = use_iconv, : Cannot open layer In addition: Warning
message: In unzip(file_loc, exdir = cache_dir, overwrite = TRUE) :
error 1 in extracting from zip file
I'm the author of the tigris package that choroplethr uses to get Census tract boundaries. That error shows up in the event of a corrupted download from the Census Bureau website. Ari's solution will work; you can also try:
library(tigris)
options(tigris_refresh = TRUE)
This will direct tigris to re-download the shapefile from the Census Bureau website, and allow you to still use caching. Once it is fixed, set options(tigris_refresh = FALSE) to control future re-downloads.
Thank you for using choroplethr.
I have never gotten this error myself, but it's possible that it relates to a caching issue with the tigris package. I say that because it looks very similar to this issue.
Here is the code which solved that user's problem:
library(tigris)
options(tigris_use_cache = FALSE)
That code causes tigris to not use its cache.
Please type that code into your R session and try the choroplethr code again.

"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.

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?

Errors working through plotting shapefiles in the ggplot wiki

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

Resources