The raster package provides classes and functions to manipulate geographic (spatial) data in 'raster' format. Raster data divides space into cells (rectangles; pixels) of equal size (in units of the coordinate reference system). Such continuous spatial data are also referred to as 'grid' data, and be contrasted with discrete (object based) spatial data (points, lines, polygons).

The package should be particularly useful when using very large datasets that can not be loaded into the computer's memory. Functions will work correctly, because they process large files in chunks, i.e., they read, compute, and write blocks of data, without loading all values into memory at once.

Below is a list of some of the most important functions grouped by theme. See the vignette for more information and some examples (you can open it by running this command: vignette('Raster'))

Details

The package implements classes for Raster data (see Raster-class) and supports

  • Creation of Raster* objects from scratch or from file

  • Handling extremely large raster files

  • Raster algebra and overlay functions

  • Distance, neighborhood (focal) and patch functions

  • Polygon, line and point to raster conversion

  • Model predictions

  • Summarizing raster values

  • Easy access to raster cell-values

  • Plotting (making maps)

  • Manipulation of raster extent, resolution and origin

  • Computation of row, column and cell numbers to coordinates and vice versa

  • Reading and writing various raster file types

.

I. Creating Raster* objects

RasterLayer, RasterStack, and RasterBrick objects are, as a group, referred to as Raster* objects. Raster* objects can be created, from scratch, files, or from objects of other classes, with the following functions:

rasterTo create a RasterLayer
stackTo create a RasterStack (multiple layers)
brickTo create a RasterBrick (multiple layers)
subsetSelect layers of a RasterStack/Brick
addLayerAdd a layer to a Raster* object
dropLayerRemove a layer from a RasterStack or RasterBrick
unstackCreate a list of RasterLayer objects from a RasterStack
------------------------------------------------------------------------------------------------------------------------------

II. Changing the spatial extent and/or resolution of Raster* objects

mergeCombine Raster* objects with different extents (but same origin and resolution)
mosaicCombine RasterLayers with different extents and a function for overlap areas
cropSelect a geographic subset of a Raster* object
extendEnlarge a Raster* object
trimTrim a Raster* object by removing exterior rows and/or columns that only have NAs
aggregateCombine cells of a Raster* object to create larger cells
disaggregateSubdivide cells
resampleWarp values to a Raster* object with a different origin or resolution
projectRasterproject values to a raster with a different coordinate reference system
shiftMove the location of Raster
flipFlip values horizontally or vertically
rotateRotate values around the date-line (for lon/lat data)
tTranspose a Raster* object
---------------------------------------------------------------------------------------------------------------------

III. Raster algebra

Arith-methodsArith functions (+, -, *, ^, %%, %/%, /)
Math-methodsMath functions like abs, sqrt, trunc, log, log10, exp, sin, round
Logic-methodsLogic functions (!, &, |)
Summary-methodsSummary functions (mean, max, min, range, prod, sum, any, all)
Compare-methodsCompare functions (==, !=, >, <, <=, >=)
---------------------------------------------------------------------------------------------------------------------

IV. Cell based computation

calcComputations on a single Raster* object
overlayComputations on multiple RasterLayer objects
coverFirst layer covers second layer except where the first layer is NA
maskUse values from first Raster except where cells of the mask Raster are NA
cutReclassify values using ranges
subsReclassify values using an 'is-becomes' matrix
reclassifyReclassify using a 'from-to-becomes' matrix
initInitialize cells with new values
stackApplyComputations on groups of layers in Raster* object
stackSelectSelect cell values from different layers using an index RasterLayer
---------------------------------------------------------------------------------------------------------------------

V. Spatial contextual computation

distanceShortest distance to a cell that is not NA
gridDistanceDistance when traversing grid cells that are not NA
distanceFromPointsShortest distance to any point in a set of points
directionDirection (azimuth) to or from cells that are not NA
focalFocal (neighborhood; moving window) functions
localFunLocal association (using neighborhoods) functions
boundariesDetection of boundaries (edges)
clumpFind clumps (patches)
adjacentIdentify cells that are adjacent to a set of cells on a raster
areaCompute area of cells (for longitude/latitude data)
terrainCompute slope, aspect and other characteristics from elevation data
MoranCompute global or local Moran or Geary indices of spatial autocorrelation
---------------------------------------------------------------------------------------------------------------------

VI. Model predictions

predictPredict a non-spatial model to a RasterLayer
interpolatePredict a spatial model to a RasterLayer
---------------------------------------------------------------------------------------------------------------------

VII. Data type conversion

You can coerce Raster* objects to Spatial* objects using as, as in as(object, 'SpatialGridDataFrame')

rasterRasterLayer from SpatialGrid*, image, or matrix objects
rasterizeRasterizing points, lines or polygons
rasterToPointsCreate points from a RasterLayer
rasterToPolygonsCreate polygons from a RasterLayer
rasterToContourContour lines from a RasterLayer
rasterFromXYZRasterLayer from regularly spaced points
rasterFromCellsRasterLayer from a Raster object and cell numbers
---------------------------------------------------------------------------------------------------------------------

VIII. Summarizing

cellStatsSummarize a Raster cell values with a function
summarySummary of the values of a Raster* object (quartiles and mean)
freqFrequency table of Raster cell values
crosstabCross-tabulate two Raster* objects
uniqueGet the unique values in a Raster* object
zonalSummarize a Raster* object by zones in a RasterLayer
---------------------------------------------------------------------------------------------------------------------

IX. Accessing values of Raster* object cells

Apart from the function listed below, you can also use indexing with [ for cell numbers, and [[ for row / column number combinations

getValuesGet all cell values (fails with very large rasters), or a row of values (safer)
getValuesBlockGet values for a block (a rectangular area)
getValuesFocalGet focal values for one or more rows
as.matrixGet cell values as a matrix
as.arrayGet cell values as an array
extractExtract cell values from a Raster* object (e.g., by cell, coordinates, polygon)
sampleRandomRandom sample
sampleRegularRegular sample
minValueGet the minimum value of the cells of a Raster* object (not always known)
maxValueGet the maximum value of the cells of a Raster* object (not always known)
setMinMaxCompute the minimum and maximum value of a Raster* object if these are not known
---------------------------------------------------------------------------------------------------------------------

X. Plotting

See the rasterVis package for additional plotting methods for Raster* objects using methods from 'lattice' and other packages.

Maps
plotPlot a Raster* object. The main method to create a map
plotRGBCombine three layers (red, green, blue channels) into a single 'real color' image
spplotPlot a Raster* with the spplot function (sp package)
imagePlot a Raster* with the image function
perspPerspective plot of a RasterLayer
contourContour plot of a RasterLayer
filledContourFilled contour plot of a RasterLayer
textPlot the values of a RasterLayer on top of a map
.Interacting with a map
zoom
Zoom in to a part of a mapclick
Query values of Raster* or Spatial* objects by clicking on a mapselect
Select a geometric subset of a Raster* or Spatial* objectdrawPoly
Create a SpatialPolygons object by drawing itdrawLine
Create a SpatialLines object by drawing itdrawExtent
Create an Extent object by drawing it.
Other plots
plotx-y scatter plot of the values of two RasterLayer objects
histHistogram of Raster* object values
barplotbarplot of a RasterLayer
densityDensity plot of Raster* object values
pairsPairs plot for layers in a RasterStack or RasterBrick
boxplotBox plot of the values of one or multiple layers
---------------------------------------------------------------------------------------------------------------------

XI. Getting and setting Raster* dimensions

Basic parameters of existing Raster* objects can be obtained, and in most cases changed. If there are values associated with a RasterLayer object (either in memory or via a link to a file) these are lost when you change the number of columns or rows or the resolution. This is not the case when the extent is changed (as the number of columns and rows will not be affected). Similarly, with projection you can set the projection, but this does not transform the data (see projectRaster for that).

ncolThe number of columns
nrowThe number of rows
ncellThe number of cells (can not be set directly, only via ncol or nrow)
resThe resolution (x and y)
nlayersHow many layers does the object have?
namesGet or set the layer names
xresThe x resolution (can be set with res)
yresThe y resolution (can be set with res)
xminThe minimum x coordinate (or longitude)
xmaxThe maximum x coordinate (or longitude)
yminThe minimum y coordinate (or latitude)
ymaxThe maximum y coordinate (or latitude)
extentThe extent (minimum and maximum x and y coordinates)
originThe origin of a Raster* object
crsThe coordinate reference system (map projection)
isLonLatTest if an object has a longitude/latitude coordinate reference system
filenameFilename to which a RasterLayer or RasterBrick is linked
bandnrlayer (=band) of a multi-band file that this RasterLayer is linked to
nbandsHow many bands (layers) does the file associated with a RasterLayer object have?
compareRasterCompare the geometry of Raster* objects
NAvalueGet or set the NA value (for reading from a file)
---------------------------------------------------------------------------------------------------------------------

XII. Computing row, column, cell numbers and coordinates

Cell numbers start at 1 in the upper-left corner. They increase within rows, from left to right, and then row by row from top to bottom. Likewise, row numbers start at 1 at the top of the raster, and column numbers start at 1 at the left side of the raster.

xFromColx-coordinates from column numbers
yFromRowy-coordinates from row numbers
xFromCellx-coordinates from row numbers
yFromCelly-coordinates from cell numbers
xyFromCellx and y coordinates from cell numbers
colFromXColumn numbers from x-coordinates (or longitude)
rowFromYRow numbers from y-coordinates (or latitude)
rowColFromCellRow and column numbers from cell numbers
cellFromXYCell numbers from x and y coordinates
cellFromRowColCell numbers from row and column numbers
cellsFromExtentCell numbers from extent object
coordinatesx and y coordinates for all cells
validCellIs this a valid cell number?
validColIs this a valid column number?
validRowIs this a valid row number?
---------------------------------------------------------------------------------------------------------------------

XIII. Writing files

BasicsetValues
Put new values in a Raster* objectwriteRaster
Write all values of Raster* object to diskKML
Save raster as KML file.
AdvancedblockSize
Get suggested block size for reading and writingwriteStart
Open a file for writingwriteValues
Write some valueswriteStop
Close the file after writingupdate
Change the values of an existing file---------------------------
------------------------------------------------------------------------------------------

XIV. Manipulation of SpatialPolygons* and other vector type Spatial* objects

Some of these functions are in the sp package. The name in bold is the equivalent command in ArcGIS. These functions build on the geometry ("spatial features") manipulation functions in package rgeos. These functions are extended here by also providing automated attribute data handling.

bindappend combine Spatial* objects of the same (vector) type
erase or "-"erase parts of a SpatialPolygons* object
intersect or "*"intersect SpatialPolygons* objects
union or "+"union SpatialPolygons* objects
coverupdate and identity for a SpatialPolygons and another one
symdifsymmetrical difference of two SpatialPolygons* objects
aggregatedissolve smaller polygons into larger ones
disaggregateexplode: turn polygon parts into separate polygons (in the sp package)
cropclip a Spatial* object using a rectangle (Extent object)
selectselect - interactively select spatial features
clickidentify attributes by clicking on a map
mergeJoin table (in the sp package)
overspatial queries between Spatial* objects
extractspatial queries between Spatial* and Raster* objects
as.data.framecoerce coordinates of SpatialLines or SpatialPolygons into a data.frame
---------------------------------------------------------------------------------------------------------------------

XV. Extent objects

extentCreate an extent object
intersectIntersect two extent objects
unionCombine two extent objects
roundround/floor/ceiling of the coordinates of an Extent object
alignExtentAlign an extent with a Raster* object
drawExtentCreate an Extent object by drawing it on top of a map (see plot)
---------------------------------------------------------------------------------------------------------------------

XVI. Miscellaneous

rasterOptionsShow, set, save or get session options
getDataDownload and geographic data
pointDistanceDistance between points
readIniFileRead a (windows) 'ini' file
hdrWrite header file for a number of raster formats
trimRemove leading and trailing blanks from a character string
extensionGet or set the extension of a filename
cvCoefficient of variation
modalModal value
sampleIntRandom sample of (possibly very large) range of integer values
showTmpFilesShow temporary files
removeTmpFilesRemove temporary files
---------------------------------------------------------------------------------------------------------------------

XVII. For programmers

canProcessInMemoryTest whether a file can be created in memory
pbCreateInitialize a progress bar
pbStepTake a progress bar step
pbCloseClose a progress bar
readStartOpen file connections for efficient multi-chunk reading
readStopClose file connections
rasterTmpFileGet a name for a temporary file
inMemoryAre the cell values in memory?
fromDiskAre the cell values read from a file?
---------------------------------------------------------------------------------------------------------------------

Author

Except where indicated otherwise, the functions in this package were written by Robert J. Hijmans

Acknowledgments

Extensive contributions were made by Jacob van Etten, Jonathan Greenberg, Matteo Mattiuzzi, and Michael Sumner. Significant help was also provided by Phil Heilman, Agustin Lobo, Oscar Perpinan Lamigueiro, Stefan Schlaffer, Jon Olav Skoien, Steven Mosher, and Kevin Ummel. Contributions were also made by Jochen Albrecht, Neil Best, Andrew Bevan, Roger Bivand, Isabelle Boulangeat, Lyndon Estes, Josh Gray, Tim Haering, Herry Herry, Paul Hiemstra, Ned Hornig, Mayeul Kauffmann, Bart Kranstauber, Rainer Krug, Alice Laborte, John Lewis, Lennon Li, Justin McGrath, Babak Naimi, Carsten Neumann, Joshua Perlman, Richard Plant, Edzer Pebesma, Etienne Racine, David Ramsey, Shaun Walbridge, Julian Zeidler and many others.