Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 13 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.


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

r <- stack(rlist)   

    # Add required libraries

    # Set working directory, raster, in and out shapefiles
    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, 
share|improve this answer
+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
If I have a multipolygonfile: How does the data.frame(sdata@data, m2012=r.mean) know whch polygon to assign which value to? – Stophface Mar 10 at 13:11

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
how to write the shapefile out (with the values extracted from the raster image)? – Stophface Mar 10 at 13:11

Your Answer


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.