Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I have a set of raster images which represent a specific month over the years, and I want to make a timeline of the average values of an area using a shapefile.

How do I extract the values from the rasters and import them in R in a manner that I can use them?

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

Here is example code. It is fairly straight forward to adapt this code to work in a loop for processing all of your rasters. If your rasters share a common extent and resolution you can create a raster stack and loop through the bands in the stack. To create a vector containing all rasters in a directory, in a specific format, you can use "list.files" and then pass this vector to stack.

Example:

rlist=list.files(getwd(), pattern="img$", full.names=TRUE)

r <- stack(rlist)

# Add required libraries
require(raster)
require(sp)
require(rgdal)

# Set working directory, raster, in and out shapefiles
setwd("C:/test")
inshp="MyPolys"
outshp="PolyMeans"
rdata <- "Year2012.img"

# Read polygon feature class shapefile
sdata <- readOGR(dsn=getwd(), layer=inshp)

# Read raster
r <- raster(rdata)

# Extract raster values to list object
r.vals <- extract(r, sdata)

# Use list apply to calculate mean for each polygon
r.mean <- lapply(r.vals, FUN=mean)

# Join mean values to polygon data
sdata@data <- data.frame(sdata@data, m2012=r.mean)

# Write results
writeOGR(sdata, getwd(), outshp, driver="ESRI Shapefile", check_exists=TRUE, 
     overwrite_layer=TRUE)
share|improve this answer
1  
+1 - excellent solution, well laid out and complete answer. –  Simbamangu Jul 10 '12 at 4:10
    
+1 nice solution! –  WAF Aug 30 '13 at 15:09
add comment

Read the shapefile into a SpatialPolygonsDataFrame (readOGR function from package rgdal)

Read the raster into a Raster object (raster function from package raster)

Use extract(raster, spdf) to get the grid cells under each polygon. Then run mean on them.

Repeat over your set of raster images...

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.