Using R For Basic Spatial Analysis
Using R For Basic Spatial Analysis
ANALYSIS
Dartmouth College | Research Computing
OVERVIEW
• Research Computing and Spatial Analysis at
Dartmouth
• What is Spatial Analysis?
• What is R?
• Basics of R
• Common Spatial Packages for R
• Viewing and analyzing Spatial Data in R
• Hands-on practice
• Display in GIS software
• Questions and Wrap-up
RESEARCH COMPUTING AT DARTMOUTH
Mission: Promote the advancement of research through the use of high-performance
• Research Computing computing (HPC), life sciences support and bioinformatics, GIS consulting, services and
workshops
• Workshops
• Storage
• Consulting
• Software
• Hardware
• Visit our website,
http://rc.dartmouth.edu/
• Request a research
account
• Email us
• research.computuing@da
rtmouth.edu
• stephen.p.gaughan@dart
mouth.edu
SPATIAL ANALYSIS AT DARTMOUTH
• Courses in the Geography Department and the Earth Sciences Department, GIS and spatial
analysis
• Geography Department http://geography.dartmouth.edu/
• Geog 50 Geographic Information Systems
• Geog 57 Urban Applications of GIS
• Geog 51 / Ears 65: Remote Sensing
• Geog 54 Geovisualization
• Geog 59/Ears 77 Environmental Applications of GIS
• Dartmouth College Library: Library Reference Research Guides for the R statistical
package, GIS and spatial analysis
• GIS http://researchguides.dartmouth.edu/gis
• Statistics, R http://researchguides.dartmouth.edu/statapp_koujue
• Research Computing
MORE INFO
• Data Visualization using R
• James Adams, Baker-Berry Library, [email protected]
• R Club
• Katja Koeppen, Microbiology Department organizes an R Club, [email protected]
• R has been around for more than 20 years and it has become popular at
universities, research labs and federal and state government offices in the
last ten years for many applications
• If you are already a GIS user, you’ll notice similar commands and
techniques, and of course, you’ll recognize spatial data when displayed on a
map in R
BASICS OF R (I)
THE R CONSOLE
- Console
- Terminal
- Script Editor
- Variables
- Plots, Graphics, Maps!
- Exports
- Package import
BASICS OF R (III)
SOME PACKAGES TO EXTEND R
• https://support.rstudio.com/hc/en-us/articles/201057987-Quick-list-of-
useful-R-packages
• Tidyr
• Ggplot2
• Dpylr
• xlsx
• Maps
• Sp
• Rgdal
• Parallel
COMMON SPATIAL PACKAGES FOR R
• Spatial:
• SP “spatial”
• GSTAT “geostatistics”
• RGDAL “geospatial data abstraction library for R”
• MAPS “maps”
• GGMAP “extends the plotting of ggplot2 with map data”
• RASTER “raster data processing”
• MAPTOOLS “map tools”
• SPATSTAT “wide range of spatial tools and functions”
VIEWING AND ANALYZING SPATIAL
DATA (I)
• Put a Google base map right in your
plot window, overlay spatial data on
to the map plot
12
VIEWING AND ANALYZING SPATIAL DATA (I)
GEOGRAPHIC INFORMATION ANALYSIS
• Open R Studio
• In the “Console” at the “greater than”
symbol, enter:
> install.pakages(“maps”)
GETTING STARTED
• Continue on in R Studio, entering the following commands:
install.packages("ggmap")
library(maps)
library(ggmap)
plot.new()
install.packages("ggplot2")
library(ggplot2)
library(ggmap)
ggmap(mapHanover)
ggmap(mapLatLong)
USING R SCRIPT FILES
• To make R code easier to type in, save and re-use, we can use an R Script
file.
• In R Studio, click File > New File > R Script
USING R SCRIPT FILES
• Here we see the code inside a “.R” file
• Code can be run line-by-line using the “Run” button in the upper bar
WORKING WITH SPATIAL DATA
• Open R Studio (All Programs > R
Studio)
• Downloading the Data:
• In your browser, type
dartgo.org/rspatial
• At the DartBox site, click the
ellipses ... and choose
‘Download’
• Download file Student.zip
• Copy the file to a convenient
location such as:
c:\rworkspace
• Unzip the file
READY TO DIVE IN?
• We’ll use R Studio today so we can see our spatial analysis
• Data for this session can be downloaded at:
dartgo.org/rspatial
• Download file and unzip
• Copy the file to a “Working Directory” that R will recognize
GETTING THE DATA AND R TO WORK
TOGETHER
• Use the “getwd()” and “setwd()” commands in R, and your computer’s file
browser (Finder on the Mac, Windows Explorer on the PC)
On the PC:
getwd()
[1] "C:/Users/f002d69/Documents"
> setwd("c:/users")
> getwd()
[1] "c:/users"
>
On the mac:
getwd()
[1] "/Users"
> setwd("~/Desktop")
> getwd()
[1] "/Users/sgaughan/Desktop"
MAP OVERLAY, POINT-IN-POLYGON
ANALYSIS WITH SP “OVER” FUNCTION
install.packages(“sp”)
install.packages(”rgdal”)
install.packages(”maps”)
library(sp)
library(rgdal)
library(maps)
parks <- readOGR(".", "10m_us_parks_area") • Packages “sp”, “rgdal” and “maps” can turn
your R into a GIS
mean(inside.park)
26
PLOT THE POINTS AND EXPORT
bears$park <- over(bears, parks)$Unit_Name
plot(coordinates(bears), type="n")
27
PLOT THE POINTS AND EXPORT
points(bears[inside.park, ], pch=16, col="red")
28
ADDING A LEGEND AND TITLE
# add a legend
legend("topright", cex=0.85,
c("Bear in park", "Bear not in park", "Park boundary"),
pch=c(16, 1, NA), lty=c(NA, NA, 1),
col=c("red", "grey", "green"), bty="n")
# add a title
title(expression(paste(italic("Ursus arctos"),
" sightings with respect to national
parks")))
29
INSTALL SPATIAL LIBRARIES “GSTAT”, “SP” AND “GDAL”
install.packages("sp")
install.packages("rgdal")
# import libraries
library(gstat)
library(sp)
library(rgdal)
LOAD DATASET IN TO R STUDIO AND PLOT
# load the meuse dataset in to the Rstudio environment
data(meuse)
coordinates(meuse) = ~x+y
coordinates(meuse)[1:5,]
examine the "meuse" dataset, point data set consists of 155 samples
of top soil heavy metal concentrations (ppm), along with a number of
soil and landscape variables. The samples were collected in
a flood plain of the river Meuse, near the village Stein, southern
Netherlands, 50.9686432 Lat,5.7460789 Longitude
DISPLAY THE DISTANCE TO RIVER
library(gstat)
zinc.idw <- idw(zinc~1, meuse, meuse.grid)
class(zinc.idw)
# spatialPixelsDataFrame
Reference: https://docs.qgis.org/2.2/en/docs/gentle_gis_introduction/spatial_analysis_interpolation.html
EXAMINE LINEARITY
plot(log(zinc)~sqrt(dist),
meuse)
abline(lm(log(zinc)~sqrt(d
ist), meuse))
LOAD THE LINEAR MODEL AND SUMMARIZE
Residuals:
Min 1Q Median 3Q Max
-1.04624 -0.29060 -0.01869 0.26445 1.59685
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 6.99438 0.07593 92.12 <2e-16 ***
sqrt(dist) -2.54920 0.15498 -16.45 <2e-16 ***
---
Signif. codes:
0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# the values are INTERPOLATED/ PREDICTED by the original dataset and the kriging function
spplot(lzn.kriged["var1.pred"])
DISPLAY POINTS USING QUANTILE CATEGORIZATION
library(RColorBrewer)
load(system.file("data", "meuse.rda", package = "sp"))
# use CRS from the sp pacakate to indicate the map projection/coord ref system
m<-plotGoogleMaps(meuse,filename='myMap1.htm')
# Plotting another map with icons as pie chart
m<-segmentGoogleMaps(meuse, zcol=c('zinc','dist.m'),
mapTypeId='ROADMAP', filename='myMap4.htm',
colPalette=c('#E41A1C','#377EB8'), strokeColor='black')
SHOW “MEUSE” DATA IN GOOGLE MAPS
WITH “PLOTGOOGLEMAPS” LIBRARY
DATA IN GIS SOFTWARE
R AND GIS
- MORE LINKS AND REFERENCES -
• R-GIS Tutorials
• https://cran.r-project.org/doc/contrib/intro-spatial-rl.pdf
• https://pakillo.github.io/R-GIS-tutorial/#intro
41
MORE LINKS AND REFERENCES
• http://www.r-bloggers.com/r-beginners-plotting-locations-on-
to-a-world-map/
• http://www.kevjohnson.org/making-maps-in-r/
• GGMAPS ( depends on GGPLOT2, imports RGoogleMaps
• https://cran.r-project.org/web/packages/ggmap/index.html
• Online Tutorials
• Lynda Tutorials for GIS, R https://www.lynda.com/
• ESRI Tutorials
• GIS Lounge - http://www.gislounge.com/tutorials-in-gis/
42
OTHER SPATIAL FUNCTIONS AND PACKAGES
43
OTHER SPATIAL FUNCTIONS AND PACKAGES
# Export to KML with rgdal package, import well-formatted
KML files
writeOGR(locs.gb, dsn = "locsgb.kml", layer = "locs.gb",
driver = "KML")
newmap <- readOGR("locsgb.kml", layer = "locs.gb")
# Define a projection
crs.geo <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84") #
geographical, datum WGS84 proj4string(locs) <- crs.geo #
define projection system of our data summary(locs)
44
OTHER SPATIAL FUNCTIONS AND PACKAGES
# write to shapefile
writePointsShape(locs.gb, "locsgb")
# Read shapefile
gb.shape <- readShapePoints("locsgb.shp")
plot(gb.shape)
# geostats
library(gstat)
library(geoR)
library(akima) # for spline interpolation
library(spdep) # dealing with spatial dependence
45
QUESTIONS?
46
MAP PROJECTIONS
Projections are
sometimes designed
to minimize one of
these
47
DATA MANAGEMENT
• Data Frames
• CSV format (clean csv)
• Tidy Data
• Other formats - Reading out of databases (SQL), Geographic data
constructs