User Tools

Site Tools


Translations of this page:

Back to BIS-Schools

Biodiversity data analysis with R






E10-1: Accessing spatial data sets in R

Reading and accessing vector data sets

If you want to read a shape file (i.e. vector) into R, just use the readOGR() function from the sp package:

vector ← readOGR(“<name of the shape file>”, “<name of the data layer>”)

The first argument is the path and name of the vector file. The layer name is almost always the file name of the shape file except for the “shp” extension.

Once you have read it, you get a spatial data frame. Basically this is a data frame with some additional geographical information merged to it. To access the individual attribute values (i.e. to access rows, columns or individual cells), you can use exactly the same index value or column name methods you already know from handling data frames. The only difference is that you do not directly use them after the variable name but after an @data argument. For example, if you want to access the third value (i.e. row) in the second column, of your data set, type:


In order to visualize the entire data set in a map-type figure, use the plot() function:


This will result in one map like figure for each attribute in the vector. If you only want to visualize one attribute (i.e. column of the attribute table), use:

spplot(vector)[<column number>]

Reading and accessing raster data sets

If you want to read a GeoTiff (i.e. raster) into R, just use the raster() function from the raster package:

raster ← raster(<name of the GeoTiff file>)

Once you have read it, you get a data set of type raster. To access individual rows, you must use the getValues() function according to

getValues(raster, <row number>)

which returns you all column value for the specified row. To access an individual grid cell, type

getValues(raster, <row number>)[<col number>]

In order to visualize the entire data set in a map-type figure, use the plot() function:


For any geographical data set, the projection information has to be supplied. If it is not part of the data set itself and hence can not be read during data import, the spatial reference has to be assigned to the R data object. Therefore, one needs a so called proj4 string which can be retrieved from the Spatial Reference website (among many other formats).
en/learning/schools/s01/excursus/ba-ex-10-01.txt · Last modified: 2015/09/22 16:22 (external edit)