Date post: | 13-Mar-2016 |
Category: |
Documents |
Upload: | vladimir-carter |
View: | 78 times |
Download: | 0 times |
2
Types of Spatial DataR Spatial packagesS4 R objectsProjections Spatial methods• SpatialPoints• SpatialLines/SpatialPolygons• SpatialPixels
SpatialPoints - Sample Dataset• Importing/Exporting • Spatial information and slots• Displaying
SpatialPolygons - Sample Dataset• Importing/Exporting • Spatial information and slots• Displaying• Reprojecting
SpatialPixels - Sample Dataset• Importing/Exporting rasters• Spatial information and slots• Displaying• Deriving• Thematic rasters (importing, spatial info, reclassing)• Temporary files
Outline
3
## Types of Spatial DataPoints - a set of single point locations Lines - an ordered set of points, connected by straight line segmentsPolygons – an area, with enclosed lines, possibly containing holesRasters – a collection of points or rectangular cells, in grid format
Spatial Data in R
## R Spatial packagessp Basic R classes for handling geospatial datamaptools Read and write shapefiles. Cannot read the projection file.rgeos Interface to spatial geometry for sp objects rgdal Supports GDAL raster formats and OGR vector formats..
Retains projection information when reading and writing (PROJ.4 library)raster Spatial data analysis for rasters.
## Help links for spatial tools in R# Summary of tools for Spatial data analysishttp://cran.r-project.org/web/views/Spatial.html
4
# Set working directorypath <- "W:/Techniques/Projects/Peru/Rworkshop"setwd(path)
# Load libraries
library(sp)library(maptools)library(rgeos)library(rgdal)library(raster)
Spatial Data in R
5
## Spatial classes (sp package)
getClass("Spatial")
Bivand, et al. 2008
Spatial Data in R
6
## S4 R objectsNew-style classes with formal definitions that specify the name and type of the object's components, called slots.
## The Spatial class has 2 pre-defined slots
1. bbox – The bounding box, consisting of a matrix of coordinates defining the extent of the spatial object.
2. proj4string – The class object defining the coordinate reference system (CRS)
CRS contains datum and projectiondatum – a surface that represents the shape of the earthprojection – renders the surface of an ellipsoid as a plane
Spatial Data in R
7
Spatial Data in R
# rgdal packagePROJ.4 - Cartographic Projections Library A library of projection functions to perform respective forward and inverse transformation of cartographic data.
# Format of projection string (proj4string)"+proj=prj +ellps=GRS80 +datum=datum +no_defs”
# List of common projectionshttp://www.remotesensing.org/geotiff/proj_list/
# More proj4string options.." +proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs"" +proj=utm +zone=13 +datum=NAD83"" +proj=utm +ellps=WGS84 +datum=WGS84 +zone=11, +units=m +towgs84=0,0,0"" +proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m" " +no_defs +ellps=GRS80 +towgs84=0,0,0"
## Projections
8
## Spatial methods (sp package)
Bivand, et al. 2008
Spatial Data in R
## Common attributes of R objects: # method - a function associated with a particular type of object (ex. summary, print)
9
SpatialPoints
Bivand, et al. 2008
10Bivand, et al. 2008
SpatialLines/PolygonsObjectList of ObjectsLists of List Objects
11Bivand, et al. 2008
SpatialPixelsSimilar to SpatialPoints with regularly spaced coordinates.
12
Utah, USA
Sample Dataset
13
Highest East-West oriented mountain range in the contiguous U.S. - up to 13,528 ft (4,123 m)
High Uinta Wilderness## Vegetation5 different life zones:1. shrub-montane2. aspen3. lodgepole pine4. spruce-fir5. alpine
Uinta Mountains, Utah,USA
Sample Dataset
14
SpatialPoints
15
## Import data frame with X/Y coordinates ## (FIA plot data with fuzzed/swapped coordinates)
plt <- read.csv("PlotData/plt.csv", header=TRUE, stringsAsFactors=FALSE)
## Generate SpatialPointsx <- "LON"y <- "LAT"prj <- "longlat"datum <- "NAD83"prj4str <- "+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs"
ptshp <- SpatialPointsDataFrame(plt[,c(x,y)], plt, proj4string = CRS(prj4str))class(ptshp)
# Export SpatialPointshelp(writeOGR)writeOGR(ptshp, "Outfolder", "ptshp", driver="ESRI Shapefile")
Sample DatasetSpatialPoints - Importing/Exporting
16
## Get spatial information for ptshp
summary(ptshp) # General info and summary statistics for attribute # data of ptshp
mode(ptshp) # Get mode of ptshpclass(ptshp) # Get class of ptshp
is.projected(ptshp) # Check if ptshp has projection informationproj4string(ptshp) # Set or get projection information
str(ptshp) # Structure of ptshp
Sample DatasetSpatialPoints – Spatial Info
17
## Get slot names and access slots for SpatialPointsslotNames(ptshp) # Get name of ptshp components (slots)ptshp@data # Get data frame attributes of ptshpptshp@coords # Get coordinates of ptshpptshp@bbox # Get extent of ptshpptshp@proj4string # Get projection information
head(ptshp@data) # Get first 6 rows of data frame of ptshpdim(ptshp) # Get dimensions of data frame of ptshp
Sample DatasetSpatialPoints - Slots
18
## Display ptshpplot(ptshp)
# Display ptshp points with red dots, half sizeplot(ptshp, col="RED", pch=16, cex=0.5)
# Display subsets of ptshpplot(ptshp[ptshp$INVYR==2002,], col="BLUE")plot(subset(ptshp, INVYR==2003), col="RED", add=TRUE)
# pch codes
## Help for point graphicshttp://127.0.0.1:11789/library/graphics/html/points.html
Sample DatasetSpatialPoints - Displaying
# Colorscolors()
19
Sample DatasetExercise
## Exercise 1
## 1.1 Get the min and max coordinates of the boundary of ptshp.
## 1.2 Display points where elevation (ELEVM) are >= 3000 in dark green.
## 1.3 Add points where elevation (ELEVM) are < 3000 in yellow.
## 1.4 Overlay the point with the maximum elevation (ELEVM) in red.
20
SpatialPolygons
21
# SpatialPolygons – file names# Area of Interest (AOI) boundary (Uinta Mountains, UT)aoifn <- "uintaN_aoi.shp"
# National Forest System boundary within AOInfsfn <- "uintaN_nfs.shp"
# High Uinta Wilderness boundary within AOIwildfn <- "uintaN_wild.shp"
Sample DatasetSpatialPolygons
22
## Importing shapefiles using OGR drivers (rgdal)
## OGR functionsFrom the Geospatial Data Abstraction Library (GDAL), interfaced through rgdal.Reads spatial data, including the spatial reference.
readOGR – reads OGR data source and layer into an R Spatial objectwriteOGR – writes data out using supported drivers
Note: There are 2 main arguments.. that may take different forms, depending on the available drivers.
dsn – data source namelayer – the name of the layer
Note: A driver is a software component loaded on demand to enable a device to work with a computer's operating system.
ogrDrivers()help(readOGR)
Sample DatasetSpatialPolygons - Importing/Exporting
23
## Importing polygon shapefiles ## (AOI boundary, NFS boundary, Wilderness boundary)
# dsn – data source name (folder with layers)# layer – the name of the layer (no extension)
## Set dsndsn <- "SpatialData"
## Spatial layer namesaoinm <- "uintaN_aoi" nfsnm <- "uintaN_nfs" wildnm <- "uintaN_wild"
## Import shapefilesbndpoly <- readOGR(dsn=dsn, layer=aoinm, stringsAsFactors=FALSE)nfspoly <- readOGR(dsn=dsn, layer=nfsnm, stringsAsFactors=FALSE)wildpoly <- readOGR(dsn=dsn, layer=wildnm, stringsAsFactors=FALSE)
Sample DatasetSpatialPolygons - Import
24
## Get spatial information for bndpolybndpoly # Get general information of polygonsummary(bndpoly) # Summary information for polygonmode(bndpoly) # Get mode of bndpolytypeof(bndpoly) # Get typeof class(bndpoly) # Get class of bndpolyproj4string(bndpoly) # Set or get projection information of bndpolybbox(bndpoly) # Get extent of bndpolydim(bndpoly) # Get dimension of bndpoly
str(bndpoly) # Get structure of bndpoly
Sample DatasetSpatialPolygons – Spatial Info
25
# Get slot names for class SpatialPolygons (1)getClass("SpatialPolygons")slotNames(bndpoly)
@polygons # the list of Polygons objects@plotOrder # the order to plot the Polygons@bbox # bounding box slot @proj4string # coordinate reference system slot@data # associated data frame (for class SpatialPolygonsDataFrame objects)
(1) (2) (3)
Sample DatasetSpatialPolygons - slots
26
## Display bndpolyplot(bndpoly) # Display polygon shapefileplot(bndpoly, col="blue") # Display polygon with blue fill colorplot(bndpoly, border="red", lwd=3) # red outline and line width=3
plot(bndpoly, col="blue", border="red", lwd=3) # blue fill
plot(bndpoly, col="blue", border="red", lwd=3, bg="black", axes=TRUE) # with background colored and axes labels
Sample DatasetSpatialPolygons – Displaying
27
# Get spatial information for nfspolynfspoly # Get general information of nfspolysummary(nfspoly) # Summary information for nfspolydim(nfspoly) # Dimensions of nfspoly
str(nfspoly) # Get structure of nfspoly
Sample DatasetSpatialPolygons – Spatial Info
28
# Get slot names for class SpatialPolygons (1)getClass("SpatialPolygons")slotNames(nfspoly)
@polygons # the list of Polygons objects@plotOrder # the order to plot the Polygons@bbox # bounding box slot @proj4string # coordinate reference system slot@data # associated data frame (for class SpatialPolygonsDataFrame objects)
(1) (2) (3)
Sample DatasetSpatialPolygons - slots
29
# Get slot names for class Polygons (2)getClass("Polygons")slotNames(nfspoly@polygons[[1]]) # First feature
@polygons[[1]]@Polygons # a list of rings (islands/holes) that make up the feature@polygons[[1]]@plotOrder # the order to plot the feature@polygons[[1]]@labpt # label point coordinates of the feature@polygons[[1]]@ID # unique identifier of the feature@polygons[[1]]@area # area of the feature (in units of feature projection)
(1) (2) (3)
Sample DatasetSpatialPolygons - slots
30
# Get slot names for class Polygon (3)getClass("Polygon")slotNames(slot(nfspoly@polygons[[1]], "Polygons")[[1]])
@polygons[[1]]@Polygons[[1]] # first ring of feature - class 'Polygon'@polygons[[1]]@Polygons[[1]]@labpt # label point coordinates of the feature ring@polygons[[1]]@Polygons[[1]]@area # area of the feature ring@polygons[[1]]@Polygons[[1]]@coords # coordinates of the feature ring
(1) (2) (3)
Sample DatasetSpatialPolygons - slots
31
# Accessing slots of SpatialPolygonsnfspoly@data # Data frame attributes of shpnfspoly@polygons # Get info of each polygon within Spatial Polygonsnfspoly@plotOrder # Get order of polygons within Spatial Polygonsnfspoly@bbox # Get extent of bndpoly
# Accessing slots of Polygonsslot(nfspoly, "polygons") # (2)slotsslotsPolygons <- slot(nfspoly, "polygons") # (2)slotstypeof(slotsPolygons)length(slotsPolygons)
sapply(slotsPolygons, function(x)slot(x, "ID")) # (2)slotssapply(slotsPolygons, function(x)slot(x, "area")) # (2)slots
slotsPolygon <- slot(nfspoly@polygons[[1]], "Polygons") # (3)slotsslotsPolygon <- slot(nfspoly@polygons[[2]], "Polygons") # (3)slots
Sample DatasetSpatialPolygons - slots
32
## Display nfspoly and wildpolyplot(bndpoly, col="dark blue")plot(nfspoly, border="yellow", add=TRUE, lwd=2)plot(wildpoly, add=TRUE, border="green")
# Add points – in redplot(ptshp, add=TRUE, col="red", pch=16, cex=0.5)
Sample DatasetSpatialPolygons - Displaying
33
## Notice, the point layer did not display. Check the projections. projection(bndpoly)projection(ptshp)
## Reproject ptshp to projection of bndpolypolyprj <- projection(bndpoly)ptshpprj <- spTransform(ptshp, CRSobj=CRS(polyprj))
projection(ptshpprj)
# Add points – in redplot(ptshpprj, add=TRUE, col="red", pch=16, cex=0.5)
# Add thicker boundary lineplot(bndpoly, lwd=3, add=TRUE)
# Add labels for nfspolytext(nfspoly, nfspoly$FORESTNAME, cex=0.75, pos=3, col="white")
Sample DatasetSpatialPolygons - Reprojecting
34
Sample DatasetExercise
## Exercise 2
## 2.1 Get projection of nfspoly.
## 2.2 Display the area of interest boundary (bndpoly) with no color fill.
## 2.3 Add the wilderness boundary (wildpoly) with green fill and with no outline.
## 2.4 Get total sum of area of nfspoly.
35
SpatialPixels
36
# Elevation (m)
Sample DatasetSpatialPixels
# National Elevation Dataset (NED) in meters elevfn <- "SpatialData/uintaN_elevm.img"
37
fnffn <- "SpatialData/uintaN_fnf.img"
# Forest/Nonforest map
Sample DatasetSpatialPixels
38
## Importing SpatialPixels (raster) fileshelp(raster)elev <- raster("SpatialData/uintaN_elevm.img")elevdim(elev)class(elev)
## Importing a raster stackhelp(stack)rstack <- stack("SpatialData/uintaN_elevm.img", "SpatialData/uintaN_fnf.img")rstackdim(rstack)class(rstack)
## Exporting a raster help(writeRaster)writeRaster(rstack, filename="Outfolder/rstack1.img")
# Add integer datatype and notice size of filewriteRaster(rstack, filename="Outfolder/rstack2.img", datatype="INT1U",
overwrite=TRUE)
Sample DatasetSpatialPixels - Importing/Exporting
39
## Get spatial information for elevelevclass(elev)inMemory(elev) # Checks if raster is stored in memory (RAM)unique(elev) # Get unique values of rasterextent(elev) # Get extent of rasterboxplot(elev) # Display boxplot of raster valuesdim(elev) # Get dimensions of rasterres(elev) # Get the resolution of raster (x y)ncell(elev) # Number of cells of rastermaxValue(elev) # Get Maximum value in rasterfreq(elev) # Get frequency table of raster
Sample DatasetSpatialPixels - Spatial Info
## Overview of functions in raster packagehttp://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/raster/html/raster-package.html
40
## Get slot names for class SpatialPixelsgetClass("SpatialPixels")slotNames(elev)str(elev)
# @file the source (file name) of raster# @data list of attributes of raster# @legend the legend features of raster, if exist# @title the title of raster, if exists# @extent the bounding box of raster# @ncols number of columns of raster# @nrows number of rows of raster# @crs coordinate reference system slot
## Get slot names for class SpatialPixels slotsslotNames(elev@file)elev@file@nameelev@file@nbands
slotNames(elev@data)elev@data@min
Sample DatasetSpatialPixels - slots
41
## Display rasters
plot(elev)
# Display with terrain colors – 4 classesplot(elev, col=terrain.colors(n=4))
# Display with terrain colors – 20 classesplot(elev, col=terrain.colors(n=20))
# Exclude axis labelsplot(elev, col=terrain.colors(n=4), axes=FALSE)
# Get help with other colors for continuous datahelp(terrain.colors)
# Display elevation data with contourscontour(elev)
Sample DatasetSpatialPixels - Displaying
42
## Derive new rasters
# Generate slope and aspect and hillshade from elevation datasetslp <- terrain(elev, opt=c('slope'), unit='radians')asp <- terrain(elev, opt=c('aspect'), unit='radians')hill <- hillShade(slope, asp) # Generate hillshade
# Display hillshade in grey scaleplot(hill, col=grey(0:100/100), legend=FALSE)
# Classify raster elevcl <- cut(elev, breaks=5) # 5 classesplot(elevcl) # Display classified rastercols <- c("brown", "palegreen", "orange1", "dark green", "snow")plot(elevcl, col=cols, breaks=c(0:5))
# Converts raster from meters to feetelevft <- elev * 3.28084summary(elev)summary(elevft)
Sample DatasetSpatialPixels - Deriving
43
## Get spatial information for fnf (thematic raster)fnf <- raster("SpatialData/uintaN_fnf.img")unique(fnf) # Get unique values of rasterextent(fnf) # Get extent of rasterbarplot(fnf) # Display barplot of raster values
## Display fnffnfvals <- sort(unique(fnf))plot(fnf, breaks=fnfvals, col=c("green", "brown", "blue"), legend=TRUE)
Sample DatasetSpatialPixels - fnf
## Overview of functions in raster packagehttp://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/raster/html/raster-package.html
44
## Reclass raster layer to 2 categorieshelp(reclassify)fromvect <- c(0,1,2,3)tovect <- c(2,1,2,2)rclmat <- matrix(c(fromvect, tovect), 4, 2)fnfrcl <- reclassify(x=fnf, rclmat)fnfrclunique(fnfrcl)freq(fnfrcl)
## To save to filehelp(writeRaster)stratrcl <- reclassify(x=fnf, rclmat, datatype='INT2U',filename="SpatialData/uintaN_fnfrcl.img", overwrite=TRUE)
## Plot new reclassed rasterfnfrclvals <- c(0, unique(fnfrcl))plot(fnfrcl, breaks=fnfrclvals, col=c("green","brown"), legend=TRUE)barplot(fnfrcl)
Sample Datasetreclass raster
45
Temporary Files## Note:Functions in raster package create temporary files if the values of an output RasterLayer cannot be stored in memory (RAM). This can happen when nofilename is provided to a function an in functions where you cannot provide a filename. Temporary files are automatically removed at the start of each session.
## During session:showTmpFiles()removeTmpFiles()
## You can change where the temporary folder is in the Rprofile.site file.## (C:\Program Files\R\R-3.0.0\etc\Rprofile.site)
# Addedoptions(scipen=6)options(rasterTmpDir='c:/Temp/')rasterOptions()rasterOptions(chunksize = 1e+04, maxmemory = 1e+06)
46
Sample DatasetExercise
## Exercise 3
## 3.1 Get the minimum value of elev
## 3.2 Display elev raster with heat colors and 10 classes
## 3.3 Generate slope (in degrees)
## 3.4 Classify the slope raster from 3.3 into 4 classes
## 3.5 Display the classified slope raster with unique colors. Use colors() to select color choices. Exclude axes labels.
47
# Summary of tools for Spatial data analysishttp://cran.r-project.org/web/views/Spatial.html
# Presentation – Introduction to representing spatial objects in R – Roger Bivandhttp://geostat-course.org/system/files/monday_slides.pdf
# List of common projectionshttp://www.remotesensing.org/geotiff/proj_list/
# List of common projectionshttp://www.remotesensing.org/geotiff/proj_list/
## Help for point graphicshttp://127.0.0.1:11789/library/graphics/html/points.html
## Overview of functions in raster packagehttp://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/raster/html/raster-package.html
Spatial Help Links