Title: | Geographic Data Analysis and Modeling |
---|---|
Description: | Reading, writing, manipulating, analyzing and modeling of spatial data. This package has been superseded by the "terra" package <https://CRAN.R-project.org/package=terra>. |
Authors: | Robert J. Hijmans [cre, aut] , Jacob van Etten [ctb], Michael Sumner [ctb], Joe Cheng [ctb], Dan Baston [ctb], Andrew Bevan [ctb], Roger Bivand [ctb], Lorenzo Busetto [ctb], Mort Canty [ctb], Ben Fasoli [ctb], David Forrest [ctb], Aniruddha Ghosh [ctb], Duncan Golicher [ctb], Josh Gray [ctb], Jonathan A. Greenberg [ctb], Paul Hiemstra [ctb], Kassel Hingee [ctb], Alex Ilich [ctb], Institute for Mathematics Applied Geosciences [cph], Charles Karney [ctb], Matteo Mattiuzzi [ctb], Steven Mosher [ctb], Babak Naimi [ctb], Jakub Nowosad [ctb], Edzer Pebesma [ctb], Oscar Perpinan Lamigueiro [ctb], Etienne B. Racine [ctb], Barry Rowlingson [ctb], Ashton Shortridge [ctb], Bill Venables [ctb], Rafael Wueest [ctb] |
Maintainer: | Robert J. Hijmans <[email protected]> |
License: | GPL (>=3) |
Version: | 3.6-30 |
Built: | 2024-11-01 06:10:42 UTC |
Source: | https://github.com/rspatial/raster |
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')
)
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
.
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:
raster
|
To create a RasterLayer |
stack |
To create a RasterStack (multiple layers) |
brick |
To create a RasterBrick (multiple layers) |
subset |
Select layers of a RasterStack/Brick |
addLayer |
Add a layer to a Raster* object |
dropLayer |
Remove a layer from a RasterStack or RasterBrick |
unstack |
Create a list of RasterLayer objects from a RasterStack |
--------------------------- | --------------------------------------------------------------------------------------------------- |
merge |
Combine Raster* objects with different extents (but same origin and resolution) |
mosaic |
Combine RasterLayers with different extents and a function for overlap areas |
crop |
Select a geographic subset of a Raster* object |
extend |
Enlarge a Raster* object |
trim |
Trim a Raster* object by removing exterior rows and/or columns that only have NAs |
aggregate |
Combine cells of a Raster* object to create larger cells |
disaggregate |
Subdivide cells |
resample |
Warp values to a Raster* object with a different origin or resolution |
projectRaster |
project values to a raster with a different coordinate reference system |
shift |
Move the location of Raster |
flip |
Flip values horizontally or vertically |
rotate |
Rotate values around the date-line (for lon/lat data) |
t |
Transpose a Raster* object |
--------------------------- | ------------------------------------------------------------------------------------------ |
Arith-methods |
Arith functions (+, -, *, ^, %%, %/%, / ) |
Math-methods |
Math functions like abs, sqrt, trunc, log, log10, exp, sin, round |
Logic-methods |
Logic functions (!, &, | ) |
Summary-methods |
Summary functions (mean, max, min, range, prod, sum, any, all ) |
Compare-methods |
Compare functions (==, !=, >, <, <=, >= ) |
--------------------------- | ------------------------------------------------------------------------------------------ |
calc |
Computations on a single Raster* object |
overlay |
Computations on multiple RasterLayer objects |
cover |
First layer covers second layer except where the first layer is NA |
mask |
Use values from first Raster except where cells of the mask Raster are NA
|
cut |
Reclassify values using ranges |
subs |
Reclassify values using an 'is-becomes' matrix |
reclassify |
Reclassify using a 'from-to-becomes' matrix |
init |
Initialize cells with new values |
stackApply |
Computations on groups of layers in Raster* object |
stackSelect |
Select cell values from different layers using an index RasterLayer |
--------------------------- | ------------------------------------------------------------------------------------------ |
distance |
Shortest distance to a cell that is not NA
|
gridDistance |
Distance when traversing grid cells that are not NA |
distanceFromPoints |
Shortest distance to any point in a set of points |
direction |
Direction (azimuth) to or from cells that are not NA
|
focal |
Focal (neighborhood; moving window) functions |
localFun |
Local association (using neighborhoods) functions |
boundaries |
Detection of boundaries (edges) |
clump |
Find clumps (patches) |
adjacent |
Identify cells that are adjacent to a set of cells on a raster |
area |
Compute area of cells (for longitude/latitude data) |
terrain |
Compute slope, aspect and other characteristics from elevation data |
Moran |
Compute global or local Moran or Geary indices of spatial autocorrelation |
--------------------------- | ------------------------------------------------------------------------------------------ |
predict |
Predict a non-spatial model to a RasterLayer |
interpolate |
Predict a spatial model to a RasterLayer |
--------------------------- | ------------------------------------------------------------------------------------------ |
You can coerce Raster* objects to Spatial* objects using as
, as in as(object, 'SpatialGridDataFrame')
raster |
RasterLayer from SpatialGrid*, image, or matrix objects |
rasterize |
Rasterizing points, lines or polygons |
rasterToPoints |
Create points from a RasterLayer |
rasterToPolygons |
Create polygons from a RasterLayer |
rasterToContour |
Contour lines from a RasterLayer |
rasterFromXYZ |
RasterLayer from regularly spaced points |
rasterFromCells |
RasterLayer from a Raster object and cell numbers |
--------------------------- | ------------------------------------------------------------------------------------------ |
cellStats |
Summarize a Raster cell values with a function |
summary |
Summary of the values of a Raster* object (quartiles and mean) |
freq |
Frequency table of Raster cell values |
crosstab |
Cross-tabulate two Raster* objects |
unique |
Get the unique values in a Raster* object |
zonal |
Summarize a Raster* object by zones in a RasterLayer |
--------------------------- | ------------------------------------------------------------------------------------------ |
Apart from the function listed below, you can also use indexing with [
for cell numbers, and [[
for row / column number combinations
getValues |
Get all cell values (fails with very large rasters), or a row of values (safer) |
getValuesBlock |
Get values for a block (a rectangular area) |
getValuesFocal |
Get focal values for one or more rows |
as.matrix |
Get cell values as a matrix |
as.array |
Get cell values as an array |
extract |
Extract cell values from a Raster* object (e.g., by cell, coordinates, polygon) |
sampleRandom |
Random sample |
sampleRegular |
Regular sample |
minValue |
Get the minimum value of the cells of a Raster* object (not always known) |
maxValue |
Get the maximum value of the cells of a Raster* object (not always known) |
setMinMax |
Compute the minimum and maximum value of a Raster* object if these are not known |
--------------------------- | ------------------------------------------------------------------------------------------ |
See the rasterVis package for additional plotting methods for Raster* objects using methods from 'lattice' and other packages.
Maps | |
plot |
Plot a Raster* object. The main method to create a map |
plotRGB |
Combine three layers (red, green, blue channels) into a single 'real color' image |
spplot |
Plot a Raster* with the spplot function (sp package) |
image |
Plot a Raster* with the image function |
persp |
Perspective plot of a RasterLayer |
contour |
Contour plot of a RasterLayer |
filledContour |
Filled contour plot of a RasterLayer |
text |
Plot the values of a RasterLayer on top of a map |
. | |
Interacting with a map | |
zoom |
Zoom in to a part of a map |
click |
Query values of Raster* or Spatial* objects by clicking on a map |
select |
Select a geometric subset of a Raster* or Spatial* object |
drawPoly |
Create a SpatialPolygons object by drawing it |
drawLine |
Create a SpatialLines object by drawing it |
drawExtent |
Create an Extent object by drawing it |
. | |
Other plots | |
plot |
x-y scatter plot of the values of two RasterLayer objects |
hist |
Histogram of Raster* object values |
barplot |
barplot of a RasterLayer |
density |
Density plot of Raster* object values |
pairs |
Pairs plot for layers in a RasterStack or RasterBrick |
boxplot |
Box plot of the values of one or multiple layers |
--------------------------- | ------------------------------------------------------------------------------------------ |
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).
ncol
|
The number of columns |
nrow |
The number of rows |
ncell |
The number of cells (can not be set directly, only via ncol or nrow) |
res |
The resolution (x and y) |
nlayers |
How many layers does the object have? |
names |
Get or set the layer names |
xres |
The x resolution (can be set with res) |
yres |
The y resolution (can be set with res) |
xmin |
The minimum x coordinate (or longitude) |
xmax |
The maximum x coordinate (or longitude) |
ymin |
The minimum y coordinate (or latitude) |
ymax |
The maximum y coordinate (or latitude) |
extent |
The extent (minimum and maximum x and y coordinates) |
origin |
The origin of a Raster* object |
crs |
The coordinate reference system (map projection) |
isLonLat |
Test if an object has a longitude/latitude coordinate reference system |
filename |
Filename to which a RasterLayer or RasterBrick is linked |
bandnr |
layer (=band) of a multi-band file that this RasterLayer is linked to |
nbands |
How many bands (layers) does the file associated with a RasterLayer object have? |
compareRaster |
Compare the geometry of Raster* objects |
NAvalue |
Get or set the NA value (for reading from a file) |
--------------------------- | ------------------------------------------------------------------------------------------ |
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.
xFromCol |
x-coordinates from column numbers |
yFromRow |
y-coordinates from row numbers |
xFromCell |
x-coordinates from row numbers |
yFromCell |
y-coordinates from cell numbers |
xyFromCell |
x and y coordinates from cell numbers |
colFromX |
Column numbers from x-coordinates (or longitude) |
rowFromY |
Row numbers from y-coordinates (or latitude) |
rowColFromCell |
Row and column numbers from cell numbers |
cellFromXY |
Cell numbers from x and y coordinates |
cellFromRowCol |
Cell numbers from row and column numbers |
cellsFromExtent |
Cell numbers from extent object |
coordinates |
x and y coordinates for all cells |
validCell |
Is this a valid cell number? |
validCol |
Is this a valid column number? |
validRow |
Is this a valid row number? |
--------------------------- | ------------------------------------------------------------------------------------------ |
Basic | |
setValues |
Put new values in a Raster* object |
writeRaster |
Write all values of Raster* object to disk |
KML |
Save raster as KML file |
. | |
Advanced | |
blockSize |
Get suggested block size for reading and writing |
writeStart |
Open a file for writing |
writeValues |
Write some values |
writeStop |
Close the file after writing |
update |
Change the values of an existing file |
--------------------------- | ------------------------------------------------------------------------------------------ |
Some of these functions are in the sp
package. The name in bold is the equivalent command in ArcGIS.
bind |
append 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 |
cover |
update and identity for a SpatialPolygons and another one |
symdif |
symmetrical difference of two SpatialPolygons* objects |
aggregate |
dissolve smaller polygons into larger ones |
disaggregate |
explode: turn polygon parts into separate polygons (in the sp package) |
crop |
clip a Spatial* object using a rectangle (Extent object) |
select |
select - interactively select spatial features |
click |
identify attributes by clicking on a map |
merge |
Join table (in the sp package) |
over |
spatial queries between Spatial* objects |
extract |
spatial queries between Spatial* and Raster* objects |
as.data.frame |
coerce coordinates of SpatialLines or SpatialPolygons into a data.frame |
--------------------------- | ------------------------------------------------------------------------------------------ |
extent |
Create an extent object |
intersect |
Intersect two extent objects |
union |
Combine two extent objects |
round |
round/floor/ceiling of the coordinates of an Extent object |
alignExtent |
Align an extent with a Raster* object |
drawExtent |
Create an Extent object by drawing it on top of a map (see plot) |
--------------------------- | ------------------------------------------------------------------------------------------ |
rasterOptions |
Show, set, save or get session options |
pointDistance |
Distance between points |
readIniFile |
Read a (windows) 'ini' file |
hdr |
Write header file for a number of raster formats |
trim |
Remove leading and trailing blanks from a character string |
extension |
Get or set the extension of a filename |
cv |
Coefficient of variation |
modal |
Modal value |
sampleInt |
Random sample of (possibly very large) range of integer values |
showTmpFiles |
Show temporary files |
removeTmpFiles |
Remove temporary files |
--------------------------- | ------------------------------------------------------------------------------------------ |
canProcessInMemory |
Test whether a file can be created in memory |
pbCreate |
Initialize a progress bar |
pbStep |
Take a progress bar step |
pbClose |
Close a progress bar |
readStart |
Open file connections for efficient multi-chunk reading |
readStop |
Close file connections |
rasterTmpFile |
Get a name for a temporary file |
inMemory |
Are the cell values in memory? |
fromDisk |
Are the cell values read from a file? |
--------------------------- | ------------------------------------------------------------------------------------------ |
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.
Except where indicated otherwise, the functions in this package were written by Robert J. Hijmans
Add a layer to a Raster* object or drop a layer from a RasterStack or RasterBrick. The object returned is always a RasterStack (unless nothing to add or drop was provided, in which case the original object is returned).
addLayer(x, ...) dropLayer(x, i, ...)
addLayer(x, ...) dropLayer(x, i, ...)
x |
Raster* object |
i |
integer. Indices of the layers to be dropped |
... |
Additional arguments. The layers to add for addLayer. None implemented for dropLayer) |
RasterStack
file <- system.file("external/test.grd", package="raster") s <- stack(file, file, file) r <- raster(file) s <- addLayer(s, r/2, r*2) s s <- dropLayer(s, c(3, 5)) nlayers(s)
file <- system.file("external/test.grd", package="raster") s <- stack(file, file, file) r <- raster(file) s <- addLayer(s, r/2, r*2) s s <- dropLayer(s, c(3, 5)) nlayers(s)
Identify cells that are adjacent to a set of cells on a raster.
## S4 method for signature 'BasicRaster' adjacent(x, cells, directions=4, pairs=TRUE, target=NULL, sorted=FALSE, include=FALSE, id=FALSE, ...)
## S4 method for signature 'BasicRaster' adjacent(x, cells, directions=4, pairs=TRUE, target=NULL, sorted=FALSE, include=FALSE, id=FALSE, ...)
x |
Raster* object |
cells |
vector of cell numbers for which adjacent cells should be found. Cell numbers start with 1 in the upper-left corner and increase from left to right and from top to bottom |
directions |
the number of directions in which cells should be connected: 4 (rook's case), 8 (queen's case), 16 (knight and one-cell queen moves), or 'bishop' to connect cells with one-cell diagonal moves. Or a neighborhood matrix (see Details) |
pairs |
logical. If |
target |
optional vector of target cell numbers that should be considered. All other adjacent cells are ignored |
sorted |
logical. Should the results be sorted? |
include |
logical. Should the focal cells be included in the result? |
id |
logical. Should the id of the cells be included in the result? (numbered from 1 to length(cells) |
... |
additional arguments. None implemented |
A neighborhood matrix identifies the cells around each cell that are considered adjacent. The matrix should have one, and only one, cell with value 0 (the focal cell); at least one cell with value 1 (the adjacent cell(s)); All other cells are not considered adjacent and ignored.
matrix or vector with adjacent cells.
Robert J. Hijmans and Jacob van Etten
r <- raster(nrows=10, ncols=10) adjacent(r, cells=c(1, 55), directions=8, pairs=TRUE) a <- adjacent(r, cell = c(1,55,90), directions=4, sorted=TRUE) a r[c(1,55,90)] <- 1 r[a] <- 2 plot(r) # same result as above rook <- matrix(c(NA, 1, NA, 1, 0, 1, NA, 1, NA), ncol=3, byrow=TRUE) adjacent(r, cells = c(1,55,90), directions=rook, sorted=TRUE) # Count the number of times that a cell with a certain value # occurs next to a cell with a certain value set.seed(0) r <- raster(ncol=10, nrow=10) values(r) <- round(runif(ncell(r)) * 5) a <- adjacent(r, 1:ncell(r), 4, pairs=TRUE) tb <- table(r[a[,1]], r[a[,2]]) tb # make a matrix out of the 'table' object tb <- unclass(tb) plot(raster(tb, xmn=-0.5, xmx=5.5, ymn=-0.5, ymx=5.5))
r <- raster(nrows=10, ncols=10) adjacent(r, cells=c(1, 55), directions=8, pairs=TRUE) a <- adjacent(r, cell = c(1,55,90), directions=4, sorted=TRUE) a r[c(1,55,90)] <- 1 r[a] <- 2 plot(r) # same result as above rook <- matrix(c(NA, 1, NA, 1, 0, 1, NA, 1, NA), ncol=3, byrow=TRUE) adjacent(r, cells = c(1,55,90), directions=rook, sorted=TRUE) # Count the number of times that a cell with a certain value # occurs next to a cell with a certain value set.seed(0) r <- raster(ncol=10, nrow=10) values(r) <- round(runif(ncell(r)) * 5) a <- adjacent(r, 1:ncell(r), 4, pairs=TRUE) tb <- table(r[a[,1]], r[a[,2]]) tb # make a matrix out of the 'table' object tb <- unclass(tb) plot(raster(tb, xmn=-0.5, xmx=5.5, ymn=-0.5, ymx=5.5))
Raster* objects:
Aggregate a Raster* object to create a new RasterLayer or RasterBrick with a lower resolution (larger cells). Aggregation groups rectangular areas to create larger cells. The value for the resulting cells is computed with a user-specified function.
SpatialPolygon*:
Aggregate a SpatialPolygon* object, optionally by combining polygons that have the same attributes for one or more variables. If the polygons touch or overlap, internal boundaries are optionally "dissolved".
## S4 method for signature 'Raster' aggregate(x, fact, fun=mean, expand=TRUE, na.rm=TRUE, filename='', ...) ## S4 method for signature 'SpatialPolygons' aggregate(x, by, sums, dissolve=TRUE, vars=NULL, ...)
## S4 method for signature 'Raster' aggregate(x, fact, fun=mean, expand=TRUE, na.rm=TRUE, filename='', ...) ## S4 method for signature 'SpatialPolygons' aggregate(x, by, sums, dissolve=TRUE, vars=NULL, ...)
x |
Raster* object or SpatialPolygons* object |
fact |
postive integer. Aggregation factor expressed as number of cells in each direction (horizontally and vertically). Or two integers (horizontal and vertical aggregation factor) or three integers (when also aggregating over layers). See Details |
fun |
function used to aggregate values |
expand |
logical. If |
na.rm |
logical. If |
filename |
character. Output filename (optional) |
... |
if |
by |
character or integer. The variables (column names or numbers) that should be used to aggregate (dissolve) the SpatialPolygons by only maintaining unique combinations of these variables. The default setting is to use no variables and aggregate all polygons. You can also supply a vector with a length of length(x) |
sums |
list with function(s) and variable(s) to summarize. This should be a list of lists in which each element of the main lists has two items. The first item is function (e.g. mean), the second element is a vector of column names (or indices) that need to summarize with that function. Be careful with character and factor variables (you can use, e.g. 'first' |
vars |
deprecated. Same as |
dissolve |
logical. If |
Aggregation of a x
will result in a Raster* object with fewer cells. The number of cells is the number of cells of x
divided by fact*fact
(when fact is a single number) or prod(fact)
(when fact consists of 2 or 3 numbers). If necessary this number is adjusted according to the value of expand
. For example, fact=2
will result in a new Raster* object with 2*2=4
times fewer cells. If two numbers are supplied, e.g., fact=c(2,3)
, the first will be used for aggregating in the horizontal direction, and the second for aggregating in the vertical direction, and the returned object will have 2*3=6
times fewer cells. Likewise, fact=c(2,3,4)
aggregates cells in groups of 2 (rows) by 3 (columns) and 4 (layers).
Aggregation starts at the upper-left end of a raster (you can use flip
if you want to start elsewhere). If a division of the number of columns or rows with factor
does not return an integer, the extent of the resulting Raster object will either be somewhat smaller or somewhat larger than the original RasterLayer. For example, if an input RasterLayer has 100 columns, and fact=12
, the output Raster object will have either 8 columns (expand=FALSE
) (using 8 x 12 = 96
of the original columns) or 9 columns (expand=TRUE
). In both cases, the maximum x coordinate of the output RasterLayer would, of course, also be adjusted.
The function fun
should take multiple numbers, and return a single number. For example mean
, modal
, min
or max
.
It should also accept a na.rm
argument (or ignore it as one of the 'dots' arguments).
RasterLayer or RasterBrick, or a SpatialPolygons* object
Robert J. Hijmans and Jacob van Etten
disaggregate
, resample
. For SpatialPolygons* disaggregate
r <- raster() # a new aggregated raster, no values ra <- aggregate(r, fact=10) r <- setValues(r, runif(ncell(r))) # a new aggregated raster, max of the values ra <- aggregate(r, fact=10, fun=max) # multiple layers s <- stack(r, r*2) x <- aggregate(s,2) #SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) p pa0 <- aggregate(p) pa0 pa1 <- aggregate(p, by='NAME_1', sums=list(list(mean, 'ID_2'))) pa1
r <- raster() # a new aggregated raster, no values ra <- aggregate(r, fact=10) r <- setValues(r, runif(ncell(r))) # a new aggregated raster, max of the values ra <- aggregate(r, fact=10, fun=max) # multiple layers s <- stack(r, r*2) x <- aggregate(s,2) #SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) p pa0 <- aggregate(p) pa0 pa1 <- aggregate(p, by='NAME_1', sums=list(list(mean, 'ID_2'))) pa1
Align an Extent object with the (boundaries of the) cells of a Raster* object
alignExtent(extent, object, snap='near')
alignExtent(extent, object, snap='near')
extent |
Extent object |
object |
Raster* object |
snap |
Character. One of 'near', 'in', or 'out', to determine in which direction the extent should be aligned. To the nearest border, inwards or outwards |
Aligning an Extent object to another object assures that it gets the same origin and resolution. This should only be used to adjust objects because of imprecision in the data. alignExtent should not be used to force data to match that really does not match (use e.g. resample
or (dis)aggregate for this).
Extent object
extent
, drawExtent
, Extent-class
r <- raster() e <- extent(-10.1, 9.9, -20.1, 19.9) ea <- alignExtent(e, r) e extent(r) ea
r <- raster() e <- extent(-10.1, 9.9, -20.1, 19.9) ea <- alignExtent(e, r) e extent(r) ea
Animate (sequentially plot) the layers of a RasterStack or RasterBrick* object to create a movie
## S4 method for signature 'RasterStackBrick' animate(x, pause=0.25, main, zlim, maxpixels=50000, n=10, ...)
## S4 method for signature 'RasterStackBrick' animate(x, pause=0.25, main, zlim, maxpixels=50000, n=10, ...)
x |
Raster* object |
pause |
numeric. How long should be the pause be between layers? |
main |
title for each layer. If not supplied the z-value is used if available. Otherwise the names are used. |
zlim |
numeric vector of lenght 2. Range of values to plot |
maxpixels |
integer > 0. Maximum number of cells to use for the plot. If |
n |
integer > 0. Number of loops |
... |
Additional arguments passed to |
None
b <- brick(system.file("external/rlogo.grd", package="raster")) animate(b, n=1)
b <- brick(system.file("external/rlogo.grd", package="raster")) animate(b, n=1)
NA
by interpolating between layersapproxNA uses the stats
function approx
to estimate values for cells that are NA
by interpolation across layers. Layers are considered equidistant, unless an argument 'z' is used, or getZ
returns values, in which case these values are used to determine distance between layers.
For estimation based on neighbouring cells see focal
## S4 method for signature 'RasterStackBrick' approxNA(x, filename="", method="linear", yleft, yright, rule=1, f=0, ties=mean, z=NULL, NArule=1, ...)
## S4 method for signature 'RasterStackBrick' approxNA(x, filename="", method="linear", yleft, yright, rule=1, f=0, ties=mean, z=NULL, NArule=1, ...)
x |
RasterStack or RasterBrick object |
filename |
character. Output filename (optional) |
method |
specifies the interpolation method to be used. Choices are "linear" or "constant" (step function; see the example in |
yleft |
the value to be returned before a non- |
yright |
the value to be returned after the last non- |
rule |
an integer (of length 1 or 2) describing how interpolation is to take place at for the first and last cells (before or after any non- |
f |
for method = "constant" a number between 0 and 1 inclusive, indicating a compromise between left- and right-continuous step functions. If y0 and y1 are the values to the left and right of the point then the value is |
ties |
Handling of tied 'z' values. Either a function with a single vector argument returning a single number result or the string "ordered" |
z |
numeric vector to indicate the distance between layers (e.g., time, depth). The default is 1:nlayers(x) |
NArule |
single integer used to determine what to do when only a single layer with a non- |
... |
additional arguments as for |
RasterBrick
r <- raster(ncols=5, nrows=5) r1 <- setValues(r, runif(ncell(r))) r2 <- setValues(r, runif(ncell(r))) r3 <- setValues(r, runif(ncell(r))) r4 <- setValues(r, runif(ncell(r))) r5 <- setValues(r, NA) r6 <- setValues(r, runif(ncell(r))) r1[6:10] <- NA r2[5:15] <- NA r3[8:25] <- NA s <- stack(r1,r2,r3,r4,r5,r6) s[1:5] <- NA x1 <- approxNA(s) x2 <- approxNA(s, rule=2) x3 <- approxNA(s, rule=2, z=c(1,2,3,5,14,15))
r <- raster(ncols=5, nrows=5) r1 <- setValues(r, runif(ncell(r))) r2 <- setValues(r, runif(ncell(r))) r3 <- setValues(r, runif(ncell(r))) r4 <- setValues(r, runif(ncell(r))) r5 <- setValues(r, NA) r6 <- setValues(r, runif(ncell(r))) r1[6:10] <- NA r2[5:15] <- NA r3[8:25] <- NA s <- stack(r1,r2,r3,r4,r5,r6) s[1:5] <- NA x1 <- approxNA(s) x2 <- approxNA(s, rule=2) x3 <- approxNA(s, rule=2, z=c(1,2,3,5,14,15))
Raster objects: Compute the approximate surface area of cells in an unprojected (longitude/latitude) Raster object. It is an approximation because area is computed as the height (latitudinal span) of a cell (which is constant among all cells) times the width (longitudinal span) in the (latitudinal) middle of a cell. The width is smaller at the poleward side than at the equator-ward side of a cell. This variation is greatest near the poles and the values are thus not very precise for very high latitudes.
SpatialPolygons: Compute the area of the spatial features. Works for both planar and angular (lon/lat) coordinate reference systems
## S4 method for signature 'RasterLayer' area(x, filename="", na.rm=FALSE, weights=FALSE, ...) ## S4 method for signature 'RasterStackBrick' area(x, filename="", na.rm=FALSE, weights=FALSE, ...) ## S4 method for signature 'SpatialPolygons' area(x, ...)
## S4 method for signature 'RasterLayer' area(x, filename="", na.rm=FALSE, weights=FALSE, ...) ## S4 method for signature 'RasterStackBrick' area(x, filename="", na.rm=FALSE, weights=FALSE, ...) ## S4 method for signature 'SpatialPolygons' area(x, ...)
x |
Raster* or SpatialPolygons object |
filename |
character. Filename for the output Raster object (optional) |
na.rm |
logical. If |
weights |
logical. If |
... |
additional arguments as for |
If x
is a RasterStack/Brick, a RasterBrick will be returned if na.rm=TRUE
. However, if na.rm=FALSE
, a RasterLayer is returned, because the values would be the same for all layers.
If x
is a Raster* object: RasterLayer or RasterBrick. Cell values represent the size of the cell in km2, or the relative size if weights=TRUE
. If the CRS is not longitude/latitude the values returned are the product of the cell resolution (typically in square meter).
If x
is a SpatialPolygons* object: area of each spatial object in squared meters if the CRS is longitude/latitude, or in squared map units (typically meter)
r <- raster(nrow=18, ncol=36) a <- area(r) p <- shapefile(system.file("external/lux.shp", package="raster")) p$area <- round(area(p) / 10000000,1) p$area
r <- raster(nrow=18, ncol=36) a <- area(r) p <- shapefile(system.file("external/lux.shp", package="raster")) p$area <- round(area(p) / 10000000,1) p$area
Standard arithmetic operators for computations with Raster* objects and numeric values. The following operators are available:
+, -, *, /, ^, %%, %/%
The input Raster* objects should have the same extent, origin and resolution. If only the extent differs, the computation will continue for the intersection of the Raster objects. Operators are applied on a cell by cell basis. For a RasterLayer, numeric values are recycled by row. For a RasterStack or RasterBrick, recycling is done by layer. RasterLayer objects can be combined RasterStack/Brick objects, in which case the RasterLayer is 'recycled'. When using multiple RasterStack or RasterBrick objects, the number of layers of these objects needs to be the same.
In addition to arithmetic with Raster* objects, the following operations are supported for SpatialPolygons* objects.
Given SpatialPolygon objects x
and y
:
x+y
is the same as union(x, y)
. For SpatialLines* and SpatialPoints* it is equivalent to bind(x, y)
x*y
is the same as intersect(x, y)
x-y
is the same as erase(x, y)
If the values of the output Raster* cannot be held in memory, they will be saved to a temporary file.
You can use options
to set the default file format, datatype and progress bar.
A Raster* object, and in some cases the side effect of a new file on disk.
r1 <- raster(ncols=10, nrows=10) values(r1) <- runif(ncell(r1)) r2 <- setValues(r1, 1:ncell(r1) / ncell(r1) ) r3 <- r1 + r2 r2 <- r1 / 10 r3 <- r1 * (r2 - 1 + r1^2 / r2) # recycling by row r4 <- r1 * 0 + 1:ncol(r1) # multi-layer object mutiplication, no recycling b1 <- brick(r1, r2, r3) b2 <- b1 * 10 # recycling by layer b3 <- b1 + c(1, 5, 10) # addition of the cell-values of two RasterBrick objects b3 <- b2 + b1 # summing two RasterBricks and one RasterLayer. The RasterLayer is 'recycled' b3 <- b1 + b2 + r1
r1 <- raster(ncols=10, nrows=10) values(r1) <- runif(ncell(r1)) r2 <- setValues(r1, 1:ncell(r1) / ncell(r1) ) r3 <- r1 + r2 r2 <- r1 / 10 r3 <- r1 * (r2 - 1 + r1^2 / r2) # recycling by row r4 <- r1 * 0 + 1:ncol(r1) # multi-layer object mutiplication, no recycling b1 <- brick(r1, r2, r3) b2 <- b1 * 10 # recycling by layer b3 <- b1 + c(1, 5, 10) # addition of the cell-values of two RasterBrick objects b3 <- b2 + b1 # summing two RasterBricks and one RasterLayer. The RasterLayer is 'recycled' b3 <- b1 + b2 + r1
as.character
returns a text (R code) representation of a Raster* or Extent object. The main purpose of this is to allow quick generation of objects to use in examples on, for example, stackoverflow.com.
## S4 method for signature 'Raster' as.character(x, ...) ## S4 method for signature 'Extent' as.character(x, ...)
## S4 method for signature 'Raster' as.character(x, ...) ## S4 method for signature 'Extent' as.character(x, ...)
x |
Raster* or Extent object |
... |
additional arguments, none implemented |
character
r <- raster(ncol=3, nrow=3) values(r) <- 1:ncell(r) as.character(r) s <- stack(r, r) as.character(s) as.character(extent(s)) x <- as.character(s) eval(parse(text=x)) y <- as.character(extent(s)) eval(parse(text=y))
r <- raster(ncol=3, nrow=3) values(r) <- 1:ncell(r) as.character(r) s <- stack(r, r) as.character(s) as.character(extent(s)) x <- as.character(s) eval(parse(text=x)) y <- as.character(extent(s)) eval(parse(text=y))
as.matrix
returns all values of a Raster* object as a matrix. For RasterLayers, rows and columns in the matrix represent rows and columns in the RasterLayer object. For other Raster* objects, the matrix returned by as.matrix
has columns for each layer and rows for each cell.
as.array
returns an array of matrices that are like those returned by as.matrix
for a RasterLayer
If there is insufficient memory to load all values, you can use getValues
or getValuesBlock
to read chunks of the file. You could also first use sampleRegular
The methods for Spatial* objects allow for easy creation of a data.frame with the coordinates and attributes; the default method only returns the attributes data.frame
## S4 method for signature 'Raster' as.data.frame(x, row.names=NULL, optional=FALSE, xy=FALSE, na.rm=FALSE, long=FALSE, ...) ## S4 method for signature 'SpatialPolygons' as.data.frame(x, row.names=NULL, optional=FALSE, xy=FALSE, centroids=TRUE, sepNA=FALSE, ...) ## S4 method for signature 'SpatialLines' as.data.frame(x, row.names=NULL, optional=FALSE, xy=FALSE, sepNA=FALSE, ...)
## S4 method for signature 'Raster' as.data.frame(x, row.names=NULL, optional=FALSE, xy=FALSE, na.rm=FALSE, long=FALSE, ...) ## S4 method for signature 'SpatialPolygons' as.data.frame(x, row.names=NULL, optional=FALSE, xy=FALSE, centroids=TRUE, sepNA=FALSE, ...) ## S4 method for signature 'SpatialLines' as.data.frame(x, row.names=NULL, optional=FALSE, xy=FALSE, sepNA=FALSE, ...)
x |
Raster* object |
row.names |
|
optional |
logical. If |
xy |
logical. If |
na.rm |
logical. If |
long |
logical. If |
centroids |
logical. If |
sepNA |
logical. If |
... |
Additional arguments (none) |
data.frame
r <- raster(ncol=3, nrow=3) values(r) <- sqrt(1:ncell(r)) r[3:5] <- NA as.data.frame(r) s <- stack(r, r*2) as.data.frame(s) as.data.frame(s, na.rm=TRUE)
r <- raster(ncol=3, nrow=3) values(r) <- sqrt(1:ncell(r)) r[3:5] <- NA as.data.frame(r) s <- stack(r, r*2) as.data.frame(s) as.data.frame(s, na.rm=TRUE)
Create a list of RasterLayer objects from Raster* objects
## S4 method for signature 'Raster' as.list(x, ...)
## S4 method for signature 'Raster' as.list(x, ...)
x |
Raster* object |
... |
additional Raster* objects |
list
r <- raster(ncol=3, nrow=3) values(r) <- 1:ncell(r) as.list(r) s <- stack(r,r*2,r*3) as.list(s, r)
r <- raster(ncol=3, nrow=3) values(r) <- 1:ncell(r) as.list(r) s <- stack(r,r*2,r*3) as.list(s, r)
Change values of a Raster* object to logical or integer values. With as.logical
, zero becomes FALSE
, all other values become TRUE
. With as.integer
values are truncated.
## S4 method for signature 'Raster' as.logical(x, filename='', ...) ## S4 method for signature 'Raster' as.integer(x, filename='', ...)
## S4 method for signature 'Raster' as.logical(x, filename='', ...) ## S4 method for signature 'Raster' as.integer(x, filename='', ...)
x |
Raster* object |
filename |
character. Output filename (optional) |
... |
additional optional arguments as for |
r <- raster(nrow=10, ncol=10) set.seed(0) values(r) <- runif(ncell(r)) * 10 r r <- as.integer(r) r as.logical(r)
r <- raster(nrow=10, ncol=10) set.seed(0) values(r) <- runif(ncell(r)) * 10 r r <- as.integer(r) r as.logical(r)
as.vector
returns a vector of cell values. For a RasterLayer it is equivalent to getValues(x).
as.matrix
returns all values of a Raster* object as a matrix. For RasterLayers, rows and columns in the matrix represent rows and columns in the RasterLayer object. For other Raster* objects, the matrix returned by as.matrix
has columns for each layer and rows for each cell.
as.array
returns an array of matrices that are like those returned by as.matrix
for a RasterLayer
If there is insufficient memory to load all values, you can use getValues
or getValuesBlock
to read chunks of the file.
as.matrix
and as.vector
can also be used to obtain the coordinates from an Extent object.
as.matrix(x, ...) as.array(x, ...) ## S4 method for signature 'Extent' as.vector(x, mode='any') ## S4 method for signature 'Raster' as.vector(x, mode='any')
as.matrix(x, ...) as.array(x, ...) ## S4 method for signature 'Extent' as.vector(x, mode='any') ## S4 method for signature 'Raster' as.vector(x, mode='any')
x |
Raster* or (for |
mode |
Character string giving an atomic mode (such as "numeric" or "character") or "list", or "any". Note: this argument is currently ignored! |
... |
additional arguments:
|
matrix, array, or vector
r <- raster(ncol=3, nrow=3) values(r) <- 1:ncell(r) as.matrix(r) s <- stack(r,r) as.array(s) as.vector(extent(s))
r <- raster(ncol=3, nrow=3) values(r) <- 1:ncell(r) as.matrix(r) s <- stack(r,r) as.array(s) as.vector(extent(s))
Implementation of the generic as.raster
function to create a 'raster' (small r) object. NOT TO BE CONFUSED with the Raster* (big R) objects defined by the raster package! Such objects can be used for plotting with the rasterImage
function.
as.raster(x, ...)
as.raster(x, ...)
x |
RasterLayer object |
... |
Additional arguments.
|
'raster' object
r <- raster(ncol=3, nrow=3) values(r) <- 1:ncell(r) as.raster(r)
r <- raster(ncol=3, nrow=3) values(r) <- 1:ncell(r) as.raster(r)
For Raster* objects x and y, atan2(y, x) returns the angle in radians for the tangent y/x, handling the case when x is zero. See Trig
See Math-methods
for other trigonometric and mathematical functions that can be used with Raster* objects.
atan2(y, x)
atan2(y, x)
y |
Raster* object |
x |
Raster* object |
r1 <- r2 <- raster(nrow=10, ncol=10) values(r1) <- (runif(ncell(r1))-0.5) * 10 values(r2) <- (runif(ncell(r1))-0.5) * 10 atan2(r1, r2)
r1 <- r2 <- raster(nrow=10, ncol=10) values(r1) <- (runif(ncell(r1))-0.5) * 10 values(r2) <- (runif(ncell(r1))-0.5) * 10 atan2(r1, r2)
Compute Moran's I or Geary's C measures of global spatial autocorrelation in a RasterLayer, or compute the the local Moran or Geary index (Anselin, 1995).
Geary(x, w=matrix(c(1,1,1,1,0,1,1,1,1), 3,3)) Moran(x, w=matrix(c(1,1,1,1,0,1,1,1,1), 3,3)) MoranLocal(x, w=matrix(c(1,1,1,1,0,1,1,1,1), 3,3)) GearyLocal(x, w=matrix(c(1,1,1,1,0,1,1,1,1), 3,3))
Geary(x, w=matrix(c(1,1,1,1,0,1,1,1,1), 3,3)) Moran(x, w=matrix(c(1,1,1,1,0,1,1,1,1), 3,3)) MoranLocal(x, w=matrix(c(1,1,1,1,0,1,1,1,1), 3,3)) GearyLocal(x, w=matrix(c(1,1,1,1,0,1,1,1,1), 3,3))
x |
RasterLayer |
w |
Spatial weights defined by or a rectangular matrix with odd length (3, 5, ...) sides (as in |
The default setting uses a 3x3 neighborhood to compute "Queen's case" indices. You can use a filter (weights matrix) to do other things, such as "Rook's case", or different lags.
A single value (Moran's I or Geary's C) or a RasterLayer (Local Moran or Geary values)
Robert J. Hijmans and Babak Naimi
Moran, P.A.P., 1950. Notes on continuous stochastic phenomena. Biometrika 37:17-23
Geary, R.C., 1954. The contiguity ratio and statistical mapping. The Incorporated Statistician 5: 115-145
Anselin, L., 1995. Local indicators of spatial association-LISA. Geographical Analysis 27:93-115
The spdep package for additional and more general approaches for computing indices of spatial autocorrelation
r <- raster(nrows=10, ncols=10) values(r) <- 1:ncell(r) Moran(r) # Rook's case f <- matrix(c(0,1,0,1,0,1,0,1,0), nrow=3) Moran(r, f) Geary(r) x1 <- MoranLocal(r) # Rook's case x2 <- MoranLocal(r, w=f)
r <- raster(nrows=10, ncols=10) values(r) <- 1:ncell(r) Moran(r) # Rook's case f <- matrix(c(0,1,0,1,0,1,0,1,0), nrow=3) Moran(r, f) Geary(r) x1 <- MoranLocal(r) # Rook's case x2 <- MoranLocal(r, w=f)
A 'band' refers to a single layer for a possibly multi-layer file. Most RasterLayer objects will refer to files with a single layer. The term 'band' is frequently used in remote sensing to refer to a variable (layer) in a multi-variable dataset as these variables typically reperesent reflection in different bandwidths in the electromagnetic spectrum. But in that context, bands could be stored in a single or in separate files. In the context of the raster package, the term band is equivalent to a layer in a raster file.
nbands
returns the number of bands of the file that a RasterLayer points to (and 1 if it does not point at any file). This functions also works for a RasterStack for which it is equivalent to nlayers
.
band
returns the specific band the RasterLayer refers to (1 if the RasterLayer points at single layer file or does not point at any file).
nbands(x) bandnr(x, ...)
nbands(x) bandnr(x, ...)
x |
RasterLayer |
... |
Additional arguments (none at this time) |
numeric >= 1
f <- system.file("external/rlogo.grd", package="raster") r <- raster(f, layer=2) nbands(r) bandnr(r)
f <- system.file("external/rlogo.grd", package="raster") r <- raster(f, layer=2) nbands(r) bandnr(r)
Create a barplot of the values of a RasterLayer. For large datasets a regular sample with a size of approximately maxpixels
is used.
## S4 method for signature 'RasterLayer' barplot(height, maxpixels=1000000, digits=0, breaks=NULL, col=rainbow, ...)
## S4 method for signature 'RasterLayer' barplot(height, maxpixels=1000000, digits=0, breaks=NULL, col=rainbow, ...)
height |
RasterLayer |
maxpixels |
integer. To regularly subsample very large objects |
digits |
integer used to determine how to |
breaks |
breaks used to group the data as in |
col |
a color generating function such as |
... |
additional arguments for plotting as in |
A numeric vector (or matrix, when beside = TRUE
) of the coordinates of the bar midpoints, useful for adding to the graph. See barplot
f <- system.file("external/test.grd", package="raster") r <- raster(f) barplot(r, digits=-2, las=2, ylab='Frequency') op <- par(no.readonly = TRUE) par(mai = c(1, 2, .5, .5)) barplot(r, breaks=10, col=c('red', 'blue'), horiz=TRUE, digits=NULL, las=1) par(op)
f <- system.file("external/test.grd", package="raster") r <- raster(f) barplot(r, digits=-2, las=2, ylab='Frequency') op <- par(no.readonly = TRUE) par(mai = c(1, 2, .5, .5)) barplot(r, breaks=10, col=c('red', 'blue'), horiz=TRUE, digits=NULL, las=1) par(op)
Bind (append) Spatial* objects into a single object. All objects must be of the same vector type base class (SpatialPoints, SpatialLines, or SpatialPolygons)
## S4 method for signature 'SpatialPolygons,SpatialPolygons' bind(x, y, ..., keepnames=FALSE) ## S4 method for signature 'SpatialLines,SpatialLines' bind(x, y, ..., keepnames=FALSE) ## S4 method for signature 'SpatialPoints,SpatialPoints' bind(x, y, ..., keepnames=FALSE) ## S4 method for signature 'data.frame,data.frame' bind(x, y, ..., variables=NULL) ## S4 method for signature 'list,missing' bind(x, y, ..., keepnames=FALSE)
## S4 method for signature 'SpatialPolygons,SpatialPolygons' bind(x, y, ..., keepnames=FALSE) ## S4 method for signature 'SpatialLines,SpatialLines' bind(x, y, ..., keepnames=FALSE) ## S4 method for signature 'SpatialPoints,SpatialPoints' bind(x, y, ..., keepnames=FALSE) ## S4 method for signature 'data.frame,data.frame' bind(x, y, ..., variables=NULL) ## S4 method for signature 'list,missing' bind(x, y, ..., keepnames=FALSE)
x |
Spatial* object or data.frame, or a list of Spatial* objects |
y |
Spatial* object or data.frame, or missing |
... |
Additional Spatial* objects |
keepnames |
Logical. If |
variables |
character. Variable (column) names to keep, If |
Spatial* object
p <- readRDS(system.file("external/lux.rds", package="raster")) mersch <- p[p$NAME_2=='Mersch', ] diekirch <- p[p$NAME_2=='Diekirch', ] remich <- p[p$NAME_2=='Remich', ] remich$NAME_1 <- NULL x <- bind(mersch, diekirch, remich) plot(x) data.frame(x)
p <- readRDS(system.file("external/lux.rds", package="raster")) mersch <- p[p$NAME_2=='Mersch', ] diekirch <- p[p$NAME_2=='Diekirch', ] remich <- p[p$NAME_2=='Remich', ] remich$NAME_1 <- NULL x <- bind(mersch, diekirch, remich) plot(x) data.frame(x)
This function can be used to suggest chunk sizes (always a number of entire rows), and corresponding row numbers, to be used when processing Raster* objects in chunks. Normally used together with writeValues
.
## S4 method for signature 'Raster' blockSize(x, chunksize, n=nlayers(x), minblocks=4, minrows=1)
## S4 method for signature 'Raster' blockSize(x, chunksize, n=nlayers(x), minblocks=4, minrows=1)
x |
Raster* object |
chunksize |
Integer, normally missing. Can be used to set the block size; unit is number of cells. Block size is then computed in units of number of rows (always >= 1) |
n |
Integer. number of layers to consider. The function divides chunksize by n to determine blocksize |
minblocks |
Integer. Minimum number of blocks |
minrows |
Integer. Minimum number of rows in each block |
A list with three elements:
rows
, the suggested row numbers at which to start the blocks for reading and writing,
nrows
, the number of rows in each block, and,
n
, the total number of blocks
r <- raster(system.file("external/test.grd", package="raster")) blockSize(r)
r <- raster(system.file("external/test.grd", package="raster")) blockSize(r)
Detect boundaries (edges). boundaries are cells that have more than one class in the 4 or 8 cells surrounding it, or, if classes=FALSE
, cells with values and cells with NA
.
## S4 method for signature 'RasterLayer' boundaries(x, type='inner', classes=FALSE, directions=8, asNA=FALSE, filename="", ...)
## S4 method for signature 'RasterLayer' boundaries(x, type='inner', classes=FALSE, directions=8, asNA=FALSE, filename="", ...)
x |
RasterLayer object |
type |
character. 'inner' or 'outer' |
classes |
character. Logical. If |
directions |
integer. Which cells are considered adjacent? Should be 8 (Queen's case) or 4 (Rook's case) |
asNA |
logical. If |
filename |
character. Filename for the output RasterLayer (optional) |
... |
additional arguments as for |
RasterLayer. Cell values are either 1 (a border) or 0 (not a border), or NA
r <- raster(nrow=18, ncol=36, xmn=0) r[150:250] <- 1 r[251:450] <- 2 plot( boundaries(r, type='inner') ) plot( boundaries(r, type='outer') ) plot( boundaries(r, classes=TRUE) )
r <- raster(nrow=18, ncol=36, xmn=0) r[150:250] <- 1 r[251:450] <- 2 plot( boundaries(r, type='inner') ) plot( boundaries(r, type='outer') ) plot( boundaries(r, classes=TRUE) )
Box plot of layers in a Raster object
## S4 method for signature 'RasterStackBrick' boxplot(x, maxpixels=100000, ...) ## S4 method for signature 'RasterLayer' boxplot(x, y=NULL, maxpixels=100000, ...)
## S4 method for signature 'RasterStackBrick' boxplot(x, maxpixels=100000, ...) ## S4 method for signature 'RasterLayer' boxplot(x, y=NULL, maxpixels=100000, ...)
x |
Raster* object |
y |
If |
maxpixels |
Integer. Number of pixels to sample from each layer of large Raster objects |
... |
Arguments passed to |
r1 <- r2 <- r3 <- raster(ncol=10, nrow=10) values(r1) <- rnorm(ncell(r1), 100, 40) values(r2) <- rnorm(ncell(r1), 80, 10) values(r3) <- rnorm(ncell(r1), 120, 30) s <- stack(r1, r2, r3) names(s) <- c('A', 'B', 'C') boxplot(s, notch=TRUE, col=c('red', 'blue', 'orange'), main='Box plot', ylab='random' )
r1 <- r2 <- r3 <- raster(ncol=10, nrow=10) values(r1) <- rnorm(ncell(r1), 100, 40) values(r2) <- rnorm(ncell(r1), 80, 10) values(r3) <- rnorm(ncell(r1), 120, 30) s <- stack(r1, r2, r3) names(s) <- c('A', 'B', 'C') boxplot(s, notch=TRUE, col=c('red', 'blue', 'orange'), main='Box plot', ylab='random' )
A RasterBrick is a multi-layer raster object. They are typically created from a multi-layer (band) file; but they can also exist entirely in memory. They are similar to a RasterStack (that can be created with stack
), but processing time should be shorter when using a RasterBrick. Yet they are less flexible as they can only point to a single file.
A RasterBrick can be created from RasterLayer objects, from a RasterStack, or from a (multi-layer) file. The can also be created from SpatialPixels*, SpatialGrid*, and Extent objects, and from a three-dimensional array.
## S4 method for signature 'character' brick(x, ...) ## S4 method for signature 'RasterStack' brick(x, values=TRUE, nl, filename='', ...) ## S4 method for signature 'RasterBrick' brick(x, nl, ...) ## S4 method for signature 'RasterLayer' brick(x, ..., values=TRUE, nl=1, filename='') ## S4 method for signature 'missing' brick(nrows=180, ncols=360, xmn=-180, xmx=180, ymn=-90, ymx=90, nl=1, crs) ## S4 method for signature 'Extent' brick(x, nrows=10, ncols=10, crs="", nl=1) ## S4 method for signature 'array' brick(x, xmn=0, xmx=1, ymn=0, ymx=1, crs="", transpose=FALSE) ## S4 method for signature 'SpatialGrid' brick(x) ## S4 method for signature 'SpatialPixels' brick(x)
## S4 method for signature 'character' brick(x, ...) ## S4 method for signature 'RasterStack' brick(x, values=TRUE, nl, filename='', ...) ## S4 method for signature 'RasterBrick' brick(x, nl, ...) ## S4 method for signature 'RasterLayer' brick(x, ..., values=TRUE, nl=1, filename='') ## S4 method for signature 'missing' brick(nrows=180, ncols=360, xmn=-180, xmx=180, ymn=-90, ymx=90, nl=1, crs) ## S4 method for signature 'Extent' brick(x, nrows=10, ncols=10, crs="", nl=1) ## S4 method for signature 'array' brick(x, xmn=0, xmx=1, ymn=0, ymx=1, crs="", transpose=FALSE) ## S4 method for signature 'SpatialGrid' brick(x) ## S4 method for signature 'SpatialPixels' brick(x)
x |
character (filename, see Details); Raster* object; missing; array; SpatialGrid*; SpatialPixels*; Extent; or list of Raster* objects. Supported file types are the 'native' raster package format and those that can be read via GDAL, and NetCDF files (see details) |
... |
see Details |
values |
logical. If |
nl |
integer > 0. How many layers should the RasterBrick have? |
filename |
character. Filename if you want the RasterBrick to be saved on disk |
nrows |
integer > 0. Number of rows |
ncols |
integer > 0. Number of columns |
xmn |
minimum x coordinate (left border) |
xmx |
maximum x coordinate (right border) |
ymn |
minimum y coordinate (bottom border) |
ymx |
maximum y coordinate (top border) |
crs |
character or object of class CRS. PROJ4 type description of a Coordinate Reference System (map projection). If this argument is missing, and the x coordinates are within -360 .. 360 and the y coordinates are within -90 .. 90, "+proj=longlat +datum=WGS84" is used |
transpose |
if |
If x
is a RasterLayer, the additional arguments can be used to pass additional Raster* objects.
If there is a filename
argument, the additional arguments are as for writeRaster
.
If x
represents a filename there is the following additional argument:
native
: logical. If TRUE
(not the default), reading and writing of IDRISI, BIL, BSQ, BIP, and Arc ASCII files is done with native (raster package) drivers, rather then via GDAL.
In addition, if x
is a NetCDF filename there are the following additional arguments:
varname
: character. The variable name (e.g. 'altitude' or 'precipitation'. If not supplied and the file has multiple
variables are a guess will be made (and reported))
lvar
: integer > 0 (default=3). To select the 'level variable' (3rd dimension variable) to use, if the file has 4 dimensions (e.g. depth instead of time)
level
: integer > 0 (default=1). To select the 'level' (4th dimension variable) to use, if the file has 4 dimensions, e.g. to create a RasterBrick of weather over time at a certain height.
dims
: integer vector to indicated the order of the dimensions. Default is dims=c(1,2,3)
(rows, cols, time).
To use NetCDF files the ncdf4
package needs to be available. It is assumed that these files follow, or are compatible with the CF-1 convention.
RasterBrick
b <- brick(system.file("external/rlogo.grd", package="raster")) b nlayers(b) names(b) extract(b, 870)
b <- brick(system.file("external/rlogo.grd", package="raster")) b nlayers(b) names(b) extract(b, 870)
Calculate a buffer around all cells that are not NA
or around SpatialPoints, Lines, or Polygons.
Note that the distance unit of the buffer width
parameter is meters if the RasterLayer is not projected (+proj=longlat
), and in map units (typically also meters) when it is projected.
## S4 method for signature 'RasterLayer' buffer(x, width=0, filename='', doEdge=FALSE, ...) ## S4 method for signature 'Spatial' buffer(x, width=1, dissolve=TRUE, ...)
## S4 method for signature 'RasterLayer' buffer(x, width=0, filename='', doEdge=FALSE, ...) ## S4 method for signature 'Spatial' buffer(x, width=1, dissolve=TRUE, ...)
x |
RasterLayer or Spatial* object |
width |
numeric > 0. Unit is meter if |
filename |
character. Filename for the output RasterLayer (optional) |
doEdge |
logical. If |
dissolve |
logical. If |
... |
Additional arguments as for |
RasterLayer or SpatialPolygons* object
distance
, gridDistance
, pointDistance
r <- raster(ncol=36,nrow=18) values(r) <- NA r[500] <- 1 b <- buffer(r, width=5000000) #plot(b)
r <- raster(ncol=36,nrow=18) values(r) <- NA r[500] <- 1 b <- buffer(r, width=5000000) #plot(b)
Calculate values for a new Raster* object from another Raster* object, using a formula.
If x
is a RasterLayer, fun
is typically a function that can take a single vector as input, and return a vector of values of the same length (e.g. sqrt
). If x
is a RasterStack or RasterBrick, fun should operate on a vector of values (one vector for each cell). calc
returns a RasterLayer if fun
returns a single value (e.g. sum
) and it returns a RasterBrick if fun
returns more than one number, e.g., fun=quantile
.
In many cases, what can be achieved with calc
, can also be accomplished with a more intuitive 'raster-algebra' notation (see Arith-methods
). For example, r <- r * 2
instead of
r <- calc(r, fun=function(x){x * 2}
, or r <- sum(s)
instead of
r <- calc(s, fun=sum)
. However, calc
should be faster when using complex formulas on large datasets. With calc
it is possible to set an output filename and file type preferences.
See (overlay
) to use functions that refer to specific layers, like (function(a,b,c){a + sqrt(b) / c}
)
## S4 method for signature 'Raster,function' calc(x, fun, filename='', na.rm, forcefun=FALSE, forceapply=FALSE, ...)
## S4 method for signature 'Raster,function' calc(x, fun, filename='', na.rm, forcefun=FALSE, forceapply=FALSE, ...)
x |
Raster* object |
fun |
function |
filename |
character. Output filename (optional) |
na.rm |
Remove |
forcefun |
logical. Force |
forceapply |
logical. Force |
... |
Additional arguments as for |
The intent of some functions can be ambiguous. Consider:
library(raster)
r <- raster(volcano)
calc(r, function(x) x * 1:10)
In this case, the cell values are multiplied in a vectorized manner and a single layer is returned where the first cell has been multiplied with one, the second cell with two, the 11th cell with one again, and so on. But perhaps the intent was to create 10 new layers (x*1, x*2, ...
)? This can be achieved by using argument forceapply=TRUE
calc(r, function(x) x * 1:10, forceapply=TRUE)
a Raster* object
For large objects calc
will compute values chunk by chunk. This means that for the result of fun
to be correct it should not depend on having access to _all_ values at once. For example, to scale the values of a Raster* object by subtracting its mean value (for each layer), you would _not_ do, for Raster object x
:
calc(x, function(x)scale(x, scale=FALSE))
Because the mean value of each chunk will likely be different. Rather do something like
m <- cellStats(x, 'mean')
x - m
Robert J. Hijmans and Matteo Mattiuzzi
overlay
, reclassify
, Arith-methods, Math-methods
r <- raster(ncols=36, nrows=18) values(r) <- 1:ncell(r) # multiply values with 10 fun <- function(x) { x * 10 } rc1 <- calc(r, fun) # set values below 100 to NA. fun <- function(x) { x[x<100] <- NA; return(x) } rc2 <- calc(r, fun) # set NA values to -9999 fun <- function(x) { x[is.na(x)] <- -9999; return(x)} rc3 <- calc(rc2, fun) # using a RasterStack as input s <- stack(r, r*2, sqrt(r)) # return a RasterLayer rs1 <- calc(s, sum) # return a RasterBrick rs2 <- calc(s, fun=function(x){x * 10}) # recycling by layer rs3 <- calc(s, fun=function(x){x * c(1, 5, 10)}) # use overlay when you want to refer to individual layer in the function # but it can be done with calc: rs4 <- calc(s, fun=function(x){x[1]+x[2]*x[3]}) ## # Some regression examples ## # create data r <- raster(nrow=10, ncol=10) s1 <- lapply(1:12, function(i) setValues(r, rnorm(ncell(r), i, 3))) s2 <- lapply(1:12, function(i) setValues(r, rnorm(ncell(r), i, 3))) s1 <- stack(s1) s2 <- stack(s2) # regression of values in one brick (or stack) with another s <- stack(s1, s2) # s1 and s2 have 12 layers; coefficients[2] is the slope fun <- function(x) { lm(x[1:12] ~ x[13:24])$coefficients[2] } x1 <- calc(s, fun) # regression of values in one brick (or stack) with 'time' time <- 1:nlayers(s) fun <- function(x) { lm(x ~ time)$coefficients[2] } x2 <- calc(s, fun) # get multiple layers, e.g. the slope _and_ intercept fun <- function(x) { lm(x ~ time)$coefficients } x3 <- calc(s, fun) ### A much (> 100 times) faster approach is to directly use ### linear algebra and pre-compute some constants ## add 1 for a model with an intercept X <- cbind(1, time) ## pre-computing constant part of least squares invXtX <- solve(t(X) %*% X) %*% t(X) ## much reduced regression model; [2] is to get the slope quickfun <- function(y) (invXtX %*% y)[2] x4 <- calc(s, quickfun)
r <- raster(ncols=36, nrows=18) values(r) <- 1:ncell(r) # multiply values with 10 fun <- function(x) { x * 10 } rc1 <- calc(r, fun) # set values below 100 to NA. fun <- function(x) { x[x<100] <- NA; return(x) } rc2 <- calc(r, fun) # set NA values to -9999 fun <- function(x) { x[is.na(x)] <- -9999; return(x)} rc3 <- calc(rc2, fun) # using a RasterStack as input s <- stack(r, r*2, sqrt(r)) # return a RasterLayer rs1 <- calc(s, sum) # return a RasterBrick rs2 <- calc(s, fun=function(x){x * 10}) # recycling by layer rs3 <- calc(s, fun=function(x){x * c(1, 5, 10)}) # use overlay when you want to refer to individual layer in the function # but it can be done with calc: rs4 <- calc(s, fun=function(x){x[1]+x[2]*x[3]}) ## # Some regression examples ## # create data r <- raster(nrow=10, ncol=10) s1 <- lapply(1:12, function(i) setValues(r, rnorm(ncell(r), i, 3))) s2 <- lapply(1:12, function(i) setValues(r, rnorm(ncell(r), i, 3))) s1 <- stack(s1) s2 <- stack(s2) # regression of values in one brick (or stack) with another s <- stack(s1, s2) # s1 and s2 have 12 layers; coefficients[2] is the slope fun <- function(x) { lm(x[1:12] ~ x[13:24])$coefficients[2] } x1 <- calc(s, fun) # regression of values in one brick (or stack) with 'time' time <- 1:nlayers(s) fun <- function(x) { lm(x ~ time)$coefficients[2] } x2 <- calc(s, fun) # get multiple layers, e.g. the slope _and_ intercept fun <- function(x) { lm(x ~ time)$coefficients } x3 <- calc(s, fun) ### A much (> 100 times) faster approach is to directly use ### linear algebra and pre-compute some constants ## add 1 for a model with an intercept X <- cbind(1, time) ## pre-computing constant part of least squares invXtX <- solve(t(X) %*% X) %*% t(X) ## much reduced regression model; [2] is to get the slope quickfun <- function(y) (invXtX %*% y)[2] x4 <- calc(s, quickfun)
Get cell number(s) of a Raster* object from row and/or column numbers. Cell numbers start at 1 in the upper left corner, and increase from left to right, and then from top to bottom. The last cell number equals the number of cells of the Raster* object.
cellFromRowCol(object, row, col, ...) cellFromRowColCombine(object, row, col, ...) cellFromRow(object, rownr) cellFromCol(object, colnr) colFromX(object, x) rowFromY(object, y) cellFromXY(object, xy) cellFromLine(object, lns) cellFromPolygon(object, p, weights=FALSE) fourCellsFromXY(object, xy, duplicates=TRUE)
cellFromRowCol(object, row, col, ...) cellFromRowColCombine(object, row, col, ...) cellFromRow(object, rownr) cellFromCol(object, colnr) colFromX(object, x) rowFromY(object, y) cellFromXY(object, xy) cellFromLine(object, lns) cellFromPolygon(object, p, weights=FALSE) fourCellsFromXY(object, xy, duplicates=TRUE)
object |
Raster* object (or a SpatialPixels* or SpatialGrid* object) |
colnr |
column number; or vector of column numbers |
rownr |
row number; or vector of row numbers |
col |
column number; or vector of column numbers |
row |
row number; or vector of row numbers |
x |
x coordinate(s) |
y |
y coordinate(s) |
xy |
matrix of x and y coordinates, or a SpatialPoints or SpatialPointsDataFrame object |
lns |
SpatialLines object |
p |
SpatialPolygons object |
weights |
Logical. If |
duplicates |
Logical. If |
... |
additional arguments (none implemented) |
cellFromRowCol
returns the cell numbers obtained for each row / col number pair. In contrast, cellFromRowColCombine
returns the cell numbers obtained by the combination of all row and column numbers supplied as arguments.
fourCellsFromXY
returns the four cells that are nearest to a point (if the point falls on the raster). Also see adjacent
.
vector of row, column or cell numbers. cellFromLine
and cellFromPolygon
return a list, fourCellsFromXY
returns a matrix.
xyFromCell, cellsFromExtent, rowColFromCell
r <- raster(ncols=10, nrows=10) cellFromRowCol(r, 5, 5) cellFromRowCol(r, 1:2, 1:2) cellFromRowColCombine(r, 1:3, 1:2) cellFromCol(r, 1) cellFromRow(r, 1) colFromX(r, 0.5) rowFromY(r, 0.5) cellFromXY(r, cbind(c(0.5,5), c(15, 88))) fourCellsFromXY(r, cbind(c(0.5,5), c(15, 88))) cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20)) cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0)) pols <- SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1), Polygons(list(Polygon(cds2)), 2))) cellFromPolygon(r, pols)
r <- raster(ncols=10, nrows=10) cellFromRowCol(r, 5, 5) cellFromRowCol(r, 1:2, 1:2) cellFromRowColCombine(r, 1:3, 1:2) cellFromCol(r, 1) cellFromRow(r, 1) colFromX(r, 0.5) rowFromY(r, 0.5) cellFromXY(r, cbind(c(0.5,5), c(15, 88))) fourCellsFromXY(r, cbind(c(0.5,5), c(15, 88))) cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20)) cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0)) pols <- SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1), Polygons(list(Polygon(cds2)), 2))) cellFromPolygon(r, pols)
cellsFromExtent returns the cell numbers for a Raster* object that are within a specfied extent (rectangular area), supply an object of class Extent, or another Raster* object.
extentFromCells returns an Extent object from a Raster* object and cell numbers. All cells are within the returned Extent.
cellsFromExtent(object, extent, expand=FALSE) extentFromCells(object, cells)
cellsFromExtent(object, extent, expand=FALSE) extentFromCells(object, cells)
object |
A Raster* object |
extent |
An object of class Extent (which you can create with newExtent(), or another Raster* object ) |
expand |
Logical. If |
cells |
numeric. A vector of cell numbers |
a vector of cell numbers
r <- raster() bb <- extent(-5, 5, -5, 5) cells <- cellsFromExtent(r, bb) r <- crop(r, bb) values(r) <- cells e <- extentFromCells(r, 50:55)
r <- raster() bb <- extent(-5, 5, -5, 5) cells <- cellsFromExtent(r, bb) r <- crop(r, bb) values(r) <- cells e <- extentFromCells(r, 50:55)
Compute statistics for the cells of each layer of a Raster* object. In the raster
package, functions such as max, min, and mean, when used with Raster* objects as argument, return a new Raster* object (with a value computed for each cell). In contrast, cellStats returns a single value, computed from the all the values of a layer. Also see layerStats
## S4 method for signature 'RasterLayer' cellStats(x, stat='mean', na.rm=TRUE, asSample=TRUE, ...) ## S4 method for signature 'RasterStackBrick' cellStats(x, stat='mean', na.rm=TRUE, asSample=TRUE, ...)
## S4 method for signature 'RasterLayer' cellStats(x, stat='mean', na.rm=TRUE, asSample=TRUE, ...) ## S4 method for signature 'RasterStackBrick' cellStats(x, stat='mean', na.rm=TRUE, asSample=TRUE, ...)
x |
Raster* object |
stat |
The function to be applied. See Details |
na.rm |
Logical. Should |
asSample |
Logical. Only relevant for |
... |
Additional arguments |
cellStats
will fail (gracefully) for very large Raster* objects except for a number of known functions: sum, mean, min, max, sd, 'skew' and 'rms'. 'skew' (skewness) and 'rms' (Root Mean Square) must be supplied as a character value (with quotes), the other known functions may be supplied with or without quotes. For other functions you could perhaps use a sample of the RasterLayer that can be held in memory (see sampleRegular
)
Numeric
freq
, quantile
, minValue
, maxValue
, setMinMax
r <- raster(nrow=18, ncol=36) values(r) <- runif(ncell(r)) * 10 # works for large files cellStats(r, 'mean') # same, but does not work for very large files cellStats(r, mean) # multi-layer object cellStats(brick(r,r), mean)
r <- raster(nrow=18, ncol=36) values(r) <- runif(ncell(r)) * 10 # works for large files cellStats(r, 'mean') # same, but does not work for very large files cellStats(r, mean) # multi-layer object cellStats(brick(r,r), mean)
Clamp values to a minimum and maximum value. That is, all values below the lower clamp value and above the upper clamp value become NA (or the lower/upper value if useValue=TRUE
)
## S4 method for signature 'Raster' clamp(x, lower=-Inf, upper=Inf, useValues=TRUE, filename="", ...) ## S4 method for signature 'numeric' clamp(x, lower=-Inf, upper=Inf, ...)
## S4 method for signature 'Raster' clamp(x, lower=-Inf, upper=Inf, useValues=TRUE, filename="", ...) ## S4 method for signature 'numeric' clamp(x, lower=-Inf, upper=Inf, ...)
x |
RasterLayer, or numeric vector |
lower |
numeric. lowest value |
upper |
numeric. highest value |
useValues |
logical. If |
filename |
character. Filename for the output RasterLayer (optional) |
... |
additional arguments as for |
Raster object
r <- raster(ncols=12, nrows=12) values(r) <- 1:ncell(r) rc <- clamp(r, 25, 75) rc
r <- raster(ncols=12, nrows=12) values(r) <- 1:ncell(r) rc <- clamp(r, 25, 75) rc
Clear cell values of a Raster* object from memory
clearValues(x)
clearValues(x)
x |
Raster* object |
a Raster* object
r <- raster(ncol=10, nrow=10) values(r) <- 1:ncell(r) r <- clearValues(r)
r <- raster(ncol=10, nrow=10) values(r) <- 1:ncell(r) r <- clearValues(r)
Click on a map (plot) to get values of a Raster* or Spatial* object at that location; and optionally the coordinates and cell number of the location. For SpatialLines and SpatialPoints you need to click twice (draw a box).
## S4 method for signature 'Raster' click(x, n=Inf, id=FALSE, xy=FALSE, cell=FALSE, type="n", show=TRUE, ...) ## S4 method for signature 'SpatialGrid' click(x, n=1, id=FALSE, xy=FALSE, cell=FALSE, type="n", ...) ## S4 method for signature 'SpatialPolygons' click(x, n=1, id=FALSE, xy=FALSE, type="n", ...) ## S4 method for signature 'SpatialLines' click(x, ...) ## S4 method for signature 'SpatialPoints' click(x, ...)
## S4 method for signature 'Raster' click(x, n=Inf, id=FALSE, xy=FALSE, cell=FALSE, type="n", show=TRUE, ...) ## S4 method for signature 'SpatialGrid' click(x, n=1, id=FALSE, xy=FALSE, cell=FALSE, type="n", ...) ## S4 method for signature 'SpatialPolygons' click(x, n=1, id=FALSE, xy=FALSE, type="n", ...) ## S4 method for signature 'SpatialLines' click(x, ...) ## S4 method for signature 'SpatialPoints' click(x, ...)
x |
Raster*, or Spatial* object (or missing) |
n |
number of clicks on the map |
id |
Logical. If |
xy |
Logical. If |
cell |
Logical. If |
type |
One of "n", "p", "l" or "o". If "p" or "o" the points are plotted; if "l" or "o" they are joined by lines. See ?locator |
show |
logical. Print the values after each click? |
... |
additional graphics parameters used if type != "n" for plotting the locations. See ?locator |
The value(s) of x
at the point(s) clicked on (or touched by the box drawn).
The plot only provides the coordinates for a spatial query, the values are read from the Raster* or Spatial* object that is passed as an argument. Thus you can extract values from an object that has not been plotted, as long as it spatialy overlaps with with the extent of the plot.
Unless the process is terminated prematurely values at at most n
positions are determined. The identification process can be terminated by clicking the second mouse button and selecting 'Stop' from the menu, or from the 'Stop' menu on the graphics window.
## Not run: r <- raster(system.file("external/test.grd", package="raster")) plot(r) click(r) # now click on the plot (map) ## End(Not run)
## Not run: r <- raster(system.file("external/test.grd", package="raster")) plot(r) click(r) # now click on the plot (map) ## End(Not run)
Detect clumps (patches) of connected cells. Each clump gets a unique ID. NA and zero are used as background values (i.e. these values are used to separate clumps). You can use queen's or rook's case, using the directions
argument. For larger files that are processed in chunks, the highest clump number is not necessarily equal to the number of clumps (unless you use argument gaps=FALSE
).
## S4 method for signature 'RasterLayer' clump(x, filename="", directions=8, gaps=TRUE, ...)
## S4 method for signature 'RasterLayer' clump(x, filename="", directions=8, gaps=TRUE, ...)
x |
RasterLayer |
filename |
Character. Filename for the output RasterLayer (optional) |
directions |
Integer. Which cells are considered adjacent? Should be 8 (Queen's case) or 4 (Rook's case) |
gaps |
Logical. If |
... |
Additional arguments as for |
RasterLayer
This function requires that the igraph package is available.
Robert J. Hijmans and Jacob van Etten
r <- raster(ncols=12, nrows=12) set.seed(0) values(r) <- round(runif(ncell(r))*0.7 ) rc <- clump(r) freq(rc) plot(rc)
r <- raster(ncols=12, nrows=12) set.seed(0) values(r) <- round(runif(ncell(r))*0.7 ) rc <- clump(r) freq(rc) plot(rc)
beginCluster
creates, and endCluster
deletes a 'snow' cluster object. This object can be used for multi-core computing with those 'raster' functions that support it.
beginCluster
determines the number of nodes (cores) that are available and uses all of them (unless the argument n
is used).
NOTE: beginCluster may fail when the package 'nws' is installed. You can fix that by removing the 'nws' package, or by setting the cluster type manually, e.g. beginCluster(type="SOCK")
endCluster closes the cluster and removes the object.
The use of the cluster is automatic in these functions: projectRaster
, resample
and in extract
when using polygons.
clusterR
is a flexible interface for using cluster with other functions. This function only works with functions that have a Raster* object as first argument and that operate on a cell by cell basis (i.e., there is no effect of neigboring cells) and return an object with the same number of cells as the input raster object. The first argument of the function called must be a Raster* object. There can only be one Raster* object argument. For example, it works with calc
and it also works with overlay
as long as you provide a single RasterStack or RasterBrick as the first argument.
This function is particularly useful to speed up computations in functions like predict, interpolate, and perhaps calc.
Among other functions, it does _not_ work with merge, crop, mosaic, (dis)aggregate, resample, projectRaster, focal, distance, buffer, direction. But note that projectRaster has a build-in capacity for clustering that is automatically used if beginCluster() has been called.
beginCluster(n, type='SOCK', nice, exclude) endCluster() clusterR(x, fun, args=NULL, export=NULL, filename='', cl=NULL, m=2, ...)
beginCluster(n, type='SOCK', nice, exclude) endCluster() clusterR(x, fun, args=NULL, export=NULL, filename='', cl=NULL, m=2, ...)
n |
Integer. The number of nodes to be used (optional) |
type |
Character. The cluster type to be used |
nice |
Integer. To set the prioirty for the workers, between -20 and 20 (UNIX like platforms only) |
exclude |
Character. Packages to exclude from loading on the nodes (because they may fail there) but are required/loaded on the master |
x |
Raster* object |
fun |
function that takes |
args |
list with the arguments for the function (excluding |
export |
character. Vector of variable names to export to the cluster nodes such that the are visible to fun (e.g. a parameter that is not passed as an argument) |
filename |
character. Output filename (optional) |
cl |
cluster object (do not use it if beginCluster() has been called |
m |
tuning parameter to determine how many blocks should be used. The number is rounded and multiplied with the number of nodes. |
... |
additional arguments as for |
beginCluster and endCluster: None. The side effect is to create or delete a cluster object.
clusterR: as for the function called with argument fun
If you want to write your own cluster-enabled functions see getCluster, returnCluster
, and the vignette about writing functions.
Matteo Mattiuzzi and Robert J. Hijmans
## Not run: # set up the cluster object for parallel computing beginCluster() r <- raster() values(r) <- 1:ncell(r) x <- clusterR(r, sqrt, verbose=T) f1 <- function(x) calc(x, sqrt) y <- clusterR(r, f1) s <- stack(r, r*2, r*3) f2 <- function(d,e,f) (d + e) / (f * param) param <- 122 ov <- clusterR(s, overlay, args=list(fun=f2), export='param') pts <- matrix(c(0,0, 45,45), ncol=2, byrow=T) d <- clusterR(r, distanceFromPoints, args=list(xy=pts)) values(r) <- runif(ncell(r)) m <- c(0, 0.25, 1, 0.25, 0.5, 2, 0.5, 1, 3) m <- matrix(m, ncol=3, byrow=TRUE) rc1 <- clusterR(r, reclassify, args=list(rcl=m, right=FALSE), filename=rasterTmpFile(), datatype='INT2S', overwrite=TRUE) # equivalent to: rc2 <- reclassify(r, rcl=m, right=FALSE, filename=rasterTmpFile(), datatype='INT2S', overwrite=TRUE) # example with the calc function a <- 10 f3 <- function(x) sum(x)+a z1 <- clusterR(s, calc, args=list(fun=f3), export='a') # for some raster functions that use another function as an argument # you can write your own parallel function instead of using clusterR # get cluster object created with beginCluster cl <- getCluster() library(parallel) clusterExport(cl, "a") z2 <- calc(s, fun=function(x){ parApply(cl, x, 1, f3)} ) # set flag that cluster is available again returnCluster() # # done with cluster object endCluster() ## End(Not run)
## Not run: # set up the cluster object for parallel computing beginCluster() r <- raster() values(r) <- 1:ncell(r) x <- clusterR(r, sqrt, verbose=T) f1 <- function(x) calc(x, sqrt) y <- clusterR(r, f1) s <- stack(r, r*2, r*3) f2 <- function(d,e,f) (d + e) / (f * param) param <- 122 ov <- clusterR(s, overlay, args=list(fun=f2), export='param') pts <- matrix(c(0,0, 45,45), ncol=2, byrow=T) d <- clusterR(r, distanceFromPoints, args=list(xy=pts)) values(r) <- runif(ncell(r)) m <- c(0, 0.25, 1, 0.25, 0.5, 2, 0.5, 1, 3) m <- matrix(m, ncol=3, byrow=TRUE) rc1 <- clusterR(r, reclassify, args=list(rcl=m, right=FALSE), filename=rasterTmpFile(), datatype='INT2S', overwrite=TRUE) # equivalent to: rc2 <- reclassify(r, rcl=m, right=FALSE, filename=rasterTmpFile(), datatype='INT2S', overwrite=TRUE) # example with the calc function a <- 10 f3 <- function(x) sum(x)+a z1 <- clusterR(s, calc, args=list(fun=f3), export='a') # for some raster functions that use another function as an argument # you can write your own parallel function instead of using clusterR # get cluster object created with beginCluster cl <- getCluster() library(parallel) clusterExport(cl, "a") z2 <- calc(s, fun=function(x){ parApply(cl, x, 1, f3)} ) # set flag that cluster is available again returnCluster() # # done with cluster object endCluster() ## End(Not run)
Get or set the colortable of a RasterLayer. A colortable is a vector of 256 colors in the RGB triple format as returned by the rgb
function (e.g. "#C4CDDA").
When setting the colortable, it is assumed that the values are integers in the range [0,255]
colortable(x) colortable(x) <- value
colortable(x) colortable(x) <- value
x |
RasterLayer object |
value |
vector of 256 character values |
r <- raster(ncol=10, nrow=10) values(r) <- sample(0:255, ncell(r), replace=TRUE) ctab <- sample(rainbow(256)) colortable(r) <- ctab plot(r) head(colortable(r))
r <- raster(ncol=10, nrow=10) values(r) <- sample(0:255, ncell(r), replace=TRUE) ctab <- sample(rainbow(256)) colortable(r) <- ctab plot(r) head(colortable(r))
These methods compare the location and resolution of Raster* objects. That is, they compare their spatial extent, projection, and number of rows and columns.
For BasicRaster
objects you can use ==
and !=
, the values returned is a single logical value TRUE
or FALSE
For RasterLayer objects, these operators also compare the values associated with the objects, and the result is a RasterLayer object with logical (Boolean) values.
The following methods have been implemented for RasterLayer objects:
==, !=, >, <, <=, >=
A logical value or a RasterLayer object, and in some cases the side effect of a new file on disk.
r1 <- raster() r1 <- setValues(r1, round(10 * runif(ncell(r1)))) r2 <- setValues(r1, round(10 * runif(ncell(r1)))) as(r1, 'BasicRaster') == as(r2, 'BasicRaster') r3 <- r1 == r2 b <- extent(0, 360, 0, 180) r4 <- setExtent(r2, b) as(r2, 'BasicRaster') != as(r4, 'BasicRaster') # The following would give an error. You cannot compare RasterLayer # that do not have the same BasicRaster properties. #r3 <- r1 > r4
r1 <- raster() r1 <- setValues(r1, round(10 * runif(ncell(r1)))) r2 <- setValues(r1, round(10 * runif(ncell(r1)))) as(r1, 'BasicRaster') == as(r2, 'BasicRaster') r3 <- r1 == r2 b <- extent(0, 360, 0, 180) r4 <- setExtent(r2, b) as(r2, 'BasicRaster') != as(r4, 'BasicRaster') # The following would give an error. You cannot compare RasterLayer # that do not have the same BasicRaster properties. #r3 <- r1 > r4
Compare CRS objects
compareCRS(x, y, unknown=FALSE, verbatim=FALSE, verbose=FALSE)
compareCRS(x, y, unknown=FALSE, verbatim=FALSE, verbose=FALSE)
x |
CRS object, or object from which it can be extracted with |
y |
same as |
unknown |
logical. Return |
verbatim |
logical. If |
verbose |
logical. If |
logical
sp::identicalCRS
, crs
compareCRS("+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +ellps=WGS84", "+proj=longlat +datum=WGS84") compareCRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0", "+proj=longlat +datum=WGS84") compareCRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0", "+proj=longlat +datum=WGS84", verbatim=TRUE) compareCRS("+proj=longlat +datum=WGS84", NA) compareCRS("+proj=longlat +datum=WGS84", NA, unknown=TRUE)
compareCRS("+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +ellps=WGS84", "+proj=longlat +datum=WGS84") compareCRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0", "+proj=longlat +datum=WGS84") compareCRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0", "+proj=longlat +datum=WGS84", verbatim=TRUE) compareCRS("+proj=longlat +datum=WGS84", NA) compareCRS("+proj=longlat +datum=WGS84", NA, unknown=TRUE)
Evaluate whether a two or more Raster* objects have the same extent, number of rows and columns, projection, resolution, and origin (or a subset of these comparisons).
all.equal is a wrapper around compareRaster with options values=TRUE
, stopiffalse=FALSE
and showwarning=TRUE
.
compareRaster(x, ..., extent=TRUE, rowcol=TRUE, crs=TRUE, res=FALSE, orig=FALSE, rotation=TRUE, values=FALSE, tolerance, stopiffalse=TRUE, showwarning=FALSE)
compareRaster(x, ..., extent=TRUE, rowcol=TRUE, crs=TRUE, res=FALSE, orig=FALSE, rotation=TRUE, values=FALSE, tolerance, stopiffalse=TRUE, showwarning=FALSE)
x |
Raster* object |
... |
Raster* objects |
extent |
logical. If |
rowcol |
logical. If |
crs |
logical. If |
res |
logical. If |
orig |
logical. If |
rotation |
logical. If |
values |
logical. If |
tolerance |
numeric between 0 and 0.5. If not supplied, the default value is used (see |
stopiffalse |
logical. If |
showwarning |
logical. If |
r1 <- raster() r2 <- r1 r3 <- r1 compareRaster(r1, r2, r3) nrow(r3) <- 10 # compareRaster(r1, r3) compareRaster(r1, r3, stopiffalse=FALSE) compareRaster(r1, r3, rowcol=FALSE) all.equal(r1, r2) all.equal(r1, r3)
r1 <- raster() r2 <- r1 r3 <- r1 compareRaster(r1, r2, r3) nrow(r3) <- 10 # compareRaster(r1, r3) compareRaster(r1, r3, stopiffalse=FALSE) compareRaster(r1, r3, rowcol=FALSE) all.equal(r1, r2) all.equal(r1, r3)
Contour plot of a RasterLayer.
## S4 method for signature 'RasterLayer' contour(x, maxpixels=100000, ...)
## S4 method for signature 'RasterLayer' contour(x, maxpixels=100000, ...)
x |
Raster* object |
maxpixels |
maximum number of pixels used to create the contours |
... |
any argument that can be passed to |
persp
, filledContour
, rasterToContour
r <- raster(system.file("external/test.grd", package="raster")) plot(r) contour(r, add=TRUE)
r <- raster(system.file("external/test.grd", package="raster")) plot(r) contour(r, add=TRUE)
Local correlation coefficient for two RasterLayer objects (using a focal neighborhood) or for two RasterStack or Brick objects (with the same number of layers (> 2))
## S4 method for signature 'RasterLayer,RasterLayer' corLocal(x, y, ngb=5, method=c("pearson", "kendall", "spearman"), test=FALSE, filename='', ...) ## S4 method for signature 'RasterStackBrick,RasterStackBrick' corLocal(x, y, method=c("pearson", "kendall", "spearman"), test=FALSE, filename='', ...)
## S4 method for signature 'RasterLayer,RasterLayer' corLocal(x, y, ngb=5, method=c("pearson", "kendall", "spearman"), test=FALSE, filename='', ...) ## S4 method for signature 'RasterStackBrick,RasterStackBrick' corLocal(x, y, method=c("pearson", "kendall", "spearman"), test=FALSE, filename='', ...)
x |
RasterLayer or RasterStack/RasterBrick |
y |
object of the same class as |
ngb |
neighborhood size. Either a single integer or a vector of two integers c(nrow, ncol) |
method |
character indicating which correlation coefficient is to be used. One of |
test |
logical. If |
filename |
character. Output filename (optional) |
... |
additional arguments as for |
RasterLayer
NA
values are omitted
b <- stack(system.file("external/rlogo.grd", package="raster")) b <- aggregate(b, 2, mean) set.seed(0) b[[2]] <- flip(b[[2]], 'y') + runif(ncell(b)) b[[1]] <- b[[1]] + runif(ncell(b)) x <- corLocal(b[[1]], b[[2]], test=TRUE ) # plot(x) # only cells where the p-value < 0.1 xm <- mask(x[[1]], x[[2]] < 0.1, maskvalue=FALSE) plot(xm) # for global correlation, use the cor function x <- as.matrix(b) cor(x, method="spearman") # use sampleRegular for large datasets x <- sampleRegular(b, 1000) cor.test(x[,1], x[,2]) # RasterStack or Brick objects y <- corLocal(b, flip(b, 'y'))
b <- stack(system.file("external/rlogo.grd", package="raster")) b <- aggregate(b, 2, mean) set.seed(0) b[[2]] <- flip(b[[2]], 'y') + runif(ncell(b)) b[[1]] <- b[[1]] + runif(ncell(b)) x <- corLocal(b[[1]], b[[2]], test=TRUE ) # plot(x) # only cells where the p-value < 0.1 xm <- mask(x[[1]], x[[2]] < 0.1, maskvalue=FALSE) plot(xm) # for global correlation, use the cor function x <- as.matrix(b) cor(x, method="spearman") # use sampleRegular for large datasets x <- sampleRegular(b, 1000) cor.test(x[,1], x[,2]) # RasterStack or Brick objects y <- corLocal(b, flip(b, 'y'))
For Raster* objects: Replace NA
values in the first Raster object (x
) with the values of the second (y
), and so forth for additional Rasters. If x
has multiple layers, the subsequent Raster objects should have the same number of layers, or have a single layer only (which will be recycled).
For SpatialPolygons* objects: Areas of x
that overlap with y
are replaced by (or intersected with) y
.
## S4 method for signature 'RasterLayer,RasterLayer' cover(x, y, ..., filename='') ## S4 method for signature 'RasterStackBrick,Raster' cover(x, y, ..., filename='') ## S4 method for signature 'SpatialPolygons,SpatialPolygons' cover(x, y, ..., identity=FALSE)
## S4 method for signature 'RasterLayer,RasterLayer' cover(x, y, ..., filename='') ## S4 method for signature 'RasterStackBrick,Raster' cover(x, y, ..., filename='') ## S4 method for signature 'SpatialPolygons,SpatialPolygons' cover(x, y, ..., identity=FALSE)
x |
Raster* or SpatialPolygons* object |
y |
Same as |
filename |
character. Output filename (optional) |
... |
Same as |
identity |
logical. If |
RasterLayer or RasterBrick object, or SpatialPolygons object
# raster objects r1 <- raster(ncols=36, nrows=18) values(r1) <- 1:ncell(r1) r2 <- setValues(r1, runif(ncell(r1))) r2[r2 < 0.5] <- NA r3 <- cover(r2, r1) #SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(p) b <- SpatialPolygonsDataFrame(b, data.frame(ID_1=9)) cv1 <- cover(p, b) cv2 <- cover(p, b, identity=TRUE)
# raster objects r1 <- raster(ncols=36, nrows=18) values(r1) <- 1:ncell(r1) r2 <- setValues(r1, runif(ncell(r1))) r2[r2 < 0.5] <- NA r3 <- cover(r2, r1) #SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(p) b <- SpatialPolygonsDataFrame(b, data.frame(ID_1=9)) cv1 <- cover(p, b) cv2 <- cover(p, b, identity=TRUE)
crop returns a geographic subset of an object as specified by an Extent object (or object from which an extent object can be extracted/created).
If x
is a Raster* object, the Extent is aligned to x
. Areas included in y
but outside the extent of x
are ignored (see extend
if you want a larger area).
## S4 method for signature 'Raster' crop(x, y, filename="", snap='near', datatype=NULL, ...) ## S4 method for signature 'Spatial' crop(x, y, ...)
## S4 method for signature 'Raster' crop(x, y, filename="", snap='near', datatype=NULL, ...) ## S4 method for signature 'Spatial' crop(x, y, ...)
x |
Raster* object or SpatialPolygons*, SpatialLines*, or SpatialPoints* object |
y |
Extent object, or any object from which an Extent object can be extracted (see Details) |
filename |
Character, output filename. Optional |
snap |
Character. One of 'near', 'in', or 'out', for use with |
datatype |
Character. Output |
... |
Additional arguments as for |
Objects from which an Extent can be extracted/created include RasterLayer, RasterStack, RasterBrick and objects of the Spatial* classes from the sp package. You can check this with the extent
function. New Extent objects can also be created with function extent
and drawExtent
by clicking twice on a plot.
To crop by row and column numbers you can create an extent like this (for Raster x
, row 5 to 10, column 7 to 12)
crop(x, extent(x, 5, 10, 7, 12))
RasterLayer or RasterBrick object; or SpatialLines or SpatialPolygons object.
values within the extent of a Raster* object can be set to NA with mask
r <- raster(nrow=45, ncol=90) values(r) <- 1:ncell(r) e <- extent(-160, 10, 30, 60) rc <- crop(r, e) # use row and column numbers: rc2 <- crop(r, extent(r, 5, 10, 7, 15)) # crop Raster* with Spatial* object b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(r) rb <- crop(r, b) # crop a SpatialPolygon* object with another one p <- shapefile(system.file("external/lux.shp", package="raster")) pb <- crop(p, b)
r <- raster(nrow=45, ncol=90) values(r) <- 1:ncell(r) e <- extent(-160, 10, 30, 60) rc <- crop(r, e) # use row and column numbers: rc2 <- crop(r, extent(r, 5, 10, 7, 15)) # crop Raster* with Spatial* object b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(r) rb <- crop(r, b) # crop a SpatialPolygon* object with another one p <- shapefile(system.file("external/lux.shp", package="raster")) pb <- crop(p, b)
Cross-tabulate two RasterLayer objects, or mulitiple layers in a RasterStack or RasterBrick to create a contingency table.
## S4 method for signature 'Raster,Raster' crosstab(x, y, digits=0, long=FALSE, useNA=FALSE, progress='', ...) ## S4 method for signature 'RasterStackBrick,missing' crosstab(x, digits=0, long=FALSE, useNA=FALSE, progress='', ...)
## S4 method for signature 'Raster,Raster' crosstab(x, y, digits=0, long=FALSE, useNA=FALSE, progress='', ...) ## S4 method for signature 'RasterStackBrick,missing' crosstab(x, digits=0, long=FALSE, useNA=FALSE, progress='', ...)
x |
Raster* object |
y |
Raster* object if |
digits |
integer. The number of digits for rounding the values before cross-tabulation |
long |
logical. If |
useNA |
logical, indicting if the table should includes counts of |
progress |
character. "text", "window", or "" (the default, no progress bar), only for large files that cannot be processed in one step |
... |
additional arguments. none implemented |
A table or data.frame
r <- raster(nc=5, nr=5) values(r) <- runif(ncell(r)) * 2 s <- setValues(r, runif(ncell(r)) * 3) crosstab(r,s) rs <- r/s r[1:5] <- NA s[20:25] <- NA x <- stack(r, s, rs) crosstab(x, useNA=TRUE, long=TRUE)
r <- raster(nc=5, nr=5) values(r) <- runif(ncell(r)) * 2 s <- setValues(r, runif(ncell(r)) * 3) crosstab(r,s) rs <- r/s r[1:5] <- NA s[20:25] <- NA x <- stack(r, s, rs) crosstab(x, useNA=TRUE, long=TRUE)
Cut uses the base function cut
to classify the values of a Raster* object according to which interval they fall in. The intervals are defined by the argument breaks
. The leftmost interval corresponds to level one, the next leftmost to level two and so on.
cut(x, ...)
cut(x, ...)
x |
A Raster* object |
... |
additional arguments. See cut |
Raster* object
r <- raster(ncols=36, nrows=18) values(r) <- rnorm(ncell(r)) breaks <- -2:2 * 3 rc <- cut(r, breaks=breaks)
r <- raster(ncols=36, nrows=18) values(r) <- rnorm(ncell(r)) breaks <- -2:2 * 3 rc <- cut(r, breaks=breaks)
Compute the coefficient of variation (expressed as a percentage). If there is only a single value, sd
is NA
and cv
returns NA
if aszero=FALSE
(the default). However, if (aszero=TRUE
), cv
returns 0
.
## S4 method for signature 'ANY' cv(x, ..., aszero=FALSE, na.rm = FALSE) ## S4 method for signature 'Raster' cv(x, ..., aszero=FALSE, na.rm = FALSE)
## S4 method for signature 'ANY' cv(x, ..., aszero=FALSE, na.rm = FALSE) ## S4 method for signature 'Raster' cv(x, ..., aszero=FALSE, na.rm = FALSE)
x |
A vector of numbers (typically integers for modal), or a Raster* object |
... |
additional (vectors of) numbers, or Raster objects |
aszero |
logical. If |
na.rm |
Remove (ignore) NA values |
vector or RasterLayer
data <- c(0,1,2,3,3,3,3,4,4,4,5,5,6,7,7,8,9,NA) cv(data, na.rm=TRUE)
data <- c(0,1,2,3,3,3,3,4,4,4,5,5,6,7,7,8,9,NA) cv(data, na.rm=TRUE)
These are helper functions for programmers and for debugging that provide information about whether a Raster object has associated values, and if these are in memory or on disk.
fromDisk
is TRUE
if the data source is a file on disk; and FALSE
if the object only exists in memory.
inMemory
i is TRUE
if all values are currently in memory (RAM); and FALSE
if not (in which case they either are on disk, or there are no values).
hasValues
is TRUE
if the object has cell values.
fromDisk(x) ## S4 method for signature 'BasicRaster' inMemory(x) ## S4 method for signature 'BasicRaster' hasValues(x)
fromDisk(x) ## S4 method for signature 'BasicRaster' inMemory(x) ## S4 method for signature 'BasicRaster' hasValues(x)
x |
Raster* object |
Logical
rs <- raster(system.file("external/test.grd", package="raster")) inMemory(rs) fromDisk(rs) rs <- readAll(rs) inMemory(rs) fromDisk(rs) rs <- rs + 1 inMemory(rs) fromDisk(rs) rs <- raster(rs) inMemory(rs) fromDisk(rs) rs <- setValues(rs, 1:ncell(rs)) inMemory(rs) fromDisk(rs) #rs <- writeRaster(rs, filename=rasterTmpFile(), overwrite=TRUE) #inMemory(rs) #fromDisk(rs)
rs <- raster(system.file("external/test.grd", package="raster")) inMemory(rs) fromDisk(rs) rs <- readAll(rs) inMemory(rs) fromDisk(rs) rs <- rs + 1 inMemory(rs) fromDisk(rs) rs <- raster(rs) inMemory(rs) fromDisk(rs) rs <- setValues(rs, 1:ncell(rs)) inMemory(rs) fromDisk(rs) #rs <- writeRaster(rs, filename=rasterTmpFile(), overwrite=TRUE) #inMemory(rs) #fromDisk(rs)
Get the datatype of a RasterLayer object. The datatype determines the interpretation of values written to disk. Changing the datatype of a Raster* object does not directly affect the way they are stored in memory. For native file formats (.grd/.gri files) it does affect how values are read from file. This is not the case for file formats that are read via GDAL (such as .tif and .img files) or netcdf.
If you change the datatype of a RasterLayer and then read values from a native format file these may be completely wrong, so only do this for debugging or when the information in the header file was wrong. To set the datatype of a new file, you can give a 'datatype' argument to the functions that write values to disk (e.g. writeRaster
).
dataType(x) dataType(x) <- value
dataType(x) dataType(x) <- value
x |
A |
value |
A data type (see below) |
Setting the data type is useful if you want to write values to disk. In other cases use functions such as round()
Datatypes are described by 5 characters. The first three indicate whether the values are integers, decimal number or logical values. The fourth character indicates the number of bytes used to save the values on disk, and the last character indicates whether the numbers are signed (i.e. can be negative and positive values) or not (only zero and positive values allowed)
The following datatypes are available:
Datatype definition | minimum possible value | maximum possible value |
LOG1S |
FALSE (0) | TRUE (1) |
INT1S |
-127 | 127 |
INT1U |
0 | 255 |
INT2S |
-32,767 | 32,767 |
INT2U |
0 | 65,534 |
INT4S |
-2,147,483,647 | 2,147,483,647 |
INT4U |
0 | 4,294,967,296 |
FLT4S |
-3.4e+38 | 3.4e+38 |
FLT8S |
-1.7e+308 | 1.7e+308 |
For all integer types, except the single byte types, the lowest (signed) or highest (unsigned) value is used to store NA
. Single byte files do not have NA
values. Logical values are stored as signed single byte integers, they do have an NA
value (-127)
INT4U
is available but they are best avoided as R does not support 32-bit unsigned integers.
Raster* object
r <- raster(system.file("external/test.grd", package="raster")) dataType(r) ## Not run: s <- writeRaster(r, 'new.grd', datatype='INT2U', overwrite=TRUE) dataType(s) ## End(Not run)
r <- raster(system.file("external/test.grd", package="raster")) dataType(r) ## Not run: s <- writeRaster(r, 'new.grd', datatype='INT2U', overwrite=TRUE) dataType(s) ## End(Not run)
Create density plots of values in a Raster object
## S4 method for signature 'Raster' density(x, layer, maxpixels=100000, plot=TRUE, main, ...)
## S4 method for signature 'Raster' density(x, layer, maxpixels=100000, plot=TRUE, main, ...)
x |
Raster object |
layer |
numeric. Can be used to subset the layers to plot in a multilayer object (RasterBrick or RasterStack) |
maxpixels |
the maximum number of (randomly sampled) cells to be used for creating the plot |
plot |
if |
main |
main title for each plot (can be missing) |
... |
Additional arguments passed to base plot |
density plot (and a density object, returned invisibly if plot=TRUE)
logo <- stack(system.file("external/rlogo.grd", package="raster")) density(logo)
logo <- stack(system.file("external/rlogo.grd", package="raster")) density(logo)
Get or set the number of rows, columns, and layers of a Raster* object. You cannot use this function to set the dimensions of a RasterStack object.
When setting the dimensions, you can provide a row number, or a vector with the row and the column number (for a RasterLayer and a RasterBrick), or a row and column number and the number of layers (only for a RasterBrick)
## S4 method for signature 'BasicRaster' dim(x)
## S4 method for signature 'BasicRaster' dim(x)
x |
Raster(* object |
Integer or Raster* object
r <- raster() dim(r) dim(r) <- c(18) dim(r) dim(r) <- c(18, 36) dim(r) b <- brick(r) dim(b) dim(b) <- c(10, 10, 5) dim(b)
r <- raster() dim(r) dim(r) <- c(18) dim(r) dim(r) <- c(18, 36) dim(r) b <- brick(r) dim(b) dim(b) <- c(10, 10, 5) dim(b)
The direction (azimuth) to or from the nearest cell that is not NA
. The direction unit is in radians, unless you use argument degrees=TRUE
.
## S4 method for signature 'RasterLayer' direction(x, filename='', degrees=FALSE, from=FALSE, doEdge=FALSE, ...)
## S4 method for signature 'RasterLayer' direction(x, filename='', degrees=FALSE, from=FALSE, doEdge=FALSE, ...)
x |
RasterLayer object |
filename |
Character. Output filename (optional) |
degrees |
Logical. If |
from |
Logical. Default is |
doEdge |
Logical. If |
... |
Additional arguments as for |
RasterLayer
For the direction between (longitude/latitude) points, see the azimuth
function in the geosphere
package
r <- raster(ncol=36,nrow=18) values(r) <- NA r[306] <- 1 b <- direction(r) #plot(b)
r <- raster(ncol=36,nrow=18) values(r) <- NA r[306] <- 1 b <- direction(r) #plot(b)
Disaggregate a RasterLayer to create a new RasterLayer with a higher resolution (smaller cells). The values in the new RasterLayer are the same as in the larger original cells unless you specify method="bilinear"
, in which case values are locally interpolated (using the resample
function).
## S4 method for signature 'Raster' disaggregate(x, fact=NULL, method='', filename='', ...)
## S4 method for signature 'Raster' disaggregate(x, fact=NULL, method='', filename='', ...)
x |
a Raster object |
fact |
integer. amount of disaggregation expressed as number of cells (horizontally and vertically). This can be a single integer or two integers c(x,y), in which case the first one is the horizontal disaggregation factor and y the vertical disaggreation factor. If a single integer value is supplied, cells are disaggregated with the same factor in x and y direction |
method |
Character. |
filename |
Character. Output filename (optional) |
... |
Additional arguments as for |
Raster object
Robert J. Hijmans and Jim Regetz
r <- raster(ncols=10, nrows=10) rd <- disaggregate(r, fact=c(10, 2)) ncol(rd) nrow(rd) values(r) <- 1:ncell(r) rd <- disaggregate(r, fact=c(4, 2), method='bilinear')
r <- raster(ncols=10, nrows=10) rd <- disaggregate(r, fact=c(10, 2)) ncol(rd) nrow(rd) values(r) <- 1:ncell(r) rd <- disaggregate(r, fact=c(4, 2), method='bilinear')
For a single RasterLayer
(y
is missing) this method computes the distance, for all cells that are NA
, to the nearest cell that is not NA
.
The distance unit is in meters if the RasterLayer is not projected (+proj=longlat
) and in map units (typically also meters) when it is projected.
If two RasterLayer
objects are provided, the cell-value distances are computed.
If two Spatial
vector type objects are provided, the distances between pairs of geographic object are computed.
## S4 method for signature 'RasterLayer,missing' distance(x, y, filename='', doEdge=TRUE, ...) ## S4 method for signature 'RasterLayer,RasterLayer' distance(x, y, ...) ## S4 method for signature 'Spatial,Spatial' distance(x, y, ...)
## S4 method for signature 'RasterLayer,missing' distance(x, y, filename='', doEdge=TRUE, ...) ## S4 method for signature 'RasterLayer,RasterLayer' distance(x, y, ...) ## S4 method for signature 'Spatial,Spatial' distance(x, y, ...)
x |
RasterLayer object |
y |
missing, RasterLayer or Spatial object |
filename |
Character. Filename for the output RasterLayer (optional) |
doEdge |
Logical. If |
... |
Additional arguments as for |
RasterLayer
distanceFromPoints
, gridDistance
, pointDistance
See the gdistance
package for more advanced distances, and the geosphere
package for great-circle distances (and more) between points in longitude/latitude coordinates.
r <- raster(ncol=36,nrow=18) values(r) <- NA r[500] <- 1 dist <- distance(r) #plot(dist / 1000)
r <- raster(ncol=36,nrow=18) values(r) <- NA r[500] <- 1 dist <- distance(r) #plot(dist / 1000)
The function calculates the distance from a set of points to all cells of a Raster* object.
The distance unit is in meters if the coordinate reference system (crs) of the Raster* object is (+proj=longlat
) or assumed to be if the crs is NA
. In all other cases it is in the units defined by the crs (which typically is meters).
distanceFromPoints(object, xy, filename='', ...)
distanceFromPoints(object, xy, filename='', ...)
object |
Raster object |
xy |
matrix of x and y coordinates, or a SpatialPoints* object. |
filename |
character. Optional filename for the output RasterLayer |
... |
Additional arguments as for |
Distances for longlat
data are computed on the WGS84 spheroid using GeographicLib (Karney, 2013)
RasterLayer
C.F.F. Karney, 2013. Algorithms for geodesics, J. Geodesy 87: 43-55. doi:10.1007/s00190-012-0578-z.
crs
, distance
, gridDistance
, pointDistance
r <- raster(ncol=36,nrow=18) xy <- c(0,0) d1 <- distanceFromPoints(r, xy) crs(r) = '+proj=utm +zone=12 +datum=WGS84' d2 <- distanceFromPoints(r, xy) par(mfrow=c(1,2)) plot(d1) plot(d2)
r <- raster(ncol=36,nrow=18) xy <- c(0,0) d1 <- distanceFromPoints(r, xy) crs(r) = '+proj=utm +zone=12 +datum=WGS84' d2 <- distanceFromPoints(r, xy) par(mfrow=c(1,2)) plot(d1) plot(d2)
Draw a line or polygon on a plot (map) and save it for later use. After calling the function, start clicking on the map. To finish, right-click and select 'stop'.
drawPoly(sp=TRUE, col='red', lwd=2, ...) drawLine(sp=TRUE, col='red', lwd=2, ...)
drawPoly(sp=TRUE, col='red', lwd=2, ...) drawLine(sp=TRUE, col='red', lwd=2, ...)
sp |
logical. If |
col |
the color of the lines to be drawn |
lwd |
the width of the lines to be drawn |
... |
additional arguments padded to locator |
If sp==TRUE
a SpatialPolygons or SpatialLines object; otherwise a matrix of coordinates
Click on two points of a plot (map) to obtain an object of class Extent
('bounding box')
drawExtent(show=TRUE, col="red")
drawExtent(show=TRUE, col="red")
show |
logical. If |
col |
sets the color of the lines of the extent |
Extent
## Not run: r1 <- raster(nrow=10, ncol=10) values(r1) <- runif(ncell(r1)) plot(r1) # after running the following line, click on the map twice e <- drawExtent() # after running the following line, click on the map twice mean(values(crop(r1, drawExtent()))) ## End(Not run)
## Not run: r1 <- raster(nrow=10, ncol=10) values(r1) <- runif(ncell(r1)) plot(r1) # after running the following line, click on the map twice e <- drawExtent() # after running the following line, click on the map twice mean(values(crop(r1, drawExtent()))) ## End(Not run)
intersect
Erase parts of a SpatialPolygons* or SpatialLines* object with a SpatialPolygons* object
## S4 method for signature 'SpatialPolygons,SpatialPolygons' erase(x, y, ...) ## S4 method for signature 'SpatialLines,SpatialPolygons' erase(x, y, ...)
## S4 method for signature 'SpatialPolygons,SpatialPolygons' erase(x, y, ...) ## S4 method for signature 'SpatialLines,SpatialPolygons' erase(x, y, ...)
x |
SpatialPolygons or SpatialLines object |
y |
SpatialPolygons object |
... |
Additional arguments (none) |
Spatial*
The equivalent for raster data is mask
# erase parts of polygons with other polygons p <- shapefile(system.file("external/lux.shp", package="raster")) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(p) e <- erase(p, b) plot(e) # erase parts of lines with polygons r <- raster(extent(p) +c(-.1,.1,-.1,.1), crs=crs(p)) start <- xyFromCell(r, cellFromCol(r, 1)) end <- xyFromCell(r, cellFromCol(r, ncol(r))) lines <- do.call(spLines, lapply(1:10, function(i)rbind(start[i,], end[i,]))) crs(lines) <- crs(p) e2 <- erase(lines, p) plot(p) lines(lines, col='blue', lwd=4, lty=3) lines(e2, col='red', lwd=2)
# erase parts of polygons with other polygons p <- shapefile(system.file("external/lux.shp", package="raster")) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(p) e <- erase(p, b) plot(e) # erase parts of lines with polygons r <- raster(extent(p) +c(-.1,.1,-.1,.1), crs=crs(p)) start <- xyFromCell(r, cellFromCol(r, 1)) end <- xyFromCell(r, cellFromCol(r, ncol(r))) lines <- do.call(spLines, lapply(1:10, function(i)rbind(start[i,], end[i,]))) crs(lines) <- crs(p) e2 <- erase(lines, p) plot(p) lines(lines, col='blue', lwd=4, lty=3) lines(e2, col='red', lwd=2)
Extend returns an Raster* object with a larger spatial extent. The output Raster object has the outer minimum and maximum coordinates of the input Raster and Extent arguments. Thus, all of the cells of the original raster are included. See crop
if you (also) want to remove rows or columns.
There is also an extend method for Extent objects to enlarge (or reduce) an Extent. You can also use algebraic notation to do that (see examples).
This function has replaced function "expand" (to avoid a name conflict with the Matrix package).
## S4 method for signature 'Raster' extend(x, y, value=NA, snap="near", filename='', ...) ## S4 method for signature 'Extent' extend(x, y, ...)
## S4 method for signature 'Raster' extend(x, y, value=NA, snap="near", filename='', ...) ## S4 method for signature 'Extent' extend(x, y, ...)
x |
Raster or Extent object |
y |
If If |
value |
value to assign to new cells |
snap |
Character. One of "near", "in", or "out", to determine in which direction the extent should be aligned. To the nearest border, inwards or outwards |
filename |
Character (optional) |
... |
Additional arguments as for |
RasterLayer or RasterBrick, or Extent
Robert J. Hijmans and Etienne B. Racine (Extent method)
r <- raster(xmn=-150, xmx=-120, ymx=60, ymn=30, ncol=36, nrow=18) values(r) <- 1:ncell(r) e <- extent(-180, 0, 0, 90) re <- extend(r, e) # extend with a number of rows and columns (at each side) re2 <- extend(r, c(2,10)) # Extent object e <- extent(r) e extend(e, 10) extend(e, 10, -10, 0, 20) e + 10 e * 2
r <- raster(xmn=-150, xmx=-120, ymx=60, ymn=30, ncol=36, nrow=18) values(r) <- 1:ncell(r) e <- extent(-180, 0, 0, 90) re <- extend(r, e) # extend with a number of rows and columns (at each side) re2 <- extend(r, c(2,10)) # Extent object e <- extent(r) e extend(e, 10) extend(e, 10, -10, 0, 20) e + 10 e * 2
Get or change a filename extension
extension(filename, value=NULL, maxchar=10) extension(filename) <- value
extension(filename, value=NULL, maxchar=10) extension(filename) <- value
filename |
A filename, with or without the path |
value |
A file extension with or without a dot, e.g., ".txt" or "txt" |
maxchar |
Maximum number of characters after the last dot in the filename, for that string to be considered a filename extension |
A file extension, filename or path.
If ext(filename)
is used without a value
argument, it returns the file extension; otherwise it returns the filename (with new extensions set to value
fn <- "c:/temp folder/filename.exten sion" extension(fn) extension(fn) <- ".txt" extension(fn) fn <- extension(fn, '.document') extension(fn) extension(fn, maxchar=4)
fn <- "c:/temp folder/filename.exten sion" extension(fn) extension(fn) <- ".txt" extension(fn) fn <- extension(fn, '.document') extension(fn) extension(fn, maxchar=4)
This function returns an Extent object of a Raster* or Spatial* object (or an Extent object), or creates an Extent object from a 2x2 matrix (first row: xmin, xmax; second row: ymin, ymax), vector (length=4; order= xmin, xmax, ymin, ymax) or list (with at least two elements, with names 'x' and 'y')
bbox
returns a sp
package like 'bbox' object (a matrix)
extent(x, ...)
extent(x, ...)
x |
Raster* or Extent object, a matrix, a bbox, or a vector of four numbers |
... |
Additional arguments. When x is a single number representing 'xmin', you can pass three additional numbers (xmax, ymin, ymax) When |
Extent object
Robert J. Hijmans; Etienne Racine wrote the extent function for a list
r <- raster() extent(r) extent(c(0, 20, 0, 20)) #is equivalent to extent(0, 20, 0, 20) extent(matrix(c(0, 0, 20, 20), nrow=2)) x <- list(x=c(0,1,2), y=c(-3,5)) extent(x) #crop the extent by row and column numbers extent(r, 1, 20, 10, 30)
r <- raster() extent(r) extent(c(0, 20, 0, 20)) #is equivalent to extent(0, 20, 0, 20) extent(matrix(c(0, 0, 20, 20), nrow=2)) x <- list(x=c(0,1,2), y=c(-3,5)) extent(x) #crop the extent by row and column numbers extent(r, 1, 20, 10, 30)
use round(x, digits=0)
to round the coordinates of an Extent object to the number of digits specified. This can be useful when dealing with a small imprecision in the data (e.g. 179.9999 instead of 180). floor
and ceiling
move the coordiantes to the outer or inner whole integer numbers.
It is also possible to use Arithmetic functions with Extent objects (but these work perhaps unexpectedly!)
See Math-methods
for these (and many more) methods with Raster* objects.
## S4 method for signature 'Extent' floor(x) ## S4 method for signature 'Extent' ceiling(x)
## S4 method for signature 'Extent' floor(x) ## S4 method for signature 'Extent' ceiling(x)
x |
Extent object |
e <- extent(c(0.999999, 10.000011, -60.4, 60)) round(e) ceiling(e) floor(e)
e <- extent(c(0.999999, 10.000011, -60.4, 60)) round(e) ceiling(e) floor(e)
Objects of class Extent are used to define the spatial extent (extremes) of objects of the BasicRaster and Raster* classes.
You can use the extent
function to create Extent objects, or to extract them from Raster* and Spatial* objects.
xmin
:minimum x coordinate
xmax
:maximum x coordinate
ymin
:minumum y coordinate
ymax
:maximum y coordinate
display values of a Extent object
ext <- extent(-180,180,-90,90) ext
ext <- extent(-180,180,-90,90) ext
Extract values from a Raster* object at the locations of spatial vector data. There are methods for points, lines, and polygons (classes from 'sp' or 'sf'), for a matrix or data.frame of points. You can also use cell numbers and Extent (rectangle) objects to extract values.
If y
represents points, extract
returns the values of a Raster* object for the cells in which a set of points fall.
If y
represents lines, the extract
method returns the values of the cells of a Raster* object that are touched by a line. If y
represents polygons, the extract
method returns the values of the cells of a Raster* object that are covered by a polygon. A cell is covered if its center is inside the polygon (but see the weights
option for considering partly covered cells; and argument small
for getting values for small polygons).
It is also possible to extract values for point locations from SpatialPolygons.
## S4 method for signature 'Raster,matrix' extract(x, y, method='simple', buffer=NULL, small=FALSE, cellnumbers=FALSE, fun=NULL, na.rm=TRUE, layer, nl, df=FALSE, factors=FALSE, ...) ## S4 method for signature 'Raster,SpatialLines' extract(x, y, fun=NULL, na.rm=FALSE, cellnumbers=FALSE, df=FALSE, layer, nl, factors=FALSE, along=FALSE, sp=FALSE, ...) ## S4 method for signature 'Raster,SpatialPolygons' extract(x, y, fun=NULL, na.rm=FALSE, exact=FALSE, weights=FALSE, normalizeWeights=TRUE, cellnumbers=FALSE, small=TRUE, df=FALSE, layer, nl, factors=FALSE, sp=FALSE, ...) ## S4 method for signature 'SpatialPolygons,SpatialPoints' extract(x, y, ...)
## S4 method for signature 'Raster,matrix' extract(x, y, method='simple', buffer=NULL, small=FALSE, cellnumbers=FALSE, fun=NULL, na.rm=TRUE, layer, nl, df=FALSE, factors=FALSE, ...) ## S4 method for signature 'Raster,SpatialLines' extract(x, y, fun=NULL, na.rm=FALSE, cellnumbers=FALSE, df=FALSE, layer, nl, factors=FALSE, along=FALSE, sp=FALSE, ...) ## S4 method for signature 'Raster,SpatialPolygons' extract(x, y, fun=NULL, na.rm=FALSE, exact=FALSE, weights=FALSE, normalizeWeights=TRUE, cellnumbers=FALSE, small=TRUE, df=FALSE, layer, nl, factors=FALSE, sp=FALSE, ...) ## S4 method for signature 'SpatialPolygons,SpatialPoints' extract(x, y, ...)
x |
Raster* object |
y |
points represented by a two-column matrix or data.frame, or |
method |
character. |
buffer |
numeric. The radius of a buffer around each point from which to extract cell values. If the distance between the sampling point and the center of a cell is less than or equal to the buffer, the cell is included. The buffer can be specified as a single value, or as a vector of the length of the number of points. If the data are not projected (latitude/longitude), the unit should be meters. Otherwise it should be in map-units (typically also meters). |
small |
logical. If |
fun |
function to summarize the values (e.g. |
na.rm |
logical. Only useful when an argument |
cellnumbers |
logical. If |
df |
logical. If |
exact |
logical. If |
weights |
logical. If |
normalizeWeights |
logical. If |
factors |
logical. If |
layer |
integer. First layer for which you want values (if |
nl |
integer. Number of layers for which you want values (if |
along |
boolean. Should returned values be ordered to go along the lines? |
sp |
boolean. Should the extracted values be added to the data.frame of the Spatial* object |
... |
additional arguments (none implemented) |
A vector for RasterLayer objects, and a matrix for RasterStack or RasterBrick objects. A list (or a data.frame if df=TRUE
) if y
is a SpatialPolygons* or SpatialLines* object or if a buffer
argument is used (but not a fun
argument). If sp=TRUE
and y
is a Spatial* object and fun
is not NULL a Spatial* object is returned. The order of the returned values corresponds to the order of object y
. If df=TRUE
, this is also indicated in the first variable ('ID').
r <- raster(ncol=36, nrow=18, vals=1:(18*36)) ############################### # extract values by cell number ############################### extract(r, c(1:2, 10, 100)) s <- stack(r, sqrt(r), r/r) extract(s, c(1, 10, 100), layer=2, n=2) ############################### # extract values with points ############################### xy <- cbind(-50, seq(-80, 80, by=20)) extract(r, xy) sp <- SpatialPoints(xy) extract(r, sp, method='bilinear') # examples with a buffer extract(r, xy[1:3,], buffer=1000000) extract(r, xy[1:3,], buffer=1000000, fun=mean) ## illustrating the varying size of a buffer (expressed in meters) ## on a longitude/latitude raster z <- extract(r, xy, buffer=1000000) s <- raster(r) for (i in 1:length(z)) { s[z[[i]]] <- i } ## compare with raster that is not longitude/latitude crs(r) <- "+proj=utm +zone=17" xy[,1] <- 50 z <- extract(r, xy, buffer=8) for (i in 1:length(z)) { s[z[[i]]] <- i } plot(s) # library(maptools) # data(wrld_simpl) # plot(wrld_simpl, add=TRUE) ############################### # extract values with lines ############################### r <- raster(ncol=36, nrow=18, vals=1:(18*36)) cds1 <- rbind(c(-50,0), c(0,60), c(40,5), c(15,-45), c(-10,-25)) cds2 <- rbind(c(80,20), c(140,60), c(160,0), c(140,-55)) lines <- spLines(cds1, cds2) extract(r, lines) ############################### # extract values with polygons ############################### cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20)) cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0)) polys <- spPolygons(cds1, cds2) v <- extract(r, polys) # mean for each polygon unlist(lapply(v, function(x) if (!is.null(x)) mean(x, na.rm=TRUE) else NA )) # v <- extract(r, polys, cellnumbers=TRUE) # weighted mean # v <- extract(r, polys, weights=TRUE, fun=mean) # equivalent to: # v <- extract(r, polys, weights=TRUE) # sapply(v, function(x) if (!is.null(x)) {sum(apply(x, 1, prod)) / sum(x[,2])} else NA) ############################### # extract values with an extent ############################### e <- extent(150,170,-60,-40) extract(r, e) #plot(r) #plot(e, add=T)
r <- raster(ncol=36, nrow=18, vals=1:(18*36)) ############################### # extract values by cell number ############################### extract(r, c(1:2, 10, 100)) s <- stack(r, sqrt(r), r/r) extract(s, c(1, 10, 100), layer=2, n=2) ############################### # extract values with points ############################### xy <- cbind(-50, seq(-80, 80, by=20)) extract(r, xy) sp <- SpatialPoints(xy) extract(r, sp, method='bilinear') # examples with a buffer extract(r, xy[1:3,], buffer=1000000) extract(r, xy[1:3,], buffer=1000000, fun=mean) ## illustrating the varying size of a buffer (expressed in meters) ## on a longitude/latitude raster z <- extract(r, xy, buffer=1000000) s <- raster(r) for (i in 1:length(z)) { s[z[[i]]] <- i } ## compare with raster that is not longitude/latitude crs(r) <- "+proj=utm +zone=17" xy[,1] <- 50 z <- extract(r, xy, buffer=8) for (i in 1:length(z)) { s[z[[i]]] <- i } plot(s) # library(maptools) # data(wrld_simpl) # plot(wrld_simpl, add=TRUE) ############################### # extract values with lines ############################### r <- raster(ncol=36, nrow=18, vals=1:(18*36)) cds1 <- rbind(c(-50,0), c(0,60), c(40,5), c(15,-45), c(-10,-25)) cds2 <- rbind(c(80,20), c(140,60), c(160,0), c(140,-55)) lines <- spLines(cds1, cds2) extract(r, lines) ############################### # extract values with polygons ############################### cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20)) cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0)) polys <- spPolygons(cds1, cds2) v <- extract(r, polys) # mean for each polygon unlist(lapply(v, function(x) if (!is.null(x)) mean(x, na.rm=TRUE) else NA )) # v <- extract(r, polys, cellnumbers=TRUE) # weighted mean # v <- extract(r, polys, weights=TRUE, fun=mean) # equivalent to: # v <- extract(r, polys, weights=TRUE) # sapply(v, function(x) if (!is.null(x)) {sum(apply(x, 1, prod)) / sum(x[,2])} else NA) ############################### # extract values with an extent ############################### e <- extent(150,170,-60,-40) extract(r, e) #plot(r) #plot(e, add=T)
These are shorthand methods that call other methods that should normally be used, such as getValues
, extract
, crop
.
object[i]
can be used to access values of a Raster* object, using cell numbers. You can also use row and column numbers as index, using object[i,j]
or object[i,]
or object[,j]
. In addition you can supply an Extent, SpatialPolygons, SpatialLines or SpatialPoints object.
If drop=TRUE
(the default) cell values are returned (a vector for a RasterLayer, a matrix for a RasterStack or RasterBrick). If drop=FALSE
a Raster* object is returned that has the extent covering the requested cells, and with all other non-requested cells within this extent set to NA
.
If you supply a RasterLayer, its values will be used as logical (TRUE/FALSE) indices if both Raster objects have the same extent and resolution; otherwise the cell values within the extent of the RasterLayer are returned.
Double brackes '[[ ]]' can be used to extract one or more layers from a multi-layer object.
x[i]
x[i,j]
Arguments
x |
a Raster* object | |
i |
cell number(s), row number(s), a (logical) RasterLayer, Spatial* object | |
j |
column number(s) (only available if i is (are) a row number(s)) | |
drop |
If TRUE , cell values are returned. Otherwise, a Raster* object is returned |
|
getValues, setValues, extract, crop, rasterize
r <- raster(ncol=10, nrow=5) values(r) <- 1:ncell(r) r[1] r[1:10] r[1,] r[,1] r[1:2, 1:2] s <- stack(r, sqrt(r)) s[1:3] s[[2]]
r <- raster(ncol=10, nrow=5) values(r) <- 1:ncell(r) r[1] r[1:10] r[1,] r[,1] r[1:2, 1:2] s <- stack(r, sqrt(r)) s[1:3] s[[2]]
These functions return or set the extreme coordinates of a Raster* object; and return them for Spatial* objects.
xmin(x) xmax(x) ymin(x) ymax(x) xmin(x, ...) <- value xmax(x, ...) <- value ymin(x, ...) <- value ymax(x, ...) <- value
xmin(x) xmax(x) ymin(x) ymax(x) xmin(x, ...) <- value xmax(x, ...) <- value ymin(x, ...) <- value ymax(x, ...) <- value
x |
Raster* or Extent object |
value |
numeric. x or y coordinate |
... |
additional arguments. None implemented |
numeric
r <- raster(xmn=-0.5, xmx = 9.5, ncols=10) xmin(r) xmax(r) ymin(r) ymax(r) xmin(r) <- -180 xmax(r) <- 180
r <- raster(xmn=-0.5, xmx = 9.5, ncols=10) xmin(r) xmax(r) ymin(r) ymax(r) xmin(r) <- -180 xmax(r) <- 180
Returns the minimum or maximum value of a RasterLayer or layer in a RasterStack
minValue(x, ...) maxValue(x, ...)
minValue(x, ...) maxValue(x, ...)
x |
RasterLayer or RasterStack object |
... |
Additional argument: layer number (for RasterStack or RasterBrick objects) |
If a Raster* object is created from a file on disk, the min and max values are often not known (depending on the file format). You can use setMinMax
to set them in the Raster* object.
a number
r <- raster() r <- setValues(r, 1:ncell(r)) minValue(r) maxValue(r) r <- setValues(r, round(100 * runif(ncell(r)) + 0.5)) minValue(r) maxValue(r) r <- raster(system.file("external/test.grd", package="raster")) minValue(r) maxValue(r)
r <- raster() r <- setValues(r, 1:ncell(r)) minValue(r) maxValue(r) r <- setValues(r, round(100 * runif(ncell(r)) + 0.5)) minValue(r) maxValue(r) r <- raster(system.file("external/test.grd", package="raster")) minValue(r) maxValue(r)
These functions allow for defining a RasterLayer as a categorical variable. Such a RasterLayer is linked to other values via a "Raster Attribute Table" (RAT). Thus the cell values are an index, whereas the actual values of interest are in the RAT. The RAT is a data.frame. The first column in the RAT ("ID") has the unique cell values of the layer; this column should normally not be changed. The other columns can be of any basic type (factor, character, integer, numeric or logical). The functions documented here are mainly available such that files with a RAT can be read and processed; currently there is not too much further support. Whether a layer is defined as a factor or not is currently ignored by almost all functions. An exception is the 'extract' function (when used with option df=TRUE).
Function 'levels' returns the RAT for inspection. It can be modified and set using levels <- value
(but use caution as it is easy to mess things up).
as.factor
and ratify
create a layer with a RAT table. Function 'deratify' creates a single layer for a (or each) variable in the RAT table.
is.factor(x) as.factor(x) levels(x) ## S4 method for signature 'Raster' ratify(x, filename="", count=FALSE, ...) factorValues(x, v, layer=1, att=NULL, append.names=FALSE) deratify(x, att=NULL, layer=1, complete=FALSE, drop=TRUE, fun='mean', filename='', ...) asFactor(x, ...)
is.factor(x) as.factor(x) levels(x) ## S4 method for signature 'Raster' ratify(x, filename="", count=FALSE, ...) factorValues(x, v, layer=1, att=NULL, append.names=FALSE) deratify(x, att=NULL, layer=1, complete=FALSE, drop=TRUE, fun='mean', filename='', ...) asFactor(x, ...)
x |
Raster* object |
v |
integer cell values |
layer |
integer > 0 indicating which layer to use (in a RasterStack or RasterBrick) |
att |
numeric or character. Which variable(s) in the RAT table should be used. If |
append.names |
logical. Should names of data.frame returned by a combination of the name of the layer and the RAT variables? (can be useful for multilayer objects |
filename |
character. Optional |
count |
logical. If |
... |
additional arguments as for |
complete |
logical. If |
drop |
logical. If |
fun |
character. Used to get a single value for each class for a weighted RAT table. 'mean', 'min', 'max', 'smallest', or 'largest' |
Raster* object; list (levels); boolean (is.factor); matrix (factorValues)
asFactor is deprecated and should not be used
set.seed(0) r <- raster(nrow=10, ncol=10) values(r) <- runif(ncell(r)) * 10 is.factor(r) r <- round(r) f <- as.factor(r) is.factor(f) x <- levels(f)[[1]] x x$code <- letters[10:20] levels(f) <- x levels(f) f r <- raster(nrow=10, ncol=10) values(r) = 1 r[51:100] = 2 r[3:6, 1:5] = 3 r <- ratify(r) rat <- levels(r)[[1]] rat$landcover <- c("Pine", "Oak", "Meadow") rat$code <- c(12,25,30) levels(r) <- rat r # extract values for some cells i <- extract(r, c(1,2, 25,100)) i # get the attribute values for these cells factorValues(r, i) # write to file: # rr <- writeRaster(r, rasterTmpFile(), overwrite=TRUE) # rr # create a single-layer factor x <- deratify(r, "landcover") x is.factor(x) levels(x)
set.seed(0) r <- raster(nrow=10, ncol=10) values(r) <- runif(ncell(r)) * 10 is.factor(r) r <- round(r) f <- as.factor(r) is.factor(f) x <- levels(f)[[1]] x x$code <- letters[10:20] levels(f) <- x levels(f) f r <- raster(nrow=10, ncol=10) values(r) = 1 r[51:100] = 2 r[3:6, 1:5] = 3 r <- ratify(r) rat <- levels(r)[[1]] rat$landcover <- c("Pine", "Oak", "Meadow") rat$code <- c(12,25,30) levels(r) <- rat r # extract values for some cells i <- extract(r, c(1,2, 25,100)) i # get the attribute values for these cells factorValues(r, i) # write to file: # rr <- writeRaster(r, rasterTmpFile(), overwrite=TRUE) # rr # create a single-layer factor x <- deratify(r, "landcover") x is.factor(x) levels(x)
Get the filename of a Raster* object. You cannot set the filename of an object (except for RasterStack objects); but you can provide a 'filename= ' argument to a function that creates a new RasterLayer or RasterBrick* object.
filename(x)
filename(x)
x |
A Raster* object |
a Raster* object
r <- raster( system.file("external/test.grd", package="raster") ) filename(r)
r <- raster( system.file("external/test.grd", package="raster") ) filename(r)
Filled contour plot of a RasterLayer. This is a wrapper around filled.contour
for RasterLayer objects.
filledContour(x, y=1, maxpixels=100000, ...)
filledContour(x, y=1, maxpixels=100000, ...)
x |
A Raster* object |
y |
Integer. The layer number of x (if x has multiple layers) |
maxpixels |
The maximum number of pixels |
... |
Any argument that can be passed to |
r <- raster(system.file("external/test.grd", package="raster")) filledContour(r)
r <- raster(system.file("external/test.grd", package="raster")) filledContour(r)
Flip the values of a Raster* object by inverting the order of the rows (direction=y) or the columns direction='x'.
## S4 method for signature 'RasterLayer' flip(x, direction='y', filename='', ...) ## S4 method for signature 'RasterStackBrick' flip(x, direction='y', filename='', ...)
## S4 method for signature 'RasterLayer' flip(x, direction='y', filename='', ...) ## S4 method for signature 'RasterStackBrick' flip(x, direction='y', filename='', ...)
x |
Raster* object |
direction |
Character. 'y' or 'x'; or 1 (=x) or 2 (=y) |
filename |
character. Output filename (optional) |
... |
if |
RasterLayer or RasterBrick
r <- raster(nrow=18, ncol=36) m <- matrix(1:ncell(r), nrow=18) values(r) <- as.vector(t(m)) rx <- flip(r, direction='x') values(r) <- as.vector(m) ry <- flip(r, direction='y')
r <- raster(nrow=18, ncol=36) m <- matrix(1:ncell(r), nrow=18) values(r) <- as.vector(t(m)) rx <- flip(r, direction='x') values(r) <- as.vector(m) ry <- flip(r, direction='y')
Compute the flow path (drainage path) starting at a given point. See package gdistance
for more path computations.
flowPath(x, p, ...)
flowPath(x, p, ...)
x |
RasterLayer of flow direction (as can be created with |
p |
starting point. Either two numbers: x (longitude) and y (latitude) coordinates; or a single cell number |
... |
additional arguments (none implemented) |
numeric (cell numbers)
Ashton Shortridge
data(volcano) v <- raster(volcano, xmn=2667400, xmx=2668010, ymn=6478700, ymx=6479570, crs="+init=epsg:27200") fd <- terrain(v, opt = "flowdir") path <- flowPath(fd, 2407) xy <- xyFromCell(fd, path) plot(v) lines(xy)
data(volcano) v <- raster(volcano, xmn=2667400, xmx=2668010, ymn=6478700, ymx=6479570, crs="+init=epsg:27200") fd <- terrain(v, opt = "flowdir") path <- flowPath(fd, 2407) xy <- xyFromCell(fd, path) plot(v) lines(xy)
Calculate focal ("moving window") values for the neighborhood of focal cells using a matrix of weights, perhaps in combination with a function.
## S4 method for signature 'RasterLayer' focal(x, w, fun, filename='', na.rm=FALSE, pad=FALSE, padValue=NA, NAonly=FALSE, ...)
## S4 method for signature 'RasterLayer' focal(x, w, fun, filename='', na.rm=FALSE, pad=FALSE, padValue=NA, NAonly=FALSE, ...)
x |
RasterLayer |
w |
matrix of weights (the moving window), e.g. a 3 by 3 matrix with values 1; see Details. The matrix does not need to be square, but the sides must be odd numbers. If you need even sides, you can add a column or row with weights of zero or |
fun |
function (optional). The function fun should take multiple numbers, and return a single number. For example mean, modal, min or max. It should also accept a |
filename |
character. Filename for a new raster (optional) |
na.rm |
logical. If |
pad |
logical. If |
padValue |
numeric. The value of the cells of the padded rows and columns |
NAonly |
logical. If |
... |
Additional arguments as for |
focal
uses a matrix of weights for the neighborhood of the focal cells. The default function is sum
. It is computationally much more efficient to adjust the weights-matrix than to use another function through the fun
argument. Thus while the following two statements are equivalent (if there are no NA
values), the first one is faster than the second one:
a <- focal(x, w=matrix(1/9, nc=3, nr=3))
b <- focal(x, w=matrix(1,3,3), fun=mean)
There is, however, a difference if NA
values are considered. One can use the na.rm=TRUE
option which may make sense when using a function like mean
. However, the results would be wrong when using a weights matrix.
Laplacian filter: filter=matrix(c(0,1,0,1,-4,1,0,1,0), nrow=3)
Sobel filters: fx=matrix(c(-1,-2,-1,0,0,0,1,2,1) / 4, nrow=3)
and fy=matrix(c(1,0,-1,2,0,-2,1,0,-1)/4, nrow=3)
see the focalWeight
function to create distance based circular, rectangular, or Gaussian filters.
Note that there is a difference between 0 and NA in the weights matrix. A zero weight cell is included in the computation, whereas a NA weight cell is excluded. This does not matter for "sum", nor for "mean" (zeros are removed), but it affects many other functions such as "var" as you could be adding a lot of zeros that should not be there.
RasterLayer
r <- raster(ncols=36, nrows=18, xmn=0) values(r) <- runif(ncell(r)) # 3x3 mean filter r3 <- focal(r, w=matrix(1/9,nrow=3,ncol=3)) # 5x5 mean filter r5 <- focal(r, w=matrix(1/25,nrow=5,ncol=5)) # Gaussian filter gf <- focalWeight(r, 2, "Gauss") rg <- focal(r, w=gf) # The max value for the lower-rigth corner of a 3x3 matrix around a focal cell f = matrix(c(0,0,0,0,1,1,0,1,1), nrow=3) f rm <- focal(r, w=f, fun=max) # global lon/lat data: no 'edge effect' for the columns xmin(r) <- -180 r3g <- focal(r, w=matrix(1/9,nrow=3,ncol=3)) ## Not run: ## focal can be used to create a cellular automaton # Conway's Game of Life w <- matrix(c(1,1,1,1,0,1,1,1,1), nr=3,nc=3) gameOfLife <- function(x) { f <- focal(x, w=w, pad=TRUE, padValue=0) # cells with less than two or more than three live neighbours die x[f<2 | f>3] <- 0 # cells with three live neighbours become alive x[f==3] <- 1 x } # simulation function sim <- function(x, fun, n=100, pause=0.25) { for (i in 1:n) { x <- fun(x) plot(x, legend=FALSE, asp=NA, main=i) dev.flush() Sys.sleep(pause) } invisible(x) } # Gosper glider gun m <- matrix(0, nc=48, nr=34) m[c(40, 41, 74, 75, 380, 381, 382, 413, 417, 446, 452, 480, 486, 517, 549, 553, 584, 585, 586, 619, 718, 719, 720, 752, 753, 754, 785, 789, 852, 853, 857, 858, 1194, 1195, 1228, 1229)] <- 1 init <- raster(m) # run the model sim(init, gameOfLife, n=150, pause=0.05) ## Implementation of Sobel edge-detection filter ## for RasterLayer r sobel <- function(r) { fy <- matrix(c(1,0,-1,2,0,-2,1,0,-1), nrow=3) fx <- matrix(c(-1,-2,-1,0,0,0,1,2,1) , nrow=3) rx <- focal(r, fx) ry <- focal(r, fy) sqrt(rx^2 + ry^2) } ## End(Not run)
r <- raster(ncols=36, nrows=18, xmn=0) values(r) <- runif(ncell(r)) # 3x3 mean filter r3 <- focal(r, w=matrix(1/9,nrow=3,ncol=3)) # 5x5 mean filter r5 <- focal(r, w=matrix(1/25,nrow=5,ncol=5)) # Gaussian filter gf <- focalWeight(r, 2, "Gauss") rg <- focal(r, w=gf) # The max value for the lower-rigth corner of a 3x3 matrix around a focal cell f = matrix(c(0,0,0,0,1,1,0,1,1), nrow=3) f rm <- focal(r, w=f, fun=max) # global lon/lat data: no 'edge effect' for the columns xmin(r) <- -180 r3g <- focal(r, w=matrix(1/9,nrow=3,ncol=3)) ## Not run: ## focal can be used to create a cellular automaton # Conway's Game of Life w <- matrix(c(1,1,1,1,0,1,1,1,1), nr=3,nc=3) gameOfLife <- function(x) { f <- focal(x, w=w, pad=TRUE, padValue=0) # cells with less than two or more than three live neighbours die x[f<2 | f>3] <- 0 # cells with three live neighbours become alive x[f==3] <- 1 x } # simulation function sim <- function(x, fun, n=100, pause=0.25) { for (i in 1:n) { x <- fun(x) plot(x, legend=FALSE, asp=NA, main=i) dev.flush() Sys.sleep(pause) } invisible(x) } # Gosper glider gun m <- matrix(0, nc=48, nr=34) m[c(40, 41, 74, 75, 380, 381, 382, 413, 417, 446, 452, 480, 486, 517, 549, 553, 584, 585, 586, 619, 718, 719, 720, 752, 753, 754, 785, 789, 852, 853, 857, 858, 1194, 1195, 1228, 1229)] <- 1 init <- raster(m) # run the model sim(init, gameOfLife, n=150, pause=0.05) ## Implementation of Sobel edge-detection filter ## for RasterLayer r sobel <- function(r) { fy <- matrix(c(1,0,-1,2,0,-2,1,0,-1), nrow=3) fx <- matrix(c(-1,-2,-1,0,0,0,1,2,1) , nrow=3) rx <- focal(r, fx) ry <- focal(r, fy) sqrt(rx^2 + ry^2) } ## End(Not run)
Calculate focal ("moving window") weight matrix for use in the focal
function. The sum of the values adds up to one.
focalWeight(x, d, type=c('circle', 'Gauss', 'rectangle'), fillNA=FALSE)
focalWeight(x, d, type=c('circle', 'Gauss', 'rectangle'), fillNA=FALSE)
x |
Raster* object |
d |
numeric. If |
type |
character indicating the type of filter to be returned |
fillNA |
logical. If |
matrix that can be used in focal
r <- raster(ncols=180, nrows=180, xmn=0, crs="+proj=utm +zone=1") # Gaussian filter for square cells gf <- focalWeight(r, .5, "Gauss") focalWeight(r, 2, "circle", fillNA=TRUE)
r <- raster(ncols=180, nrows=180, xmn=0, crs="+proj=utm +zone=1") # Gaussian filter for square cells gf <- focalWeight(r, .5, "Gauss") focalWeight(r, 2, "circle", fillNA=TRUE)
Frequency table of the values of a RasterLayer.
## S4 method for signature 'RasterLayer' freq(x, digits=0, value=NULL, useNA='ifany', progress='', ...) ## S4 method for signature 'RasterStackBrick' freq(x, digits=0, value=NULL, useNA='ifany', merge=FALSE, progress='', ...)
## S4 method for signature 'RasterLayer' freq(x, digits=0, value=NULL, useNA='ifany', progress='', ...) ## S4 method for signature 'RasterStackBrick' freq(x, digits=0, value=NULL, useNA='ifany', merge=FALSE, progress='', ...)
x |
RasterLayer |
digits |
non-negative integer for rounding the cell values. Argument is passed to |
value |
numeric, logical or NA. An optional single value to only count the number of cells with that value |
useNA |
character. What to do with NA values? Options are "no", "ifany", "always". See to |
progress |
character to specify a progress bar. Choose from 'text', 'window', or ” (the default, no progress bar) |
merge |
logical. If |
... |
additional arguments (none implemented) |
matrix (RasterLayer). List of matrices (one for each layer) or data.frame (if merge=TRUE
) (RasterStack or RasterBrick)
r <- raster(nrow=18, ncol=36) values(r) <- runif(ncell(r)) r[1:5] <- NA r <- r * r * r * 5 freq(r) freq(r, value=2) s <- stack(r, r*2, r*3) freq(s, merge=TRUE)
r <- raster(nrow=18, ncol=36) values(r) <- runif(ncell(r)) r[1:5] <- NA r <- r * r * r * 5 freq(r) freq(r, value=2) s <- stack(r, r*2, r*3) freq(s, merge=TRUE)
These functions can be used to get or set the gain and offset parameters used to transform values when reading them from a file. The gain and offset parameters are applied to the raw values using the formula below:
value <- value * gain + offset
The default value for gain is 1 and for offset is 0. 'gain' is sometimes referred to as 'scale'.
Note that setting gain and/or offset are intended to be used with values that are stored in a file. For a Raster* object with values in memory, assigning gain or offset values will lead to the inmediate computation of new values; in such cases it would be clearer to use Arith-methods
.
gain(x) gain(x) <- value offs(x) offs(x) <- value
gain(x) gain(x) <- value offs(x) offs(x) <- value
x |
Raster* object |
value |
Single numeric value |
Raster* object or numeric value(s)
r <- raster(system.file("external/test.grd", package="raster")) gain(r) offs(r) r[1505:1510] gain(r) <- 10 offs(r) <- 5 r[1505:1510]
r <- raster(system.file("external/test.grd", package="raster")) gain(r) offs(r) r[1505:1510] gain(r) <- 10 offs(r) <- 5 r[1505:1510]
Extract the coordinates of a Spatial object
## S4 method for signature 'SpatialPolygons' geom(x, sepNA=FALSE, ...) ## S4 method for signature 'SpatialLines' geom(x, sepNA=FALSE, ...) ## S4 method for signature 'SpatialPoints' geom(x, ...) ## S4 method for signature 'data.frame' geom(x, d, gt, crs, ...)
## S4 method for signature 'SpatialPolygons' geom(x, sepNA=FALSE, ...) ## S4 method for signature 'SpatialLines' geom(x, sepNA=FALSE, ...) ## S4 method for signature 'SpatialPoints' geom(x, ...) ## S4 method for signature 'data.frame' geom(x, d, gt, crs, ...)
x |
SpatialPolygons*, SpatialLines*, or SpatialPoints* object; or a data.frame |
sepNA |
logical. If |
... |
additional arguments, none implemented |
d |
data.frame that matches the number of objects in data.frame |
gt |
character. geometry type. Must be one of "polygons", "lines", "points" |
crs |
character. PROJ.4 crs string |
Matrix with 6, (5 SpatialLines), or 3 (SpatialPoints) columns. object (sequential object number) part (sequential part number within the object; not for SpatialPoints), cump (cumulative part number; not for SpatialPoints), hole (is this a hole or not; only for SpatialPolygons), x (x coordinate or longitude), y (y coordinate or latitude)
p <- readRDS(system.file("external/lux.rds", package="raster")) x <- geom(p) head(x) # and back to a SpatialPolygonsDataFrame x <- data.frame(x) sp <- as(x, "SpatialPolygons") crs(sp) <- crs(p) spdf <- SpatialPolygonsDataFrame(sp, data.frame(p), match.ID=FALSE)
p <- readRDS(system.file("external/lux.rds", package="raster")) x <- geom(p) head(x) # and back to a SpatialPolygonsDataFrame x <- data.frame(x) sp <- as(x, "SpatialPolygons") crs(sp) <- crs(p) spdf <- SpatialPolygonsDataFrame(sp, data.frame(p), match.ID=FALSE)
This function has been deprecated and does not work anymore.
getData(...) ccodes()
getData(...) ccodes()
... |
arguments |
getValues returns all values or the values for a number of rows of a Raster* object. Values returned for a RasterLayer are a vector. The values returned for a RasterStack or RasterBrick are always a matrix, with the rows representing cells, and the columns representing layers
values
is a shorthand version of getValues (for all rows).
getValues(x, row, nrows, ...) values(x, ...)
getValues(x, row, nrows, ...) values(x, ...)
x |
Raster* object |
row |
Numeric. Row number, should be between 1 and nrow(x), or missing in which case all values are returned |
nrows |
Numeric. Number of rows. Should be an integer > 0, or missing |
... |
Additional arguments. When x is a |
vector or matrix of raster values
getValuesBlock, getValuesFocal, setValues
r <- raster(system.file("external/test.grd", package="raster")) r v <- getValues(r) length(v) head(v) getValues(r, row=10)
r <- raster(system.file("external/test.grd", package="raster")) r v <- getValues(r) length(v) head(v) getValues(r, row=10)
getValuesBlock returns values for a block (rectangular area) of values of a Raster* object.
## S4 method for signature 'RasterLayer' getValuesBlock(x, row=1, nrows=1, col=1, ncols=(ncol(x)-col+1), format='', ...) ## S4 method for signature 'RasterBrick' getValuesBlock(x, row=1, nrows=1, col=1, ncols=(ncol(x)-col+1), lyrs, ...) ## S4 method for signature 'RasterStack' getValuesBlock(x, row=1, nrows=1, col=1, ncols=(ncol(x)-col+1), lyrs, ...)
## S4 method for signature 'RasterLayer' getValuesBlock(x, row=1, nrows=1, col=1, ncols=(ncol(x)-col+1), format='', ...) ## S4 method for signature 'RasterBrick' getValuesBlock(x, row=1, nrows=1, col=1, ncols=(ncol(x)-col+1), lyrs, ...) ## S4 method for signature 'RasterStack' getValuesBlock(x, row=1, nrows=1, col=1, ncols=(ncol(x)-col+1), lyrs, ...)
x |
Raster* object |
row |
positive integer. Row number to start from, should be between 1 and nrow(x) |
nrows |
positive integer. How many rows? Default is 1 |
col |
positive integer. Column number to start from, should be between 1 and ncol(x) |
ncols |
positive integer. How many columns? Default is the number of columns left after the start column |
format |
character. When |
lyrs |
integer (vector). Which layers? Default is all layers ( |
... |
additional arguments (none implemented) |
matrix or vector (if (x=RasterLayer)
, unless format='matrix'
)
r <- raster(system.file("external/test.grd", package="raster")) b <- getValuesBlock(r, row=100, nrows=3, col=10, ncols=5) b b <- matrix(b, nrow=3, ncol=5, byrow=TRUE) b logo <- brick(system.file("external/rlogo.grd", package="raster")) getValuesBlock(logo, row=35, nrows=3, col=50, ncols=3, lyrs=2:3)
r <- raster(system.file("external/test.grd", package="raster")) b <- getValuesBlock(r, row=100, nrows=3, col=10, ncols=5) b b <- matrix(b, nrow=3, ncol=5, byrow=TRUE) b logo <- brick(system.file("external/rlogo.grd", package="raster")) getValuesBlock(logo, row=35, nrows=3, col=50, ncols=3, lyrs=2:3)
This function returns a matrix (or matrices) for all focal values of a number of rows of a Raster* object
## S4 method for signature 'Raster' getValuesFocal(x, row, nrows, ngb, names=FALSE, padValue=NA, array=FALSE, ...)
## S4 method for signature 'Raster' getValuesFocal(x, row, nrows, ngb, names=FALSE, padValue=NA, array=FALSE, ...)
x |
Raster* object |
row |
Numeric. Row number, should be between 1 and nrow(x). Can be omitted to get all rows |
nrows |
Numeric. Number of rows, should be a positive integer smaller than |
ngb |
Neighbourhood size. Either a single integer or a vector of two integers |
names |
logical. If |
padValue |
numeric. The value of the cells of the "padded" rows and columns. That is 'virtual' values for cells within a neighbourhood, but outside the raster |
array |
logical. If |
... |
additional arguments (none implemented) |
If x
has a single layer, a matrix with one row for each focal cell, and one column for each neighbourhood cell around it.
If x
has multiple layers, an array (if array=TRUE
) or a list of such matrices (one list element (matrix) for each layer)
r <- raster(nr=5, nc=5, crs='+proj=utm +zone=12') values(r) <- 1:25 as.matrix(r) getValuesFocal(r, row=1, nrows=2, ngb=3, names=TRUE) getValuesFocal(stack(r,r), row=1, nrows=1, ngb=3, names=TRUE, array=TRUE)
r <- raster(nr=5, nc=5, crs='+proj=utm +zone=12') values(r) <- 1:25 as.matrix(r) getValuesFocal(r, row=1, nrows=2, ngb=3, names=TRUE) getValuesFocal(stack(r,r), row=1, nrows=1, ngb=3, names=TRUE, array=TRUE)
The function calculates the distance to cells of a RasterLayer when the path has to go through the centers of neighboring raster cells (currently only implemented as a 'queen' case in which cells have 8 neighbors).
The distance is in meters if the coordinate reference system (CRS) of the RasterLayer is longitude/latitude (+proj=longlat
) and in the units of the CRS (typically meters) in other cases.
Distances are computed by summing local distances between cells, which are connected with their neighbours in 8 directions.
## S4 method for signature 'RasterLayer' gridDistance(x, origin, omit=NULL, filename="", ...)
## S4 method for signature 'RasterLayer' gridDistance(x, origin, omit=NULL, filename="", ...)
x |
RasterLayer |
origin |
value(s) of the cells from which the distance is calculated |
omit |
value(s) of the cells which cannot be traversed (optional) |
filename |
character. output filename (optional) |
... |
additional arguments as for |
If the RasterLayer to be processed is big, it will be processed in chunks. This may lead to errors in the case of complex objects spread over different chunks (meandering rivers, for instance). You can try to solve these issues by varying the chunk size, see function setOptions().
RasterLayer
Jacob van Etten and Robert J. Hijmans
See distance
for 'as the crow flies' distance. Additional distance measures and options (directions, cost-distance) are available in the 'gdistance
' package.
#world lon/lat raster r <- raster(ncol=10,nrow=10, vals=1) r[48] <- 2 r[66:68] <- 3 d <- gridDistance(r,origin=2,omit=3) plot(d) #UTM small area crs(r) <- "+proj=utm +zone=15 +ellps=GRS80 +datum=NAD83 +units=m +no_defs" d <- gridDistance(r,origin=2,omit=3) plot(d)
#world lon/lat raster r <- raster(ncol=10,nrow=10, vals=1) r[48] <- 2 r[66:68] <- 3 d <- gridDistance(r,origin=2,omit=3) plot(d) #UTM small area crs(r) <- "+proj=utm +zone=15 +ellps=GRS80 +datum=NAD83 +units=m +no_defs" d <- gridDistance(r,origin=2,omit=3) plot(d)
Write header files to use together with raster binary files to read the data in other applications.
hdr(x, format, extension='.wld', filename='')
hdr(x, format, extension='.wld', filename='')
x |
RasterLayer or RasterBrick object associated with a binary values file on disk |
format |
Type of header file: 'VRT', 'BIL', 'ENVI', 'ErdasRaw', 'IDRISI', 'SAGA', 'RASTER', 'WORLDFILE', 'PRJ' |
extension |
File extension, only used with an ESRI worldfile ( |
filename |
character. Need to be provided if |
The RasterLayer object must be associated with a file on disk.
You can use writeRaster
to save a existing file in another format. But if you have a file in a 'raster' format (or similar), you can also only export a header file,
and use the data file (.gri) that already exists. The function can write a VRT (GDAL virtual raster) header (.vrt); an ENVI or BIL header (.hdr) file; an Erdas Raw (.raw) header file; an IDRISI (.rdc) or SAGA (.sgrd).
This (hopefully) allows for reading the binary data (.gri), perhaps after changing the file extension, in other programs such as ENVI or ArcGIS.
## Not run: r <- raster(system.file("external/test.grd", package="raster")) r <- writeRaster(r, filename='export.grd', overwrite=TRUE) hdr(r, format="ENVI") ## End(Not run)
## Not run: r <- raster(system.file("external/test.grd", package="raster")) r <- writeRaster(r, filename='export.grd', overwrite=TRUE) hdr(r, format="ENVI") ## End(Not run)
Show the head (first rows/columns) or tail (last rows/columns) of the cell values of a Raster* object.
head(x, ...) tail(x, ...)
head(x, ...) tail(x, ...)
x |
Raster* object |
... |
Additional arguments: |
matrix
r <- raster(nrow=25, ncol=25) values(r) = 1:ncell(r) head(r) tail(r, cols=10, rows=5)
r <- raster(nrow=25, ncol=25) values(r) = 1:ncell(r) head(r) tail(r, cols=10, rows=5)
Compute hill shade from slope and aspect layers (both in radians). Slope and aspect can be computed with function terrain
.
A hill shade layer is often used as a backdrop on top of which another, semi-transparent, layer is drawn.
hillShade(slope, aspect, angle=45, direction=0, filename='', normalize=FALSE, ...)
hillShade(slope, aspect, angle=45, direction=0, filename='', normalize=FALSE, ...)
slope |
RasterLayer object with slope values (in radians) |
aspect |
RasterLayer object with aspect values (in radians) |
angle |
The the elevation angle of the light source (sun), in degrees |
direction |
The direction (azimuth) angle of the light source (sun), in degrees |
filename |
Character. Optional filename |
normalize |
Logical. If |
... |
Standard additional arguments for writing RasterLayer files |
Andrew Bevan, Robert J. Hijmans
Horn, B.K.P., 1981. Hill shading and the reflectance map. Proceedings of the IEEE 69(1):14-47
Create a histogram of the values of a RasterLayer. For large datasets a sample is used.
## S4 method for signature 'Raster' hist(x, layer, maxpixels=100000, plot=TRUE, main, ...)
## S4 method for signature 'Raster' hist(x, layer, maxpixels=100000, plot=TRUE, main, ...)
x |
Raster* object |
layer |
integer (or character) to indicate layer number (or name). Can be used to subset the layers to plot in a multilayer Raster* object |
maxpixels |
integer. To regularly subsample very large objects |
plot |
logical. Plot the histogram or only return the histogram values |
main |
character. Main title(s) for the plot. Default is the value of |
... |
Additional arguments. See under Methods and at |
This function is principally used for the side-effect of plotting a histogram, but it also returns an S3 object of class 'histogram' (invisibly if plot=TRUE
).
r1 <- raster(nrows=50, ncols=50) r1 <- setValues(r1, runif(ncell(r1))) r2 <- setValues(r1, runif(ncell(r1))) rs <- r1 + r2 rp <- r1 * r2 par(mfrow=c(2,2)) plot(rs, main='sum') plot(rp, main='product') hist(rs) a = hist(rp) a
r1 <- raster(nrows=50, ncols=50) r1 <- setValues(r1, runif(ncell(r1))) r2 <- setValues(r1, runif(ncell(r1))) rs <- r1 + r2 rp <- r1 * r2 par(mfrow=c(2,2)) plot(rs, main='sum') plot(rp, main='product') hist(rs) a = hist(rp) a
Create an "image" type plot of a RasterLayer. This is an implementation of a generic function in the graphics package. In most cases the
plot
function would be preferable because it produces a legend (and has some additional options).
image(x, ...) ## S4 method for signature 'RasterLayer' image(x, maxpixels=500000, useRaster=TRUE, ...) ## S4 method for signature 'RasterStackBrick' image(x, y=1, maxpixels=100000, useRaster=TRUE, main, ...)
image(x, ...) ## S4 method for signature 'RasterLayer' image(x, maxpixels=500000, useRaster=TRUE, ...) ## S4 method for signature 'RasterStackBrick' image(x, y=1, maxpixels=100000, useRaster=TRUE, main, ...)
x |
Raster* object |
maxpixels |
integer > 0. Maximum number of cells to use for the plot. If |
useRaster |
If |
main |
character. Main plot title |
... |
Any argument that can be passed to |
y |
If |
raster uses rasterImage
from the graphics package. For unknown reasons this does not work on Windows Server and on a few versions of Windows XP. On that system you may need to use argument useRaster=FALSE
to get a plot.
r <- raster(system.file("external/test.grd", package="raster")) image(r)
r <- raster(system.file("external/test.grd", package="raster")) image(r)
This function reads '.ini'
files. These are text file databases that are organized in [sections] containing pairs of "name = value".
readIniFile(filename, token='=', commenttoken=';', aslist=FALSE, case)
readIniFile(filename, token='=', commenttoken=';', aslist=FALSE, case)
filename |
Character. Filename of the .ini file |
token |
Character. The character that separates the "name" (variable name) from the "value" |
commenttoken |
Character. This token and everything that follows on the same line is considered a 'comment' that is not for machine consumption and is ignored in processing |
aslist |
Logical. Should the values be returned as a list |
case |
Optional. Function that operates on the text, such as |
This function allows for using inistrings that have "=" as part of a value (but the token cannot be part of the 'name' of a variable!). Sections can be missing.
A n*3 matrix of characters with columns: section, name, value; or a list if aslist=TRUE
.
Create a new RasterLayer with values reflecting a cell property: 'x', 'y', 'col', 'row', or 'cell'. Alternatively, a function can be used. In that case, cell values are initialized without reference to pre-existing values. E.g., initialize with a random number (fun=runif
). While there are more direct ways of achieving this for small objects (see examples) for which a vector with all values can be created in memory, the init
function will also work for Raster* objects with many cells.
## S4 method for signature 'Raster' init(x, fun, filename="", ...)
## S4 method for signature 'Raster' init(x, fun, filename="", ...)
x |
Raster* object |
fun |
function to be applied. This must be a function that can take the number of cells as a single argument to return a vector of values with a length equal to the number of cells, such as |
filename |
character. Optional output filename |
... |
Additional arguments as for |
RasterLayer
For backwards compatibility, the character values valid for fun
can also be passed as named argument v
r <- raster(ncols=36, nrows=18) x <- init(r, fun='cell') y <- init(r, fun=runif) # there are different ways to set all values to 1 # for large rasters: # set1f <- function(x){rep(1, x)} # z1 <- init(r, fun=set1f, filename=rasterTmpFile(), overwrite=TRUE) # This is equivalent to (but not memory safe): z2 <- setValues(r, rep(1, ncell(r))) # or values(r) <- rep(1, ncell(r)) # or values(r) <- 1
r <- raster(ncols=36, nrows=18) x <- init(r, fun='cell') y <- init(r, fun=runif) # there are different ways to set all values to 1 # for large rasters: # set1f <- function(x){rep(1, x)} # z1 <- init(r, fun=set1f, filename=rasterTmpFile(), overwrite=TRUE) # This is equivalent to (but not memory safe): z2 <- setValues(r, rep(1, ncell(r))) # or values(r) <- rep(1, ncell(r)) # or values(r) <- 1
Make a RasterLayer with interpolated values using a fitted model object of classes such as 'gstat' (gstat package) or 'Krige' (fields package). That is, these are models that have location ('x' and 'y', or 'longitude' and 'latitude') as independent variables. If x and y are the only independent variables provide an empty (no associated data in memory or on file) RasterLayer for which you want predictions. If there are more spatial predictor variables provide these as a Raster* object in the first argument of the function. If you do not have x and y locations as implicit predictors in your model you should use predict
instead.
## S4 method for signature 'Raster' interpolate(object, model, filename="", fun=predict, xyOnly=TRUE, xyNames=c('x', 'y'), ext=NULL, const=NULL, index=1, na.rm=TRUE, debug.level=1, ...)
## S4 method for signature 'Raster' interpolate(object, model, filename="", fun=predict, xyOnly=TRUE, xyNames=c('x', 'y'), ext=NULL, const=NULL, index=1, na.rm=TRUE, debug.level=1, ...)
object |
Raster* object |
model |
model object |
filename |
character. Output filename (optional) |
fun |
function. Default value is 'predict', but can be replaced with e.g. 'predict.se' (depending on the class of the model object) |
xyOnly |
logical. If |
xyNames |
character. variable names that the model uses for the spatial coordinates. E.g., |
ext |
Extent object to limit the prediction to a sub-region of |
const |
data.frame. Can be used to add a constant for which there is no Raster object for model predictions. This is particulary useful if the constant is a character-like factor value |
index |
integer. To select the column if 'predict.model' returns a matrix with multiple columns |
na.rm |
logical. Remove cells with NA values in the predictors before solving the model (and return |
debug.level |
for gstat models only. See ? |
... |
additional arguments passed to the predict.'model' function |
Raster* object
## Thin plate spline interpolation with x and y only # some example data r <- raster(system.file("external/test.grd", package="raster")) ra <- aggregate(r, 10) xy <- data.frame(xyFromCell(ra, 1:ncell(ra))) v <- getValues(ra) # remove NAs i <- !is.na(v) xy <- xy[i,] v <- v[i] #### Thin plate spline model library(fields) tps <- Tps(xy, v) p <- raster(r) # use model to predict values at all locations p <- interpolate(p, tps) p <- mask(p, r) plot(p) ## change the fun from predict to fields::predictSE to get the TPS standard error se <- interpolate(p, tps, fun=predictSE) se <- mask(se, r) plot(se) ## another variable; let's call it elevation elevation <- (init(r, 'x') * init(r, 'y')) / 100000000 names(elevation) <- 'elev' z <- extract(elevation, xy) # add as another independent variable xyz <- cbind(xy, z) tps2 <- Tps(xyz, v) p2 <- interpolate(elevation, tps2, xyOnly=FALSE) # as a linear coveriate tps3 <- Tps(xy, v, Z=z) # Z is a separate argument in Krig.predict, so we need a new function # Internally (in interpolate) a matrix is formed of x, y, and elev (Z) pfun <- function(model, x, ...) { predict(model, x[,1:2], Z=x[,3], ...) } p3 <- interpolate(elevation, tps3, xyOnly=FALSE, fun=pfun) #### gstat examples library(gstat) data(meuse) ## inverse distance weighted (IDW) r <- raster(system.file("external/test.grd", package="raster")) data(meuse) mg <- gstat(id = "zinc", formula = zinc~1, locations = ~x+y, data=meuse, nmax=7, set=list(idp = .5)) z <- interpolate(r, mg) z <- mask(z, r) ## kriging coordinates(meuse) <- ~x+y crs(meuse) <- crs(r) ## ordinary kriging v <- variogram(log(zinc)~1, meuse) m <- fit.variogram(v, vgm(1, "Sph", 300, 1)) gOK <- gstat(NULL, "log.zinc", log(zinc)~1, meuse, model=m) OK <- interpolate(r, gOK) # examples below provided by Maurizio Marchi ## universial kriging vu <- variogram(log(zinc)~elev, meuse) mu <- fit.variogram(vu, vgm(1, "Sph", 300, 1)) gUK <- gstat(NULL, "log.zinc", log(zinc)~elev, meuse, model=mu) names(r) <- 'elev' UK <- interpolate(r, gUK, xyOnly=FALSE) ## co-kriging gCoK <- gstat(NULL, 'log.zinc', log(zinc)~1, meuse) gCoK <- gstat(gCoK, 'elev', elev~1, meuse) gCoK <- gstat(gCoK, 'cadmium', cadmium~1, meuse) gCoK <- gstat(gCoK, 'copper', copper~1, meuse) coV <- variogram(gCoK) plot(coV, type='b', main='Co-variogram') coV.fit <- fit.lmc(coV, gCoK, vgm(model='Sph', range=1000)) coV.fit plot(coV, coV.fit, main='Fitted Co-variogram') coK <- interpolate(r, coV.fit) plot(coK)
## Thin plate spline interpolation with x and y only # some example data r <- raster(system.file("external/test.grd", package="raster")) ra <- aggregate(r, 10) xy <- data.frame(xyFromCell(ra, 1:ncell(ra))) v <- getValues(ra) # remove NAs i <- !is.na(v) xy <- xy[i,] v <- v[i] #### Thin plate spline model library(fields) tps <- Tps(xy, v) p <- raster(r) # use model to predict values at all locations p <- interpolate(p, tps) p <- mask(p, r) plot(p) ## change the fun from predict to fields::predictSE to get the TPS standard error se <- interpolate(p, tps, fun=predictSE) se <- mask(se, r) plot(se) ## another variable; let's call it elevation elevation <- (init(r, 'x') * init(r, 'y')) / 100000000 names(elevation) <- 'elev' z <- extract(elevation, xy) # add as another independent variable xyz <- cbind(xy, z) tps2 <- Tps(xyz, v) p2 <- interpolate(elevation, tps2, xyOnly=FALSE) # as a linear coveriate tps3 <- Tps(xy, v, Z=z) # Z is a separate argument in Krig.predict, so we need a new function # Internally (in interpolate) a matrix is formed of x, y, and elev (Z) pfun <- function(model, x, ...) { predict(model, x[,1:2], Z=x[,3], ...) } p3 <- interpolate(elevation, tps3, xyOnly=FALSE, fun=pfun) #### gstat examples library(gstat) data(meuse) ## inverse distance weighted (IDW) r <- raster(system.file("external/test.grd", package="raster")) data(meuse) mg <- gstat(id = "zinc", formula = zinc~1, locations = ~x+y, data=meuse, nmax=7, set=list(idp = .5)) z <- interpolate(r, mg) z <- mask(z, r) ## kriging coordinates(meuse) <- ~x+y crs(meuse) <- crs(r) ## ordinary kriging v <- variogram(log(zinc)~1, meuse) m <- fit.variogram(v, vgm(1, "Sph", 300, 1)) gOK <- gstat(NULL, "log.zinc", log(zinc)~1, meuse, model=m) OK <- interpolate(r, gOK) # examples below provided by Maurizio Marchi ## universial kriging vu <- variogram(log(zinc)~elev, meuse) mu <- fit.variogram(vu, vgm(1, "Sph", 300, 1)) gUK <- gstat(NULL, "log.zinc", log(zinc)~elev, meuse, model=mu) names(r) <- 'elev' UK <- interpolate(r, gUK, xyOnly=FALSE) ## co-kriging gCoK <- gstat(NULL, 'log.zinc', log(zinc)~1, meuse) gCoK <- gstat(gCoK, 'elev', elev~1, meuse) gCoK <- gstat(gCoK, 'cadmium', cadmium~1, meuse) gCoK <- gstat(gCoK, 'copper', copper~1, meuse) coV <- variogram(gCoK) plot(coV, type='b', main='Co-variogram') coV.fit <- fit.lmc(coV, gCoK, vgm(model='Sph', range=1000)) coV.fit plot(coV, coV.fit, main='Fitted Co-variogram') coK <- interpolate(r, coV.fit) plot(coK)
It depends on the classes of the x
and y
what is returned.
If x
is a Raster* object the extent of y
is used, irrespective of the class of y
, and a Raster* is returned. This is equivalent to crop
.
If x
is a Spatial* object, a new Spatial* object is returned. If x
or y
has a data.frame, these are also returned (after merging if necessary) as part of a Spatial*DataFrame.
Intersecting SpatialPoints* with SpatialPoints* uses the extent (bounding box) of y
to get the intersection. Intersecting of SpatialPoints* and SpatialLines* is not supported because of numerical inaccuracies with that. You can use buffer
, to create SpatialPoygons* from SpatialLines* and use that in intersect.
## S4 method for signature 'Extent,ANY' intersect(x, y) ## S4 method for signature 'Raster,ANY' intersect(x, y) ## S4 method for signature 'SpatialPoints,ANY' intersect(x, y) ## S4 method for signature 'SpatialPolygons,SpatialPolygons' intersect(x, y) ## S4 method for signature 'SpatialPolygons,SpatialLines' intersect(x, y) ## S4 method for signature 'SpatialPolygons,SpatialPoints' intersect(x, y) ## S4 method for signature 'SpatialLines,SpatialPolygons' intersect(x, y) ## S4 method for signature 'SpatialLines,SpatialLines' intersect(x, y)
## S4 method for signature 'Extent,ANY' intersect(x, y) ## S4 method for signature 'Raster,ANY' intersect(x, y) ## S4 method for signature 'SpatialPoints,ANY' intersect(x, y) ## S4 method for signature 'SpatialPolygons,SpatialPolygons' intersect(x, y) ## S4 method for signature 'SpatialPolygons,SpatialLines' intersect(x, y) ## S4 method for signature 'SpatialPolygons,SpatialPoints' intersect(x, y) ## S4 method for signature 'SpatialLines,SpatialPolygons' intersect(x, y) ## S4 method for signature 'SpatialLines,SpatialLines' intersect(x, y)
x |
Extent, Raster*, SpatialPolygons*, SpatialLines* or SpatialPoints* object |
y |
same as for |
if x
is an Extent object: Extent
if x
is a Raster* object: Raster*
if x
is a SpatialPoints* object: SpatialPoints*
if x
is a SpatialPolygons* object: SpatialPolygons*
if x
is a SpatialLines* object and if y
is a SpatialLines* object: SpatialPoints*
if x
is a SpatialLines* object and if y
is a SpatialPolygons* object: SpatialLines*
e1 <- extent(-10, 10, -20, 20) e2 <- extent(0, 20, -40, 5) intersect(e1, e2) #SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') projection(b) <- projection(p) i <- intersect(p, b) plot(p) plot(b, add=TRUE, col='red') plot(i, add=TRUE, col='blue', lwd=2)
e1 <- extent(-10, 10, -20, 20) e2 <- extent(0, 20, -40, 5) intersect(e1, e2) #SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') projection(b) <- projection(p) i <- intersect(p, b) plot(p) plot(b, add=TRUE, col='red') plot(i, add=TRUE, col='blue', lwd=2)
Test whether a Raster* or other object has a longitude/latitude coordinate reference system (CRS) by inspecting the PROJ.4 coordinate reference system description. couldBeLonLat
also returns TRUE
if the CRS is NA
but the x coordinates are within -365 and 365 and the y coordinates are within -90.1 and 90.1.
## S4 method for signature 'BasicRaster' isLonLat(x, ...) ## S4 method for signature 'Spatial' isLonLat(x, ...) ## S4 method for signature 'BasicRaster' couldBeLonLat(x, warnings=TRUE, ...) ## S4 method for signature 'Spatial' couldBeLonLat(x, warnings=TRUE, ...)
## S4 method for signature 'BasicRaster' isLonLat(x, ...) ## S4 method for signature 'Spatial' isLonLat(x, ...) ## S4 method for signature 'BasicRaster' couldBeLonLat(x, warnings=TRUE, ...) ## S4 method for signature 'Spatial' couldBeLonLat(x, warnings=TRUE, ...)
x |
Raster* or Spatial* object |
warnings |
logical. If |
... |
additional arguments. None implemented |
Logical
r <- raster() isLonLat(r) crs(r) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +ellps=WGS84" isLonLat(r)
r <- raster() isLonLat(r) crs(r) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +ellps=WGS84" isLonLat(r)
Export raster data to a KML file and an accompanying PNG image file. Multi-layer objects can be used to create an animation. The function attempts to combine these into a single (and hence more convenient) KMZ file (a zip file containing the KML and PNG files).
See package plotKML for more advanced functionality
## S4 method for signature 'RasterLayer' KML(x, filename, col=rev(terrain.colors(255)), colNA=NA, maxpixels=100000, blur=1, zip='', overwrite=FALSE, ...) ## S4 method for signature 'RasterStackBrick' KML(x, filename, time=NULL, col=rev(terrain.colors(255)), colNA=NA, maxpixels=100000, blur=1, zip='', overwrite=FALSE, ...) ## S4 method for signature 'Spatial' KML(x, filename, zip='', overwrite=FALSE, ...)
## S4 method for signature 'RasterLayer' KML(x, filename, col=rev(terrain.colors(255)), colNA=NA, maxpixels=100000, blur=1, zip='', overwrite=FALSE, ...) ## S4 method for signature 'RasterStackBrick' KML(x, filename, time=NULL, col=rev(terrain.colors(255)), colNA=NA, maxpixels=100000, blur=1, zip='', overwrite=FALSE, ...) ## S4 method for signature 'Spatial' KML(x, filename, zip='', overwrite=FALSE, ...)
x |
Raster* object |
filename |
output filename |
time |
character vector with time lables for multilayer objects. The length of this vector should be nlayers(x) to indicate "when" or nlayers(x)+1 to indicate "begin-end" |
col |
color scheme to be used (see image) |
colNA |
The color to use for the background (default is transparent) |
maxpixels |
maximum number of pixels. If ncell(raster) > maxpixels, sampleRegular is used to reduce the number of pixels |
blur |
Integer (default=1). Higher values help avoid blurring of isolated pixels (at the expense of a png file that is blur^2 times larger) |
zip |
If there is no zip program on your path (on windows), you can supply the full path to a zip.exe here, in order to make a KMZ file |
overwrite |
logical. If |
... |
If |
None. Used for the side-effect files written to disk.
This function was adapted for the raster package by Robert J. Hijmans, with ideas from Tony Fischbach, and based on functions in the maptools package by Duncan Golicher, David Forrest and Roger Bivand.
## Not run: # Meuse data from the sp package data(meuse.grid) b <- rasterFromXYZ(meuse.grid) projection(b) <- "+init=epsg:28992" # transform to longitude/latitude p <- projectRaster(b, crs="+proj=longlat +datum=WGS84", method='ngb') KML(p, file='meuse.kml') ## End(Not run)
## Not run: # Meuse data from the sp package data(meuse.grid) b <- rasterFromXYZ(meuse.grid) projection(b) <- "+init=epsg:28992" # transform to longitude/latitude p <- projectRaster(b, crs="+proj=longlat +datum=WGS84", method='ngb') KML(p, file='meuse.kml') ## End(Not run)
Create a RasterBrick with a Boolean layer for each class (value, or subset of the values) in a RasterLayer. For example, if the cell values of a RasterLayer indicate what vegetation type they are, this function will create a layer (presence/absence; dummy variable) for each of these classes. Classes and cell values are always truncated to integers.
You can supply a second spatially overlapping RasterLayer with larger cells (do not use smaller cells!). In this case the cell values are counts for each class. A similar result might be obtained more efficiently by using layerize with a single RasterLayer followed by aggregate(x, , sum)
.
## S4 method for signature 'RasterLayer,missing' layerize(x, classes=NULL, falseNA=FALSE, filename='', ...) ## S4 method for signature 'RasterLayer,RasterLayer' layerize(x, y, classes=NULL, filename='', ...)
## S4 method for signature 'RasterLayer,missing' layerize(x, classes=NULL, falseNA=FALSE, filename='', ...) ## S4 method for signature 'RasterLayer,RasterLayer' layerize(x, y, classes=NULL, filename='', ...)
x |
RasterLayer |
y |
RasterLayer or missing |
classes |
numeric. The values (classes) for which layers should be made. If |
falseNA |
logical. If |
filename |
character. Output filename (optional) |
... |
Additional arguments as for |
RasterBrick
r <- raster(nrow=20, ncol=20) values(r) <- c(rep(NA, 50), rep(1:5, 70)) b <- layerize(r) r2 <- raster(nrow=5, ncol=5) b2 <- layerize(r, r2)
r <- raster(nrow=20, ncol=20) values(r) <- c(rep(NA, 50), rep(1:5, 70)) b <- layerize(r) r2 <- raster(nrow=5, ncol=5) b2 <- layerize(r, r2)
Compute correlation and (weighted) covariance for multi-layer Raster objects. Like cellStats
this function returns a few values, not a Raster* object (see Summary-methods
for that).
layerStats(x, stat, w, asSample=TRUE, na.rm=FALSE, ...)
layerStats(x, stat, w, asSample=TRUE, na.rm=FALSE, ...)
x |
RasterStack or RasterBrick for which to compute a statistic |
stat |
Character. The statistic to compute: either 'cov' (covariance), 'weighted.cov' (weighted covariance), or 'pearson' (correlation coefficient) |
w |
RasterLayer with the weights (should have the same extent, resolution and number of layers as |
asSample |
Logical. If |
na.rm |
Logical. Should missing values be removed? |
... |
Additional arguments (none implemetned) |
List with two items: the correlation or (weighted) covariance matrix, and the (weighted) means.
Jonathan A. Greenberg & Robert Hijmans. Weighted covariance based on code by Mort Canty
For the weighted covariance:
Canty, M.J. and A.A. Nielsen, 2008. Automatic radiometric normalization of multitemporal satellite imagery with the iteratively re-weighted MAD transformation. Remote Sensing of Environment 112:1025-1036.
Nielsen, A.A., 2007. The regularized iteratively reweighted MAD method for change detection in multi- and hyperspectral data. IEEE Transactions on Image Processing 16(2):463-478.
cellStats
, cov.wt
, weighted.mean
b <- brick(system.file("external/rlogo.grd", package="raster")) layerStats(b, 'pearson') layerStats(b, 'cov') # weigh by column number w <- init(b, v='col') layerStats(b, 'weighted.cov', w=w)
b <- brick(system.file("external/rlogo.grd", package="raster")) layerStats(b, 'pearson') layerStats(b, 'cov') # weigh by column number w <- init(b, v='col') layerStats(b, 'weighted.cov', w=w)
Local functions for two RasterLayer objects (using a focal neighborhood)
## S4 method for signature 'RasterLayer,RasterLayer' localFun(x, y, ngb=5, fun, filename='', ...)
## S4 method for signature 'RasterLayer,RasterLayer' localFun(x, y, ngb=5, fun, filename='', ...)
x |
RasterLayer or RasterStack/RasterBrick |
y |
object of the same class as |
ngb |
integer. rectangular neighbourhood size. Either a single integer or a vector of two integers c(rows, cols), such as c(3,3) to have a 3 x 3 focal window |
fun |
function |
filename |
character. Output filename (optional) |
... |
additional arguments as for |
RasterLayer
The first two arguments that fun
needs to accept are vectors representing the local cells of RasterLayer x
and y
(each of length ngb * ngb
). It also must have an ellipsis (...
) argument
set.seed(0) b <- stack(system.file("external/rlogo.grd", package="raster")) x <- flip(b[[2]], 'y') + runif(ncell(b)) y <- b[[1]] + runif(ncell(b)) f <- localFun(x, y, fun=cor) ## Not run: # local regression: rfun <- function(x, y, ...) { m <- lm(y~x) # return R^2 summary(m)$r.squared } ff <- localFun(x, y, fun=rfun) plot(f, ff) ## End(Not run)
set.seed(0) b <- stack(system.file("external/rlogo.grd", package="raster")) x <- flip(b[[2]], 'y') + runif(ncell(b)) y <- b[[1]] + runif(ncell(b)) f <- localFun(x, y, fun=cor) ## Not run: # local regression: rfun <- function(x, y, ...) { m <- lm(y~x) # return R^2 summary(m)$r.squared } ff <- localFun(x, y, fun=rfun) plot(f, ff) ## End(Not run)
The following logical (boolean) operators are available for computations with RasterLayer objects:
&, |, and !
The following functions are available with a Raster* argument:
is.na
, is.nan
, is.finite
, is.infinite
A Raster object with logical (TRUE/FALSE
values)
These are convenient operators/functions that are most usful for relatively small RasterLayers for which all the values can be held in memory.
If the values of the output RasterLayer cannot be held in memory, they will be saved to a temporary file. In that case it could be more
efficient to use calc
instead.
r <- raster(ncols=10, nrows=10) values(r) <- runif(ncell(r)) * 10 r1 <- r < 3 | r > 6 r2 <- !r1 r3 <- r >= 3 & r <= 6 r4 <- r2 == r3 r[r>3] <- NA r5 <- is.na(r) r[1:5] r1[1:5] r2[1:5] r3[1:5]
r <- raster(ncols=10, nrows=10) values(r) <- runif(ncell(r)) * 10 r1 <- r < 3 | r > 6 r2 <- !r1 r3 <- r >= 3 & r <= 6 r4 <- r2 == r3 r[r>3] <- NA r5 <- is.na(r) r[1:5] r1[1:5] r2[1:5] r3[1:5]
Create a new Raster* object that has the same values as x
, except for the cells that are NA
(or other maskvalue
) in a 'mask'. These cells become NA
(or other updatevalue
). The mask can be either another Raster* object of the same extent and resolution, or a Spatial* object (e.g. SpatialPolygons) in which case all cells that are not covered by the Spatial object are set to updatevalue
. You can use inverse=TRUE
to set the cells that are not NA
(or other maskvalue
) in the mask, or not covered by the Spatial* object, to NA
(or other updatvalue
).
## S4 method for signature 'RasterLayer,RasterLayer' mask(x, mask, filename="", inverse=FALSE, maskvalue=NA, updatevalue=NA, updateNA=FALSE, ...) ## S4 method for signature 'RasterStackBrick,RasterLayer' mask(x, mask, filename="", inverse=FALSE, maskvalue=NA, updatevalue=NA, updateNA=FALSE, ...) ## S4 method for signature 'RasterLayer,RasterStackBrick' mask(x, mask, filename="", inverse=FALSE, maskvalue=NA, updatevalue=NA, updateNA=FALSE, ...) ## S4 method for signature 'RasterStackBrick,RasterStackBrick' mask(x, mask, filename="", inverse=FALSE, maskvalue=NA, updatevalue=NA, updateNA=FALSE, ...) ## S4 method for signature 'Raster,Spatial' mask(x, mask, filename="", inverse=FALSE, updatevalue=NA, updateNA=FALSE, ...)
## S4 method for signature 'RasterLayer,RasterLayer' mask(x, mask, filename="", inverse=FALSE, maskvalue=NA, updatevalue=NA, updateNA=FALSE, ...) ## S4 method for signature 'RasterStackBrick,RasterLayer' mask(x, mask, filename="", inverse=FALSE, maskvalue=NA, updatevalue=NA, updateNA=FALSE, ...) ## S4 method for signature 'RasterLayer,RasterStackBrick' mask(x, mask, filename="", inverse=FALSE, maskvalue=NA, updatevalue=NA, updateNA=FALSE, ...) ## S4 method for signature 'RasterStackBrick,RasterStackBrick' mask(x, mask, filename="", inverse=FALSE, maskvalue=NA, updatevalue=NA, updateNA=FALSE, ...) ## S4 method for signature 'Raster,Spatial' mask(x, mask, filename="", inverse=FALSE, updatevalue=NA, updateNA=FALSE, ...)
x |
Raster* object |
mask |
Raster* object or a Spatial* object |
filename |
character. Optional output filename |
inverse |
logical. If |
maskvalue |
numeric. The value in |
updatevalue |
numeric. The value that cells of |
updateNA |
logical. If |
... |
additional arguments as in |
Raster* object
r <- raster(ncol=10, nrow=10) m <- raster(ncol=10, nrow=10) values(r) <- runif(ncell(r)) * 10 values(m) <- runif(ncell(r)) m[m < 0.5] <- NA mr <- mask(r, m) m2 <- m > .7 mr2 <- mask(r, m2, maskvalue=TRUE)
r <- raster(ncol=10, nrow=10) m <- raster(ncol=10, nrow=10) values(r) <- runif(ncell(r)) * 10 values(m) <- runif(ncell(r)) m[m < 0.5] <- NA mr <- mask(r, m) m2 <- m > .7 mr2 <- mask(r, m2, maskvalue=TRUE)
match
returns a Raster* object with the position of the matched values. The cell values are the index of the table argument.
%in%
returns a logical Raster* object indicating if the cells values were matched or not.
match(x, table, nomatch = NA_integer_, incomparables = NULL) x %in% table
match(x, table, nomatch = NA_integer_, incomparables = NULL) x %in% table
x |
Raster* object |
table |
vector of the values to be matched against |
nomatch |
the value to be returned in the case when no match is found. Note that it is coerced to integer |
incomparables |
a vector of values that cannot be matched. Any value in x matching a value in this vector is assigned the nomatch value. For historical reasons, FALSE is equivalent to NULL |
Raster* object
r <- raster(nrow=10, ncol=10) values(r) <- 1:100 m <- match(r, c(5:10, 50:55)) n <- r %in% c(5:10, 50:55)
r <- raster(nrow=10, ncol=10) values(r) <- 1:100 m <- match(r, c(5:10, 50:55)) n <- r %in% c(5:10, 50:55)
Generic mathematical functions that can be used with a Raster* object as argument:
"abs", "sign", "sqrt", "ceiling", "floor", "trunc", "cummax", "cummin",
"cumprod", "cumsum", "log", "log10", "log2", "log1p", "acos", "acosh", "asin",
"asinh", "atan", "atanh", "exp", "expm1", "cos", "cosh", "sin", "sinh", "tan", "tanh"
.
You can use the, somewhat more flexible, function calc
instead of the Math-methods.
Arith-methods
, calc
, overlay
, atan2
r1 <- raster(nrow=10, ncol=10) r1 <- setValues(r1, runif(ncell(r1)) * 10) r2 <- sqrt(r1) s <- stack(r1, r2) - 5 b <- abs(s)
r1 <- raster(nrow=10, ncol=10) r1 <- setValues(r1, runif(ncell(r1)) * 10) r2 <- sqrt(r1) s <- stack(r1, r2) - 5 b <- abs(s)
Merge Raster* objects to form a new Raster object with a larger spatial extent. If objects overlap, the values get priority in the same order as the arguments, but NA
values are ignored (except when overlap=FALSE
). See subs
to merge a Raster*
object and a data.frame
.
## S4 method for signature 'Raster,Raster' merge(x, y, ..., tolerance=0.05, filename="", overlap=TRUE, ext=NULL) ## S4 method for signature 'RasterStackBrick,missing' merge(x, ..., tolerance=0.05, filename="", ext=NULL) ## S4 method for signature 'Extent,ANY' merge(x, y, ...)
## S4 method for signature 'Raster,Raster' merge(x, y, ..., tolerance=0.05, filename="", overlap=TRUE, ext=NULL) ## S4 method for signature 'RasterStackBrick,missing' merge(x, ..., tolerance=0.05, filename="", ext=NULL) ## S4 method for signature 'Extent,ANY' merge(x, y, ...)
x |
Raster* or Extent object |
y |
Raster* if |
... |
additional Raster or Extent objects (and/or arguments for writing files as in |
tolerance |
numeric. permissible difference in origin (relative to the cell resolution). See |
filename |
character. Output filename (optional) |
overlap |
logical. If |
ext |
Extent object (optional) to limit the output to that extent |
The Raster objects must have the same origin and resolution. In areas where the Raster objects overlap, the values of the Raster object that is first in the sequence of arguments will be retained. If you would rather use the average of cell values, or do another computation, you can use mosaic
instead of merge.
RasterLayer or RasterBrick
r1 <- raster(xmx=-150, ymn=60, ncols=30, nrows=30) values(r1) <- 1:ncell(r1) r2 <- raster(xmn=-100, xmx=-50, ymx=50, ymn=30) res(r2) <- c(xres(r1), yres(r1)) values(r2) <- 1:ncell(r2) rm <- merge(r1, r2) # if you have many RasterLayer objects in a list # you can use do.call: x <- list(r1, r2) # add arguments such as filename # x$filename <- 'test.tif' m <- do.call(merge, x)
r1 <- raster(xmx=-150, ymn=60, ncols=30, nrows=30) values(r1) <- 1:ncell(r1) r2 <- raster(xmn=-100, xmx=-50, ymx=50, ymn=30) res(r2) <- c(xres(r1), yres(r1)) values(r2) <- 1:ncell(r2) rm <- merge(r1, r2) # if you have many RasterLayer objects in a list # you can use do.call: x <- list(r1, r2) # add arguments such as filename # x$filename <- 'test.tif' m <- do.call(merge, x)
Get or set a metadata to a Raster object
## S4 method for signature 'Raster' metadata(x) metadata(x) <- value
## S4 method for signature 'Raster' metadata(x) metadata(x) <- value
x |
Raster* object |
value |
list with named elements. Each element may be another list of named elements (but these nested lists are not allowed to be lists themselves) |
Raster* object or list
The metadata can contain single values or vectors of basic data types (character, integer, numeric) and Date. Some other types may also be supported. You cannot use a matrix or data.frame as a meta-data element.
r <- raster(nc=10, nr=10) values(r) <- 1:ncell(r) m <- list(wave=list(a=1, b=2, c=c('cool', 'important')), that=list(red='44', blue=1:5, days=as.Date(c('2014-1-15','2014-2-15'))), this='888 miles from here', today=NA) metadata(r) <- m ## Not run: x <- writeRaster(r, rasterTmpFile(), overwrite=TRUE) metax <- metadata(x) identical(metax, m) # nested too deep badmeta1 <- list(wave=list(a=1, b=2, c='x'), that=list(red='4', blue=list(bad=5))) metadata(r) <- badmeta1 # missing names badmeta2 <- list(wave=list(1, 2, c='x'), that=list(red='44', blue=14), this='8m') metadata(r) <- badmeta2 # matrix not allowed badmeta3 <- list(wave=list(a=1, b=matrix(1:4, ncol=2), c='x'), that=list(red='4')) metadata(r) <- badmeta3 ## End(Not run)
r <- raster(nc=10, nr=10) values(r) <- 1:ncell(r) m <- list(wave=list(a=1, b=2, c=c('cool', 'important')), that=list(red='44', blue=1:5, days=as.Date(c('2014-1-15','2014-2-15'))), this='888 miles from here', today=NA) metadata(r) <- m ## Not run: x <- writeRaster(r, rasterTmpFile(), overwrite=TRUE) metax <- metadata(x) identical(metax, m) # nested too deep badmeta1 <- list(wave=list(a=1, b=2, c='x'), that=list(red='4', blue=list(bad=5))) metadata(r) <- badmeta1 # missing names badmeta2 <- list(wave=list(1, 2, c='x'), that=list(red='44', blue=14), this='8m') metadata(r) <- badmeta2 # matrix not allowed badmeta3 <- list(wave=list(a=1, b=matrix(1:4, ncol=2), c='x'), that=list(red='4')) metadata(r) <- badmeta3 ## End(Not run)
Compute the mode for a vector of numbers, or across raster layers. The mode, or modal value, is the most frequent value in a set of values.
## S4 method for signature 'ANY' modal(x, ..., ties='random', na.rm=FALSE, freq=FALSE) ## S4 method for signature 'Raster' modal(x, ..., ties='random', na.rm=FALSE, freq=FALSE)
## S4 method for signature 'ANY' modal(x, ..., ties='random', na.rm=FALSE, freq=FALSE) ## S4 method for signature 'Raster' modal(x, ..., ties='random', na.rm=FALSE, freq=FALSE)
x |
vector of numbers (typically integers), characters, logicals, or factors, or a Raster* object |
... |
additional argument of the same type as |
ties |
character. Indicates how to treat ties. Either 'random', 'lowest', 'highest', 'first', or 'NA' |
na.rm |
logical. If |
freq |
return the frequency of the modal value, instead of the modal value |
vector or RasterLayer. The vector has length 1 and is of the same type as x
, except when x
is a factor and additional arguments (values) are supplied, in which case the values are coerced to characters and a character value is returned.
data <- c(0,1,2,3,3,3,3,4,4,4,5,5,6,7,7,8,9,NA) modal(data, na.rm=TRUE)
data <- c(0,1,2,3,3,3,3,4,4,4,5,5,6,7,7,8,9,NA) modal(data, na.rm=TRUE)
Mosaic Raster* objects to form a new object with a larger spatial extent. A function is used to compute cell values in areas where layers overlap (in contrast to the merge
function which uses the values of the 'upper' layer). All objects must have the same origin, resolution, and coordinate reference system.
## S4 method for signature 'Raster,Raster' mosaic(x, y, ..., fun, tolerance=0.05, filename="")
## S4 method for signature 'Raster,Raster' mosaic(x, y, ..., fun, tolerance=0.05, filename="")
x |
Raster* object |
y |
Raster* object |
... |
Additional Raster or Extent objects (and/or arguments for writing files as in |
fun |
Function. E.g. mean, min, or max. Must be a function that accepts a 'na.rm' argument |
tolerance |
Numeric. permissible difference in origin (relative to the cell resolution). See |
filename |
Character. Output filename (optional) |
The Raster objects must have the same origin and resolution.
RasterLayer or RasterBrick object.
r <- raster(ncol=100, nrow=100) r1 <- crop(r, extent(-10, 11, -10, 11)) r2 <- crop(r, extent(0, 20, 0, 20)) r3 <- crop(r, extent(9, 30, 9, 30)) values(r1) <- 1:ncell(r1) values(r2) <- 1:ncell(r2) values(r3) <- 1:ncell(r3) m1 <- mosaic(r1, r2, r3, fun=mean) s1 <- stack(r1, r1*2) s2 <- stack(r2, r2/2) s3 <- stack(r3, r3*4) m2 <- mosaic(s1, s2, s3, fun=min) # if you have a list of Raster objects, you can use do.call x <- list(r1, r2, r3) names(x)[1:2] <- c('x', 'y') x$fun <- mean x$na.rm <- TRUE y <- do.call(mosaic, x)
r <- raster(ncol=100, nrow=100) r1 <- crop(r, extent(-10, 11, -10, 11)) r2 <- crop(r, extent(0, 20, 0, 20)) r3 <- crop(r, extent(9, 30, 9, 30)) values(r1) <- 1:ncell(r1) values(r2) <- 1:ncell(r2) values(r3) <- 1:ncell(r3) m1 <- mosaic(r1, r2, r3, fun=mean) s1 <- stack(r1, r1*2) s2 <- stack(r2, r2/2) s3 <- stack(r3, r3*4) m2 <- mosaic(s1, s2, s3, fun=min) # if you have a list of Raster objects, you can use do.call x <- list(r1, r2, r3) names(x)[1:2] <- c('x', 'y') x$fun <- mean x$na.rm <- TRUE y <- do.call(mosaic, x)
Helper function to compute 'moving' functions, such as the 'moving average'
movingFun(x, n, fun=mean, type='around', circular=FALSE, na.rm=FALSE)
movingFun(x, n, fun=mean, type='around', circular=FALSE, na.rm=FALSE)
x |
A vector of numbers |
n |
Size of the 'window', i.e. the number of sequential elements to use in the function |
fun |
A function like mean, min, max, sum |
type |
Character. One of 'around', 'to', or 'from'. The choice indicates which values should be used in the computation. The focal element is always used. If |
circular |
Logical. If |
na.rm |
Logical. If |
Numeric
Robert J. Hijmans, inspired by Diethelm Wuertz' rollFun function in the fTrading package
movingFun(1:12, 3, mean) movingFun(1:12, 3, mean, 'to') movingFun(1:12, 3, mean, 'from') movingFun(1:12, 3, mean, circular=TRUE) v <- c(0,1,2,3,3,3,3,4,4,4,5,5,6,7,7,8,9,NA) movingFun(v, n=5) movingFun(v, n=5, na.rm=TRUE)
movingFun(1:12, 3, mean) movingFun(1:12, 3, mean, 'to') movingFun(1:12, 3, mean, 'from') movingFun(1:12, 3, mean, circular=TRUE) v <- c(0,1,2,3,3,3,3,4,4,4,5,5,6,7,7,8,9,NA) movingFun(v, n=5) movingFun(v, n=5, na.rm=TRUE)
Get or set the names of the layers of a Raster* object
## S4 method for signature 'Raster' names(x) ## S4 replacement method for signature 'Raster' names(x)<-value ## S4 method for signature 'Raster' labels(object)
## S4 method for signature 'Raster' names(x) ## S4 replacement method for signature 'Raster' names(x)<-value ## S4 method for signature 'Raster' labels(object)
x |
Raster* object |
object |
Raster* object |
value |
character (vector) |
Character
r <- raster(ncols=5, nrows=5) values(r) <- 1:ncell(r) s <- stack(r, r, r) nlayers(s) names(s) names(s) <- c('a', 'b', 'c') names(s)[2] <- 'hello world' names(s) s labels(s)
r <- raster(ncols=5, nrows=5) values(r) <- 1:ncell(r) s <- stack(r, r, r) nlayers(s) names(s) names(s) <- c('a', 'b', 'c') names(s)[2] <- 'hello world' names(s) s labels(s)
NAvalue returns the value that is used to write NA values to disk (in 'raster' type files). If you set the NA value of a Raster* object, this value will be interpreted as NA when reading the values from a file. Values already in memory will not be affected.
If the NA value is smaller than zero, all values smaller or equal to that number will be set to NA.
NAvalue(x) <- value NAvalue(x)
NAvalue(x) <- value NAvalue(x)
x |
A |
value |
the value to be interpreted as NA; set this before reading the values from the file. Integer values are matched exactly; for decimal values files any value <= the value will be interpreted as NA |
Returns or set the NA value used for storage on disk.
r1 <- raster(system.file("external/rlogo.grd", package="raster")) r2 <- r1 NAvalue(r2) NAvalue(r2) <- 255 #plot(r1) #x11() #plot(r2)
r1 <- raster(system.file("external/rlogo.grd", package="raster")) r2 <- r1 NAvalue(r2) NAvalue(r2) <- 255 #plot(r1) #x11() #plot(r2)
Get the number of rows, columns, or cells of a Raster* object.
ncol(x) nrow(x) ncell(x) ncol(x, ...) <- value nrow(x, ...) <- value
ncol(x) nrow(x) ncell(x) ncol(x, ...) <- value nrow(x, ...) <- value
x |
a Raster object |
value |
row or column number (integer > 0) |
... |
additional arguments. None implemented |
Integer
r <- raster() ncell(r) ncol(r) nrow(r) dim(r) nrow(r) <- 18 ncol(r) <- 36 # equivalent to dim(r) <- c(18, 36)
r <- raster() ncell(r) ncol(r) nrow(r) dim(r) nrow(r) <- 18 ncol(r) <- 36 # equivalent to dim(r) <- c(18, 36)
Get the number of layers in a Raster* object, typically used with a (multilayer) RasterStack or RasterBrick object
nlayers(x)
nlayers(x)
x |
Raster* object |
integer
r <- raster(ncols=10, nrows=10) values(r) <- 1:ncell(r) s <- stack(r, r, r) nlayers(s) s <- stack(s,s) nlayers(s) s <- dropLayer(s, 2:3) nlayers(s)
r <- raster(ncols=10, nrows=10) values(r) <- 1:ncell(r) s <- stack(r, r, r) nlayers(s) s <- stack(s,s) nlayers(s) s <- dropLayer(s, 2:3) nlayers(s)
Set, inspect, reset, save a number of global options used by the raster package.
Most of these options are used when writing files to disk. They can be ignored by specific functions if the corresponding argument is provided as an argument to these functions.
The default location is returned by rasterTmpDir
. It is the same as that of the R temp directory but you can change it (for the current session) with rasterOptions(tmpdir="path")
.
To permanently set any of these options, you can add them to <your R installation>/etc/Rprofile.site>
. For example, to change the default directory used to save temporary files, add a line like this: options(rasterTmpDir='c:/temp/')
to that file. All temporary raster files in that folder that are older than 24 hrs are deleted when the raster package is loaded.
Function tmpDir
returns the location of the temporary files
rasterOptions(format, overwrite, datatype, tmpdir, tmptime, progress, timer, chunksize, minmemory, maxmemory, memfrac, todisk, setfileext, tolerance, standardnames, depracatedwarnings, addheader, default=FALSE) tmpDir(create=TRUE)
rasterOptions(format, overwrite, datatype, tmpdir, tmptime, progress, timer, chunksize, minmemory, maxmemory, memfrac, todisk, setfileext, tolerance, standardnames, depracatedwarnings, addheader, default=FALSE) tmpDir(create=TRUE)
format |
character. The default file format to use. See |
overwrite |
logical. The default value for overwriting existing files. If |
datatype |
character. The default data type to use. See dataType |
tmpdir |
character. The default location for writing temporary files; See |
tmptime |
number > 1. The number of hours after which a temporary file will be deleted. As files are deleted when loading the raster package, this option is only useful if you save this option so that it is loaded when starting a new session |
progress |
character. Valid values are "text", "window" and "" (the default in most functions, no progress bar) |
timer |
Logical. If |
chunksize |
integer. Maximum number of bytes to read/write in a single chunk while processing (chunk by chunk) disk based Raster* objects |
maxmemory |
numeric. Maximum number of bytes to read into memory. If a process is expected to require more than this value, |
minmemory |
numeric. Minimum number of bytes that are guaranteed to be fit into memory. If a process is expected to require more than this value, RAM available will be estimated. It cannot be set to a value smaller than 10000 |
memfrac |
numeric. Fraction of available RAM that may be used by a process |
todisk |
logical. For debugging only. Default is |
setfileext |
logical. Default is |
tolerance |
numeric. The tolerance used when comparing the origin and resolution of Raster* objects. Expressed as the fraction of a single cell. This should be a number between 0 and 0.5 |
standardnames |
logical. Default is |
depracatedwarnings |
logical. If |
addheader |
character. If not equal to |
default |
logical. If |
create |
logical. If |
list of the current options (invisibly). If no arguments are provided the options are printed.
## Not run: rasterOptions() rasterOptions(chunksize=2e+07) ## End(Not run)
## Not run: rasterOptions() rasterOptions(chunksize=2e+07) ## End(Not run)
Origin returns (or sets) the coordinates of the point of origin of a Raster* object. This is the point closest to (0, 0) that you could get if you moved towards that point in steps of the x and y resolution.
origin(x, ...) origin(x) <- value
origin(x, ...) origin(x) <- value
x |
Raster* object |
value |
numeric vector of length 1 or 2 |
... |
additional arguments. None implemented |
A vector of two numbers (x and y coordinates), or a changed origin for x
.
r <- raster(xmn=-0.5, xmx = 9.5, ncols=10) origin(r) r origin(r) <- 0 r
r <- raster(xmn=-0.5, xmx = 9.5, ncols=10) origin(r) r origin(r) <- 0 r
Create a new Raster* object, based on two or more Raster* objects. (You can also use a single object, but perhaps calc
is what you are looking for in that case).
You should supply a function fun
to set the way that the RasterLayers are combined. The number of arguments in the function must match the number of Raster objects (or take any number). For example, if you combine two RasterLayers you could use multiply: fun=function(x,y){return(x*y)}
percentage: fun=function(x,y){return(100 * x / y)}
. If you combine three layers you could use fun=function(x,y,z){return((x + y) * z)}
Note that the function must work for vectors (not only for single numbers). That is, it must return the same number of elements as its input vectors. Alternatively, you can also supply a function such as sum
, that takes n
arguments (as '...'
), and perhaps also has a na.rm
argument, like in sum(..., na.rm)
.
If a single mutli-layer object is provided, its layers are treated as individual RasterLayer objects if the argument unstack=TRUE
is used. If multiple objects are provided, they should have the same number of layers, or it should be possible to recycle them (e.g., 1, 3, and 9 layers, which would return a RasterBrick with 9 layers).
## S4 method for signature 'Raster,Raster' overlay(x, y, ..., fun, filename="", recycle=TRUE, forcefun=FALSE) ## S4 method for signature 'Raster,missing' overlay(x, y, ..., fun, filename="", unstack=TRUE, forcefun=FALSE)
## S4 method for signature 'Raster,Raster' overlay(x, y, ..., fun, filename="", recycle=TRUE, forcefun=FALSE) ## S4 method for signature 'Raster,missing' overlay(x, y, ..., fun, filename="", unstack=TRUE, forcefun=FALSE)
x |
Raster* object |
y |
Raster* object, or missing (only useful if |
... |
Additional Raster objects (and/or arguments for writing files as in |
fun |
Function to be applied. When using RasterLayer objects, the number of arguments of the function should match the number of Raster objects, or it should take any number of arguments. When using multi-layer objects the function should match the number of layers of the RasterStack/Brick object (unless unstack=FALSE) |
filename |
Character. Output filename (optional) |
recycle |
Logical. Should layers from Raster objects with fewer layers be recycled? |
unstack |
Logical. Should layers be unstacked before computation (i.e. does the |
forcefun |
Boolean. If |
Instead of the overlay function you can also use arithmetic functions such as *, /, +, -
with Raster objects (see examples). In that case you cannot specify an output filename. Moreover, the overlay function should be more efficient when using large data files that cannot be loaded into memory, as the use of the complex arithmetic functions might lead to the creation of many temporary files.
While you can supply functions such as sum
or mean
, it would be more direct to use the Raster* objects as arguments to those functions (e.g. sum(r1,r2,r3)
)
See rasterize
and extract
for "overlays" involving Raster* objects and polygons, lines, or points.
Raster* object
r <- raster(ncol=10, nrow=10) r1 <- init(r, fun=runif) r2 <- init(r, fun=runif) r3 <- overlay(r1, r2, fun=function(x,y){return(x+y)}) # long version for multiplication r4 <- overlay(r1, r2, fun=function(x,y){(x*y)} ) #use the individual layers of a RasterStack to get a RasterLayer s <- stack(r1, r2) r5 <- overlay(s, fun=function(x,y) x*y ) # equivalent to r5c <- calc(s, fun=function(x) x[1]*x[2] ) #Combine RasterStack and RasterLayer objects (s2 has four layers. # r1 (one layer) and s (two layers) are recycled) s2 <- stack(r1, r2, r3, r4) b <- overlay(r1, s, s2, fun=function(x,y,z){return(x*y*z)} ) # use a single RasterLayer (same as calc function) r6 <- overlay(r1, fun=sqrt) # multiplication with more than two layers # (make sure the number of RasterLayers matches the arguments of 'fun') r7 <- overlay(r1, r2, r3, r4, fun=function(a,b,c,d){return(a*b+c*d)} ) # equivalent function, efficient if values can be loaded in memory r8 <- r1 * r2 + r3 * r4 # Also works with multi-layer objects. s1 <- stack(r1, r2, r3) x <- overlay(s1, s1, fun=function(x,y)x+y+5) # in this case the first layer of the shorter object is recycled. # i.e., s2 is treated as stack(r1, r3, r1) s2 <- stack(r1, r3) y <- overlay(s1, s2, fun=sum)
r <- raster(ncol=10, nrow=10) r1 <- init(r, fun=runif) r2 <- init(r, fun=runif) r3 <- overlay(r1, r2, fun=function(x,y){return(x+y)}) # long version for multiplication r4 <- overlay(r1, r2, fun=function(x,y){(x*y)} ) #use the individual layers of a RasterStack to get a RasterLayer s <- stack(r1, r2) r5 <- overlay(s, fun=function(x,y) x*y ) # equivalent to r5c <- calc(s, fun=function(x) x[1]*x[2] ) #Combine RasterStack and RasterLayer objects (s2 has four layers. # r1 (one layer) and s (two layers) are recycled) s2 <- stack(r1, r2, r3, r4) b <- overlay(r1, s, s2, fun=function(x,y,z){return(x*y*z)} ) # use a single RasterLayer (same as calc function) r6 <- overlay(r1, fun=sqrt) # multiplication with more than two layers # (make sure the number of RasterLayers matches the arguments of 'fun') r7 <- overlay(r1, r2, r3, r4, fun=function(a,b,c,d){return(a*b+c*d)} ) # equivalent function, efficient if values can be loaded in memory r8 <- r1 * r2 + r3 * r4 # Also works with multi-layer objects. s1 <- stack(r1, r2, r3) x <- overlay(s1, s1, fun=function(x,y)x+y+5) # in this case the first layer of the shorter object is recycled. # i.e., s2 is treated as stack(r1, r3, r1) s2 <- stack(r1, r3) y <- overlay(s1, s2, fun=sum)
Pair plots of layers in a RasterStack or RasterBrick. This is a wrapper around graphics function pairs
.
## S4 method for signature 'RasterStackBrick' pairs(x, hist=TRUE, cor=TRUE, use="pairwise.complete.obs", maxpixels=100000, ...)
## S4 method for signature 'RasterStackBrick' pairs(x, hist=TRUE, cor=TRUE, use="pairwise.complete.obs", maxpixels=100000, ...)
x |
RasterBrick or RasterStack |
hist |
Logical. If TRUE a histogram of the values is shown on the diagonal |
cor |
Logical. If TRUE the correlation coefficient is shown in the upper panels |
use |
Argument passed to the |
maxpixels |
Integer. Number of pixels to sample from each layer of large Raster objects |
... |
Additional arguments (only |
r <- raster(system.file("external/test.grd", package="raster") ) s <- stack(r, 1/r, sqrt(r)) pairs(s) ## Not run: # to make indvidual histograms: hist(r) # or scatter plots: plot(r, 1/r) ## End(Not run)
r <- raster(system.file("external/test.grd", package="raster") ) s <- stack(r, 1/r, sqrt(r)) pairs(s) ## Not run: # to make indvidual histograms: hist(r) # or scatter plots: plot(r, 1/r) ## End(Not run)
Perspective plot of a RasterLayer. This is an implementation of a generic function in the graphics package.
## S4 method for signature 'RasterLayer' persp(x, maxpixels=1e+05, ext=NULL, ...) ## S4 method for signature 'RasterStackBrick' persp(x, y=1, maxpixels=10000, ext=NULL, ...)
## S4 method for signature 'RasterLayer' persp(x, maxpixels=1e+05, ext=NULL, ...) ## S4 method for signature 'RasterStackBrick' persp(x, y=1, maxpixels=10000, ext=NULL, ...)
x |
Raster* object |
y |
integer |
maxpixels |
integer > 0. Maximum number of cells to use for the plot. If |
ext |
Extent. Can be used to zoom in to a region (see also |
... |
Any argument that can be passed to |
r <- raster(system.file("external/test.grd", package="raster")) persp(r)
r <- raster(system.file("external/test.grd", package="raster")) persp(r)
Plot (that is, make a map of) the values of a Raster* object, or make a scatterplot of their values.
Points, lines, and polygons can be drawn on top of a map using plot(..., add=TRUE)
, or with functions like points, lines, polygons
See the rasterVis
package for more advanced (trellis/lattice) plotting of Raster* objects.
## S4 method for signature 'Raster,ANY' plot(x, y, maxpixels=500000, col, alpha=NULL, colNA=NA, add=FALSE, ext=NULL, useRaster=TRUE, interpolate=FALSE, addfun=NULL, nc, nr, maxnl=16, main, npretty=0, ...) ## S4 method for signature 'Raster,Raster' plot(x, y, maxpixels=100000, cex, xlab, ylab, nc, nr, maxnl=16, main, add=FALSE, gridded=FALSE, ncol=25, nrow=25, ...)
## S4 method for signature 'Raster,ANY' plot(x, y, maxpixels=500000, col, alpha=NULL, colNA=NA, add=FALSE, ext=NULL, useRaster=TRUE, interpolate=FALSE, addfun=NULL, nc, nr, maxnl=16, main, npretty=0, ...) ## S4 method for signature 'Raster,Raster' plot(x, y, maxpixels=100000, cex, xlab, ylab, nc, nr, maxnl=16, main, add=FALSE, gridded=FALSE, ncol=25, nrow=25, ...)
x |
Raster* object |
y |
If |
maxpixels |
integer > 0. Maximum number of cells to use for the plot. If |
col |
A color palette, i.e. a vector of n contiguous colors generated by functions like rainbow, heat.colors, topo.colors, bpy.colors or one or your own making, perhaps using |
alpha |
Number between 0 and 1 to set transparency. 0 is entirely transparent, 1 is not transparent (NULL is equivalent to 1) |
colNA |
The color to use for the background (default is transparent) |
add |
Logical. Add to current plot? |
ext |
An extent object to zoom in a region (see also |
useRaster |
If |
interpolate |
Logical. Should the image be interpolated (smoothed)? Only used when |
addfun |
Function to add additional items such as points or polygons to the plot (map). Typically containing statements like "points(xy); plot(polygons, add=TRUE)". This is particularly useful to add something to each map when plotting a multi-layer Raster* object. |
npretty |
integer. Number of decimals for pretty lables on the axes |
... |
Graphical parameters. Any argument that can be passed to |
xlab |
Optional. x-axis label) |
ylab |
Optional. y-axis label) |
nc |
Optional. The number of columns to divide the plotting device in (when plotting multiple layers in a RasterLayer or RasterBrick object) |
nr |
Optional. The number of rows to divide the plotting device in (when plotting multiple layers in a RasterLayer or RasterBrick object) |
maxnl |
integer. Maximum number of layers to plot (for a multi-layer object) |
main |
character. Main plot title |
cex |
Symbol size for scatter plots |
gridded |
logical. If |
ncol |
integer. Number of columns for gridding |
nrow |
integer. Number of rows for gridding |
Most of the code for the plot function for a single Raster* object was taken from image.plot (fields package).
Raster objects with a color-table (e.g. a graphics file) are plotted according to that color table.
raster uses rasterImage
from the graphics package. For unknown reasons this does not work on Windows Server and on a few versions of Windows XP. On that system you may need to use argument useRaster=FALSE
to get a plot.
The rasterVis
package has lattice based methods for plotting Raster* objects (like spplot
)
red-green-blue plots (e.g. false color composites) can be made with plotRGB
barplot
, hist
, text
, persp
, contour
, pairs
# RasterLayer r <- raster(nrows=10, ncols=10) r <- setValues(r, 1:ncell(r)) plot(r) e <- extent(r) plot(e, add=TRUE, col='red', lwd=4) e <- e / 2 plot(e, add=TRUE, col='red') # Scatterplot of 2 RasterLayers r2 <- sqrt(r) plot(r, r2) plot(r, r2, gridded=TRUE) # Multi-layer object (RasterStack / Brick) s <- stack(r, r2, r/r) plot(s, 2) plot(s) # two objects, different range, one scale: values(r) <- runif(ncell(r)) r2 <- r/2 brks <- seq(0, 1, by=0.1) nb <- length(brks)-1 cols <- rev(terrain.colors(nb)) par(mfrow=c(1,2)) plot(r, breaks=brks, col=cols, lab.breaks=brks, zlim=c(0,1), main='first') plot(r2, breaks=brks, col=cols, lab.breaks=brks, zlim=c(0,1), main='second') # breaks and labels x <- raster(nc=10, nr=10) values(x) <- runif(ncell(x)) brk <- c(0, 0.25, 0.75, 1) arg <- list(at=c(0.12,0.5,0.87), labels=c("Low","Med.","High")) plot(x, col=terrain.colors(3), breaks=brk) plot(x, col=terrain.colors(3), breaks=brk, axis.args=arg) par(mfrow=c(1,1)) # color ramp plot(x, col=colorRampPalette(c("red", "white", "blue"))(255)) # adding random points to the map xy <- cbind(-180 + runif(10) * 360, -90 + runif(10) * 180) points(xy, pch=3, cex=5) # for SpatialPolygons do # plot(pols, add=TRUE) # adding the same points to each map of each layer of a RasterStack fun <- function() { points(xy, cex=2) points(xy, pch=3, col='red') } plot(s, addfun=fun)
# RasterLayer r <- raster(nrows=10, ncols=10) r <- setValues(r, 1:ncell(r)) plot(r) e <- extent(r) plot(e, add=TRUE, col='red', lwd=4) e <- e / 2 plot(e, add=TRUE, col='red') # Scatterplot of 2 RasterLayers r2 <- sqrt(r) plot(r, r2) plot(r, r2, gridded=TRUE) # Multi-layer object (RasterStack / Brick) s <- stack(r, r2, r/r) plot(s, 2) plot(s) # two objects, different range, one scale: values(r) <- runif(ncell(r)) r2 <- r/2 brks <- seq(0, 1, by=0.1) nb <- length(brks)-1 cols <- rev(terrain.colors(nb)) par(mfrow=c(1,2)) plot(r, breaks=brks, col=cols, lab.breaks=brks, zlim=c(0,1), main='first') plot(r2, breaks=brks, col=cols, lab.breaks=brks, zlim=c(0,1), main='second') # breaks and labels x <- raster(nc=10, nr=10) values(x) <- runif(ncell(x)) brk <- c(0, 0.25, 0.75, 1) arg <- list(at=c(0.12,0.5,0.87), labels=c("Low","Med.","High")) plot(x, col=terrain.colors(3), breaks=brk) plot(x, col=terrain.colors(3), breaks=brk, axis.args=arg) par(mfrow=c(1,1)) # color ramp plot(x, col=colorRampPalette(c("red", "white", "blue"))(255)) # adding random points to the map xy <- cbind(-180 + runif(10) * 360, -90 + runif(10) * 180) points(xy, pch=3, cex=5) # for SpatialPolygons do # plot(pols, add=TRUE) # adding the same points to each map of each layer of a RasterStack fun <- function() { points(xy, cex=2) points(xy, pch=3, col='red') } plot(s, addfun=fun)
Make a Red-Green-Blue plot based on three layers (in a RasterBrick or RasterStack). Three layers (sometimes referred to as "bands" because they may represent different bandwidths in the electromagnetic spectrum) are combined such that they represent the red, green and blue channel. This function can be used to make 'true (or false) color images' from Landsat and other multi-band satellite images.
## S4 method for signature 'RasterStackBrick' plotRGB(x, r=1, g=2, b=3, scale, maxpixels=500000, stretch=NULL, ext=NULL, interpolate=FALSE, colNA='white', alpha, bgalpha, addfun=NULL, zlim=NULL, zlimcol=NULL, axes=FALSE, xlab='', ylab='', asp=NULL, add=FALSE, margins=FALSE, ...)
## S4 method for signature 'RasterStackBrick' plotRGB(x, r=1, g=2, b=3, scale, maxpixels=500000, stretch=NULL, ext=NULL, interpolate=FALSE, colNA='white', alpha, bgalpha, addfun=NULL, zlim=NULL, zlimcol=NULL, axes=FALSE, xlab='', ylab='', asp=NULL, add=FALSE, margins=FALSE, ...)
x |
RasterBrick or RasterStack |
r |
integer. Index of the Red channel, between 1 and nlayers(x) |
g |
integer. Index of the Green channel, between 1 and nlayers(x) |
b |
integer. Index of the Blue channel, between 1 and nlayers(x) |
scale |
integer. Maximum (possible) value in the three channels. Defaults to 255 or to the maximum value of |
maxpixels |
integer > 0. Maximum number of pixels to use |
stretch |
character. Option to stretch the values to increase the contrast of the image: "lin" or "hist" |
ext |
An |
interpolate |
logical. If |
colNA |
color for the background ( |
alpha |
transparency. Integer between 0 (transparent) and 255 (opaque) |
bgalpha |
Background transparency. Integer between 0 (transparent) and 255 (opaque) |
addfun |
Function to add additional items such as points or polygons to the plot (map). See |
zlim |
numeric vector of length 2. Range of values to plot (optional) |
zlimcol |
If |
axes |
logical. If |
xlab |
character. Label of x-axis |
ylab |
character. Label of y-axis |
asp |
numeric. Aspect (ratio of x and y. If NULL, and appropriate value is computed to match data for the longitude/latitude coordinate reference system, and 1 for planar coordinate reference systems |
add |
logical. If |
margins |
logical. If |
... |
graphical parameters as in |
Robert J. Hijmans; stretch option based on functions by Josh Gray
b <- brick(system.file("external/rlogo.grd", package="raster")) plotRGB(b) plotRGB(b, 3, 2, 1) plotRGB(b, 3, 2, 1, stretch='hist')
b <- brick(system.file("external/rlogo.grd", package="raster")) plotRGB(b) plotRGB(b, 3, 2, 1) plotRGB(b, 3, 2, 1, stretch='hist')
Calculate the geographic distance between two (sets of) points on the WGS ellipsoid (lonlat=TRUE
) or on a plane (lonlat=FALSE
). If both sets do not have the same number of points, the distance between each pair of points is given. If both sets have the same number of points, the distance between each point and the corresponding point in the other set is given, except if allpairs=TRUE
.
pointDistance(p1, p2, lonlat, allpairs=FALSE, ...)
pointDistance(p1, p2, lonlat, allpairs=FALSE, ...)
p1 |
x and y coordinate of first (set of) point(s), either as c(x, y), matrix(ncol=2), or SpatialPoints*. |
p2 |
x and y coordinate of second (set of) second point(s) (like for |
lonlat |
logical. If |
allpairs |
logical. Only relevant if the number of points in |
... |
Additional arguments. None implemented |
A single value, or a vector, or matrix of values giving the distance in meters (lonlat=TRUE) or map-units (for instance, meters in the case of UTM)
If p2
is missing, a distance matrix is returned
Robert J. Hijmans and Jacob van Etten. The distance for longitude/latitude data uses GeographicLib by C.F.F. Karney
distanceFromPoints, distance, gridDistance
, spDistsN1
.
The geosphere
package has many additional distance functions and other functions that operate on spherical coordinates
a <- cbind(c(1,5,55,31),c(3,7,20,22)) b <- cbind(c(4,2,8,65),c(50,-90,20,32)) pointDistance(c(0, 0), c(1, 1), lonlat=FALSE) pointDistance(c(0, 0), c(1, 1), lonlat=TRUE) pointDistance(c(0, 0), a, lonlat=TRUE) pointDistance(a, b, lonlat=TRUE) #Make a distance matrix dst <- pointDistance(a, lonlat=TRUE) # coerce to dist object dst <- as.dist(dst)
a <- cbind(c(1,5,55,31),c(3,7,20,22)) b <- cbind(c(4,2,8,65),c(50,-90,20,32)) pointDistance(c(0, 0), c(1, 1), lonlat=FALSE) pointDistance(c(0, 0), c(1, 1), lonlat=TRUE) pointDistance(c(0, 0), a, lonlat=TRUE) pointDistance(a, b, lonlat=TRUE) #Make a distance matrix dst <- pointDistance(a, lonlat=TRUE) # coerce to dist object dst <- as.dist(dst)
Make a Raster object with predictions from a fitted model object (for example, obtained with lm
, glm
). The first argument is a Raster object with the independent (predictor) variables. The names
in the Raster object should exactly match those expected by the model. This will be the case if the same Raster object was used (via extract
) to obtain the values to fit the model (see the example). Any type of model (e.g. glm, gam, randomForest) for which a predict method has been implemented (or can be implemented) can be used.
This approach (predict a fitted model to raster data) is commonly used in remote sensing (for the classification of satellite images) and in ecology, for species distribution modeling.
## S4 method for signature 'Raster' predict(object, model, filename="", fun=predict, ext=NULL, const=NULL, index=1, na.rm=TRUE, inf.rm=FALSE, factors=NULL, format, datatype, overwrite=FALSE, progress='', ...)
## S4 method for signature 'Raster' predict(object, model, filename="", fun=predict, ext=NULL, const=NULL, index=1, na.rm=TRUE, inf.rm=FALSE, factors=NULL, format, datatype, overwrite=FALSE, progress='', ...)
object |
Raster* object. Typically a multi-layer type (RasterStack or RasterBrick) |
model |
fitted model of any class that has a 'predict' method (or for which you can supply a similar method as |
filename |
character. Optional output filename |
fun |
function. Default value is 'predict', but can be replaced with e.g. predict.se (depending on the type of model), or your own custom function. |
ext |
Extent object to limit the prediction to a sub-region of |
const |
data.frame. Can be used to add a constant for which there is no Raster object for model predictions. Particularly useful if the constant is a character-like factor value for which it is currently not possible to make a RasterLayer |
index |
integer. To select the column(s) to use if predict.'model' returns a matrix with multiple columns |
na.rm |
logical. Remove cells with |
inf.rm |
logical. Remove cells with values that are not finite (some models will fail with -Inf/Inf values). This option is ignored when |
factors |
list with levels for factor variables. The list elements should be named with names that correspond to names in |
format |
character. Output file type. See writeRaster (optional) |
datatype |
character. Output data type. See dataType (optional) |
overwrite |
logical. If TRUE, "filename" will be overwritten if it exists |
progress |
character. "text", "window", or "" (the default, no progress bar) |
... |
additional arguments to pass to the predict.'model' function |
RasterLayer or RasterBrick
Use interpolate
if your model has 'x' and 'y' as implicit independent variables (e.g., in kriging).
# A simple model to predict the location of the R in the R-logo using 20 presence points # and 50 (random) pseudo-absence points. This type of model is often used to predict # species distributions. See the dismo package for more of that. # create a RasterStack or RasterBrick with with a set of predictor layers logo <- brick(system.file("external/rlogo.grd", package="raster")) names(logo) ## Not run: # the predictor variables par(mfrow=c(2,2)) plotRGB(logo, main='logo') plot(logo, 1, col=rgb(cbind(0:255,0,0), maxColorValue=255)) plot(logo, 2, col=rgb(cbind(0,0:255,0), maxColorValue=255)) plot(logo, 3, col=rgb(cbind(0,0,0:255), maxColorValue=255)) par(mfrow=c(1,1)) ## End(Not run) # known presence and absence points p <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85, 66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31, 22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2) a <- matrix(c(22, 33, 64, 85, 92, 94, 59, 27, 30, 64, 60, 33, 31, 9, 99, 67, 15, 5, 4, 30, 8, 37, 42, 27, 19, 69, 60, 73, 3, 5, 21, 37, 52, 70, 74, 9, 13, 4, 17, 47), ncol=2) # extract values for points xy <- rbind(cbind(1, p), cbind(0, a)) v <- data.frame(cbind(pa=xy[,1], extract(logo, xy[,2:3]))) #build a model, here an example with glm model <- glm(formula=pa~., data=v) #predict to a raster r1 <- predict(logo, model, progress='text') plot(r1) points(p, bg='blue', pch=21) points(a, bg='red', pch=21) # use a modified function to get a RasterBrick with p and se # from the glm model. The values returned by 'predict' are in a list, # and this list needs to be transformed to a matrix predfun <- function(model, data) { v <- predict(model, data, se.fit=TRUE) cbind(p=as.vector(v$fit), se=as.vector(v$se.fit)) } # predfun returns two variables, so use index=1:2 r2 <- predict(logo, model, fun=predfun, index=1:2) ## Not run: # You can use multiple cores to speed up the predict function # by calling it via the clusterR function (you may need to install the snow package) beginCluster() r1c <- clusterR(logo, predict, args=list(model)) r2c <- clusterR(logo, predict, args=list(model=model, fun=predfun, index=1:2)) ## End(Not run) # principal components of a RasterBrick # here using sampling to simulate an object too large # to feed all its values to prcomp sr <- sampleRandom(logo, 100) pca <- prcomp(sr) # note the use of the 'index' argument x <- predict(logo, pca, index=1:3) plot(x) ## Not run: # partial least square regression library(pls) model <- plsr(formula=pa~., data=v) # this returns an array: predict(model, v[1:5,]) # write a function to turn that into a matrix pfun <- function(x, data) { y <- predict(x, data) d <- dim(y) dim(y) <- c(prod(d[1:2]), d[3]) y } pp <- predict(logo, model, fun=pfun, index=1:3) # Random Forest library(randomForest) rfmod <- randomForest(pa ~., data=v) ## note the additional argument "type='response'" that is ## passed to predict.randomForest r3 <- predict(logo, rfmod, type='response', progress='window') ## get a RasterBrick with class membership probabilities vv <- v vv$pa <- as.factor(vv$pa) rfmod2 <- randomForest(pa ~., data=vv) r4 <- predict(logo, rfmod2, type='prob', index=1:2) spplot(r4) # cforest (other Random Forest implementation) example with factors argument v$red <- as.factor(round(v$red/100)) logo$red <- round(logo[[1]]/100) library(party) m <- cforest(pa~., control=cforest_unbiased(mtry=3), data=v) f <- list(levels(v$red)) names(f) <- 'red' # the second argument in party:::predict.RandomForest # is "OOB", and not "newdata" or similar. We need to write a wrapper # predict function to deal with this predfun <- function(m, d, ...) predict(m, newdata=d, ...) pc <- predict(logo, m, OOB=TRUE, factors=f, fun=predfun) # knn example, using calc instead of predict library(class) cl <- factor(c(rep(1, nrow(p)), rep(0, nrow(a)))) train <- extract(logo, rbind(p, a)) k <- calc(logo, function(x) as.integer(as.character(knn(train, x, cl)))) ## End(Not run)
# A simple model to predict the location of the R in the R-logo using 20 presence points # and 50 (random) pseudo-absence points. This type of model is often used to predict # species distributions. See the dismo package for more of that. # create a RasterStack or RasterBrick with with a set of predictor layers logo <- brick(system.file("external/rlogo.grd", package="raster")) names(logo) ## Not run: # the predictor variables par(mfrow=c(2,2)) plotRGB(logo, main='logo') plot(logo, 1, col=rgb(cbind(0:255,0,0), maxColorValue=255)) plot(logo, 2, col=rgb(cbind(0,0:255,0), maxColorValue=255)) plot(logo, 3, col=rgb(cbind(0,0,0:255), maxColorValue=255)) par(mfrow=c(1,1)) ## End(Not run) # known presence and absence points p <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85, 66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31, 22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2) a <- matrix(c(22, 33, 64, 85, 92, 94, 59, 27, 30, 64, 60, 33, 31, 9, 99, 67, 15, 5, 4, 30, 8, 37, 42, 27, 19, 69, 60, 73, 3, 5, 21, 37, 52, 70, 74, 9, 13, 4, 17, 47), ncol=2) # extract values for points xy <- rbind(cbind(1, p), cbind(0, a)) v <- data.frame(cbind(pa=xy[,1], extract(logo, xy[,2:3]))) #build a model, here an example with glm model <- glm(formula=pa~., data=v) #predict to a raster r1 <- predict(logo, model, progress='text') plot(r1) points(p, bg='blue', pch=21) points(a, bg='red', pch=21) # use a modified function to get a RasterBrick with p and se # from the glm model. The values returned by 'predict' are in a list, # and this list needs to be transformed to a matrix predfun <- function(model, data) { v <- predict(model, data, se.fit=TRUE) cbind(p=as.vector(v$fit), se=as.vector(v$se.fit)) } # predfun returns two variables, so use index=1:2 r2 <- predict(logo, model, fun=predfun, index=1:2) ## Not run: # You can use multiple cores to speed up the predict function # by calling it via the clusterR function (you may need to install the snow package) beginCluster() r1c <- clusterR(logo, predict, args=list(model)) r2c <- clusterR(logo, predict, args=list(model=model, fun=predfun, index=1:2)) ## End(Not run) # principal components of a RasterBrick # here using sampling to simulate an object too large # to feed all its values to prcomp sr <- sampleRandom(logo, 100) pca <- prcomp(sr) # note the use of the 'index' argument x <- predict(logo, pca, index=1:3) plot(x) ## Not run: # partial least square regression library(pls) model <- plsr(formula=pa~., data=v) # this returns an array: predict(model, v[1:5,]) # write a function to turn that into a matrix pfun <- function(x, data) { y <- predict(x, data) d <- dim(y) dim(y) <- c(prod(d[1:2]), d[3]) y } pp <- predict(logo, model, fun=pfun, index=1:3) # Random Forest library(randomForest) rfmod <- randomForest(pa ~., data=v) ## note the additional argument "type='response'" that is ## passed to predict.randomForest r3 <- predict(logo, rfmod, type='response', progress='window') ## get a RasterBrick with class membership probabilities vv <- v vv$pa <- as.factor(vv$pa) rfmod2 <- randomForest(pa ~., data=vv) r4 <- predict(logo, rfmod2, type='prob', index=1:2) spplot(r4) # cforest (other Random Forest implementation) example with factors argument v$red <- as.factor(round(v$red/100)) logo$red <- round(logo[[1]]/100) library(party) m <- cforest(pa~., control=cforest_unbiased(mtry=3), data=v) f <- list(levels(v$red)) names(f) <- 'red' # the second argument in party:::predict.RandomForest # is "OOB", and not "newdata" or similar. We need to write a wrapper # predict function to deal with this predfun <- function(m, d, ...) predict(m, newdata=d, ...) pc <- predict(logo, m, OOB=TRUE, factors=f, fun=predfun) # knn example, using calc instead of predict library(class) cl <- factor(c(rep(1, nrow(p)), rep(0, nrow(a)))) train <- extract(logo, rbind(p, a)) k <- calc(logo, function(x) as.integer(as.character(knn(train, x, cl)))) ## End(Not run)
These are low level functions that can be used by programmers to develop new functions. If in doubt, it is almost certain that you do not need these functions as these are already embedded in all other functions in the raster package.
canProcessInMemory
is typically used within functions. In the raster package this function is used to determine if the amount of memory needed for the function is available. If there is not enough memory available, the function returns FALSE
, and the function that called it will write the results to a temporary file.
readStart opens file connection(s) for reading, readStop removes it.
pbCreate creates a progress bar, pbStep sets the progress, and pbClose closes it.
canProcessInMemory(x, n=4, verbose=FALSE) pbCreate(nsteps, progress, style=3, label='Progress', ...) pbStep(pb, step=NULL, label='') pbClose(pb, timer) readStart(x, ...) readStop(x) getCluster() returnCluster()
canProcessInMemory(x, n=4, verbose=FALSE) pbCreate(nsteps, progress, style=3, label='Progress', ...) pbStep(pb, step=NULL, label='') pbClose(pb, timer) readStart(x, ...) readStop(x) getCluster() returnCluster()
x |
RasterLayer or RasterBrick object (for connections) or RasterStack object (canProcessInMemory) |
n |
integer. The number of copies of the Raster* object cell values that a function needs to be able to have in memory |
verbose |
logical. If |
nsteps |
integer. Number of steps the progress bar will make from start to end (e.g. nrow(raster)) |
progress |
character. 'text', 'window', or ” |
style |
style for text progress bar. See |
label |
character. Label for the window type progress bar |
... |
additional arguments (None implemented, except for 'silent=TRUE' for readStart for files read with gdal, and other arguments passed to gdal.open) |
pb |
progress bar object created with pbCreate |
step |
which step is this ( 1 <= step <= nsteps ). If step is |
timer |
logical. If |
canProcessInMemory: logical
closeConnection: RasterLayer or RasterBrick object
getCluster: snow cluster object
r <- raster(nrow=100, ncol=100) canProcessInMemory(r, 4) r <- raster(nrow=50000, ncol=50000) canProcessInMemory(r, 2, verbose=TRUE) rasterOptions(maxmem=Inf, memfrac=.8) rasterOptions(default=TRUE)
r <- raster(nrow=100, ncol=100) canProcessInMemory(r, 4) r <- raster(nrow=50000, ncol=50000) canProcessInMemory(r, 2, verbose=TRUE) rasterOptions(maxmem=Inf, memfrac=.8) rasterOptions(default=TRUE)
Get or set the coordinate reference system (CRS) of a Raster* object.
## S4 method for signature 'ANY' crs(x, asText=FALSE, ...) ## S4 method for signature 'Raster' wkt(obj) crs(x, ...) <- value projection(x, asText=TRUE) projection(x) <- value
## S4 method for signature 'ANY' crs(x, asText=FALSE, ...) ## S4 method for signature 'Raster' wkt(obj) crs(x, ...) <- value projection(x, asText=TRUE) projection(x) <- value
x |
Raster* or Spatial object |
obj |
Raster*, Spatial, or CRS object |
asText |
logical. If |
... |
additional arguments. None implemented |
value |
|
projections are done by with the PROJ library
Raster*, Spatial*, or character object
crs
replaces earlier function projection
.
For compatibility with sp
you can use proj4string
instead of crs
.
wkt
returns the "well-known-text" representation of the crs.
r <- raster() crs(r) crs(r) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +datum=WGS84" crs(r) w <- wkt(r) w cat(w, "\n")
r <- raster() crs(r) crs(r) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +datum=WGS84" crs(r) w <- wkt(r) w cat(w, "\n")
Project the values of a Raster* object to a new Raster* object with another projection (coordinate reference system, (CRS)).
You can do this by providing the new projection as a single argument in which case the function sets the extent and resolution of the new object. To have more control over the transformation, and, for example, to assure that the new object lines up with other datasets, you can provide a Raster* object with the properties that the input data should be projected to.
projectExtent
returns a RasterLayer with a projected extent, but without any values. This RasterLayer can then
be adjusted (e.g. by setting its resolution) and used as a template 'to'
in projectRaster
.
projectRaster(from, to, res, crs, method="bilinear", alignOnly=FALSE, over=FALSE, filename="", ...) projectExtent(object, crs)
projectRaster(from, to, res, crs, method="bilinear", alignOnly=FALSE, over=FALSE, filename="", ...) projectExtent(object, crs)
from |
Raster* object |
to |
Raster* object with the parameters to which 'from' should be projected |
res |
single or (vector of) two numerics. To, optionally, set the output resolution if 'to' is missing |
crs |
character or object of class 'CRS'. PROJ.4 description of the coordinate reference system. In projectRaster this is used to set the output CRS if 'to' is missing, or if 'to' has no valid CRS |
method |
method used to compute values for the new RasterLayer. Either 'ngb' (nearest neighbor), which is useful for categorical variables, or 'bilinear' (bilinear interpolation; the default value), which is appropriate for continuous variables. |
alignOnly |
logical. Use |
over |
logical. If |
filename |
character. Output filename |
... |
additional arguments as for |
object |
Raster* object |
There are two approaches you can follow to project the values of a Raster object.
1) Provide a crs
argument, and, optionally, a res
argument, but do not provide a to
argument.
2) Create a template Raster with the CRS you want to project to. You can use an existing object, or use projectExtent
for this or an existing Raster* object. Also set the number of rows and columns (or the resolution), and perhaps adjust the extent. The resolution of the output raster should normally be similar to that of the input raster. Then use that object as from
argument to project the input Raster to.
This is the preferred method because you have most control. For example you can assure that the resulting Raster object lines up with other Raster objects.
Projection is performed using the PROJ library.
Also see projInfo('proj')
, projInfo('ellps')
, and projInfo('datum')
for valid PROJ.4 values.
RasterLayer or RasterBrick object.
If the resolution of the output is much larger than that of the input, you should first aggregate the input such that the resolution of the input becomes more similar (perhaps a little smaller) to the output.
User beware. Sadly, the PROJ.4 notation has been partly deprecated in the GDAL/PROJ library that is used by this function. You can still use it, but *only* with the the WGS84 datum. Other datums are silently ignored.
When printing a Spat* object the PROJ.4 notation is shown because it is the most concise and clear format available. However, internally a WKT representation is used (see crs
).
Vector (points, lines, polygons) can be transformed with spTransform
.
projectExtent
does not work very well when transforming projected circumpolar data to (e.g.) longitude/latitude.
With such data you may need to adjust the returned object. E.g. do ymax(object) <- 90
Robert J. Hijmans and Joe Cheng
# create a new (not projected) RasterLayer with cellnumbers as values r <- raster(xmn=-110, xmx=-90, ymn=40, ymx=60, ncols=40, nrows=40, crs="+proj=longlat") r <- setValues(r, 1:ncell(r)) projection(r) # proj.4 projection description newproj <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +datum=WGS84" #simplest approach pr1 <- projectRaster(r, crs=newproj) # alternatively also set the resolution pr2 <- projectRaster(r, crs=newproj, res=20000) # inverse projection, back to the properties of 'r' inv <- projectRaster(pr2, r) # to have more control, provide an existing Raster object, here we create one # using projectExtent (no values are transferred) pr3 <- projectExtent(r, newproj) # Adjust the cell size res(pr3) <- 200000 # now project pr3 <- projectRaster(r, pr3)
# create a new (not projected) RasterLayer with cellnumbers as values r <- raster(xmn=-110, xmx=-90, ymn=40, ymx=60, ncols=40, nrows=40, crs="+proj=longlat") r <- setValues(r, 1:ncell(r)) projection(r) # proj.4 projection description newproj <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +datum=WGS84" #simplest approach pr1 <- projectRaster(r, crs=newproj) # alternatively also set the resolution pr2 <- projectRaster(r, crs=newproj, res=20000) # inverse projection, back to the properties of 'r' inv <- projectRaster(pr2, r) # to have more control, provide an existing Raster object, here we create one # using projectExtent (no values are transferred) pr3 <- projectExtent(r, newproj) # Adjust the cell size res(pr3) <- 200000 # now project pr3 <- projectRaster(r, pr3)
Properties of the values of the file that a RasterLayer object points to
dataSize
returns the number of bytes used for each value (pixel, grid cell)
dataSigned
is TRUE for data types that include negative numbers.
dataSize(object) dataSigned(object)
dataSize(object) dataSigned(object)
object |
Raster* object |
varies
r <- raster(system.file("external/test.grd", package="raster")) dataSize(r) dataSigned(r) dataType(r)
r <- raster(system.file("external/test.grd", package="raster")) dataSize(r) dataSigned(r) dataType(r)
Compute quantiles for the cell values of a RasterLayer. If you want to compute quantiles for each cell across a number of layers, you can use calc(x, fun=quantile)
.
quantile(x, ...)
quantile(x, ...)
x |
Raster object |
... |
Additional arguments: |
ncells can be used to set the number of cells to be sampled, for very large raster datasets.
A vector of quantiles
r <- raster(ncol=100, nrow=100) values(r) <- rnorm(ncell(r), 0, 50) quantile(r) quantile(r, probs = c(0.25, 0.75), type=7,names = FALSE)
r <- raster(ncol=100, nrow=100) values(r) <- rnorm(ncell(r), 0, 50) quantile(r) quantile(r, probs = c(0.25, 0.75), type=7,names = FALSE)
Methods to create a RasterLayer object. RasterLayer objects can be created from scratch, a file, an Extent object, a matrix, an 'image' object, or from a Raster*, Spatial*, im (spatstat) asc, kasc (adehabitat*), grf (geoR) or kde object.
In many cases, e.g. when a RasterLayer is created from a file, it does (initially) not contain any cell (pixel) values in (RAM) memory, it only has the parameters that describe the RasterLayer. You can access cell-values with getValues, extract
and related functions. You can assign new values with setValues
and with replacement
.
For an overview of the functions in the raster package have a look here: raster-package
.
## S4 method for signature 'character' raster(x, band=1, ...) ## S4 method for signature 'RasterLayer' raster(x) ## S4 method for signature 'RasterStack' raster(x, layer=0) ## S4 method for signature 'RasterBrick' raster(x, layer=0) ## S4 method for signature 'missing' raster(nrows=180, ncols=360, xmn=-180, xmx=180, ymn=-90, ymx=90, crs, ext, resolution, vals=NULL) ## S4 method for signature 'Extent' raster(x, nrows=10, ncols=10, crs="", ...) ## S4 method for signature 'matrix' raster(x, xmn=0, xmx=1, ymn=0, ymx=1, crs="", template=NULL) ## S4 method for signature 'Spatial' raster(x, origin, ...) ## S4 method for signature 'SpatialGrid' raster(x, layer=1, values=TRUE) ## S4 method for signature 'SpatialPixels' raster(x, layer=1, values=TRUE) ## S4 method for signature 'sf' raster(x, origin, ...)
## S4 method for signature 'character' raster(x, band=1, ...) ## S4 method for signature 'RasterLayer' raster(x) ## S4 method for signature 'RasterStack' raster(x, layer=0) ## S4 method for signature 'RasterBrick' raster(x, layer=0) ## S4 method for signature 'missing' raster(nrows=180, ncols=360, xmn=-180, xmx=180, ymn=-90, ymx=90, crs, ext, resolution, vals=NULL) ## S4 method for signature 'Extent' raster(x, nrows=10, ncols=10, crs="", ...) ## S4 method for signature 'matrix' raster(x, xmn=0, xmx=1, ymn=0, ymx=1, crs="", template=NULL) ## S4 method for signature 'Spatial' raster(x, origin, ...) ## S4 method for signature 'SpatialGrid' raster(x, layer=1, values=TRUE) ## S4 method for signature 'SpatialPixels' raster(x, layer=1, values=TRUE) ## S4 method for signature 'sf' raster(x, origin, ...)
x |
filename (character), Extent, Raster*, sf, SpatialPixels*, SpatialGrid*, object, 'image', matrix, im, or missing. Supported file types are the 'native' raster package format and those that can be read by GDAL |
band |
integer. The layer to use in a multi-layer file |
... |
Additional arguments, see Details |
layer |
integer. The layer (variable) to use in a multi-layer file, or the layer to extract from a RasterStack/Brick or SpatialPixelsDataFrame or SpatialGridDataFrame. An empty RasterLayer (no associated values) is returned if |
values |
logical. If |
nrows |
integer > 0. Number of rows |
ncols |
integer > 0. Number of columns |
xmn |
minimum x coordinate (left border) |
xmx |
maximum x coordinate (right border) |
ymn |
minimum y coordinate (bottom border) |
ymx |
maximum y coordinate (top border) |
ext |
object of class Extent. If present, the arguments xmn, xmx, ymn and ynx are ignored |
crs |
character or object of class CRS. PROJ.4 type description of a Coordinate Reference System (map projection). If this argument is missing, and the x coordinates are within -360 .. 360 and the y coordinates are within -90 .. 90, "+proj=longlat +datum=WGS84" is used. Also see under Details if |
resolution |
numeric vector of length 1 or 2 to set the resolution (see |
vals |
optional. Values for the new RasterLayer. Accepted formats are as for |
origin |
minimum y coordinate (bottom border) |
template |
Raster* or Extent object used to set the extent (and CRS in case of a Raster* object). If not |
If x
is a filename, the following additional variables are recognized:
sub
: positive integer. Subdataset number for a file with subdatasets
native
: logical. Default is FALSE
. If TRUE
, reading and writing of IDRISI, BIL, BSQ, BIP, SAGA, and Arc ASCII files is done with native (raster package) drivers, rather then via GDAL. 'raster' and netcdf format files are always read with native drivers.
RAT
: logical. The default is TRUE
, in which case a raster attribute table is created for files that have one
offset
: integer. To indicate the number of header rows on non-standard ascii files (rarely useful; use with caution)
crs
: character. PROJ.4 string to set the CRS. Ignored when the file provides a CRS description that can be interpreted.
If x
represents a NetCDF file, the following additional variable is recognized:
varname
: character. The variable name, such as 'tasmax' or 'pr'. If not supplied and the file has multiple variables are a guess will be made (and reported)
lvar
: integer > 0 (default=3). To select the 'level variable' (3rd dimension variable) to use, if the file has 4 dimensions (e.g. depth instead of time)
level
: integer > 0 (default=1). To select the 'level' (4th dimension variable) to use, if the file has 4 dimensions, e.g. to create a RasterBrick of weather over time at a certain height.
To use NetCDF files the ncdf4
package needs to be available. It is assumed that these files follow, or are compatible with, the CF-1 convention (The GMT format may also work). If the ncdf file does not have a standard extension (which is used to recognize the file format), you can use argument ncdf=TRUE
to indicate the format.
If x
is a Spatial
or an Extent
object, additional arguments are for the method with signature 'missing'
RasterLayer
# Create a RasterLayer object from a file # N.B.: For your own files, omit the 'system.file' and 'package="raster"' bits # these are just to get the path to files installed with the package f <- system.file("external/test.grd", package="raster") f r <- raster(f) logo <- raster(system.file("external/rlogo.grd", package="raster")) #from scratch r1 <- raster(nrows=108, ncols=21, xmn=0, xmx=10) #from an Extent object e <- extent(r) r2 <- raster(e) #from another Raster* object r3 <- raster(r) s <- stack(r, r, r) r4 <- raster(s) r5 <- raster(s, 3)
# Create a RasterLayer object from a file # N.B.: For your own files, omit the 'system.file' and 'package="raster"' bits # these are just to get the path to files installed with the package f <- system.file("external/test.grd", package="raster") f r <- raster(f) logo <- raster(system.file("external/rlogo.grd", package="raster")) #from scratch r1 <- raster(nrows=108, ncols=21, xmn=0, xmx=10) #from an Extent object e <- extent(r) r2 <- raster(e) #from another Raster* object r3 <- raster(r) s <- stack(r, r, r) r4 <- raster(s) r5 <- raster(s, 3)
A raster is a database organized as a rectangular grid that is sub-divided into rectangular cells of equal area (in terms of the units of the coordinate reference system). The 'raster' package defines a number of "S4 classes" to manipulate such data.
The main user level classes are RasterLayer
, RasterStack
and RasterBrick
. They all inherit from BasicRaster
and can contain values for the raster cells.
An object of the RasterLayer
class refers to a single layer (variable) of raster data. The object can point to a file on disk that holds the values of the raster cells, or hold these values in memory. Or it can not have any associated values at all.
A RasterStack
represents a collection of RasterLayer
objects with the same extent and resolution. Organizing RasterLayer
objects in a RasterStack
can be practical when dealing with multiple layers; for example to summarize their values (see calc
) or in spatial modeling (see predict
).
An object of class RasterBrick
can also contain multiple layers of raster data, but they are more tightly related. An object of class RasterBrick
can refer to only a single (multi-layer) data file, whereas each layer in a RasterStack
can refer to another file (or another band in a multi-band file). This has implications for processing speed and flexibility. A RasterBrick
should process quicker than a RasterStack
(irrespective if values are on disk or in memory). However, a RasterStack
is more flexible as a single object can refer to layers that have values stored on disk as well as in memory. If a layer that does not refer to values on disk (they only exists in memory) is added to a RasterBrick
, it needs to load all its values into memory (and this may not be possible because of memory size limitations).
Objects can be created from file or from each other with the following functions: raster, brick
and stack.
Raster*
objects can also be created from SpatialPixels* and SpatialGrid* objects from the sp package using as
, or simply with the function raster
, brick
, or stack
. Vice versa, Raster*
objects can be coerced into a sp type object with as( , )
, e.g. as(x, 'SpatialGridDataFrame')
.
Common generic methods implemented for these classes include:
summary
, show
, dim
, and plot, ...
[
is implemented for RasterLayer.
The classes described above inherit from the BasicRaster
class which inherits from BasicRaster
. The BasicRaster
class describes the main properties of a raster such as the number of columns and rows, and it contains an object of the link[raster]{Extent-class}
to describe its spatial extent (coordinates). It also holds the 'coordinate reference system' in a slot of class CRS-class
defined in the sp
package. A BasicRaster
cannot contain any raster cell values and is therefore seldomly used.
The Raster*
class inherits from BasicRaster
. It is a virtual class; which means that you cannot create an object of this class. It is used only to define methods for all the classes that inherit from it (RasterLayer
, RasterStack
and RasterBrick
). Another virtual class is the RasterStackBrick
class. It is formed by a class union of RasterStack
and RasterBrick
. You cannot make objects of it, but methods defined for objects of this class as arguments will accept objects of the RasterLayer
and RasterStack
as that argument.
Classes RasterLayer
and RasterBrick
have a slot with an object of class RasterFile
that describes the properties of the file they point to (if they do). RasterLayer
has a slot with an object of class SingleLayerData
, and the RasterBrick
class has a slot with an object of class MultipleLayerData
. These 'datalayer' classes can contain (some of) the values of the raster cells.
These classes are not further described here because users should not need to directly access these slots. The 'setter' functions such as setValues
should be used instead. Using such 'setter' functions is much safer because a change in one slot should often affect the values in other slots.
Objects can be created by calls of the form new("RasterLayer", ...)
, or with the helper functions such as raster
.
Slots for RasterLayer and RasterBrick objects
title
:Character
file
:Object of class ".RasterFile"
data
:Object of class ".SingleLayerData"
or ".MultipleLayerData"
history
:To record processing history, not yet in use
legend
:Object of class .RasterLegend
, Default legend. Should store preferences for plotting. Not yet implemented except that it stores the color table of images, if available
extent
:Object of Extent-class
ncols
:Integer
nrows
:Integer
crs
:Object of class "CRS"
, i.e. the coordinate reference system. In Spatial* objects this slot is called 'proj4string'
showClass("RasterLayer")
showClass("RasterLayer")
This function returns a new raster based on an existing raster and cell numbers for that raster.
The new raster is cropped to the cell numbers provided, and, if values=TRUE
has values that are the cell numbers of the original raster.
rasterFromCells(x, cells, values=TRUE)
rasterFromCells(x, cells, values=TRUE)
x |
Raster* object (or a SpatialPixels* or SpatialGrid* object) |
cells |
vector of cell numbers |
values |
Logical. If |
Cell numbers start at 1 in the upper left corner, and increase from left to right, and then from top to bottom. The last cell number equals the number of cells of the Raster* object.
RasterLayer
r <- raster(ncols=100, nrows=100) cells <- c(3:5, 210) r <- rasterFromCells(r, cells) cbind(1:ncell(r), getValues(r))
r <- raster(ncols=100, nrows=100) cells <- c(3:5, 210) r <- rasterFromCells(r, cells) cbind(1:ncell(r), getValues(r))
Create a Raster* object from x, y and z values. x and y represent spatial coordinates and must be on a regular grid. If the resolution is not supplied, it is assumed to be the minimum distance between x and y coordinates, but a resolution of up to 10 times smaller is evaluated if a regular grid can otherwise not be created. z values can be single or multiple columns (variables) If the exact properties of the RasterLayer are known beforehand, it may be preferable to simply create a new RasterLayer with the raster function instead, compute cell numbers and assign the values with these (see example below).
rasterFromXYZ(xyz, res=c(NA,NA), crs="", digits=5)
rasterFromXYZ(xyz, res=c(NA,NA), crs="", digits=5)
xyz |
matrix or data.frame with at least three columns: x and y coordinates, and values (z). There may be several 'z' variables (columns) |
res |
numeric. The x and y cell resolution (optional) |
crs |
CRS object or a character string describing a projection and datum in PROJ.4 format |
digits |
numeric, indicating the requested precision for detecting whether points are on a regular grid (a low number of digits is a low precision) |
RasterLayer or RasterBrick
See rasterize for points that are not on a regular grid
r <- raster(nrow=5, ncol=5, xmn=0, xmx=10, ymn=0, ymx=10, crs="") set.seed(1) values(r) <- sample(1:25) r[r < 15] <- NA xyz <- rasterToPoints(r) rst <- rasterFromXYZ(xyz) # equivalent to: rr <- raster(nrow=5, ncol=5, xmn=0, xmx=10, ymn=0, ymx=10) cells <- cellFromXY(rr, xyz[,1:2]) rr[cells] <- xyz[,3] # multiple layers xyzz <- cbind(xyz, a=1:nrow(xyz), b=nrow(xyz):1) b <- rasterFromXYZ(xyzz)
r <- raster(nrow=5, ncol=5, xmn=0, xmx=10, ymn=0, ymx=10, crs="") set.seed(1) values(r) <- sample(1:25) r[r < 15] <- NA xyz <- rasterToPoints(r) rst <- rasterFromXYZ(xyz) # equivalent to: rr <- raster(nrow=5, ncol=5, xmn=0, xmx=10, ymn=0, ymx=10) cells <- cellFromXY(rr, xyz[,1:2]) rr[cells] <- xyz[,3] # multiple layers xyzz <- cbind(xyz, a=1:nrow(xyz), b=nrow(xyz):1) b <- rasterFromXYZ(xyzz)
Transfer values associated with 'object' type spatial data (points, lines, polygons) to raster cells.
For polygons, values are transferred if the polygon covers the center of a raster cell. For lines, values are transferred to all cells that are touched by a line. You can combine this behaviour by rasterizing polygons as lines first and then as polygons.
If x
represents points, each point is assigned to a grid cell. Points that fall on a border between cells are placed in the cell to the right and/or in the cell below. The value of a grid cell is determined by the values associated with the points and function fun
.
## S4 method for signature 'matrix,Raster' rasterize(x, y, field, fun='last', background=NA, mask=FALSE, update=FALSE, updateValue='all', filename="", na.rm=TRUE, ...) ## S4 method for signature 'SpatialPoints,Raster' rasterize(x, y, field, fun='last', background=NA, mask=FALSE, update=FALSE, updateValue='all', filename="", na.rm=TRUE, ...) ## S4 method for signature 'SpatialLines,Raster' rasterize(x, y, field, fun='last', background=NA, mask=FALSE, update=FALSE, updateValue='all', filename="", ...) ## S4 method for signature 'SpatialPolygons,Raster' rasterize(x, y, field, fun='last', background=NA, mask=FALSE, update=FALSE, updateValue='all', filename="", getCover=FALSE, silent=TRUE, ...)
## S4 method for signature 'matrix,Raster' rasterize(x, y, field, fun='last', background=NA, mask=FALSE, update=FALSE, updateValue='all', filename="", na.rm=TRUE, ...) ## S4 method for signature 'SpatialPoints,Raster' rasterize(x, y, field, fun='last', background=NA, mask=FALSE, update=FALSE, updateValue='all', filename="", na.rm=TRUE, ...) ## S4 method for signature 'SpatialLines,Raster' rasterize(x, y, field, fun='last', background=NA, mask=FALSE, update=FALSE, updateValue='all', filename="", ...) ## S4 method for signature 'SpatialPolygons,Raster' rasterize(x, y, field, fun='last', background=NA, mask=FALSE, update=FALSE, updateValue='all', filename="", getCover=FALSE, silent=TRUE, ...)
x |
points (a SpatialPoints* object, or a two-column matrix (or data.frame)), SpatialLines*, SpatialPolygons*, or an Extent object |
y |
Raster* object |
field |
numeric or character. The value(s) to be transferred. This can be a single number, or a vector of numbers that has the same length as the number of spatial features (points, lines, polygons). If |
fun |
function or character. To determine what values to assign to cells that are covered by multiple spatial features. You can use functions such as If You can also pass multiple functions using a statement like |
background |
numeric. Value to put in the cells that are not covered by any of the features of |
mask |
logical. If |
update |
logical. If |
updateValue |
numeric (normally an integer), or character. Only relevant when |
filename |
character. Output filename (optional) |
na.rm |
If |
getCover |
logical. If |
silent |
Logical. If |
... |
Additional arguments for file writing as for |
RasterLayer or RasterBrick
############################### # rasterize points ############################### r <- raster(ncols=36, nrows=18) n <- 1000 set.seed(123) x <- runif(n) * 360 - 180 y <- runif(n) * 180 - 90 xy <- cbind(x, y) # get the (last) indices r0 <- rasterize(xy, r) # presence/absensce (NA) (is there a point or not?) r1 <- rasterize(xy, r, field=1) # how many points? r2 <- rasterize(xy, r, fun=function(x,...)length(x)) vals <- runif(n) # sum of the values associated with the points r3 <- rasterize(xy, r, vals, fun=sum) # with a SpatialPointsDataFrame vals <- 1:n p <- data.frame(xy, name=vals) coordinates(p) <- ~x+y r <- rasterize(p, r, 'name', fun=min) #r2 <- rasterize(p, r, 'name', fun=max) #plot(r, r2, cex=0.5) ############################### # rasterize lines ############################### cds1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60)) cds2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) cds3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45)) lines <- spLines(cds1, cds2, cds3) r <- raster(ncols=90, nrows=45) r <- rasterize(lines, r) ## Not run: plot(r) plot(lines, add=TRUE) r <- rasterize(lines, r, fun='count') plot(r) values(r) <- 1:ncell(r) r <- rasterize(lines, r, mask=TRUE) plot(r) values(r) <- 1 r[lines] <- 10 plot(r) ## End(Not run) ############################### # rasterize polygons ############################### p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20)) hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20)) p1 <- list(p1, hole) p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0)) p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0)) pols <- spPolygons(p1, p2, p3) r <- raster(ncol=90, nrow=45) r <- rasterize(pols, r, fun=sum) ## Not run: plot(r) plot(pols, add=T) # add a polygon p5 <- rbind(c(-180,10), c(0,90), c(40,90), c(145,-10), c(-25, -15), c(-180,0), c(-180,10)) addpoly <- SpatialPolygons(list(Polygons(list(Polygon(p5)), 1))) addpoly <- as(addpoly, "SpatialPolygonsDataFrame") addpoly@data[1,1] <- 10 r2 <- rasterize(addpoly, r, field=1, update=TRUE, updateValue="NA") plot(r2) plot(pols, border="blue", lwd=2, add=TRUE) plot(addpoly, add=TRUE, border="red", lwd=2) # get the percentage cover of polygons in a cell r3 <- raster(ncol=36, nrow=18) r3 <- rasterize(pols, r3, getCover=TRUE) ## End(Not run)
############################### # rasterize points ############################### r <- raster(ncols=36, nrows=18) n <- 1000 set.seed(123) x <- runif(n) * 360 - 180 y <- runif(n) * 180 - 90 xy <- cbind(x, y) # get the (last) indices r0 <- rasterize(xy, r) # presence/absensce (NA) (is there a point or not?) r1 <- rasterize(xy, r, field=1) # how many points? r2 <- rasterize(xy, r, fun=function(x,...)length(x)) vals <- runif(n) # sum of the values associated with the points r3 <- rasterize(xy, r, vals, fun=sum) # with a SpatialPointsDataFrame vals <- 1:n p <- data.frame(xy, name=vals) coordinates(p) <- ~x+y r <- rasterize(p, r, 'name', fun=min) #r2 <- rasterize(p, r, 'name', fun=max) #plot(r, r2, cex=0.5) ############################### # rasterize lines ############################### cds1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60)) cds2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) cds3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45)) lines <- spLines(cds1, cds2, cds3) r <- raster(ncols=90, nrows=45) r <- rasterize(lines, r) ## Not run: plot(r) plot(lines, add=TRUE) r <- rasterize(lines, r, fun='count') plot(r) values(r) <- 1:ncell(r) r <- rasterize(lines, r, mask=TRUE) plot(r) values(r) <- 1 r[lines] <- 10 plot(r) ## End(Not run) ############################### # rasterize polygons ############################### p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20)) hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20)) p1 <- list(p1, hole) p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0)) p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0)) pols <- spPolygons(p1, p2, p3) r <- raster(ncol=90, nrow=45) r <- rasterize(pols, r, fun=sum) ## Not run: plot(r) plot(pols, add=T) # add a polygon p5 <- rbind(c(-180,10), c(0,90), c(40,90), c(145,-10), c(-25, -15), c(-180,0), c(-180,10)) addpoly <- SpatialPolygons(list(Polygons(list(Polygon(p5)), 1))) addpoly <- as(addpoly, "SpatialPolygonsDataFrame") addpoly@data[1,1] <- 10 r2 <- rasterize(addpoly, r, field=1, update=TRUE, updateValue="NA") plot(r2) plot(pols, border="blue", lwd=2, add=TRUE) plot(addpoly, add=TRUE, border="red", lwd=2) # get the percentage cover of polygons in a cell r3 <- raster(ncol=36, nrow=18) r3 <- rasterize(pols, r3, getCover=TRUE) ## End(Not run)
Functions in the raster package create temporary files if the values of an output Raster* object cannot be stored in memory (RAM). This can happen when no filename is provided to a function and in functions where you cannot provide a filename (e.g. when using 'raster algebra').
Temporary files are automatically removed at the start of each session. During a session you can use showTmpFiles
to see what is there and removeTmpFiles
to delete all the temporary files. rasterTmpFile
returns a temporary filename. These can be useful when developing your own functions. These filenames consist of prefix_date_time_pid_rn
where pid
is the process id returned by Sys.getpid
and rn
is a 5 digit random number. This should make tempfiles unique if created at different times and also when created in parallel processes (different pid) that use set.seed
and call rasterTmpFile at the same time. It is possible, however, to create overlapping names (see the examples), which is undesirable and can be avoided by setting the prefix argument.
rasterTmpFile(prefix='r_tmp_') showTmpFiles() removeTmpFiles(h=24)
rasterTmpFile(prefix='r_tmp_') showTmpFiles() removeTmpFiles(h=24)
prefix |
Character. Prefix to the filename (which will be followed by 10 random numbers) |
h |
Numeric. The minimum age of the files in number of hours (younger files are not deleted) |
rasterTmpFile
returns a valid file name
showTmpFiles
returns the names (.grd only) of the files in the temp directory
removeTmpFiles
returns nothing
## Not run: rasterTmpFile('mytemp_') showTmpFiles() removeTmpFiles(h=24) ## End(Not run)
## Not run: rasterTmpFile('mytemp_') showTmpFiles() removeTmpFiles(h=24) ## End(Not run)
RasterLayer to contour lines. This is a wrapper around contourLines
rasterToContour(x, maxpixels=100000, ...)
rasterToContour(x, maxpixels=100000, ...)
x |
a RasterLayer object |
maxpixels |
Maximum number of raster cells to use; this function fails when too many cells are used |
... |
Any argument that can be passed to |
Most of the code was taken from maptools::ContourLines2SLDF, by Roger Bivand & Edzer Pebesma
SpatialLinesDataFrame
f <- system.file("external/test.grd", package="raster") r <- raster(f) x <- rasterToContour(r) class(x) plot(r) plot(x, add=TRUE)
f <- system.file("external/test.grd", package="raster") r <- raster(f) x <- rasterToContour(r) class(x) plot(r) plot(x, add=TRUE)
Raster to point conversion. Cells with NA are not converted. A function can be used to select a subset of the raster cells (by their values).
rasterToPoints(x, fun=NULL, spatial=FALSE, ...)
rasterToPoints(x, fun=NULL, spatial=FALSE, ...)
x |
A Raster* object |
fun |
Function to select a subset of raster values |
spatial |
Logical. If |
... |
Additional arguments. Currently only |
fun
should be a simple function returning a logical value.
E.g.: fun=function(x){x==1}
or fun=function(x){x>3}
A matrix with three columns: x, y, and v (value), or a SpatialPointsDataFrame object
r <- raster(nrow=18, ncol=36) values(r) <- runif(ncell(r)) * 10 r[r>8] <- NA p <- rasterToPoints(r) p <- rasterToPoints(r, fun=function(x){x>6}) #plot(r) #points(p)
r <- raster(nrow=18, ncol=36) values(r) <- runif(ncell(r)) * 10 r[r>8] <- NA p <- rasterToPoints(r) p <- rasterToPoints(r, fun=function(x){x>6}) #plot(r) #points(p)
Raster to polygons conversion. Cells with NA are not converted. A function can be used to select a subset of the raster cells (by their values).
rasterToPolygons(x, fun=NULL, n=4, na.rm=TRUE, digits=12, dissolve=FALSE)
rasterToPolygons(x, fun=NULL, n=4, na.rm=TRUE, digits=12, dissolve=FALSE)
x |
Raster* object |
fun |
function to select a subset of raster values (only allowed if |
n |
integer. The number of nodes for each polygon. Only 4, 8, and 16 are allowed |
na.rm |
If |
digits |
number of digits to round the coordinates to |
dissolve |
logical. If |
fun
should be a simple function returning a logical value.
E.g.: fun=function(x){x==1}
or fun=function(x){x>3 & x<6}
SpatialPolygonsDataFrame
r <- raster(nrow=18, ncol=36) values(r) <- runif(ncell(r)) * 10 r[r>8] <- NA pol <- rasterToPolygons(r, fun=function(x){x>6}) #plot(r > 6) #plot(pol, add=TRUE, col='red')
r <- raster(nrow=18, ncol=36) values(r) <- runif(ncell(r)) * 10 r[r>8] <- NA pol <- rasterToPolygons(r, fun=function(x){x>6}) #plot(r > 6) #plot(pol, add=TRUE, col='red')
Read all values from a raster file associated with a Raster* object into memory. This function should normally not be used. In most cases getValues
or getValuesBlock
is more appropriate as readAll
will fail when there is no file associated with the RasterLayer (values may only exist in memory).
readAll(object)
readAll(object)
object |
a Raster* object |
getValues
, getValuesBlock
, extract
r <- raster(system.file("external/test.grd", package="raster")) r <- readAll(r)
r <- raster(system.file("external/test.grd", package="raster")) r <- readAll(r)
Reclassify values of a Raster* object. The function (re)classifies groups of values to other values. For example, all values between 1 and 10 become 1, and all values between 11 and 15 become 2 (see functions subs
and cut
for alternative approaches).
Reclassification is done with matrix rcl
, in the row order of the reclassify table. Thus, if there are overlapping ranges, the first time a number is within a range determines the reclassification value.
## S4 method for signature 'Raster' reclassify(x, rcl, filename='', include.lowest=FALSE, right=TRUE, ...)
## S4 method for signature 'Raster' reclassify(x, rcl, filename='', include.lowest=FALSE, right=TRUE, ...)
x |
Raster* object |
rcl |
matrix for reclassification. This matrix can have 3 or 2 columns. In a A |
filename |
character. Output filename (optional) |
include.lowest |
logical, indicating if a value equal to the lowest value in rcl (or highest value in the second column, for right = FALSE) should be included. The default is |
right |
logical, indicating if the intervals should be closed on the right (and open on the left) or vice versa. The default is |
... |
additional arguments as for |
Raster* object
r <- raster(ncols=36, nrows=18) values(r) <- runif(ncell(r)) # reclassify the values into three groups # all values > 0 and <= 0.25 become 1, etc. m <- c(0, 0.25, 1, 0.25, 0.5, 2, 0.5, 1, 3) rclmat <- matrix(m, ncol=3, byrow=TRUE) rc <- reclassify(r, rclmat) # for values >= 0 (instead of > 0), do rc <- reclassify(r, rclmat, include.lowest=TRUE) # equivalent to rc <- reclassify(r, c(-Inf,0.25,1, 0.25,0.5,2, 0.5,Inf,3))
r <- raster(ncols=36, nrows=18) values(r) <- runif(ncell(r)) # reclassify the values into three groups # all values > 0 and <= 0.25 become 1, etc. m <- c(0, 0.25, 1, 0.25, 0.5, 2, 0.5, 1, 3) rclmat <- matrix(m, ncol=3, byrow=TRUE) rc <- reclassify(r, rclmat) # for values >= 0 (instead of > 0), do rc <- reclassify(r, rclmat, include.lowest=TRUE) # equivalent to rc <- reclassify(r, c(-Inf,0.25,1, 0.25,0.5,2, 0.5,Inf,3))
rectify changes a rotated Raster* object into a non-rotated (rectangular) object. This is wrapper function around resample
.
## S4 method for signature 'Raster' rectify(x, ext, res, method='ngb', filename='', ...)
## S4 method for signature 'Raster' rectify(x, ext, res, method='ngb', filename='', ...)
x |
Raster* object to be rectified |
ext |
Optional. Extent object or object from which an Extent object can be extracted |
res |
Optional. Single or two numbers to set the resolution |
method |
Method used to compute values for the new RasterLayer, should be "bilinear" for bilinear interpolation, or "ngb" for nearest neighbor |
filename |
Character. Output filename |
... |
Additional arguments as for |
RasterLayer or RasterBrick object
You can set values of a Raster* object, when i
is a vector of cell numbers, a Raster*, Extent, or Spatial* object.
These are shorthand methods that work best for relatively small Raster* objects. In other cases you can use functions such as calc and rasterize
.
x[i] <- value
x[i,j] <- value
Arguments: | ||
x |
a Raster* object | |
i |
cell number(s), row number(s), Extent, Spatial* object | |
j |
columns number(s) (only available if i is (are) a row number(s)) | |
value |
new cell value(s) | |
r <- raster(ncol=10, nrow=5) values(r) <- 1:ncell(r) * 2 r[1,] <- 1 r[,1] <- 2 r[1,1] <- 3 s <- stack(r, sqrt(r)) s[s<5] <- NA
r <- raster(ncol=10, nrow=5) values(r) <- 1:ncell(r) * 2 r[1,] <- 1 r[,1] <- 2 r[1,1] <- 3 s <- stack(r, sqrt(r)) s[s<5] <- NA
Resample transfers values between non matching Raster* objects (in terms of origin and resolution). Use projectRaster
if the target has a different coordinate reference system (projection).
Before using resample, you may want to consider using these other functions instead: aggregate
, disaggregate
, crop
, extend
, merge
.
## S4 method for signature 'Raster,Raster' resample(x, y, method="bilinear", filename="", ...)
## S4 method for signature 'Raster,Raster' resample(x, y, method="bilinear", filename="", ...)
x |
Raster* object to be resampled |
y |
Raster* object with parameters that |
method |
method used to compute values for the new RasterLayer, should be |
filename |
character. Output filename (optional) |
... |
Additional arguments as for |
RasterLayer or RasterBrick object
Robert J. Hijmans and Joe Cheng
aggregate
, disaggregate
, crop
, extend
, merge
, projectRaster
r <- raster(nrow=3, ncol=3) values(r) <- 1:ncell(r) s <- raster(nrow=10, ncol=10) s <- resample(r, s, method='bilinear') #par(mfrow=c(1,2)) #plot(r) #plot(s)
r <- raster(nrow=3, ncol=3) values(r) <- 1:ncell(r) s <- raster(nrow=10, ncol=10) s <- resample(r, s, method='bilinear') #par(mfrow=c(1,2)) #plot(r) #plot(s)
Get (or set) the x and/or y resolution of a Raster* object
xres(x) yres(x) res(x) res(x) <- value
xres(x) yres(x) res(x) res(x) <- value
x |
Raster* object |
value |
Resolution (single number or vector of two numbers) |
A single numeric value or two numeric values.
r <- raster(ncol=18, nrow=18) xres(r) yres(r) res(r) res(r) <- 1/120 # set yres differently res(r) <- c(1/120, 1/60)
r <- raster(ncol=18, nrow=18) xres(r) yres(r) res(r) res(r) <- 1/120 # set yres differently res(r) <- c(1/120, 1/60)
Make a Red-Green-Blue object that can be used to create images.
## S4 method for signature 'RasterLayer' RGB(x, filename='', col=rainbow(25), breaks=NULL, alpha=FALSE, colNA='white', zlim=NULL, zlimcol=NULL, ext=NULL, ...)
## S4 method for signature 'RasterLayer' RGB(x, filename='', col=rainbow(25), breaks=NULL, alpha=FALSE, colNA='white', zlim=NULL, zlimcol=NULL, ext=NULL, ...)
x |
RasterLayer |
filename |
character. Output filename (optional) |
col |
A color palette, that is a vector of n contiguous colors generated by functions like rainbow, heat.colors, topo.colors, bpy.colors or one or your own making, perhaps using |
breaks |
numeric. A set of finite numeric breakpoints for the colours: must have one more breakpoint than colour and be in increasing order |
alpha |
If |
colNA |
color for the background ( |
zlim |
vector of lenght 2. Range of values to plot |
zlimcol |
If |
ext |
An |
... |
additional arguments as for |
RasterBrick
r <- raster(system.file("external/test.grd", package="raster")) x <- RGB(r) plot(x, col=gray(0:9/10)) plotRGB(x)
r <- raster(system.file("external/test.grd", package="raster")) x <- RGB(r) plot(x, col=gray(0:9/10)) plotRGB(x)
Rotate a Raster* object that has x coordinates (longitude) from 0 to 360, to standard coordinates between -180 and 180 degrees. Longitude between 0 and 360 is frequently used in global climate models.
## S4 method for signature 'Raster' rotate(x, filename='', ...)
## S4 method for signature 'Raster' rotate(x, filename='', ...)
x |
Raster* object |
filename |
character. Output filename (optional) |
... |
additional arguments as for |
RasterLayer or a RasterBrick object
r <- raster(nrow=18, ncol=36) m <- matrix(1:ncell(r), nrow=18) values(r) <- as.vector(t(m)) extent(r) <- extent(0, 360, -90, 90) rr <- rotate(r)
r <- raster(nrow=18, ncol=36) m <- matrix(1:ncell(r), nrow=18) values(r) <- as.vector(t(m)) extent(r) <- extent(0, 360, -90, 90) rr <- rotate(r)
Do the raster cells have a rotation?
rotated(x)
rotated(x)
x |
A Raster* object |
Logical value
r <- raster() rotated(r)
r <- raster() rotated(r)
These functions take a single RasterLayer argument x
and change its values to integers.
ceiling
returns a RasterLayer with the smallest integers not less than the corresponding values of x.
floor
returns a RasterLayer with the largest integers not greater than the corresponding values of x.
trunc
returns a RasterLayer with the integers formed by truncating the values in x toward 0.
round
returns a RasterLayer with values rounded to the specified number of digits (decimal places; default 0).
see ?base::round
a RasterLayer object
ceiling(x) floor(x) trunc(x, ...) round(x, digits = 0)
a RasterLayer object
integer indicating the precision to be used
additional arguments
r <- raster(ncol=10, nrow=10) values(r) <- runif(ncell(r)) * 10 s <- round(r)
r <- raster(ncol=10, nrow=10) values(r) <- runif(ncell(r)) * 10 s <- round(r)
These functions get the row and/or column number from a cell number of a Raster* object)
colFromCell(object, cell) rowFromCell(object, cell) rowColFromCell(object, cell)
colFromCell(object, cell) rowFromCell(object, cell) rowColFromCell(object, cell)
object |
Raster* object (or a SpatialPixels* or SpatialGrid* object) |
cell |
cell number(s) |
The colFromCell and similar functions accept a single value, or a vector or list of these values, Cell numbers start at 1 in the upper left corner, and increase from left to right, and then from top to bottom. The last cell number equals the number of cells of the Raster* object.
row of column number(s)
r <- raster(ncols=10, nrows=10) colFromCell(r, c(5,15)) rowFromCell(r, c(5,15)) rowColFromCell(r, c(5,15))
r <- raster(ncols=10, nrows=10) colFromCell(r, c(5,15)) rowFromCell(r, c(5,15)) rowColFromCell(r, c(5,15))
Sum values of Raster objects by row or column.
## S4 method for signature 'Raster' rowSums(x, na.rm=FALSE, dims=1L,...) ## S4 method for signature 'Raster' colSums(x, na.rm=FALSE, dims=1L,...)
## S4 method for signature 'Raster' rowSums(x, na.rm=FALSE, dims=1L,...) ## S4 method for signature 'Raster' colSums(x, na.rm=FALSE, dims=1L,...)
x |
Raster* object |
na.rm |
logical. If |
dims |
this argument is ignored |
... |
additional arguments (none implemented) |
vector (if x
is a RasterLayer) or matrix
See cellStats
for summing all cells values
r <- raster(ncols=2, nrows=5) values(r) <- 1:10 as.matrix(r) rowSums(r) colSums(r)
r <- raster(ncols=2, nrows=5) values(r) <- 1:10 as.matrix(r) rowSums(r) colSums(r)
Take a random sample from a range of integer values between 1 and n
. Its purpose is similar to that of sample
, but that function fails when n
is very large.
sampleInt(n, size, replace=FALSE)
sampleInt(n, size, replace=FALSE)
n |
Positive number (integer); the number of items to choose from |
size |
Non-negative integer; the number of items to choose |
replace |
Logical. Should sampling be with replacement? |
vector of integer numbers
sampleInt(1e+12, 10) # this may fail: # sample.int(1e+12, 10) # sample.int(1e+9, 10)
sampleInt(1e+12, 10) # this may fail: # sample.int(1e+12, 10) # sample.int(1e+9, 10)
Take a random sample from the cell values of a Raster* object (without replacement).
## S4 method for signature 'Raster' sampleRandom(x, size, na.rm=TRUE, ext=NULL, cells=FALSE, rowcol=FALSE, xy=FALSE, sp=FALSE, asRaster=FALSE, ...)
## S4 method for signature 'Raster' sampleRandom(x, size, na.rm=TRUE, ext=NULL, cells=FALSE, rowcol=FALSE, xy=FALSE, sp=FALSE, asRaster=FALSE, ...)
x |
Raster* object |
size |
positive integer giving the number of items to choose |
na.rm |
logical. If |
ext |
Extent object. To limit regular sampling to the area within the extent |
cells |
logical. If |
rowcol |
logical. If |
xy |
logical. If |
sp |
logical. If |
asRaster |
logical. If |
... |
Additional arguments as in |
With argument na.rm=TRUE
, the returned sample may be smaller than requested
A vector, matrix (if cells=TRUE
or x
is a multi-layered object), or a SpatialPointsDataFrame (if sp=TRUE
)
sampleRegular, sampleStratified
r <- raster(system.file("external/test.grd", package="raster")) sampleRandom(r, size=10) s <- stack(r, r) sampleRandom(s, size=5, cells=TRUE, sp=TRUE)
r <- raster(system.file("external/test.grd", package="raster")) sampleRandom(r, size=10) s <- stack(r, r) sampleRandom(s, size=5, cells=TRUE, sp=TRUE)
Take a systematic sample from a Raster* object.
## S4 method for signature 'Raster' sampleRegular(x, size, ext=NULL, cells=FALSE, xy=FALSE, asRaster=FALSE, sp=FALSE, ...)
## S4 method for signature 'Raster' sampleRegular(x, size, ext=NULL, cells=FALSE, xy=FALSE, asRaster=FALSE, sp=FALSE, ...)
x |
Raster object |
size |
positive integer giving the number of items to choose. |
ext |
Extent. To limit regular sampling to the area within that box |
cells |
logical. Also return sampled cell numbers (if asRaster=FALSE) |
xy |
logical. If |
asRaster |
logical. If |
sp |
logical. If |
... |
additional arguments. None implemented |
A vector (single layer object), matrix (multi-layered object; or if cells=TRUE
, or xy=TRUE
), Raster* object (if asRaster=TRUE
), or SpatialPointsDataFrame (if sp=TRUE
)
sampleRandom
, sampleStratified
r <- raster(system.file("external/test.grd", package="raster")) v <- sampleRegular(r, size=100) x <- sampleRegular(r, size=100, asRaster=TRUE)
r <- raster(system.file("external/test.grd", package="raster")) v <- sampleRegular(r, size=100) x <- sampleRegular(r, size=100, asRaster=TRUE)
Take a stratified random sample from the cell values of a Raster* object (without replacement). An attempt is made to sample size
cells from each stratum. The values in the RasterLayer x
are rounded to integers; with each value representing a stratum.
## S4 method for signature 'RasterLayer' sampleStratified(x, size, exp=10, na.rm=TRUE, xy=FALSE, ext=NULL, sp=FALSE, ...)
## S4 method for signature 'RasterLayer' sampleStratified(x, size, exp=10, na.rm=TRUE, xy=FALSE, ext=NULL, sp=FALSE, ...)
x |
Raster* object, with values (rounded to integers) representing strata |
size |
positive integer giving the number of items to choose |
exp |
numeric >= 1. 'Expansion factor' that is multiplied with size to get an intial sample. Can be increased when you get an insufficient number of samples for small strata |
na.rm |
logical. If |
xy |
logical. Return coordinates of cells rather than cell numbers |
ext |
Extent object. To limit regular sampling to the area within the extent |
sp |
logical. If |
... |
Additional arguments. None implemented |
The function may not work well when the size (number of cells) of some strata is relatively small.
matrix of cell numbers (and optionally coordinates) by stratum
r <- raster(ncol=10, nrow=10) names(r) <- 'stratum' values(r) <- round((runif(ncell(r))+0.5)*3) sampleStratified(r, size=3)
r <- raster(ncol=10, nrow=10) names(r) <- 'stratum' values(r) <- round((runif(ncell(r))+0.5)*3) sampleStratified(r, size=3)
Center and/or scale raster data
## S4 method for signature 'Raster' scale(x, center=TRUE, scale=TRUE)
## S4 method for signature 'Raster' scale(x, center=TRUE, scale=TRUE)
x |
Raster* object |
center |
logical or numeric. If |
scale |
logical or numeric. If |
Raster* object
b <- brick(system.file("external/rlogo.grd", package="raster")) bs <- scale(b)
b <- brick(system.file("external/rlogo.grd", package="raster")) bs <- scale(b)
Add a scalebar to a plot
scalebar(d, xy = NULL, type = "line", divs = 2, below = "", lonlat = NULL, label, adj=c(0.5, -0.5), lwd = 2, ...)
scalebar(d, xy = NULL, type = "line", divs = 2, below = "", lonlat = NULL, label, adj=c(0.5, -0.5), lwd = 2, ...)
d |
distance covered by scalebar |
xy |
x and y coordinate to place the plot. Can be NULL. Use |
type |
"line" or "bar" |
divs |
Number of divisions for a bar type. 2 or 4 |
below |
Text to go below scalebar (e.g., "kilometers") |
lonlat |
Logical or NULL. If logical, |
adj |
adjustment for text placement |
label |
Vector of three numbers to label the scale bar (beginning, midpoint, end) |
lwd |
line width for the "line" type scalebar |
... |
arguments to be passed to other methods |
None. Use for side effect of a scalebar added to a plot
Robert J. Hijmans; partly based on a function by Josh Gray
f <- system.file("external/test.grd", package="raster") r <- raster(f) plot(r) scalebar(1000) scalebar(1000, xy=c(178000, 333500), type='bar', divs=4)
f <- system.file("external/test.grd", package="raster") r <- raster(f) plot(r) scalebar(1000) scalebar(1000, xy=c(178000, 333500), type='bar', divs=4)
Geometrically subset Raster* or Spatial* objects by drawing on a plot (map).
## S4 method for signature 'Raster' select(x, use='rec', ...) ## S4 method for signature 'Spatial' select(x, use='rec', draw=TRUE, col='cyan', size=2, ...)
## S4 method for signature 'Raster' select(x, use='rec', ...) ## S4 method for signature 'Spatial' select(x, use='rec', draw=TRUE, col='cyan', size=2, ...)
x |
Raster*, SpatialPoints*, SpatialLines*, or SpatialPolygons* |
use |
character: 'rec' or 'pol'. To use a rectangle or a polygon for selecting |
draw |
logical. Add the selected features to the plot? |
col |
color to use to draw the selected features (when |
size |
integer > 0. Size to draw the selected features with (when |
... |
additional arguments. None implemented |
Raster* or Spatial* object
## Not run: # select a subset of a RasterLayer r <- raster(nrow=10, ncol=10) values(r) <- 1:ncell(r) plot(r) s <- select(r) # now click on the map twice # plot the selection on a new canvas: x11() plot(s) # select a subset of a SpatialPolygons object p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20)) hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20)) p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0)) p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0)) pols <- SpatialPolygons( list( Polygons(list(Polygon(p1), Polygon(hole)), 1), Polygons(list(Polygon(p2)), 2), Polygons(list(Polygon(p3)), 3))) pols@polygons[[1]]@Polygons[[2]]@hole <- TRUE plot(pols, col=rainbow(3)) ps <- select(pols) # now click on the map twice ps ## End(Not run)
## Not run: # select a subset of a RasterLayer r <- raster(nrow=10, ncol=10) values(r) <- 1:ncell(r) plot(r) s <- select(r) # now click on the map twice # plot the selection on a new canvas: x11() plot(s) # select a subset of a SpatialPolygons object p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20)) hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20)) p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0)) p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0)) pols <- SpatialPolygons( list( Polygons(list(Polygon(p1), Polygon(hole)), 1), Polygons(list(Polygon(p2)), 2), Polygons(list(Polygon(p3)), 3))) pols@polygons[[1]]@Polygons[[2]]@hole <- TRUE plot(pols, col=rainbow(3)) ps <- select(pols) # now click on the map twice ps ## End(Not run)
setExtent sets the extent of a Raster* object. Either by providing a new Extent object or by setting the extreme coordinates one by one.
setExtent(x, ext, keepres=FALSE, snap=FALSE) extent(x) <- value
setExtent(x, ext, keepres=FALSE, snap=FALSE) extent(x) <- value
x |
A Raster* object |
ext |
An object of class Extent (which you can create with |
keepres |
logical. If |
snap |
logical. If |
value |
An object of class Extent (which you can create with |
a Raster* object
r <- raster() bb <- extent(-10, 10, -20, 20) extent(r) <- bb r <- setExtent(r, bb, keepres=TRUE)
r <- raster() bb <- extent(-10, 10, -20, 20) extent(r) <- bb r <- setExtent(r, bb, keepres=TRUE)
The minimum and maximum value of a RasterLayer are computed (from a file on disk if necessary) and stored in the returned Raster* object.
setMinMax(x, ...)
setMinMax(x, ...)
x |
Raster object |
... |
additional arguments, none implemented |
Raster object
r <- raster(system.file("external/test.grd", package="raster")) r r <- setMinMax(r) r
r <- raster(system.file("external/test.grd", package="raster")) r r <- setMinMax(r) r
Assign (new) values to a Raster* object.
## S4 method for signature 'RasterLayer' setValues(x, values, ...) ## S4 method for signature 'RasterBrick' setValues(x, values, layer=-1, ...) ## S4 method for signature 'RasterStack' setValues(x, values, layer=-1, ...) ## S4 method for signature 'RasterLayerSparse' setValues(x, values, index=NULL, ...) values(x) <- value
## S4 method for signature 'RasterLayer' setValues(x, values, ...) ## S4 method for signature 'RasterBrick' setValues(x, values, layer=-1, ...) ## S4 method for signature 'RasterStack' setValues(x, values, layer=-1, ...) ## S4 method for signature 'RasterLayerSparse' setValues(x, values, index=NULL, ...) values(x) <- value
x |
A |
values |
Cell values to associate with the Raster* object. There should be values for all cells |
value |
Cell values to associate with the Raster* object. There should be values for all cells |
layer |
Layer number (only relevant for RasterBrick and RasterStack objects). If missing, the values of all layers is set |
index |
Cell numbers corresponding to the values |
... |
Additional arguments (none implemented) |
a Raster* object
While you can access the 'values' slot of the objects directly, you would do that at your own peril because when setting values, multiple slots need to be changed; which is what setValues takes care of.
r <- raster(ncol=10, nrow=10) vals <- 1:ncell(r) r <- setValues(r, vals) # equivalent to values(r) <- vals
r <- raster(ncol=10, nrow=10) vals <- 1:ncell(r) r <- setValues(r, vals) # equivalent to values(r) <- vals
Reading and writing of "ESRI shapefile" format spatial data. Only the three vector types (points, lines, and polygons) can be stored in shapefiles.
A shapefile should consist of at least four files: .shp (the geometry), .dbf (the attributes), .shx (the index that links the two, and .prj (the coordinate reference system). If the .prj file is missing, a warning is given. If any other file is missing an error occurs (although one could in principle recover the .shx from the .shp file). Additional files are ignored.
## S4 method for signature 'character' shapefile(x, stringsAsFactors=FALSE, verbose=FALSE, warnPRJ=TRUE, ...) ## S4 method for signature 'Spatial' shapefile(x, filename='', overwrite=FALSE, ...)
## S4 method for signature 'character' shapefile(x, stringsAsFactors=FALSE, verbose=FALSE, warnPRJ=TRUE, ...) ## S4 method for signature 'Spatial' shapefile(x, filename='', overwrite=FALSE, ...)
x |
character (a file name, when reading a shapefile) or Spatial* object (when writing a shapefile) |
filename |
character. Filename to write a shapefile |
overwrite |
logical. Overwrite existing shapefile? |
verbose |
logical. If |
warnPRJ |
logical. If |
stringsAsFactors |
logical. If |
... |
Additional arguments (none) |
Spatial*DataFrame (reading). Nothing is returned when writing a shapefile.
filename <- system.file("external/lux.shp", package="raster") filename p <- shapefile(filename) ## Not run: shapefile(p, 'copy.shp') ## End(Not run)
filename <- system.file("external/lux.shp", package="raster") filename p <- shapefile(filename) ## Not run: shapefile(p, 'copy.shp') ## End(Not run)
Shift the location of a Raster* of vector type Spatial* object in the x and/or y direction
## S4 method for signature 'Raster' shift(x, dx=0, dy=0, filename='', ...) ## S4 method for signature 'SpatialPolygons' shift(x, dx=0, dy=0, ...) ## S4 method for signature 'SpatialLines' shift(x, dx=0, dy=0, ...) ## S4 method for signature 'SpatialPoints' shift(x, dx=0, dy=0, ...)
## S4 method for signature 'Raster' shift(x, dx=0, dy=0, filename='', ...) ## S4 method for signature 'SpatialPolygons' shift(x, dx=0, dy=0, ...) ## S4 method for signature 'SpatialLines' shift(x, dx=0, dy=0, ...) ## S4 method for signature 'SpatialPoints' shift(x, dx=0, dy=0, ...)
x |
Raster* or Spatial* object |
dx |
numeric. The shift in horizontal direction |
dy |
numeric. The shift in vertical direction |
filename |
character file name (optional) |
... |
if |
Same object type as x
flip
, rotate
, and the elide function in the maptools package
r <- raster() r <- shift(r, dx=1, dy=-1)
r <- raster() r <- shift(r, dx=1, dy=-1)
DEPRACATED. Use terrain
instead.
slopeAspect(dem, filename='', out=c('slope', 'aspect'), unit='radians', neighbors=8, flatAspect, ...)
slopeAspect(dem, filename='', out=c('slope', 'aspect'), unit='radians', neighbors=8, flatAspect, ...)
dem |
DEPRACATED |
filename |
DEPRACATED |
out |
DEPRACATED |
unit |
DEPRACATED |
neighbors |
DEPRACATED |
flatAspect |
DEPRACATED |
... |
DEPRACATED |
Helper functions to simplify the creation of SpatialLines* or SpatialPolygons* objects from coordinates.
spLines(x, ..., attr=NULL, crs="") spPolygons(x, ..., attr=NULL, crs="")
spLines(x, ..., attr=NULL, crs="") spPolygons(x, ..., attr=NULL, crs="")
x |
matrix of list with matrices. Each matrix must have two columns with x and y coordinates (or longitude and latitude, in that order). Multi-line or multi-polygon objects can be formed by combining matrices in a list |
... |
additional matrices and/or lists with matrices |
attr |
data.frame with the attributes to create a *DataFrame object. The number of rows must match the number of lines/polgyons |
crs |
the coordinate reference system (PROJ4 or WKT notation) |
SpatialLines* or SpatialPolygons*
x1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60)) x2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) x3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45)) x4 <- rbind(c(41,-41.5), c(51,-35), c(62,-41), c(51,-50)) a <- spLines(x1, x2, x3) b <- spLines(x1, list(x2, x3), attr=data.frame(id=1:2), crs='+proj=longlat +datum=WGS84') b hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-130,10)) d <- spPolygons(list(x1,hole), x2, list(x3, x4)) att <- data.frame(ID=1:3, name=c('a', 'b', 'c')) e <- spPolygons(list(x1,hole), x2, list(x3, x4), attr=att, crs='+proj=longlat +datum=WGS84') e
x1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60)) x2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) x3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45)) x4 <- rbind(c(41,-41.5), c(51,-35), c(62,-41), c(51,-50)) a <- spLines(x1, x2, x3) b <- spLines(x1, list(x2, x3), attr=data.frame(id=1:2), crs='+proj=longlat +datum=WGS84') b hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-130,10)) d <- spPolygons(list(x1,hole), x2, list(x3, x4)) att <- data.frame(ID=1:3, name=c('a', 'b', 'c')) e <- spPolygons(list(x1,hole), x2, list(x3, x4), attr=att, crs='+proj=longlat +datum=WGS84') e
A wrapper function around spplot (sp package). With spplot it is easy to map several layers with a single legend for all maps. ssplot is itself a wrapper around the levelplot function in the lattice package, and see the help for these functions for additional options.
One of the advantages of the wrapper function for Raster* objects is the additional maxpixels
argument to sample large objects for faster drawing.
There are also added spplot methods for Spatial objects that have no data.frame and for SpatVector (terra package)
## S4 method for signature 'Raster' spplot(obj, ..., maxpixels=50000, as.table=TRUE, zlim)
## S4 method for signature 'Raster' spplot(obj, ..., maxpixels=50000, as.table=TRUE, zlim)
obj |
Raster* object |
... |
|
maxpixels |
integer. Number of pixels to sample from each layer of large Raster objects |
as.table |
If |
zlim |
Vector of two elements indicating the minimum and maximum values to be mapped (values outside that ranage are set to these limits) |
The rasterVis package has more advanced plotting methods for Raster objects
r <- raster(system.file("external/test.grd", package="raster")) s <- stack(r, r*2) names(s) <- c('meuse', 'meuse x 2') spplot(s) pts <- data.frame(sampleRandom(r, 10, xy=TRUE)) coordinates(pts) <- ~ x + y spplot(s, scales = list(draw = TRUE), xlab = "easting", ylab = "northing", col.regions = rainbow(99, start=.1), names.attr=c('original', 'times two'), sp.layout = list("sp.points", pts, pch=20, cex=2, col='black'), par.settings = list(fontsize = list(text = 12)), at = seq(0, 4000, 500))
r <- raster(system.file("external/test.grd", package="raster")) s <- stack(r, r*2) names(s) <- c('meuse', 'meuse x 2') spplot(s) pts <- data.frame(sampleRandom(r, 10, xy=TRUE)) coordinates(pts) <- ~ x + y spplot(s, scales = list(draw = TRUE), xlab = "easting", ylab = "northing", col.regions = rainbow(99, start=.1), names.attr=c('original', 'times two'), sp.layout = list("sp.points", pts, pch=20, cex=2, col='black'), par.settings = list(fontsize = list(text = 12)), at = seq(0, 4000, 500))
A RasterStack is a collection of RasterLayer objects with the same spatial extent and resolution. A RasterStack can be created from RasterLayer objects, or from raster files, or both. It can also be created from a SpatialPixelsDataFrame or a SpatialGridDataFrame object.
## S4 method for signature 'character' stack(x, ..., bands=NULL, varname="", native=FALSE, RAT=TRUE, quick=FALSE) ## S4 method for signature 'Raster' stack(x, ..., layers=NULL) ## S4 method for signature 'missing' stack(x) ## S4 method for signature 'list' stack(x, bands=NULL, native=FALSE, RAT=TRUE, ...)
## S4 method for signature 'character' stack(x, ..., bands=NULL, varname="", native=FALSE, RAT=TRUE, quick=FALSE) ## S4 method for signature 'Raster' stack(x, ..., layers=NULL) ## S4 method for signature 'missing' stack(x) ## S4 method for signature 'list' stack(x, bands=NULL, native=FALSE, RAT=TRUE, ...)
x |
filename (character), Raster* object, missing (to create an empty RasterStack), SpatialGrid*, SpatialPixels*, or list (of filenames and/or Raster* objects). If |
bands |
integer. which bands (layers) of the file should be used (default is all layers) |
layers |
integer (or character with layer names) indicating which layers of a RasterBrick should be used (default is all layers) |
native |
logical. If |
RAT |
logical. If |
quick |
logical. If |
varname |
character. To select the variable of interest in a NetCDF file (see |
... |
additional filenames or Raster* objects |
RasterStack
addLayer, dropLayer, raster, brick
# file with one layer fn <- system.file("external/test.grd", package="raster") s <- stack(fn, fn) r <- raster(fn) s <- stack(r, fn) nlayers(s) # file with three layers slogo <- stack(system.file("external/rlogo.grd", package="raster")) nlayers(slogo) slogo
# file with one layer fn <- system.file("external/test.grd", package="raster") s <- stack(fn, fn) r <- raster(fn) s <- stack(r, fn) nlayers(s) # file with three layers slogo <- stack(system.file("external/rlogo.grd", package="raster")) nlayers(slogo) slogo
Apply a function on subsets of a RasterStack or RasterBrick. The layers to be combined are indicated with the vector indices
.
The function used should return a single value, and the number of layers in the output Raster* equals the number of unique values in indices
.
For example, if you have a RasterStack with 6 layers, you can use indices=c(1,1,1,2,2,2)
and fun=sum
. This will return a RasterBrick with two layers. The first layer is the sum of the first three layers in the input RasterStack, and the second layer is the sum of the last three layers in the input RasterStack. Indices are recycled such that indices=c(1,2)
would also return a RasterBrick with two layers (one based on the odd layers (1,3,5), the other based on the even layers (2,4,6)).
See calc
if you want to use a more efficient function that returns multiple layers based on _all_ layers in the Raster* object.
stackApply(x, indices, fun, filename='', na.rm=TRUE, ...)
stackApply(x, indices, fun, filename='', na.rm=TRUE, ...)
x |
Raster* object |
indices |
integer. Vector of length |
fun |
function that returns a single value, e.g. |
na.rm |
logical. If |
filename |
character. Optional output filename |
... |
additional arguments as for |
A new Raster* object, and in some cases the side effect of a new file on disk.
r <- raster(ncol=10, nrow=10) values(r) <- 1:ncell(r) s <- brick(r,r,r,r,r,r) s <- s * 1:6 b1 <- stackApply(s, indices=c(1,1,1,2,2,2), fun=sum) b1 b2 <- stackApply(s, indices=c(1,2,3,1,2,3), fun=sum) b2
r <- raster(ncol=10, nrow=10) values(r) <- 1:ncell(r) s <- brick(r,r,r,r,r,r) s <- s * 1:6 b1 <- stackApply(s, indices=c(1,1,1,2,2,2), fun=sum) b1 b2 <- stackApply(s, indices=c(1,2,3,1,2,3), fun=sum) b2
A RasterStack is a collection of RasterLayers with the same spatial extent and resolution. They can be created from RasterLayer objects, or from file names. These two functions allow you to save the references to raster files and recreate a rasterStack object later. They only work if the RasterStack points to layers that have their values on disk. The values are not saved, only the references to the files.
stackOpen(stackfile) stackSave(x, filename)
stackOpen(stackfile) stackSave(x, filename)
stackfile |
Filename for the RasterStack (to save it on disk) |
x |
RasterStack object |
filename |
File name |
When a RasterStack is saved to a file, only pointers (filenames) to raster datasets are saved, not the data. If the name or location of a raster file changes, the RasterStack becomes invalid.
RasterStack object
file <- system.file("external/test.grd", package="raster") s <- stack(c(file, file)) ## Not run: s <- stackSave(s, "mystack") # note that filename adds an extension .stk to a stackfile s2 <- stackOpen("mystack.stk") s2 ## End(Not run)
file <- system.file("external/test.grd", package="raster") s <- stack(c(file, file)) ## Not run: s <- stackSave(s, "mystack") # note that filename adds an extension .stk to a stackfile s2 <- stackOpen("mystack.stk") s2 ## End(Not run)
Use a Raster* object to select cell values from different layers in a multi-layer Raster* object. The object to select values y
should have values between 1
and nlayers(x)
. The values of y
are rounded.
See extract
for extraction of values by cell, point, or otherwise.
## S4 method for signature 'RasterStackBrick,Raster' stackSelect(x, y, recycle=FALSE, type='index', filename='', ...)
## S4 method for signature 'RasterStackBrick,Raster' stackSelect(x, y, recycle=FALSE, type='index', filename='', ...)
x |
RasterStack or RasterBrick object |
y |
Raster* object |
recycle |
Logical. Recursively select values (default = |
type |
Character. Only relevant when |
filename |
Character. Output filename (optional) |
... |
Additional arguments as for |
Raster* object
r <- raster(ncol=10, nrow=10, vals=1) s <- stack(r, r+2, r+5) values(r) <- round((runif(ncell(r)))*3) x <- stackSelect(s, r)
r <- raster(ncol=10, nrow=10, vals=1) s <- stack(r, r+2, r+5) values(r) <- round((runif(ncell(r)))*3) x <- stackSelect(s, r)
Linear stretch of values in a Raster object. Provide the desired output range (minv and maxv) and the lower and upper bounds in the original data, either as quantiles (if minq=0
and maxq=1
you use the minimum and maximum cell values), or as actual values (smin
and smax
; e.g. precomputed quantile values). If smin
and smax
are both not NA
, minq
and maxq
are ignored.
## S4 method for signature 'Raster' stretch(x, minv=0, maxv=255, minq=0, maxq=1, smin=NA, smax=NA, samplesize=1000000, filename='', ...)
## S4 method for signature 'Raster' stretch(x, minv=0, maxv=255, minq=0, maxq=1, smin=NA, smax=NA, samplesize=1000000, filename='', ...)
x |
Raster object |
minv |
numeric >= 0 and smaller than maxv. lower bound of stretched value |
maxv |
numeric <= 255 and larger than maxv. upper bound of stretched value |
minq |
numeric >= 0 and smaller than maxq. lower quantile bound of original value. Ignored if smin is supplied |
maxq |
numeric <= 1 and larger than minq. upper quantile bound of original value. Ignored if smax is supplied |
smin |
numeric < smax. user supplied lower value for the layers, to be used instead of a quantile computed by the function itself |
smax |
numeric > smin. user supplied upper value for the layers, to be used instead of a quantile computed by the function itself |
samplesize |
numeric > 1. If samplesize < ncell(x), a regular sample of samplesize is taken from x to compute the quantiles (to speed things up) |
filename |
character. Filename for the output Raster object (optional) |
... |
additional arguments as for |
Raster
stretch argument in plotRGB
r <- raster(nc=10, nr=10) values(r) <- rep(1:2, 50) stretch(r) s <- stack(r, r*2) stretch(s)
r <- raster(nc=10, nr=10) values(r) <- rep(1:2, 50) stretch(r) s <- stack(r, r*2) stretch(s)
Extract a set of layers from a RasterStack or RasterBrick object.
## S4 method for signature 'Raster' subset(x, subset, drop=TRUE, filename='', ...) ## S4 method for signature 'RasterStack' subset(x, subset, drop=TRUE, filename='', ...)
## S4 method for signature 'Raster' subset(x, subset, drop=TRUE, filename='', ...) ## S4 method for signature 'RasterStack' subset(x, subset, drop=TRUE, filename='', ...)
x |
RasterBrick or RasterStack object |
subset |
integer or character. Should indicate the layers (represented as integer or by their name) |
drop |
If |
filename |
character. Output filename (optional) |
... |
additional arguments as for |
Raster* object
s <- stack(system.file("external/rlogo.grd", package="raster")) sel <- subset(s, 2:3) # Note that this is equivalent to sel2 <- s[[2:3]] # and in this particular case: sel3 <- dropLayer(s, 1) nlayers(s) nlayers(sel) # effect of 'drop=FALSE' when selecting a single layer sel <- subset(s, 2) class(sel) sel <- subset(s, 2, drop=FALSE) class(sel)
s <- stack(system.file("external/rlogo.grd", package="raster")) sel <- subset(s, 2:3) # Note that this is equivalent to sel2 <- s[[2:3]] # and in this particular case: sel3 <- dropLayer(s, 1) nlayers(s) nlayers(sel) # effect of 'drop=FALSE' when selecting a single layer sel <- subset(s, 2) class(sel) sel <- subset(s, 2, drop=FALSE) class(sel)
Substitute (replace) values in a Raster* object with values in a data.frame
. The data.frame
should have a column to identify the key (ID) to match with the cell values of the Raster* object, and one or more columns with replacement values. By default these are the first and second column but you can specify other columns with arguments by
and which
. It is possible to match one table to multiple layers, or to use multiple layers as a single key, but not both.
## S4 method for signature 'Raster,data.frame' subs(x, y, by=1, which=2, subsWithNA=TRUE, filename='', ...)
## S4 method for signature 'Raster,data.frame' subs(x, y, by=1, which=2, subsWithNA=TRUE, filename='', ...)
x |
Raster* object |
y |
data.frame |
by |
column number(s) or name(s) identifying the key (ID) to match rows in data.frame |
which |
column number or name that has the new (replacement) values |
subsWithNA |
logical. If |
filename |
character. Optional output filename |
... |
additional arguments as for |
You could obtain the same result with reclassify
, but subs
is more efficient for simple replacement. Use reclassify
if you want to replace ranges of values with new values.
You can also replace values using a fitted model. E.g. fit a model to glm
or loess
and then call predict
Raster object
r <- raster(ncol=10, nrow=10) values(r) <- round(runif(ncell(r)) * 10) df <- data.frame(id=2:8, v=c(10,10,11,11,12:14)) x <- subs(r, df) x2 <- subs(r, df, subsWithNA=FALSE) df$v2 <- df$v * 10 x3 <- subs(r, df, which=2:3) s <- stack(r, r*3) names(s) <- c('first', 'second') x4 <- subs(s, df) x5 <- subs(s, df, which=2:3)
r <- raster(ncol=10, nrow=10) values(r) <- round(runif(ncell(r)) * 10) df <- data.frame(id=2:8, v=c(10,10,11,11,12:14)) x <- subs(r, df) x2 <- subs(r, df, subsWithNA=FALSE) df$v2 <- df$v * 10 x3 <- subs(r, df, which=2:3) s <- stack(r, r*3) names(s) <- c('first', 'second') x4 <- subs(s, df) x5 <- subs(s, df, which=2:3)
Summarize a Raster* object. A sample is used for very large files.
## S4 method for signature 'RasterLayer' summary(object, maxsamp=100000, ...)
## S4 method for signature 'RasterLayer' summary(object, maxsamp=100000, ...)
object |
Raster* object |
maxsamp |
positive integer. Sample size used for large datasets |
... |
additional arguments. None implemented |
matrix with (an estimate of) the median, minimum and maximum values, the first and third quartiles, and the number of cells with NA
values
cellStats, link[raster]{quantile}
The following summary methods are available for Raster* objects:
mean, median, max, min, range, prod, sum, any, all
All methods take na.rm
as an additional logical argument. Default is na.rm=FALSE
. If TRUE
, NA
values are removed from calculations.
These methods compute a summary statistic based on cell values of RasterLayers and the result of these methods is always a single RasterLayer (except for range, which returns a RasterBrick with two layers). See calc
for functions not included here (e.g. median) or any other custom functions.
You can mix RasterLayer, RasterStack and RasterBrick objects with single numeric or logical values. However, because generic functions are used, the method applied is chosen based on the first argument: 'x
'. This means that if r
is a RasterLayer object, mean(r, 5)
will work, but mean(5, r)
will not work.
To summarize all cells within a single RasterLayer, see cellStats
and maxValue
and minValue
a RasterLayer
r1 <- raster(nrow=10, ncol=10) r1 <- setValues(r1, runif(ncell(r1))) r2 <- setValues(r1, runif(ncell(r1))) r3 <- setValues(r1, runif(ncell(r1))) r <- max(r1, r2, r3) r <- range(r1, r2, r3, 1.2) s <- stack(r1, r2, r3) r <- mean(s, 2)
r1 <- raster(nrow=10, ncol=10) r1 <- setValues(r1, runif(ncell(r1))) r2 <- setValues(r1, runif(ncell(r1))) r3 <- setValues(r1, runif(ncell(r1))) r <- max(r1, r2, r3) r <- range(r1, r2, r3, 1.2) s <- stack(r1, r2, r3) r <- mean(s, 2)
Symetrical difference of SpatialPolygons* objects
## S4 method for signature 'SpatialPolygons,SpatialPolygons' symdif(x, y, ...)
## S4 method for signature 'SpatialPolygons,SpatialPolygons' symdif(x, y, ...)
x |
SpatialPolygons* object |
y |
SpatialPolygons* object |
... |
Additional SpatialPolygons* object(s) |
SpatialPolygons*
#SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(p) sd <- symdif(p, b) plot(sd, col='red')
#SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(p) sd <- symdif(p, b) plot(sd, col='red')
Compute slope, aspect and other terrain characteristics from a raster with elevation data. The elevation data should be in map units (typically meter) for projected (planar) raster data. They should be in meters when the coordinate reference system (CRS) is longitude/latitude.
## S4 method for signature 'RasterLayer' terrain(x, opt="slope", unit="radians", neighbors=8, filename="", ...)
## S4 method for signature 'RasterLayer' terrain(x, opt="slope", unit="radians", neighbors=8, filename="", ...)
x |
RasterLayer object with elevation values. Values should have the same unit as the map units, or in meters when the crs is longitude/latitude |
opt |
Character vector containing one or more of these options: slope, aspect, TPI, TRI, roughness, flowdir (see Details) |
unit |
Character. 'degrees', 'radians' or 'tangent'. Only relevant for slope and aspect. If 'tangent' is selected that is used for slope, but for aspect 'degrees' is used (as 'tangent' has no meaning for aspect) |
neighbors |
Integer. Indicating how many neighboring cells to use to compute slope for any cell. Either 8 (queen case) or 4 (rook case). Only used for slope and aspect, see Details |
filename |
Character. Output filename (optional) |
... |
Standard additional arguments for writing Raster* objects to file |
When neighbors=4
, slope and aspect are computed according to Fleming and Hoffer (1979) and Ritter (1987). When neigbors=8
, slope and aspect are computed according to Horn (1981). The Horn algorithm may be best for rough surfaces, and the Fleming and Hoffer algorithm may be better for smoother surfaces (Jones, 1997; Burrough and McDonnell, 1998).
If slope = 0, aspect is set to 0.5*pi radians (or 90 degrees if unit='degrees'). When computing slope or aspect, the CRS (projection
) of the RasterLayer x
must be known (may not be NA
), to be able to safely differentiate between planar and longitude/latitude data.
flowdir returns the 'flow direction' (of water), i.e. the direction of the greatest drop in elevation (or the smallest rise if all neighbors are higher). They are encoded as powers of 2 (0 to 7). The cell to the right of the focal cell 'x' is 1, the one below that is 2, and so on:
32 | 64 | 128 |
16 | x | 1 |
8 | 4 | 2 |
If two cells have the same drop in elevation, a random cell is picked. That is not ideal as it may prevent the creation of connected flow networks. ArcGIS implements the approach of Greenlee (1987) and I might adopt that in the future.
The terrain indices are according to Wilson et al. (2007). TRI (Terrain Ruggedness Index) is the mean of the absolute differences between the value of a cell and the value of its 8 surrounding cells. TPI (Topographic Position Index) is the difference between the value of a cell and the mean value of its 8 surrounding cells. Roughness is the difference between the maximum and the minimum value of a cell and its 8 surrounding cells.
Such measures can also be computed with the focal
function:
f <- matrix(1, nrow=3, ncol=3)
TRI <- focal(x, w=f, fun=function(x, ...) sum(abs(x[-5]-x[5]))/8, pad=TRUE, padValue=NA)
TPI <- focal(x, w=f, fun=function(x, ...) x[5] - mean(x[-5]), pad=TRUE, padValue=NA)
rough <- focal(x, w=f, fun=function(x, ...) max(x) - min(x), pad=TRUE, padValue=NA, na.rm=TRUE)
Burrough, P., and R.A. McDonnell, 1998. Principles of Geographical Information Systems. Oxford University Press.
Fleming, M.D. and Hoffer, R.M., 1979. Machine processing of landsat MSS data and DMA topographic data for forest cover type mapping. LARS Technical Report 062879. Laboratory for Applications of Remote Sensing, Purdue University, West Lafayette, Indiana.
Greenlee, D.D., 1987. Raster and vector processing for scanned linework. Photogrammetric Engineering and Remote Sensing 53:1383-1387
Horn, B.K.P., 1981. Hill shading and the reflectance map. Proceedings of the IEEE 69:14-47
Jones, K.H., 1998. A comparison of algorithms used to compute hill slope as a property of the DEM. Computers & Geosciences 24: 315-323
Ritter, P., 1987. A vector-based slope and aspect generation algorithm. Photogrammetric Engineering and Remote Sensing 53: 1109-1111
Wilson, M.F.J., O'Connell, B., Brown, C., Guinan, J.C., Grehan, A.J., 2007. Multiscale terrain analysis of multibeam bathymetry data for habitat mapping on the continental slope. Marine Geodesy 30: 3-35.
Plots labels, that is a textual (rather than color) representation of values, on top an existing plot (map).
## S4 method for signature 'RasterLayer' text(x, labels, digits=0, fun=NULL, halo=FALSE, ...) ## S4 method for signature 'RasterStackBrick' text(x, labels, digits=0, fun=NULL, halo=FALSE, ...) ## S4 method for signature 'SpatialPolygons' text(x, labels, halo=FALSE, ...) ## S4 method for signature 'SpatialPoints' text(x, labels, halo=FALSE, ...)
## S4 method for signature 'RasterLayer' text(x, labels, digits=0, fun=NULL, halo=FALSE, ...) ## S4 method for signature 'RasterStackBrick' text(x, labels, digits=0, fun=NULL, halo=FALSE, ...) ## S4 method for signature 'SpatialPolygons' text(x, labels, halo=FALSE, ...) ## S4 method for signature 'SpatialPoints' text(x, labels, halo=FALSE, ...)
x |
Raster*, SpatialPoints* or SpatialPolygons* object |
labels |
character. Optional. Vector of labels with |
digits |
integer. how many digits should be used? |
fun |
function to subset the values plotted (as in |
halo |
logical. If |
... |
additional arguments to pass to graphics function |
r <- raster(nrows=4, ncols=4) r <- setValues(r, 1:ncell(r)) plot(r) text(r) plot(r) text(r, halo=TRUE, hc='blue', col='white', hw=0.2) plot(r, col=bpy.colors(5)) text(r, fun=function(x){x<5 | x>12}, col=c('red', 'white'), vfont=c("sans serif", "bold"), cex=2)
r <- raster(nrows=4, ncols=4) r <- setValues(r, 1:ncell(r)) plot(r) text(r) plot(r) text(r, halo=TRUE, hc='blue', col='white', hw=0.2) plot(r, col=bpy.colors(5)) text(r, fun=function(x){x<5 | x>12}, col=c('red', 'white'), vfont=c("sans serif", "bold"), cex=2)
Trim (shrink) a Raster* object by removing outer rows and columns that all have the same value (e.g. NA).
Or remove the whitespace before or after a string of characters (or a matrix, or the character values in a data.frame).
## S4 method for signature 'Raster' trim(x, padding=0, values=NA, filename='', ...) ## S4 method for signature 'character' trim(x, internal=FALSE, ...)
## S4 method for signature 'Raster' trim(x, padding=0, values=NA, filename='', ...) ## S4 method for signature 'character' trim(x, internal=FALSE, ...)
x |
Raster* object or a character string |
values |
numeric. Value(s) based on which a Raster* should be trimmed |
padding |
integer. Number of outer rows/columns to keep |
filename |
character. Optional output filename |
internal |
logical. If |
... |
If |
A RasterLayer or RasterBrick object (if x
is a Raster* object) or a character string (if x
is a character string).
Robert J. Hijmans and Jacob van Etten
r <- raster(ncol=18,nrow=18) r[39:49] <- 1 r[113:155] <- 2 r[200] <- 6 s <- trim(r) trim(" hi folks ! ")
r <- raster(ncol=18,nrow=18) r[39:49] <- 1 r[113:155] <- 2 r[200] <- 6 s <- trim(r) trim(" hi folks ! ")
Extent objects: Objects are combined into their union. See crop
and extend
to union a Raster object with an Extent object.
Two SpatialPolygons* objects. Overlapping polygons (between layers, not within layers) are intersected, other spatial objects are appended. Tabular attributes are joined. See bind
if you want to combine polygons without intersection.
Single SpatialPolygons* object. Overlapping polygons are intersected. Original attributes are lost. New attributes allow for determining how many, and which, polygons overlapped.
Union for SpatialLines and SpatialPoints simply combines the two data sets; without any geometric intersections. This is equivalent to bind
.
## S4 method for signature 'Extent,Extent' union(x, y) ## S4 method for signature 'SpatialPolygons,SpatialPolygons' union(x, y) ## S4 method for signature 'SpatialPolygons,missing' union(x, y) ## S4 method for signature 'SpatialLines,SpatialLines' union(x, y) ## S4 method for signature 'SpatialPoints,SpatialPoints' union(x, y)
## S4 method for signature 'Extent,Extent' union(x, y) ## S4 method for signature 'SpatialPolygons,SpatialPolygons' union(x, y) ## S4 method for signature 'SpatialPolygons,missing' union(x, y) ## S4 method for signature 'SpatialLines,SpatialLines' union(x, y) ## S4 method for signature 'SpatialPoints,SpatialPoints' union(x, y)
x |
Extent or SpatialPolygons* object |
y |
Same as |
Extent or SpatialPolygons object
merge
for merging a data.frame with attributes of Spatial objects
and +,SpatialPolygons,SpatialPolygons-method
for an algebraic notation
e1 <- extent(-10, 10, -20, 20) e2 <- extent(0, 20, -40, 5) union(e1, e2) #SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) p0 <- aggregate(p) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(p) u <- union(p0, b) plot(u, col=2:4)
e1 <- extent(-10, 10, -20, 20) e2 <- extent(0, 20, -40, 5) union(e1, e2) #SpatialPolygons p <- shapefile(system.file("external/lux.shp", package="raster")) p0 <- aggregate(p) b <- as(extent(6, 6.4, 49.75, 50), 'SpatialPolygons') crs(b) <- crs(p) u <- union(p0, b) plot(u, col=2:4)
This function returns the unique values in a RasterLayer object or the unique combinations of the layers in a multilayer object.
## S4 method for signature 'RasterLayer,missing' unique(x, incomparables=FALSE, na.last=NA, progress="", ...) ## S4 method for signature 'RasterStackBrick,missing' unique(x, incomparables=FALSE, na.last=NA, progress="", ...)
## S4 method for signature 'RasterLayer,missing' unique(x, incomparables=FALSE, na.last=NA, progress="", ...) ## S4 method for signature 'RasterStackBrick,missing' unique(x, incomparables=FALSE, na.last=NA, progress="", ...)
x |
Raster object |
incomparables |
must be missing. The default value |
na.last |
logical. for controlling the treatment of |
progress |
character. Use "text" or "window" for a progress indicator |
... |
additional arguments. as in |
vector or matrix
r <- raster(ncol=10, nrow=10) values(r) <- round(runif(ncell(r))*10) unique(r) unique(stack(r, round(r/2)))
r <- raster(ncol=10, nrow=10) values(r) <- round(runif(ncell(r))*10) unique(r) unique(stack(r, round(r/2)))
Create a list of RasterLayer objects from a RasterStack or RasterBrick
unstack(x, ...)
unstack(x, ...)
x |
a RasterStack object |
... |
not used. further arguments passed to or from other methods |
A list of RasterLayer objects
file <- system.file("external/test.grd", package="raster") s <- stack(file, file) list1 <- unstack(s) b <- brick(s) list2 <- unstack(b)
file <- system.file("external/test.grd", package="raster") s <- stack(file, file) list1 <- unstack(s) b <- brick(s) list2 <- unstack(b)
Update cell values of a file (i.e., cell values on disk) associated with a RasterLayer or RasterBrick.
User beware: this function _will_ make changes to your file (first make a copy if you are not sure what you are doing).
Writing starts at a cell number cell
. You can write a vector of values (in cell order), or a matrix. You can also provide a vector of cell numbers (of the same length as vector v
) to update individual cells.
See writeFormats
for supported formats.
## S4 method for signature 'RasterLayer' update(object, v, cell, ...) ## S4 method for signature 'RasterBrick' update(object, v, cell, band, ...)
## S4 method for signature 'RasterLayer' update(object, v, cell, ...) ## S4 method for signature 'RasterBrick' update(object, v, cell, band, ...)
object |
RasterLayer or RasterBrick that is associated with a file |
v |
vector or matrix with new values |
cell |
cell from where to start writing. Or a vector of cell numbers if v is a vector of the same length |
.
band |
band (layer) to update (for RasterBrick objects) |
.
... |
additional arguments. None implemented |
RasterLayer or RasterBrick
## Not run: # setting up an example RasterLayer with file r <- raster(nrow=5, ncol=10, vals=0) r <- writeRaster(r, rasterTmpFile(), overwrite=TRUE, datatype='INT2S') as.matrix(r) # update with a vector starting a cell r <- update(r, v=rep(1, 5), cell=6) # 99.99 gets rounded because this is an integer file r <- update(r, v=9.99, cell=50) as.matrix(r) # update with a vector of values and matching vector of cell numbers r <- update(r, v=5:1, cell=c(5,15,25,35,45)) as.matrix(r) # updating with a marix, anchored at a cell number m <- matrix(1:10, ncol=2) r <- update(r, v=m, cell=2) as.matrix(r) ## End(Not run)
## Not run: # setting up an example RasterLayer with file r <- raster(nrow=5, ncol=10, vals=0) r <- writeRaster(r, rasterTmpFile(), overwrite=TRUE, datatype='INT2S') as.matrix(r) # update with a vector starting a cell r <- update(r, v=rep(1, 5), cell=6) # 99.99 gets rounded because this is an integer file r <- update(r, v=9.99, cell=50) as.matrix(r) # update with a vector of values and matching vector of cell numbers r <- update(r, v=5:1, cell=c(5,15,25,35,45)) as.matrix(r) # updating with a marix, anchored at a cell number m <- matrix(1:10, ncol=2) r <- update(r, v=m, cell=2) as.matrix(r) ## End(Not run)
Simple helper functions to determine if a row, column or cell number is valid for a certain Raster* object
validCell(object, cell) validCol(object, colnr) validRow(object, rownr)
validCell(object, cell) validCol(object, colnr) validRow(object, rownr)
object |
Raster* object (or a SpatialPixels* or SpatialGrid* object) |
cell |
cell number(s) |
colnr |
column number; or vector of column numbers |
rownr |
row number; or vector of row numbers |
logical value
#using a new default raster (1 degree global) r <- raster() validCell(r, c(-1, 0, 1)) validRow(r, c(-1, 1, 100, 10000))
#using a new default raster (1 degree global) r <- raster() validCell(r, c(-1, 0, 1)) validRow(r, c(-1, 1, 100, 10000))
Create a set of valid names (trimmed, no duplicates, not starting with a number).
validNames(x, prefix='layer')
validNames(x, prefix='layer')
x |
character |
prefix |
character string used if x is empty |
character
validNames(c('a', 'a', '', '1', NA, 'b', 'a'))
validNames(c('a', 'a', '', '1', NA, 'b', 'a'))
Computes the weighted mean for each cell of a number or raster layers. The weights can be spatially variable or not.
## S4 method for signature 'RasterStackBrick,vector' weighted.mean(x, w, na.rm=FALSE, filename='', ...) ## S4 method for signature 'RasterStackBrick,RasterStackBrick' weighted.mean(x, w, na.rm=FALSE,filename='', ...)
## S4 method for signature 'RasterStackBrick,vector' weighted.mean(x, w, na.rm=FALSE, filename='', ...) ## S4 method for signature 'RasterStackBrick,RasterStackBrick' weighted.mean(x, w, na.rm=FALSE,filename='', ...)
x |
RasterStack or RasterBrick |
w |
A vector of weights (one number for each layer), or for spatially variable weights, a RasterStack or RasterBrick with weights (should have the same extent, resolution and number of layers as x) |
na.rm |
Logical. Should missing values be removed? |
filename |
Character. Output filename (optional) |
... |
Additional arguments as for |
RasterLayer
Summary-methods
, weighted.mean
b <- brick(system.file("external/rlogo.grd", package="raster")) # give least weight to first layer, most to last layer wm1 <- weighted.mean(b, w=1:3) # spatially varying weights # weigh by column number w1 <- init(b, v='col') # weigh by row number w2 <- init(b, v='row') w <- stack(w1, w2, w2) wm2 <- weighted.mean(b, w=w)
b <- brick(system.file("external/rlogo.grd", package="raster")) # give least weight to first layer, most to last layer wm1 <- weighted.mean(b, w=1:3) # spatially varying weights # weigh by column number w1 <- init(b, v='col') # weigh by row number w2 <- init(b, v='row') w <- stack(w1, w2, w2) wm2 <- weighted.mean(b, w=w)
Which
returns a RasterLayer with TRUE
or FALSE
setting cells that are NA
to FALSE
(unless na.rm=FALSE
). If the RasterLayer has numbers, all values that are 0 become FALSE
and all other values become TRUE
. The function can also return the cell numbers that are TRUE
## S4 method for signature 'RasterLayer' Which(x, cells=FALSE, na.rm=TRUE, ...)
## S4 method for signature 'RasterLayer' Which(x, cells=FALSE, na.rm=TRUE, ...)
x |
RasterLayer |
cells |
logical. If |
na.rm |
logical. If |
... |
Additional arguments (none implemented) |
RasterLayer
r <- raster(ncol=10, nrow=10) set.seed(0) values(r) <- runif(ncell(r)) r[r < 0.2 ] <- 0 r[r > 0.8] <- 1 r[r > 0 & r < 1 ] <- 0.5 Which(r, cells=TRUE) Which(r > 0.5, cells=TRUE) s1 <- r > 0.5 s2 <- Which(r > 0.5) s1[1:15] s2[1:15] # this expression x1 <- Which(r, na.rm=FALSE) # is the inverse of x2 <- r==0
r <- raster(ncol=10, nrow=10) set.seed(0) values(r) <- runif(ncell(r)) r[r < 0.2 ] <- 0 r[r > 0.8] <- 1 r[r > 0 & r < 1 ] <- 0.5 Which(r, cells=TRUE) Which(r > 0.5, cells=TRUE) s1 <- r > 0.5 s2 <- Which(r > 0.5) s1[1:15] s2[1:15] # this expression x1 <- Which(r, na.rm=FALSE) # is the inverse of x2 <- r==0
Which cells have the minumum / maximum value (for a RasterLayer), or which layer has the minimum/maximum value (for a RasterStack or RasterBrick)?
which.min and which.max return the index of the first layer that has the min or max value for a cell. This can be problematic if there are ties.
In you want the index of all the layers that have the min or max value, use whiches.min or whiches.max (only for objects with less than 10 layers).
which.min(x) which.max(x) whiches.min(x, ...) whiches.max(x, ...)
which.min(x) which.max(x) whiches.min(x, ...) whiches.max(x, ...)
x |
Raster* object |
... |
additional arguments (none implemented) |
(which.*): vector of cell numbers (if x
is a RasterLayer). If x
is a RasterStack or RasterBrick, a RasterLayer giving the number of the first layer with the minimum or maximum value for a cell.
(whiches.*). An integer in which each digit represents a layer. For example, 35 means "layers 3 and 5"
There is a limit to accurate integer number representation. Therefore, do not use whiches.*
with more than 15 layers.
b <- brick(system.file("external/rlogo.grd", package="raster")) r <- which.min(b) i <- which.min(b[[3]]) xy <- xyFromCell(b, i) plot(b[[3]]) points(xy) x <- whiches.min(b) freq(x)
b <- brick(system.file("external/rlogo.grd", package="raster")) r <- which.min(b) i <- which.min(b[[3]]) xy <- xyFromCell(b, i) plot(b[[3]]) points(xy) x <- whiches.min(b) freq(x)
List supported file types for writing RasterLayer values to disk.
When a function writes a file to disk, the file format is determined by the 'format=' argument if supplied, or else by the file extension (if the extension is known). If other cases the default format is used. The 'factory-fresh' default format is 'raster', but this can be changed using rasterOptions
.
writeFormats()
writeFormats()
writeFormats returns a matrix of the file formats (the "drivers") that are supported.
Supported formats include:
File type | Long name | default extension | Multiband support | |
raster |
'Native' raster package format | .grd | Yes | |
ascii |
ESRI Ascii | .asc | No | |
SAGA |
SAGA GIS | .sdat | No | |
IDRISI |
IDRISI | .rst | No | |
CDF |
netCDF (requires ncdf4) | .nc | Yes | |
GTiff |
GeoTiff | .tif | Yes | |
ENVI |
ENVI .hdr Labelled | .envi | Yes | |
EHdr |
ESRI .hdr Labelled | .bil | Yes | |
HFA |
Erdas Imagine Images (.img) | .img | Yes | |
writeFormats()
writeFormats()
Write an entire Raster* object to a file, using one of the many supported formats. See writeValues
for writing in chunks (e.g. by row).
When writing a file to disk, the file format is determined by the 'format=' argument if supplied, or else by the file extension (if the extension is known). If other cases the default format is used. The default format is 'raster', but this setting can be changed (see rasterOptions
).
## S4 method for signature 'RasterLayer,character' writeRaster(x, filename, format, ...) ## S4 method for signature 'RasterStackBrick,character' writeRaster(x, filename, format, bylayer, suffix='numbers', ...)
## S4 method for signature 'RasterLayer,character' writeRaster(x, filename, format, ...) ## S4 method for signature 'RasterStackBrick,character' writeRaster(x, filename, format, bylayer, suffix='numbers', ...)
x |
Raster* object |
filename |
Output filename |
format |
Character. Output file type. See |
... |
Additional arguments:
You can use options=c("PROFILE=BASELINE") to create a plain tif with no GeoTIFF tags. This can be useful when writing files to be read by applications intolerant of unrecognised tags. NetCDF files have the following additional, optional, arguments:
|
bylayer |
if |
suffix |
'numbers' or 'names' to determine the suffix that each file gets when |
See writeFormats
for supported file types ("formats", "drivers").
In multi-layer files (i.e. files saved from RasterStack or RasterBrick objects), in the native 'raster' format, the band-order can be set to BIL ('Bands Interleaved by Line'), BIP ('Bands Interleaved by Pixels') or BSQ ('Bands SeQuential'). Note that bandorder is not the same as filetype here.
Supported file types include:
File type | Long name | default extension | Multiband support | |
raster |
'Native' raster package format | .grd | Yes | |
ascii |
ESRI Ascii | .asc | No | |
SAGA |
SAGA GIS | .sdat | No | |
IDRISI |
IDRISI | .rst | No | |
CDF |
netCDF (requires ncdf4) | .nc | Yes | |
GTiff |
GeoTiff | .tif | Yes | |
ENVI |
ENVI .hdr Labelled | .envi | Yes | |
EHdr |
ESRI .hdr Labelled | .bil | Yes | |
HFA |
Erdas Imagine Images (.img) | .img | Yes | |
This function is used for the side-effect of writing values to a file.
tmp <- tempdir() r <- raster(system.file("external/test.grd", package="raster")) # take a small part r <- crop(r, extent(179880, 180800, 329880, 330840) ) # write to an integer binary file rf <- writeRaster(r, filename=file.path(tmp, "allint.grd"), datatype='INT4S', overwrite=TRUE) # make a brick and save multi-layer file b <- brick(r, sqrt(r)) bf <- writeRaster(b, filename=file.path(tmp, "multi.grd"), bandorder='BIL', overwrite=TRUE) # write to a new geotiff file rf <- writeRaster(r, filename=file.path(tmp, "test.tif"), format="GTiff", overwrite=TRUE) bf <- writeRaster(b, filename=file.path(tmp, "multi.tif"), options="INTERLEAVE=BAND", overwrite=TRUE) # write to netcdf if (require(ncdf4)) { rnc <- writeRaster(r, filename=file.path(tmp, "netCDF.nc"), format="CDF", overwrite=TRUE) }
tmp <- tempdir() r <- raster(system.file("external/test.grd", package="raster")) # take a small part r <- crop(r, extent(179880, 180800, 329880, 330840) ) # write to an integer binary file rf <- writeRaster(r, filename=file.path(tmp, "allint.grd"), datatype='INT4S', overwrite=TRUE) # make a brick and save multi-layer file b <- brick(r, sqrt(r)) bf <- writeRaster(b, filename=file.path(tmp, "multi.grd"), bandorder='BIL', overwrite=TRUE) # write to a new geotiff file rf <- writeRaster(r, filename=file.path(tmp, "test.tif"), format="GTiff", overwrite=TRUE) bf <- writeRaster(b, filename=file.path(tmp, "multi.tif"), options="INTERLEAVE=BAND", overwrite=TRUE) # write to netcdf if (require(ncdf4)) { rnc <- writeRaster(r, filename=file.path(tmp, "netCDF.nc"), format="CDF", overwrite=TRUE) }
Functions for writing blocks (>= 1 row(s)) of values to files. Writing has to start at the first cell of a row (identified with argument start
) and the values written must represent 1 or more entire rows. Begin by opening a file with writeStart
, then write values to it in chunks. When writing is done close the file with writeStop
.
If you want to write all values of a Raster* object at once, you can also use writeRaster
which is easier to use but more limited. The functions described here allow writing values to file using chunks of different sizes (e.g. 1 or 10 rows). Function blockSize
can be used to suggest a chunk size to use.
## S4 method for signature 'RasterLayer,character' writeStart(x, filename, options=NULL, format, prj=FALSE, ...) ## S4 method for signature 'RasterBrick,character' writeStart(x, filename, options=NULL, format, prj=FALSE, ...) ## S4 method for signature 'RasterLayer,vector' writeValues(x, v, start, ...) ## S4 method for signature 'RasterBrick,matrix' writeValues(x, v, start, ...) ## S4 method for signature 'RasterLayer' writeStop(x) ## S4 method for signature 'RasterBrick' writeStop(x)
## S4 method for signature 'RasterLayer,character' writeStart(x, filename, options=NULL, format, prj=FALSE, ...) ## S4 method for signature 'RasterBrick,character' writeStart(x, filename, options=NULL, format, prj=FALSE, ...) ## S4 method for signature 'RasterLayer,vector' writeValues(x, v, start, ...) ## S4 method for signature 'RasterBrick,matrix' writeValues(x, v, start, ...) ## S4 method for signature 'RasterLayer' writeStop(x) ## S4 method for signature 'RasterBrick' writeStop(x)
x |
Raster* object |
filename |
character. Output file name |
options |
character, see |
format |
character, see |
prj |
logical. If |
... |
additional arguments as for |
v |
vector (RasterLayer) or matrix (RasterBrick) of values |
start |
Integer. Row number (counting starts at 1) from where to start writing |
RasterLayer or RasterBrick
writeRaster, blockSize, update
## Not run: r <- raster(system.file("external/test.grd", package="raster")) # write to a new binary file in chunks s <- raster(r) # tr <- blockSize(r) tr s <- writeStart(s, filename='test.grd', overwrite=TRUE) for (i in 1:tr$n) { v <- getValuesBlock(r, row=tr$row[i], nrows=tr$nrows[i]) s <- writeValues(s, v, tr$row[i]) } s <- writeStop(s) s2 <- writeStart(s, filename='test2.tif', format='GTiff', overwrite=TRUE) # writing last row first for (i in tr$n:1) { v <- getValuesBlock(r, row=tr$row[i], nrows=tr$nrows[i]) s2 <- writeValues(s2, v, tr$row[i]) } # row number 5 once more v <- getValuesBlock(r, row=5, nrows=1) writeValues(s2, v, 5) s2 <- writeStop(s2) ## write values of a RasterStack to a RasterBrick s <- stack(system.file("external/rlogo.grd", package="raster")) # create empty brick b <- brick(s, values=FALSE) b <- writeStart(b, filename="test.grd", format="raster",overwrite=TRUE) tr <- blockSize(b) for (i in 1:tr$n) { v <- getValuesBlock(s, row=tr$row[i], nrows=tr$nrows[i]) b <- writeValues(b, v, tr$row[i]) } b <- writeStop(b) # note that the above is equivalent to # b <- writeRaster(s, filename="test.grd", format="raster",overwrite=TRUE) ## End(Not run)
## Not run: r <- raster(system.file("external/test.grd", package="raster")) # write to a new binary file in chunks s <- raster(r) # tr <- blockSize(r) tr s <- writeStart(s, filename='test.grd', overwrite=TRUE) for (i in 1:tr$n) { v <- getValuesBlock(r, row=tr$row[i], nrows=tr$nrows[i]) s <- writeValues(s, v, tr$row[i]) } s <- writeStop(s) s2 <- writeStart(s, filename='test2.tif', format='GTiff', overwrite=TRUE) # writing last row first for (i in tr$n:1) { v <- getValuesBlock(r, row=tr$row[i], nrows=tr$nrows[i]) s2 <- writeValues(s2, v, tr$row[i]) } # row number 5 once more v <- getValuesBlock(r, row=5, nrows=1) writeValues(s2, v, 5) s2 <- writeStop(s2) ## write values of a RasterStack to a RasterBrick s <- stack(system.file("external/rlogo.grd", package="raster")) # create empty brick b <- brick(s, values=FALSE) b <- writeStart(b, filename="test.grd", format="raster",overwrite=TRUE) tr <- blockSize(b) for (i in 1:tr$n) { v <- getValuesBlock(s, row=tr$row[i], nrows=tr$nrows[i]) b <- writeValues(b, v, tr$row[i]) } b <- writeStop(b) # note that the above is equivalent to # b <- writeRaster(s, filename="test.grd", format="raster",overwrite=TRUE) ## End(Not run)
These functions get coordinates of the center of raster cells for a row, column, or cell number of a Raster* object.
## S4 method for signature 'Raster,numeric' xFromCol(object, col) ## S4 method for signature 'Raster,numeric' yFromRow(object, row) ## S4 method for signature 'Raster,numeric' xFromCell(object, cell) ## S4 method for signature 'Raster,numeric' yFromCell(object, cell) ## S4 method for signature 'BasicRaster,ANY' xyFromCell(object, cell, spatial=FALSE, ...) ## S4 method for signature 'Raster' coordinates(obj, ...) ## S4 method for signature 'Extent' coordinates(obj, ...)
## S4 method for signature 'Raster,numeric' xFromCol(object, col) ## S4 method for signature 'Raster,numeric' yFromRow(object, row) ## S4 method for signature 'Raster,numeric' xFromCell(object, cell) ## S4 method for signature 'Raster,numeric' yFromCell(object, cell) ## S4 method for signature 'BasicRaster,ANY' xyFromCell(object, cell, spatial=FALSE, ...) ## S4 method for signature 'Raster' coordinates(obj, ...) ## S4 method for signature 'Extent' coordinates(obj, ...)
object |
Raster* object (or a SpatialPixels* or SpatialGrid* object) |
col |
column number; or vector of column numbers. If missing, the x coordinates for all columns are returned |
row |
row number; or vector of row numbers. If missing, the y coordinates for all rows are returned |
cell |
cell number(s) |
spatial |
If |
... |
additional arguments. None implemented |
obj |
Raster object |
Cell numbers start at 1 in the upper left corner, and increase from left to right, and then from top to bottom. The last cell number equals the number of cells of the Raster* object.
xFromCol, yFromCol, xFromCell, yFromCell: vector of x or y coordinates
xyFromCell: matrix(x,y) with coordinate pairs
coordinates: xy coordinates for all cells
#using a new default raster (1 degree global) r <- raster() xFromCol(r, c(1, 120, 180)) yFromRow(r, 90) xyFromCell(r, 10000) xyFromCell(r, c(0, 1, 32581, ncell(r), ncell(r)+1)) #using a file from disk r <- raster(system.file("external/test.grd", package="raster")) r cellFromXY(r, c(180000, 330000)) #xy for corners of a raster: xyFromCell(r, c(1, ncol(r), ncell(r)-ncol(r)+1, ncell(r)))
#using a new default raster (1 degree global) r <- raster() xFromCol(r, c(1, 120, 180)) yFromRow(r, 90) xyFromCell(r, 10000) xyFromCell(r, c(0, 1, 32581, ncell(r), ncell(r)+1)) #using a file from disk r <- raster(system.file("external/test.grd", package="raster")) r cellFromXY(r, c(180000, 330000)) #xy for corners of a raster: xyFromCell(r, c(1, ncol(r), ncell(r)-ncol(r)+1, ncell(r)))
Initial functions for a somewhat more formal approach to get or set z values (e.g. time) associated with layers of Raster* objects. In development.
setZ(x, z, name='time') getZ(x)
setZ(x, z, name='time') getZ(x)
x |
Raster* object |
z |
vector of z values of any type (e.g. of class 'Date') |
name |
character label |
setZ: Raster* object
getZ: vector
r <- raster(ncol=10, nrow=10) s <- stack(lapply(1:3, function(x) setValues(r, runif(ncell(r))))) s <- setZ(s, as.Date('2000-1-1') + 0:2) s getZ(s)
r <- raster(ncol=10, nrow=10) s <- stack(lapply(1:3, function(x) setValues(r, runif(ncell(r))))) s <- setZ(s, as.Date('2000-1-1') + 0:2) s getZ(s)
Experimental function to apply a function over a (time) series of layers of a Raster object
zApply(x, by, fun=mean, name='', ...)
zApply(x, by, fun=mean, name='', ...)
x |
Raster* object |
by |
aggregation indices or function |
fun |
function to compute aggregated values |
name |
character label of the new time series |
... |
additional arguments |
Raster* object
Oscar Perpinan Lamigueiro & Robert J. Hijmans
# 12 values of irradiation, 1 for each month G0dm=c(2.766,3.491,4.494,5.912,6.989,7.742,7.919,7.027,5.369,3.562,2.814,2.179)*1000; # RasterBrick with 12 layers based on G0dm + noise r <- raster(nc=10, nr=10) s <- brick(lapply(1:12, function(x) setValues(r, G0dm[x]+100*rnorm(ncell(r)) ))) # time tm <- seq(as.Date('2010-01-15'), as.Date('2010-12-15'), 'month') s <- setZ(s, tm, 'months') # library(zoo) # x <- zApply(s, by=as.yearqtr, fun=mean, name='quarters')
# 12 values of irradiation, 1 for each month G0dm=c(2.766,3.491,4.494,5.912,6.989,7.742,7.919,7.027,5.369,3.562,2.814,2.179)*1000; # RasterBrick with 12 layers based on G0dm + noise r <- raster(nc=10, nr=10) s <- brick(lapply(1:12, function(x) setValues(r, G0dm[x]+100*rnorm(ncell(r)) ))) # time tm <- seq(as.Date('2010-01-15'), as.Date('2010-12-15'), 'month') s <- setZ(s, tm, 'months') # library(zoo) # x <- zApply(s, by=as.yearqtr, fun=mean, name='quarters')
Compute zonal statistics, that is summarized values of a Raster* object for each "zone" defined by a RasterLayer.
If stat
is a true function
, zonal
will fail (gracefully) for very large Raster objects, but it will in most cases work for functions that can be defined as by a character argument ('mean', 'sd', 'min', 'max', or 'sum'). In addition you can use 'count' to count the number of cells in each zone (only useful with na.rm=TRUE
, otherwise freq(z)
would be more direct.
If a function is used, it should accept a na.rm
argument (or at least a ...
argument)
## S4 method for signature 'RasterLayer,RasterLayer' zonal(x, z, fun='mean', digits=0, na.rm=TRUE, ...) ## S4 method for signature 'RasterStackBrick,RasterLayer' zonal(x, z, fun='mean', digits=0, na.rm=TRUE, ...)
## S4 method for signature 'RasterLayer,RasterLayer' zonal(x, z, fun='mean', digits=0, na.rm=TRUE, ...) ## S4 method for signature 'RasterStackBrick,RasterLayer' zonal(x, z, fun='mean', digits=0, na.rm=TRUE, ...)
x |
Raster* object |
z |
RasterLayer with codes representing zones |
fun |
function to be applied to summarize the values by zone. Either as character: 'mean', 'sd', 'min', 'max', 'sum'; or, for relatively small Raster* objects, a proper function |
digits |
integer. Number of digits to maintain in 'zones'. By default averaged to an integer (zero digits) |
na.rm |
logical. If |
... |
additional arguments. One implemented: |
A matrix with a value for each zone (unique value in zones
)
See cellStats
for 'global' statistics (i.e., all of x
is considered a single zone), and extract
for summarizing values for polygons
r <- raster(ncols=10, nrows=10) values(r) <- runif(ncell(r)) * 1:ncell(r) z <- r values(z) <- rep(1:5, each=20) # for large files, use a character value rather than a function zonal(r, z, 'sum') # for smaller files you can also provide a function ## Not run: zonal(r, z, mean) zonal(r, z, min) ## End(Not run) # multiple layers zonal(stack(r, r*10), z, 'sum')
r <- raster(ncols=10, nrows=10) values(r) <- runif(ncell(r)) * 1:ncell(r) z <- r values(z) <- rep(1:5, each=20) # for large files, use a character value rather than a function zonal(r, z, 'sum') # for smaller files you can also provide a function ## Not run: zonal(r, z, mean) zonal(r, z, min) ## End(Not run) # multiple layers zonal(stack(r, r*10), z, 'sum')
Zoom in on a map (plot) by providing a new extent, by default this is done by clicking twice on the map.
zoom(x, ...) ## S4 method for signature 'Raster' zoom(x, ext=drawExtent(), maxpixels=100000, layer=1, new=TRUE, useRaster=TRUE, ...) ## S4 method for signature 'Spatial' zoom(x, ext=drawExtent(), new=TRUE, ...) ## S4 method for signature 'missing' zoom(x, ext=drawExtent(), new=TRUE, ...)
zoom(x, ...) ## S4 method for signature 'Raster' zoom(x, ext=drawExtent(), maxpixels=100000, layer=1, new=TRUE, useRaster=TRUE, ...) ## S4 method for signature 'Spatial' zoom(x, ext=drawExtent(), new=TRUE, ...) ## S4 method for signature 'missing' zoom(x, ext=drawExtent(), new=TRUE, ...)
x |
Raster* or Spatial* (vector type) object |
ext |
Extent object, or other object from which an extent can be extracted |
maxpixels |
Maximum number of pixels used for the map |
layer |
Positive integer to select the layer to be used if x is a mutilayer Raster object |
new |
Logical. If |
useRaster |
Logical. If |
... |
additional paramters for base plot |
Extent object (invisibly)