Advanced Spatial Methods in R

52
ADVANCED SPATIAL METHODS IN R Michael Mann George Washington University Department of Geography [email protected] http://michaelmann.i234.me/

description

Advanced Spatial Methods in R. Michael Mann George Washington University Department of Geography [email protected] http://michaelmann.i234.me/. Overview. Review Basics Setting up Space-time data Space -time plots library( RasterVis ) library( plotKML ) - PowerPoint PPT Presentation

Transcript of Advanced Spatial Methods in R

Page 1: Advanced Spatial Methods in R

ADVANCED SPATIAL METHODS IN RMichael Mann George Washington UniversityDepartment of [email protected]://michaelmann.i234.me/

Page 2: Advanced Spatial Methods in R

Overview• Review Basics• Setting up Space-time data• Space-time plots

• library(RasterVis)• library(plotKML)

• Vector & Other Data Visualization• library(ggplot2)

• Mapping ggplot2 visualizations• library(ggmap)

Page 3: Advanced Spatial Methods in R

Before we begin

Best places for help• http://stackoverflow.com/

• Question & Answer form. Quick & high quality responses

• ?function_name • Look up help files for a function from any library

• http://gis.stackexchange.com/• Similar to stackoverflow, but targeted to spatial community

• The fridge – grab a beer and spend some time

Page 4: Advanced Spatial Methods in R

Interpreting My Slides!

Inputs into command line

Outputs Notes

Data is in the MMSpatialData folder

s = c("aa", "bb", "cc", "dd", "ee")s

[1] "aa” "bb” "cc” "dd” "ee" An important note

Page 5: Advanced Spatial Methods in R

Your locationQuick survey

• Please raise you hand if (before today) you have never used R or a similar language.

Page 6: Advanced Spatial Methods in R

Let’s even the playing fieldBeginners• Please look around you. Move if

there is a beginner cluster!

Experts• Put on your teaching hats!

Remember how difficult this material is. Make sure to help your teammates!

Page 7: Advanced Spatial Methods in R

OverviewHelpful Functions

Indexing a vectors = c("aa", "bb", "cc", "dd", "ee")

[1] ‘aa’

s[1]

[1] ‘bb’ ‘ee’

s[c(2,5)]

Indexing a data.frames = data.frame(col1=c(1,2,3),

col2=c(5,6,7))

vector_name[ position_# ]

[1] 2

s[2,1]

[1] 5 6 7

s[,’col2’]

col1 col21 1 52 2 63 3 7

vector_name[ row#, col# ]

[1] ‘bb’ ‘cc’ ‘dd’ ‘ee’

s[c(2:5)]

Page 8: Advanced Spatial Methods in R

Objective 1 – Raster space-time plots• library(raster)• Raster Stacks & Bricks

• Multidimensional raster objects• Multi-layer (red,green,blue)• Multi-dim (time series, multi variable)

X

Y

Z

stack[row# ,col#, Z#]

Indexing Your Data

Page 9: Advanced Spatial Methods in R

Objective 1 – Raster space-time plots• Multi-layer Raster ‘Brick’

Brick[X,Y,Z]

b <- brick(system.file("external/rlogo.grd", package="raster)plot(b)

Page 10: Advanced Spatial Methods in R

Objective 1 – Raster space-time plots• Multi-layer Raster BrickplotRGB(b, r=1, g=2, b=3)

Page 11: Advanced Spatial Methods in R

Objective 1 – Raster space-time plots• Multi-dimentional Raster Stack

• Good for time-series of rasters, or multivariate analysis

Time Seriesstack[x,y, c(cwd2000-2010) ]

Multivariatestack[x,y, c(crime,pop) ]

Page 12: Advanced Spatial Methods in R

Objective 1 – Raster space-time plots• Multi-dimentional Raster Stack

• Good for time-series of rasters, or multivariate analysis

Time Seriesstack[x,y, c(cwd2000-2010) ]

Multivariatestack[x,y, c(crime,pop) ]

Use: Data Visualization

Use: Regression Analysis, modeling

Page 13: Advanced Spatial Methods in R

Task 1.1 – Setup Raster Stack Data Helpful Functions

dir(‘C://SESYNC//data’)

grep()grep(‘a’, c( ‘a’, ‘b’, ‘c’, ‘a’ ) )

[1] ‘data.zip’ ‘ggmap vinette.pdf’….

dir()

[1] 1 4

grep(‘c’, c( ‘tab’, ‘car’, ‘bat’ ) )

[1] 2

Page 14: Advanced Spatial Methods in R

Task 1.1 – Setup Raster Stack Data Helpful Functions – Using grep to index a vector

Find the location of a element with ‘c’ in it

Query vector s with the grep[1] 3

s = c("aa", "bb", "cc", "dd", "ee")

grep(‘c’, s )

s[ grep(‘c’, s ) ]

[1] ‘cc’

Page 15: Advanced Spatial Methods in R

Task 1.1 – Setup Raster Stack Data Helpful Functions – Using grep to index a vector

Find the location of a element with ‘c’ in it

Query vector s with the grep[1] 3

s = c("aa", "bb", "cc", "dd", "ee")

grep(‘c’, s )

s[ grep(‘c’, s ) ]

[1] ‘cc’

TRY THIS!

Page 16: Advanced Spatial Methods in R

Task 1.1 – Let’s get started!

Page 17: Advanced Spatial Methods in R

Task 1.2 – Create Raster Stacks and Assign Name LabelsHelpful Functions

paste(‘Hi',c('Bill','Bob', 'Sam'), sep=' ')

paste()

[1] “Hi Bill" “Hi Bob" “Hi Sam"

paste(’aet',c(’2001',’2002’), sep=’_')

[1] "aet_2001" "aet_2002"

names()

names(rstack) = c(‘test2001’,’test2002’)

test2001

test2002

Page 18: Advanced Spatial Methods in R

Task 1.2 – Create Raster Stacks and Assign Name LabelsHelpful Functions

paste(‘Hi',c('Bill','Bob', 'Sam'), sep=' ')

paste()

[1] “Hi Bill" “Hi Bob" “Hi Sam"

paste(’aet',c(’2001',’2002’), sep=’_')

[1] "aet_2001" "aet_2002"

names()

names(rstack) = c(‘test2001’,’test2002’)

test2001

test2002

TRY PASTE()!

Page 19: Advanced Spatial Methods in R

Task 1.2 – Create Raster Stacks and Assign Time LabelsHelpful Functions

setz()

raster_stack = setZ(raster_stack, years)seq(1,15, by=3)

seq() & as.Date()

[1] 1 4 7 10 13

Years = seq(as.Date(’2001-01-01'), as.Date('2010-01-01'), by=’1 year')

[1] "2000-01-01" "2001-01-01" … [10] "2009-01-01" "2010-01-01"

Page 20: Advanced Spatial Methods in R

Task 1.2 – Create Raster Stacks and Assign Time LabelsHelpful Functions

setz()

raster_stack = setZ(raster_stack, years)seq(1,15, by=3)

seq() & as.Date()

[1] 1 4 7 10 13

Years = seq(as.Date(’2001-01-01'), as.Date('2010-01-01'), by=’1 year')

[1] "2000-01-01" "2001-01-01" … [10] "2009-01-01" "2010-01-01"

Important: setZ must be passed a series of ‘Dates’ (created with as.Date function)

Page 21: Advanced Spatial Methods in R

Task 1.2 – Let’s get started!

Page 22: Advanced Spatial Methods in R

Task 1.3 – Visualize Stack Data Indexing Your Data

plot(raster_stack[[1]]) # plot first rasterplot(raster_stack[[2]]) # plot second raster

plot( raster(raster_stack,'HDen_1989') )

Method 1

Method 2

NOTE: [[ ]] is used b/c stack is a list object

NOTE: raster() is used b/c… well that is just how it works

Page 23: Advanced Spatial Methods in R

Task 1.3 – Let’s get started!

Page 24: Advanced Spatial Methods in R

Task 1.4 – Challenge Questions

Page 25: Advanced Spatial Methods in R

Task 1.5 Visualize Space-Time Data rasterVis & plotKML packages

rasterVis• Excellent tutorial available at http://rastervis.r-forge.r-project.org/• Data Format

• Raster stack with z-dim set to dates using: as.Date()• Spatial points or polygons data.frame with z-dim set to dates

Hovmoller Plot Horizon Plot

Page 26: Advanced Spatial Methods in R

Task 1.5 Visualize Space-Time Data rasterVis & plotKML packages

rasterVis• Data Format 2

• Raster stack OR Spatial points or polygons data.frame with z-dim set to slope, or direction

Vectorplot Stream Plot

Page 27: Advanced Spatial Methods in R

Task 1.5 Visualize Space-Time Data rasterVis & plotKML packages

plotKML• Excellent tutorial: http://plotkml.r-forge.r-project.org/• Data Format

• Exports many formats including raster stacks

Note: This code outputs both a Housing.kml file and a series of other image files (.png files). In order for this to work, the Housing.kml file needs to be in the same directory as all the image files.

Page 28: Advanced Spatial Methods in R

Task 1.5 Visualize Space-Time Data rasterVis & plotKML packages

plotKML• Excellent tutorial: http://plotkml.r-forge.r-project.org/• Data Format

• Exports many formats including raster stacks

Note: This code outputs both a Housing.kml file and a series of other image files (.png files). In order for this to work, the Housing.kml file needs to be in the same directory as all the image files.

All data must be unprojected Lat Lon "+proj=longlat +datum=WGS84”

Page 29: Advanced Spatial Methods in R

Task 1.5 – Let’s get started!

Page 30: Advanced Spatial Methods in R

Task 1.6 – Let’s get started!

Page 31: Advanced Spatial Methods in R

Objective 2: Intro to ggplot2• One of the best data visualization tools in R• Documentation available here: http://ggplot2.org/

Page 32: Advanced Spatial Methods in R

Objective 2: Intro to ggplot2• A plot is made up of multiple layers.• A layer consists of data, a set of mappings between

variables and aesthetics, a geometric object and a statistical transformation

• Scales control the details of the mapping.• All components are independent and reusable.

Page 33: Advanced Spatial Methods in R

Objective 2: Intro to ggplot2• plot

• aesthetics• geometric object • scales control • ‘+’ add mappings

Typical Command

a = ggplot(movies, aes(y = budget, x = year, group = round_any(year, 10) )) + geom_boxplot() + scale_y_log10()plot(a)

Page 34: Advanced Spatial Methods in R

Task 2.1 Setting up your data

ggplot2 uses data.frames!

Page 35: Advanced Spatial Methods in R

Task 2.1 Setting up your dataHelpful Functions

aggregate( rating ~ year ,data= movies, FUN='mean')

aggregate()Summarizes data of interest by factors (categorical data)

Page 36: Advanced Spatial Methods in R

Task 2.1 Setting up your dataHelpful Functions

jepson.points = fortify(jepson, region="id")

fortify()Converts spatial polygons, lines, points to data.frame usable in ggplot2

Page 37: Advanced Spatial Methods in R

Task 2.1 Let’s get going!

Page 38: Advanced Spatial Methods in R

Objective 2: Intro to ggplot2• plot reminder

• aesthetics• geometric object • scales control • ‘+’ add mappings

Typical Command

a = ggplot(jepson.df) + aes(long,lat,group=group,fill=ECOREGION) + geom_polygon() plot(a)

Page 39: Advanced Spatial Methods in R

Task 2.2 Let’s get going!

Page 40: Advanced Spatial Methods in R

Task 2.3 Let’s get going!

Page 41: Advanced Spatial Methods in R

Task 2.4 Challenge questions

Page 42: Advanced Spatial Methods in R

Objective 3: Intro to ggmap• Ggmap enables visualization of layered graphics using

implementation similar to ggplot2 • Combines the functionality of ggplot2 and spatial

information of static maps from Google Maps, OpenStreetMap, Stamen Maps or CloudMade

Page 43: Advanced Spatial Methods in R

Objective 3: Intro to ggmap• Ggmap enables visualization of layered graphics using

implementation similar to ggplot2 1. qmap() Downloads static maps from google, or OSM

• Defined by a central Lat and Lon and a ‘Zoom’ level

2. Takes additional ‘+’ commands to overlay ggplot2 graphics

Zoom = 5 Zoom = 14

Page 44: Advanced Spatial Methods in R

Objective 3: Intro to ggmap• plot

• aesthetics• geometric object • scales control • coordinate system

• Done in background through qmap

• ‘+’ add mappings

Typical Command

HoustonMap <- qmap("houston", zoom = 13, color = "bw")HoustonMap + geom_point(data=violent_crimes,aes(x = lon, y = lat, colour = offense ) )plot( HoustonMap )

Page 45: Advanced Spatial Methods in R

Task 3.1 Setting up your dataHelpful Functions

projectRaster() & project()• Converts spatial -polygons, -lines, -points to data.frame • usable in ggplot2 & ggmap.• Ggmap data must be in unprojected lat lon (defined below)

# Project a raster to unprojected Lat Lon using nearest neighbor algorithm stack_proj = projectRaster(raster_stack, crs="+proj=longlat +datum=WGS84” , method='ngb')

# Project a polygon to unprojected Lat Lon using nearest neighbor algorithm jepson_proj = project(jepson, crs="+proj=longlat +datum=WGS84”)

Page 46: Advanced Spatial Methods in R

Task 3.1 Setting up your dataHelpful Functions

jepson.points = fortify(jepson, region="id")

fortify()Converts spatial polygons, lines, points to data.frame usable in ggplot2

Page 47: Advanced Spatial Methods in R

Task 3.1 Setting up your dataHelpful Functions

geocode("the white house")

geocode() revgeocode() Converts text addresses or location names to Lat Lon coordindates

revgeocode(c(-77.03650, 38.89768), output = c("address"))

Converts Lat Lon to text addresses

Page 48: Advanced Spatial Methods in R

Task 3.1 Setting up your dataHelpful Functions

data = data.frame(name=c(‘mike’,’john’,’jim’), age=c(4,3,6))

subset()

name age1 mike 42 john 33 jim 6

subset(data, name != ‘mike’ ) name age2 john 33 jim 6

subset(data, age > 3 ) name age1 mike 43 jim 6

Page 49: Advanced Spatial Methods in R

Task 3.1: Learn Basic ggmap Functions

Page 50: Advanced Spatial Methods in R

Task 3.2: Crime Mapping In Houston TX

Page 51: Advanced Spatial Methods in R

Task 3.3: Challenge Questions

Page 52: Advanced Spatial Methods in R

WHAT SHOULD WE REVIEW?