| Version: | 2.2-0 |
| Title: | Classes and Methods for Spatial Data |
| Depends: | R (≥ 3.5.0), methods |
| Imports: | utils, stats, graphics, grDevices, lattice, grid |
| Suggests: | RColorBrewer, gstat, deldir, knitr, maps, mapview, rmarkdown,sf, terra, raster |
| Description: | Classes and methods for spatial data; the classes document where the spatial location information resides, for 2D or 3D data. Utility functions are provided, e.g. for plotting data as maps, spatial selection, as well as methods for retrieving coordinates, for subsetting, print, summary, etc. From this version, 'rgdal', 'maptools', and 'rgeos' are no longer used at all, seehttps://r-spatial.org/r/2023/05/15/evolution4.html for details. |
| License: | GPL-2 |GPL-3 [expanded from: GPL (≥ 2)] |
| URL: | https://github.com/edzer/sp/https://edzer.github.io/sp/ |
| BugReports: | https://github.com/edzer/sp/issues |
| Collate: | bpy.colors.R AAA.R Class-CRS.R CRS-methods.R Class-Spatial.RSpatial-methods.R projected.R Class-SpatialPoints.RSpatialPoints-methods.R Class-SpatialPointsDataFrame.RSpatialPointsDataFrame-methods.R Class-SpatialMultiPoints.RSpatialMultiPoints-methods.RClass-SpatialMultiPointsDataFrame.RSpatialMultiPointsDataFrame-methods.R Class-GridTopology.RClass-SpatialGrid.R Class-SpatialGridDataFrame.RClass-SpatialLines.R SpatialLines-methods.RClass-SpatialLinesDataFrame.R SpatialLinesDataFrame-methods.RClass-SpatialPolygons.R Class-SpatialPolygonsDataFrame.RSpatialPolygons-methods.R SpatialPolygonsDataFrame-methods.RGridTopology-methods.R SpatialGrid-methods.RSpatialGridDataFrame-methods.R SpatialPolygons-internals.Rpoint.in.polygon.R SpatialPolygons-displayMethods.R zerodist.Rimage.R stack.R bubble.R mapasp.R select.spatial.R gridded.Rasciigrid.R spplot.R over.R spsample.R recenter.R dms.Rgridlines.R spdists.R rbind.R flipSGDF.R chfids.R loadmeuse.RcompassRose.R surfaceArea.R spOptions.R subset.R disaggregate.Rsp_spat1.R merge.R aggregate.R elide.R sp2Mondrian.R |
| VignetteBuilder: | knitr |
| NeedsCompilation: | yes |
| Packaged: | 2025-01-30 11:06:55 UTC; edzer |
| Author: | Edzer Pebesma [aut, cre], Roger Bivand [aut], Barry Rowlingson [ctb], Virgilio Gomez-Rubio [ctb], Robert Hijmans [ctb], Michael Sumner [ctb], Don MacQueen [ctb], Jim Lemon [ctb], Finn Lindgren [ctb], Josh O'Brien [ctb], Joseph O'Rourke [ctb], Patrick Hausmann [ctb] |
| Maintainer: | Edzer Pebesma <edzer.pebesma@uni-muenster.de> |
| Repository: | CRAN |
| Date/Publication: | 2025-02-01 09:40:02 UTC |
Class "CRS" of coordinate reference system arguments
Description
Interface class to the PROJ projection and transformation system. The class is defined as an empty stub accepting value NA in the sp package. The initiation function may call the PROJ library throughsf to verify the argument set against those known in the library, returning error messages where necessary. If the"CRS" object is instantiated usingCRS() withsf using PROJ >= 6 and GDAL >= 3, the object may also have a WKT2 (2019) string carried as acomment. The arguments for a Proj.4 string must be entered exactly as in the Proj.4 documentation, in particular there cannot be any white space in+<key>=<value> strings, and successive such strings can only be separated by blanks. Note that only “+proj=longlat +ellps=WGS84” is accepted for geographical coordinates, which must be ordered (eastings, northings); the “+ellps=” definition must be given (or expanded internally from a given “+datum=” value) for recent versions of the Proj.4 library, and should be set to an appropriate value.
Usage
CRS(projargs, doCheckCRSArgs=TRUE, SRS_string=NULL, get_source_if_boundcrs=TRUE, use_cache=TRUE)identicalCRS(x,y)Arguments
projargs | A character string of projection arguments; the arguments must be entered exactly as in the PROJ.4 documentation; if the projection is unknown, use |
doCheckCRSArgs | default TRUE |
SRS_string | default NULL, only used whensf is built with PROJ >= 6 and GDAL >= 3; a valid WKT string or SRS definition such as |
get_source_if_boundcrs | (fromrgdal 1.5-17, default TRUE) The presence of the |
use_cache | default TRUE, if FALSE ignore cached lookup values |
x | object having aproj4string method,or if |
y | object of classSpatial, or having aproj4string method |
Value
CRS returns on success an object of classCRS.identicalCRS returns a logical, indicatingwhetherx andy have identical CRS, or ifyis missing whether all objects in listxhave identical CRS.
Objects from the Class
Objects can be created by calls of the formCRS("projargs"), where "projargs" is a valid string of PROJ.4 arguments. If the argument is a zero-length string or a characterNA, the object recordsNA. If the"CRS" object is instantiated usingCRS() withsf using PROJ >= 6 and GDAL >= 3, the object may also have a WKT2 (2019) string carried as acomment. The initiation function may call the PROJ library throughsf to verify the argument set against those known in the library, returning error messages where necessary.
Slots
projargs:Object of class
"character": projection arguments; the arguments must be entered exactly as in the PROJ.4 documentation, in particular there cannot be any white space in +<arg>=<value> strings, and successive such strings can only be separated by blanks.
Methods
- show
signature(object = "CRS"): print deprecated Proj.4 projection arguments and WKT2 2019 representation if available- wkt
signature(object = "CRS"): return WKT comment on object- rebuild_CRS
rebuild a CRS object, usually used to add a WKT comment with PROJ >= 6 and GDAL >= 3
Note
Lists of projections may be seen by using the programs installed with the PROJ.4 library, in particular proj and cs2cs; with the latter, -lp lists projections, -le ellipsoids, -lu units, and -ld datum(s) known to the installed software (available insf usingsf_proj_info). These are added to in successive releases, so tracking the website or compiling and installing the most recent revisions will give the greatest choice. Finding the very important datum transformation parameters to be given with the +towgs84 tag is a further challenge, and is essential when the datums used in data to be used together differ. Tracing projection arguments is easier now than before the mass ownership of GPS receivers raised the issue of matching coordinates from different argument sets (GPS output and paper map, for example). SeeGridsDatums,sf_proj_info for help in finding CRS definitions.
The 4.9.1 release of the PROJ library omitted a small file of defaults, leading to reports of “major axis or radius = 0 or not given” errors. From 0.9-3, rgdal checks for the presence of this file (proj_def.dat), and if not found, and under similar conditions to those used by PROJ.4, adds “+ellps=WGS84” to the input string being checked bycheckCRSArgs The “+no_defs” tag ignores the file of defaults, and the default work-around implemented to get around this problem; strings including “init” and “datum” tags also trigger the avoidance of the work-around. Now messages are issued when a candidate CRS is checked; they may be suppressed usingsuppressMessages.
From release 6 of the PROJ library, when used in buildingsf with GDAL >= 3, the+datum= key in the Proj.4 string CRS representation is deprecated, and the+towgs84= and+nadgrids= keys may be deprecated soon. For this reason,sp andsf are starting to use WKT2 (2019) string representations. Insp, the"CRS" object in itself remains unchanged, but the content of its"projargs" slot may be degraded. To work around the degradation, acomment is added around the"CRS" object containing a WKT2 (2019) string whensf is available and built with PROJ >= 6 and GDAL >=3.
Author(s)
Roger BivandRoger.Bivand@nhh.no
References
Examples
CRS()CRS("")CRS(as.character(NA))CRS("+proj=longlat +datum=WGS84")run <- FALSErun <- require(sf) if (run) { print((CRS("+proj=longlat +datum=NAD27")))}if (run) { print((CRS("+init=epsg:4267")))}if (run) { print((CRS("+init=epsg:26978")))}if (run) { print((CRS(paste("+proj=sterea +lat_0=52.15616055555555", "+lon_0=5.38763888888889 +k=0.999908 +x_0=155000 +y_0=463000 +ellps=bessel", " +towgs84=565.237,50.0087,465.658,-0.406857,0.350733,-1.87035,4.0812 +units=m"))))}if (run) { print((CRS("+init=epsg:28992")))}if (run) { print((CRS("EPSG:28992")))}if (run) { print((CRS(SRS_string="EPSG:28992")))}if (run) { o <- try(CRS(SRS_string="ESRI:102760")) if (!inherits(o, "try-error")) print((o))}if (run) { o <- try(CRS("EPSG:4326")) if (!inherits(o, "try-error")) print((o))}if (run) { o <- try(CRS("ESRI:102760")) if (!inherits(o, "try-error")) print((o))}if (run) {o <- new("Spatial")proj4string(o) <- CRS("+init=epsg:27700")}if (run && !is.null(comment(slot(o, "proj4string")))) { cat(wkt(o), sep="\n") cat(wkt(slot(o, "proj4string")), sep="\n")}Class "DMS" for degree, minute, decimal second values
Description
The class provides a container for coordinates stored as degree, minute, decimal second values.
Objects from the Class
Objects can be created by calls of the formnew("DMS", ...), converted from decimal degrees usingdd2dms(), or converted from character strings usingchar2dms().
Slots
WS:Object of class
"logical"TRUE if input value negativedeg:Object of class
"numeric"degreesmin:Object of class
"numeric"minutessec:Object of class
"numeric"decimal secondsNS:Object of class
"logical"TRUE if input value is a Northing
Methods
- coerce
signature(from = "DMS", to = "numeric"): convert to decimal degrees- show
signature(object = "DMS"): print data values
Author(s)
Roger BivandRoger.Bivand@nhh.no
See Also
Examples
data(state)dd2dms(state.center$x)dd2dms(state.center$y, NS=TRUE)as.numeric(dd2dms(state.center$y))as(dd2dms(state.center$y, NS=TRUE), "numeric")as.numeric.DMS(dd2dms(state.center$y))state.center$yClass "GridTopology"
Description
class for defining a rectangular grid ofarbitrary dimension
Objects from the Class
Objects are created by using e.g.
GridTopology(c(0,0), c(1,1), c(5,5))
seeSpatialGrid
Slots
cellcentre.offset:numeric; vector with the smallest centroid coordinates foreach dimension; coordinates refer to the cell centre
cellsize:numeric; vector with the cell size in each dimension
cells.dim:integer; vector with number of cells in each dimension
Methods
- coordinates
signature(x = "SpatialGrid"): calculates coordinates foreach point on the grid- summary
signature(object = "SpatialGrid"): summarize object- coerce
signature(from = "GridTopology", to = "data.frame"): convert to data.frame with columns cellcentre.offset, cellsize and cells.dim
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
SpatialGridDataFrame-class,SpatialGrid-class
Examples
x = GridTopology(c(0,0), c(1,1), c(5,5))class(x)xsummary(x)coordinates(x)y = SpatialGrid(grid = x)class(y)yGrids and Datums PE&RS listing
Description
A data.frame of years and months of Grids & Datums column publications by country and country code.
Usage
data("GridsDatums")Format
A data frame with 241 observations on the following 4 variables.
countryname of PE&RS column
monthissue month
yearpublication year
ISOISO code for country
Details
The journalPhotogrammetric Engineering & Remote Sensing, run by the American Society for Photogrammetry and Remote Sensing (ASPRS), began publishing a more-or-less monthly column on the spatial reference systems used in different countries, including their datums. The column first appeared in September 1997, and continued until March 2016; subsequent columns are updated reprints of previous ones. Some also cover other topics, such as world and Martian spatial reference systems. They are written by Clifford J. Mugnier, Louisiana State University, Fellow Emeritus ASPRS. To access the columns, visithttps:\/\/www.asprs.org/asprs-publications/grids-and-datums.
Source
https:\/\/www.asprs.org/asprs-publications/grids-and-datums
Examples
data(GridsDatums)GridsDatums[grep("Norway", GridsDatums$country),]GridsDatums[grep("Google", GridsDatums$country),]GridsDatums[grep("^Mars$", GridsDatums$country),]create objects of class Line or Lines
Description
create objects of classLine orLines from coordinates
Usage
Line(coords)Lines(slinelist, ID)Arguments
coords | 2-column numeric matrix with coordinates for a single line |
slinelist | list with elements of classLine-class |
ID | a single word unique character identifier, character vector of length one |
Value
Line returns an object of classLine-class;Lines returns an object of classLines-class
See Also
Examples
# from the sp vignette:l1 = cbind(c(1,2,3),c(3,2,2))l1a = cbind(l1[,1]+.05,l1[,2]+.05)l2 = cbind(c(1,2,3),c(1,1.5,1))Sl1 = Line(l1)Sl1a = Line(l1a)Sl2 = Line(l2)S1 = Lines(list(Sl1, Sl1a),)S2 = Lines(list(Sl2),)Class "Line"
Description
class for line objects
Objects from the Class
Objects can be created by calls of the formnew("Line", ...),or (preferred) by calls to the functionLine
Slots
coords:Object of class
"matrix", containing theline coordinates
Methods
- coordinates
signature(obj = "Line"): retrieve coordinatesfrom line- lines
signature(x = "Line"): add lines to a plot
Author(s)
Roger Bivand, Edzer Pebesma
See Also
Lines-class,SpatialLines-class
Class "Lines"
Description
class for sets of line objects
Arguments
SL,Lines | an Lines object |
Objects from the Class
Objects can be created by calls to the functionLine
Slots
Lines:Object of class
"list", containing elementsof classLine-classID:"character"vector of length one, with unique identifier string
Methods
- coordinates
signature(obj = "Line"): retrieve coordinatesfrom lines; returns list with matrices- lines
signature(x = "Line"): add lines to a plot
Author(s)
Roger Bivand, Edzer Pebesma
See Also
Lines-class,SpatialLines-class
Class "Polygon"
Description
class for spatial polygon
Objects from the Class
Objects can be created by calls to the functionPolygon
Slots
ringDir:Object of class
"integer"; the ring direction of the ring (polygon) coordinates, holes are expected to be anti-clockwiselabpt:Object of class
"numeric"; an x, y coordinate pair forming the label point of the polygonarea:Object of class
"numeric"; the planar area of the polygon, does not respect projection as objects of this class have no projection definedhole:Object of class
"logical"; does the polygon seem to be a holecoords:Object of class
"matrix"; coordinates of the polygon;first point should equal the last point
Extends
Class"Line", directly.
Methods
No methods defined with class "Polygon" in the signature.
Author(s)
Roger Bivand
See Also
Polygons-class,SpatialPolygons-class
Class "Polygons"
Description
Collection of objects of class"Polygon"
Objects from the Class
Objects can be created by calls to the functionPolygons
Slots
Polygons:Object of class
"list"; list with objectsof classPolygon-classplotOrder:Object of class
"integer"; order in whichthe Polygon objects should be plotted, currently by order of decreasing sizelabpt:Object of class
"numeric"; pair of x, y coordinates giving a label point, the label point of the largest polygon componentID:Object of class
"character"; unique identifier stringarea:Object of class
"numeric"; the gross total planar area of the Polygon list but not double-counting holes (changed from 0.9-58 - islands are summed, holes are ignored rather than subtracted); these values are used to make sure that polygons of a smaller area are plotted after polygons of a larger area, does not respect projection as objects of this class have no projection defined
Methods
No methods defined with class "Polygons" in the signature.
Note
By default, single polygons (where Polygons is a list of length one) are not expected to be holes, but in multiple polygons, hole definitions for member polygons can be set. Polygon objects belonging to an Polygons object should either not overlap one-other, or should be fully included (as lakes or islands in lakes). They should not be self-intersecting. Checking of hole FALSE/TRUE status for Polygons objects is now handled by round-trip coercion tosf and back tosp.
Author(s)
Roger Bivand
Rlogo jpeg image
Description
Rlogo jpeg image data as imported bygetRasterData in the rgdal package
Usage
data(Rlogo)Format
The format is:int [1:101, 1:77, 1:3] 255 255 255 255 255 255 255 255 255 255 ...
Examples
data(Rlogo)d = dim(Rlogo)cellsize = abs(c(gt[2],gt[6]))cells.dim = c(d[1], d[2]) # c(d[2],d[1])cellcentre.offset = c(x = gt[1] + 0.5 * cellsize[1], y = gt[4] - (d[2] - 0.5) * abs(cellsize[2]))grid = GridTopology(cellcentre.offset, cellsize, cells.dim)df = as.vector(Rlogo[,,1])for (band in 2:d[3]) df = cbind(df, as.vector(Rlogo[,,band]))df = as.data.frame(df)names(df) = paste("band", 1:d[3], sep="")Rlogo <- SpatialGridDataFrame(grid = grid, data = df)summary(Rlogo)spplot(Rlogo, zcol=1:3, names.attr=c("red","green","blue"), col.regions=grey(0:100/100),main="example of three-layer (RGB) raster image", as.table=TRUE)Class "Spatial"
Description
An abstract class from which useful spatial classes arederived
Usage
Spatial(bbox, proj4string = CRS(as.character(NA)))## S3 method for class 'Spatial'subset(x, subset, select, drop = FALSE, ...)Arguments
bbox | a bounding box matrix |
proj4string | a CRS object |
x | object of class Spatial |
subset | |
select | |
drop | |
... | passed through |
Objects from the Class
are never to be generated; only derived classes can be meaningful
Slots
bbox:Object of class
"matrix"; 2-column matrixholding the minimum in first and maximum in second column for thex-coordinate (first row), y-coordinate (second row) and optionally,for points and grids only, further coordinates. The constructed Spatial object will be invalid if any bbox values are NA or infinite. The column names must bec("min", "max")proj4string:Object of class
"CRS". The name of this slot was chosen to reflect the use of Proj.4 strings to represent coordinate reference systems (CRS). The slot name will continue to be used, but as PROJ >= 6 and GDAL >= 3 are taken into use for reading files and for projection and transformation, the Proj.4 string CRS representation is being supplemented by a WKT2 (2019) representation. The reason for the modification is that important keys in the Proj.4 string representation are being deprecated in PROJ >= 6 and GDAL >= 3. Legacy"CRS"objects hold only a valid Proj.4 string, which can be used for unprojecting or reprojecting coordinates; it is initialised to NA. If the"CRS"object is instantiated usingCRS()withrgdal using PROJ >= 6 and GDAL >= 3, the object may also have a WKT2 (2019) string carried as acomment. Non-NA strings may be checked for validity in the rgdal package, but attempts to assign a string containing "longlat" to data extending beyond longitude [-180, 360] or lattitude [-90, 90] will be stopped or warned, useset_ll_warnto warn rather than stop, andset_ll_TOLto change the default tolerance for the range exceedance tests.
Methods
- bbox
signature(obj = "Spatial"): retrieves the bbox element- dimensions
signature(obj = "Spatial"): retrieves the numberof spatial dimensions spanned- gridded
signature(obj = "Spatial"): logical, tells whetherthe data is on a regular spatial grid- plot
signature(x = "Spatial", y = "missing"): plot methodfor spatial objects; does nothing but setting up a plotting region choosinga suitable aspect if not given(see below), colouring the plot background using either a bg= argument or par("bg"), and possibly drawing axes.- summary
signature(object = "Spatial"): summarize object$retrieves attribute column
$<-sets or replaces attribute column, or promote ageometry-only object to an object having an attribute
- rebuild_CRS
rebuild a CRS object, usually used to add a WKT comment with PROJ >= 6 and GDAL >= 3
plot method arguments
The plot method for “Spatial” objects takes the following arguments:
- x
object of class Spatial
- xlim
default NULL; the x limits (x1, x2) of the plot
- ylim
default NULL; the y limits of the plot
- asp
default NA; the y/x aspect ratio
- axes
default FALSE; a logical value indicating whether both axes should be drawn
- bg
default
par("bg"); colour to be used for the background of the device region- xaxs
The style of axis interval calculation to be used for the x-axis
- yaxs
The style of axis interval calculation to be used for the y-axis
- lab
A numerical vector of the form
c(x, y, len)which modifies the default way that axes are annotated- setParUsrBB
default FALSE; set the
par“usr” bounding box; see below- bgMap
object of class
ggmap, or returned by functionRgoogleMaps::GetMap- expandBB
numeric; factor to expand the plotting region default:
bbox(x)with oneach side (1=below, 2=left, 3=above and 4=right); defaults toc(0,0,0,0); settingxlimorylimoverrides this.- ...
passed through
Warning
this class is not useful in itself, but all spatialclasses in this package derive from it
Note
The default aspect for map plots is 1; if however data are notprojected (coordinates are longlat), the aspect is by default set to1/cos(My * pi)/180) with My the y coordinate of the middle of the map(the mean of ylim, which defaults to the y range of bounding box).
The argumentsetParUsrBB may be used to pass the logical valueTRUE to functions withinplot.Spatial. When set toTRUE, par(“usr”) will be overwritten withc(xlim, ylim), which defaults to the bounding box of the spatial object. This is only needed in the particular context of graphic output to a specified device with given width and height, to be matched to the spatial object, when using par(“xaxs”) and par(“yaxs”) in addition topar(mar=c(0,0,0,0)).
Author(s)
r-spatial team; Edzer Pebesma,edzer.pebesma@uni-muenster.deRoger Bivand, Barry Rowlingson, Virgilio G\'omez-Rubio
See Also
SpatialPoints-class,SpatialGrid-class,SpatialPointsDataFrame-class,SpatialGridDataFrame-class
Examples
o <- new("Spatial")proj4string(o) <- CRS("+init=epsg:27700")if (!is.null(comment(slot(o, "proj4string")))) { cat(strsplit(wkt(o), "\n")[[1]], sep="\n") cat(strsplit(wkt(slot(o, "proj4string")), "\n")[[1]], sep="\n")}Class "SpatialGrid"
Description
class for defining a full, rectangular grid ofarbitrary dimension
Objects from the Class
Objects are created by using e.g.
SpatialGrid(grid)
with grid of classGridTopology-class
Slots
gridobject of classGridTopology-class, defining thegrid topology (offset, cellsize, dim)
bbox:Object of class
"matrix"; bounding boxproj4string:Object of class
"CRS"; projection
Extends
Class"SpatialPoints" directly;Class"Spatial", by class"SpatialPoints".
Methods
- coordinates
signature(x = "SpatialGrid"): calculates coordinates foreach point on the grid; coordinates are not stored in objects of class SpatialGrid- summary
signature(object = "SpatialGrid"): summarize object- plot
signature(x = "SpatialGrid"): plots cell centers- "["
signature(x = "SpatialGrid"): select rows and columns
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
SpatialGridDataFrame-class,SpatialGrid
Examples
x = GridTopology(c(0,0), c(1,1), c(5,5))class(x)xsummary(x)coordinates(x)y = SpatialGrid(grid = x)class(y)yClass "SpatialGridDataFrame"
Description
Class for spatial attributes that have spatial locationson a (full) regular grid.
Objects from the Class
Objects can be created by calls of the formas(x,"SpatialGridDataFrame"), wherex is of classSpatialPixelsDataFrame-class, or by importing through rgdal. Ordered full grids are stored instead or unordered non-NA cells;
Slots
grid:seeGridTopology-class; grid parameters
bbox:Object of class
"matrix"; bounding boxproj4string:Object of class
"CRS"; projectiondata:Object of class data.frame, containing attribute data
Extends
Class"SpatialGrid", directly.Class"Spatial", by class"SpatialGrid".
Methods
- coordinates
signature(x = "SpatialGridDataFrame"): retrieves (and calculates!) coordinates- [
signature(x = "SpatialGridDataFrame"): selects rows, columns, and attributes; returns anobject of classSpatialGridDataFrame- as.matrix
signature(x = "SpatialGridDataFrame"): coerce to matrix; increasing col index corresponds to decreasing y coordinate, row index increases with coordinate index- as.array
signature(x = "SpatialGridDataFrame"): coerce to array; increasing array index for the second dimension corresponds to decreasing coordinates, all other coordinate dimensions increase with array index- cbind
signature(...): if arguments have identical topology, combine theirattribute values
Plot method arguments
The plot methods for “SpatialPixelsDataFrame” or “SpatialGridDataFrame” objects take the following arguments:
- x
object of classSpatialPixelsDataFrame orSpatialGridDataFrame
- ...
arguments passed on toimage.SpatialGridDataFrame
- attr
integer or character, indicating the attribute variable to be plotted; default 1
- col
color ramp to be used; default
bpy.colors(100)for continuous, orRColorBrewer::brewer.pal(nlevels(x[[1]]), "Set2")for factor variables- breaks
for continuous attributes: values at which color breaks should take place
- zlim
for continuous attributes: numeric of length 2, specifying the range of attribute values to be plotted; default to data range
range(as.numeric(x[[attr]])[is.finite(x[[attr]])])- axes
logical: draw x and y axes? default
FALSE- xaxs
character, default "i", seepar
- yaxs
character, default equal to
xaxs, seepar- at
numeric or NULL, values at which axis tics and labels should be drawn; default NULL (usepretty)
- border
color, to be used for drawing grid lines; default NA (don't draw grid lines)
- axis.pos
integer, 1-4; default 4, seeaxis
- add.axis
logical: draw axis along scale? default
TRUE- what
what to draw:
"image","scale", or"both"; default "both"- scale.size
size for the scale bar; uselcm to specify in absolute size, or a numericvalue such as
1/6to specify relative size; defaultlcm(2.8)- scale.shrink
non-negative numeric indicating the amount to shrink the scale length, default 0
- scale.frac
for categorical attributes: numeric between 0 and 1, indicating the scale width, default 0.3
- scale.n
for categorical attributes: integer, indicating how many scale categories should fill a complete width; default 15
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
SpatialGrid-class, which does not contain the attribute data,andSpatialPixelsDataFrame-class which holds possibly incomplete grids
Plotting gridded data with sp:https://r-spatial.org/r/2016/03/08/plotting-spatial-grids.html
Examples
data(meuse.grid) # only the non-missing valued cellscoordinates(meuse.grid) = c("x", "y") # promote to SpatialPointsDataFramegridded(meuse.grid) <- TRUE # promote to SpatialPixelsDataFramex = as(meuse.grid, "SpatialGridDataFrame") # creates the full gridx[["idist"]] = 1 - x[["dist"]] # assigns new attributeimage(x["idist"]) # note the single [ for attribute selection# toy example:df = data.frame(z = c(1:6,NA,8,9), xc = c(1,1,1,2,2,2,3,3,3), yc = c(rep(c(0, 1.5, 3),3)))coordinates(df) = ~xc+ycgridded(df) = TRUEdf = as(df, "SpatialGridDataFrame") # to full gridimage(df["z"])# draw labels to verify:cc = coordinates(df)z=df[["z"]]zc=as.character(z)zc[is.na(zc)]="NA"text(cc[,1],cc[,2],zc)# the following is weird, but illustrates the concept of row/col selection:fullgrid(meuse.grid) = TRUEimage(meuse.grid)image(meuse.grid[20:70, 10:70, "dist"], add = TRUE, col = bpy.colors())# as.matrix, as.arraysgdim = c(3,4)SG = SpatialGrid(GridTopology(rep(0,2), rep(10,2), sgdim))SGDF = SpatialGridDataFrame(SG, data.frame(val = 1:12))as.array(SGDF)as.matrix(SGDF)as(SGDF, "array")create objects of class SpatialLines or SpatialLinesDataFrame
Description
create objects of classSpatialLines orSpatialLinesDataFrame fromlists ofLines objects and data.frames; extract list od Lines from a SpatialLines object
Usage
SpatialLines(LinesList, proj4string = CRS(as.character(NA)))SpatialLinesDataFrame(sl, data, match.ID = TRUE)as.SpatialLines.SLDF(SLDF)getSpatialLinesMidPoints(SL)LineLength(cc, longlat = FALSE, sum = TRUE)LinesLength(Ls, longlat = FALSE)SpatialLinesLengths(SL, longlat)Arguments
LinesList | list with objects of classLines-class |
proj4string | Object of class |
sl,SL | object of classSpatialLines-class |
data | object of class |
match.ID | logical: (default TRUE): match SpatialLines memberLines ID slot values with data.frame row names, and re-order thedata frame rows if necessary; if character: indicates the columnin |
SLDF | SpatialLinesDataFrame object |
Ls | Object of class |
cc | Object of class |
longlat | if FALSE, Euclidean distance, if TRUE Great Circle distance in kilometers |
sum | logical; if |
Value
SpatialLines returns object of classSpatialLines;SpatialLinesDataFrame returns object of classSpatialLinesDataFramegetSpatialLinesMidPoints returns an object of classSpatialPoints,each point containing the (weighted) mean of the lines elements; weighted in the sense that mean is called twice.
See Also
a class for spatial lines
Description
a class that holds spatial lines
Objects from the Class
hold a list of Lines objects; each Lines object holds a listof Line (line) objects.
Slots
lines:Object of class
"list"; list members are all ofclassLines-classbbox:Object of class
"matrix"; seeSpatial-classproj4string:Object of class
"CRS"; seeCRS-class
Extends
Class"Spatial", directly.
Methods
- [
signature(obj = "SpatialLines"): select subset of (sets of) lines; NAs are not permitted in the row index- coordinates
value is a list of lists with matrices
- plot
signature(x = "SpatialLines", y = "missing"): plot lines in SpatialLines object- lines
signature(x = "SpatialLines"): add lines in SpatialLines object to a plot- rbind
signature(object = "SpatialLines"): rbind-like method, see notes- summary
signature(object = "SpatialLines"): summarize object
plot method arguments
The plot method for “SpatialLines” objects takes the following arguments:
- x
object of class SpatialLines
- xlim
default NULL; the x limits (x1, x2) of the plot
- ylim
default NULL; the y limits of the plot
- col
default 1; default plotting color
- lwd
default 1; line width
- lty
default 1; line type
- add
default FALSE; add to existing plot
- axes
default FALSE; a logical value indicating whether both axes should be drawn
- lend
default 0; line end style
- ljoin
default 0; line join style
- lmitre
default 10; line mitre limit
- ...
passed through
- setParUsrBB
set the
par“usr” bounding box, see note inSpatial-class
Note
rbind calls the functionSpatialLines, where it is checked that all IDs are unique. Ifrbind-ingSpatialLines without unique IDs, it is possible to set the argumentmakeUniqueIDs = TRUE, althoughit is preferred to change these explicitly withspChFIDs.
Author(s)
Roger Bivand, Edzer Pebesma
See Also
Examples
# from the sp vignette:l1 = cbind(c(1,2,3),c(3,2,2))rownames(l1) = letters[1:3]l1a = cbind(l1[,1]+.05,l1[,2]+.05)rownames(l1a) = letters[1:3]l2 = cbind(c(1,2,3),c(1,1.5,1))rownames(l2) = letters[1:3]Sl1 = Line(l1)Sl1a = Line(l1a)Sl2 = Line(l2)S1 = Lines(list(Sl1, Sl1a),)S2 = Lines(list(Sl2),)Sl = SpatialLines(list(S1,S2))summary(Sl)plot(Sl, col = c("red", "blue"))a class for spatial lines with attributes
Description
this class holds data consisting of (sets of lines), where eachset of lines relates to an attribute row in a data.frame
Objects from the Class
can be created by the functionSpatialLinesDataFrame
Slots
data:Object of classdata.frame containing the attribute table
lines:Object of class
"list"; seeSpatialLines-classbbox:Object of class
"matrix"; seeSpatial-classproj4string:Object of class
"CRS"; seeCRS-class
Extends
Class"SpatialLines", directly.Class"Spatial", by class"SpatialLines".
Methods
Methods defined with class "SpatialLinesDataFrame" in the signature:
- [
signature(x = "SpatialLinesDataFrame"): subset rows orcolumns; in case of row subsetting, the line sets are also subsetted; NAs are not permitted in the row index- coordinates
signature(obj = "SpatialLinesDataFrame"): retrievesa list with lists of coordinate matrices- show
signature(object = "SpatialLinesDataFrame"): print method- plot
signature(x = "SpatialLinesDataFrame"): plot points- lines
signature(object = "SpatialLinesDataFrame"): add lines to plot- rbind
signature(object = "SpatialLinesDataFrame"): rbind-like method
Note
rbind forSpatialLinesDataFrame is only possible for objects with unique IDs. If you want torbind objectswith duplicated IDs, seespChFIDs.
Author(s)
Roger Bivand; Edzer Pebesma
See Also
create objects of class SpatialMultiPoints or SpatialMultiPointsDataFrame
Description
create objects of classSpatialMultiPoints-class orSpatialMultiPointsDataFrame-class fromcoordinates, and from coordinates anddata.frames
Usage
SpatialMultiPoints(coords, proj4string=CRS(as.character(NA)), bbox = NULL)SpatialMultiPointsDataFrame(coords, data, proj4string = CRS(as.character(NA)), match.ID, bbox = NULL)Arguments
coords | list with in each element a numeric matrix or data.frame with coordinates (each row representing a point); in case of SpatialMultiPointsDataFrame an objectof classSpatialMultiPoints-class is also allowed |
proj4string | projection string of classCRS-class |
bbox | bounding box matrix, usually NULL and constructed from the data, but may be passed through for coercion purposes if clearly needed |
data | object of class |
match.ID | logical or character; if missing, and |
Value
SpatialMultiPoints returns an object of classSpatialMultiPoints;SpatialMultiPointsDataFrame returns an object of classSpatialMultiPointsDataFrame;
See Also
coordinates,SpatialMultiPoints-class,SpatialMultiPointsDataFrame-class
Examples
cl1 = cbind(rnorm(3, 10), rnorm(3, 10))cl2 = cbind(rnorm(5, 10), rnorm(5, 0))cl3 = cbind(rnorm(7, 0), rnorm(7, 10))mp = SpatialMultiPoints(list(cl1, cl2, cl3))mpx = rbind(mp, mp) # rbind methodplot(mp, col = 2, cex = 1, pch = 1:3)mpmp[1:2]print(mp, asWKT=TRUE, digits=3)mpdf = SpatialMultiPointsDataFrame(list(cl1, cl2, cl3), data.frame(a = 1:3))mpdfmpdfx = rbind(mpdf, mpdf) # rbind methodplot(mpdf, col = mpdf$a, cex = 1:3)as(mpdf, "data.frame")mpdf[1:2,]Class "SpatialMultiPoints"
Description
Class for (irregularly spaced) MultiPoints
Objects from the Class
Objects can be created by calls of the formSpatialPoints(x).
Slots
coords:Object of class
"list", containing thecoordinates of point sets (each list element is a matrix)bbox:Object of class
"matrix", with bounding boxproj4string:Object of class
"CRS", projection string
Extends
Class"Spatial", directly.
Methods
- [
signature(x = "SpatialMultiPoints"): subsets point sets- coerce
signature(from = "SpatialPoints", to = "data.frame"): coerce to data.frame- coordinates
signature(obj = "SpatialMultiPoints"): retrievesall the coordinates, as one single matrix- plot
signature(x = "SpatialPoints", y = "missing"): plot points- summary
signature(object = "SpatialPoints"): summarize object- points
signature(x = "SpatialPoints"): add point symbols to plot- show
signature(object = "SpatialPoints"): prints coordinates- rbind
signature(object = "SpatialPoints"): rbind-like method
plot method arguments
The plot method for “SpatialPoints” objects takes the following arguments:
- x
object of class SpatialPoints
- pch
default 3; either an integer specifying a symbol or a single character to be used as the default in plotting points
- axes
default FALSE; a logical value indicating whether both axes should be drawn
- add
default FALSE; add to existing plot
- xlim
default NULL; the x limits (x1, x2) of the plot
- ylim
default NULL; the y limits of the plot
- ...
passed through
- setParUsrBB
default FALSE; set the
par“usr” bounding box, see note inSpatial-class- cex
default 1; numerical value giving the amount by which plotting text and symbols should be magnified relative to the default
- col
default 1; default plotting color
- lwd
default 1; line width
- bg
default 1; colour to be used for the background of the device region
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
SpatialMultiPointsDataFrame-classSpatialPoints-class
Examples
cl1 = cbind(rnorm(3, 10), rnorm(3, 10))cl2 = cbind(rnorm(5, 10), rnorm(5, 0))cl3 = cbind(rnorm(7, 0), rnorm(7, 10))mp = SpatialMultiPoints(list(cl1, cl2, cl3))plot(mp, col = 2, cex = 1, pch = 1:3)mpmp[1:2]print(mp, asWKT=TRUE, digits=3)Class "SpatialMultiPointsDataFrame"
Description
Class for spatial attributes that correspond to point sets
Usage
## S4 method for signature 'SpatialMultiPointsDataFrame'x[i, j, ..., drop = TRUE] ## S4 method for signature 'SpatialMultiPointsDataFrame,data.frame'coerce(from, to, strict=TRUE) ## S4 method for signature 'SpatialMultiPointsDataFrame'coordinates(obj) ## S4 method for signature 'SpatialMultiPointsDataFrame'show(object) ## S4 method for signature 'SpatialMultiPointsDataFrame'points(x)Arguments
x,from,obj,object |
|
to | class to which to coerce |
strict | see |
i | row indices |
j | column indices |
drop | see |
... | indices passed through |
Slots
data:Object of class data.frame containingthe attribute data (may or may not contain the coordinates in its columns)
coords:Object of class
"list"; the list with coordinates matrices;points are rows in the matrix, the list length equals the number of rows in thedataslotbbox:Object of class
"matrix"; bounding boxproj4string:Object of class
"CRS"; projection string
Extends
Class"SpatialMultiPoints", directly.Class"Spatial", by class"SpatialMultiPoints".
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
coordinates,SpatialMultiPoints-class
Examples
# create three sets of points:cl1 = cbind(rnorm(3, 10), rnorm(3, 10))cl2 = cbind(rnorm(5, 10), rnorm(5, 0))cl3 = cbind(rnorm(7, 0), rnorm(7, 10))mpdf = SpatialMultiPointsDataFrame(list(cl1, cl2, cl3), data.frame(a = 1:3))mpdfplot(mpdf, col = mpdf$a, cex = 1:3)as(mpdf, "data.frame")mpdf[1:2,]define spatial grid
Description
defines spatial grid by offset, cell size and dimensions
Usage
GridTopology(cellcentre.offset, cellsize, cells.dim)SpatialPixels(points, tolerance = sqrt(.Machine$double.eps),proj4string = CRS(as.character(NA)), round = NULL, grid = NULL)SpatialGrid(grid, proj4string = CRS(as.character(NA)))coordinatevalues(obj)points2grid(points, tolerance = sqrt(.Machine$double.eps), round=NULL)getGridIndex(cc, grid, all.inside = TRUE)getGridTopology(obj)areaSpatialGrid(obj)Arguments
cellcentre.offset | numeric; vector with the smallest centroid coordinates foreach dimension; coordinates refer to the cell centre |
cellsize | numeric; vector with the cell size in each dimension |
cells.dim | integer; vector with number of cells in each dimension |
points | coordinates, object of classSpatialPoints-class |
grid | grid topology; object of classGridTopology-class;for calls to |
tolerance | precision, used to which extent points are exactly ona grid |
round | default NULL, otherwise a value passed to as the digits argument to |
proj4string | object of classCRS-class |
obj | object of class or deriving fromSpatialGrid-class |
cc | numeric matrix with coordinates |
all.inside | logical; if TRUE and |
Value
GridTopology returns a value of classGridTopology-class;SpatialGrid returns an object of classSpatialGrid-class
coordinatevalues returns a list with the unique x-coordinates,the unique y-coordinate, etc. instead of thecoordinates of allgrid cells
SpatialGrid returns an object of classSpatialGrid-class.
points2grid returns theGridTopology-class from a set of points.
getGridIndex finds the index of a set of point coordinates in a givengrid topology, and depending onall.inside setting, generates NAor an error message if points are outside the grid domain.
getGridTopology returns the slot of classGridTopology-class fromobj.
areaSpatialGrid returns the spatial area of (the non-missing valued cellsof) the grid. For objects of classSpatialGridDataFrame-classthe area refers to cells where any (one or more) of the attribute columnsare non-missing valued.
Note
SpatialGrid stores grid topology and may or may not store the coordinatesof the actual points, which may form a subset of the full grid. To findout or change this, seefullgrid.
points2grid tries to figure out the grid topology from points. It succeedsonly if points on a grid line have constant y column, and points on agrid column have constant x coordinate, etc. In other cases, use signifon the raw coordinate matrices to make sure this is the case.
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
SpatialGrid-class,SpatialGridDataFrame-class,
Examples
x = GridTopology(c(0,0), c(1,1), c(5,4))class(x)xsummary(x)coordinates(x)coordinates(GridTopology(c(0,0), c(1,1), c(5,4)))coordinatevalues(x)data(meuse.grid)coordinates(meuse.grid) <- c("x", "y")points2grid(meuse.grid)data(meuse.grid)set.seed(1)meuse.grid$x <- meuse.grid$x + rnorm(length(meuse.grid$x), 0, 0.002)meuse.grid$y <- meuse.grid$y + rnorm(length(meuse.grid$y), 0, 0.002)coordinates(meuse.grid) <- c("x", "y")#EJP# points2grid(meuse.grid, tolerance=0.76, round=1)data(meuse.grid)a <- which(meuse.grid$x == 180140)b <- which(meuse.grid$x == 180180)c <- which(meuse.grid$x == 179260)d <- which(meuse.grid$y == 332460)e <- which(meuse.grid$y == 332420)f <- which(meuse.grid$y == 330740)meuse.grid <- meuse.grid[-c(a, b, c, d, e, f),]coordinates(meuse.grid) <- c("x", "y")points2grid(meuse.grid)data(meuse.grid)set.seed(1)meuse.grid$x <- meuse.grid$x + rnorm(length(meuse.grid$x), 0, 0.002)meuse.grid$y <- meuse.grid$y + rnorm(length(meuse.grid$y), 0, 0.002)meuse.grid <- meuse.grid[-c(a, b, c, d, e, f),]coordinates(meuse.grid) <- c("x", "y")# EJP# points2grid(meuse.grid, tolerance=0.69, round=1)Class "SpatialPixels"
Description
class for defining a pixels, forming apossibly incomplete rectangular grid of arbitrary dimension
Objects from the Class
Objects are created by using e.g.
SpatialPixels(points)
with points of classSpatialPoints-class
Slots
gridobject of classGridTopology-class, defining thegrid topology (offset, cellsize, dim)
grid.indexinteger; index of points in full grid
coordscoordinates of points, or bbox of grid
bbox:Object of class
"matrix"; bounding boxproj4string:Object of class
"CRS"; projection
Extends
Class"SpatialPoints" directly;Class"Spatial", by class"SpatialPoints".
Methods
- coordinates
signature(x = "SpatialPixels"): calculates coordinates foreach point on the grid; coordinates are not stored in objects of class SpatialGrid- summary
signature(object = "SpatialPixels"): summarize object- plot
signature(x = "SpatialPixels"): plots cell centers- "["
signature(x = "SpatialPixels"): select pixel cells; the argumentdrop=FALSE(default) does not recalculate grid topology for the selection, ifdrop=TRUEthe grid topology is recomputed, and might change.- rbind
signature(x = "SpatialPixels"): rbind-like method
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
SpatialPixelsDataFrame-class,SpatialGrid-class
Examples
data(meuse.grid)pts = meuse.grid[c("x", "y")]y = SpatialPixels(SpatialPoints(pts))class(y)ysummary(y)plot(y) # plots gridplot(y, grid = FALSE) # plots pointsdefine spatial grid with attribute data
Description
defines spatial grid by offset, cell size and dimensions
Usage
SpatialPixelsDataFrame(points, data, tolerance = sqrt(.Machine$double.eps), proj4string = CRS(as.character(NA)), round = NULL, grid = NULL)SpatialGridDataFrame(grid, data, proj4string = CRS(as.character(NA)))Arguments
points | coordinates, either as numeric matrix or as object of classSpatialPoints-class |
grid | grid topology; object of classGridTopology-class; forcalls to |
data | data.frame; contains the attribute (actual grid) data |
tolerance | precision up to which extent points should be exactly on a grid |
round | default NULL, otherwise a value passed to as the digits argument to |
proj4string | object of classCRS-class in the firstform only used when |
Value
SpatialPixelsDataFrame returns an object of classSpatialPixelsDataFrame-class; SpatialGridDataFrame returns an objectof classSpatialGridDataFrame-class.
Note
SpatialPixels stores grid topology and coordinates of the actual points,which may be in the form of a subset (set of pixels) of a full grid. Tofind out or change this, seefullgrid andSpatialGrid-class.
Author(s)
Edzer Pebesma
See Also
gridded,gridded<-,SpatialGrid,SpatialGrid-class
Examples
data(meuse.grid)m = SpatialPixelsDataFrame(points = meuse.grid[c("x", "y")], data = meuse.grid)class(m)summary(m)Class "SpatialPixelsDataFrame"
Description
Class for spatial attributes that have spatial locationson a regular grid.
Objects from the Class
Objects can be created by calls of the formas(x,"SpatialPixelsDataFrame"), wherex is of classSpatialPointsDataFrame-class, or by importing through rgdal. Ordered full grids are stored instead or unordered non-NA cells;
Slots
bbox:Object of class
"matrix"; bounding boxproj4string:Object of class
"CRS"; projectioncoords:seeSpatialPoints; points slot
coords.nrsgrid:seeGridTopology-class; grid parameters
grid.index:integer; index of points in the list to pointsin the full (ordered) grid. x cycles fastest; all coordinates increasefrom low to hight except y, which decreases from high to low
data:Object of class data.frame, containing the attribute data
Extends
Class"SpatialPixels", directly.Class"Spatial", by class"SpatialPixels".
Methods
- coordinates
signature(x = "SpatialPixelsDataFrame"): retrieves coordinates- [
signature(x = "SpatialPixelsDataFrame"): selects row(s) and/or attribute(s), and returns anobject of classSpatialPixelsDataFrame; rows refer here to the pixelnumbers, not grid lines. For selecting a square block in a grid, coerce toaSpatialGridDataFrame-class first, and use[on that object- as.matrix
signature(x = "SpatialPixelsDataFrame"): coerce to matrix- rbind
signature(x = "SpatialPixelsDataFrame"): rbind-like method- plot
signature(x = "SpatialPixelsDataFrame", y = "missing"): seeSpatialGridDataFrame-class for details
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
SpatialPixels-class, which does not contain the attribute data
Examples
data(meuse.grid) # only the non-missing valued cellscoordinates(meuse.grid) = c("x", "y") # promote to SpatialPointsDataFramegridded(meuse.grid) <- TRUE # promote to SpatialPixelsDataFramemeuse.grid[["idist"]] = 1 - meuse.grid[["dist"]] # assigns new attributeimage(meuse.grid["idist"]) # note the single [# toy example:df = data.frame(z = c(1:6,NA,8,9), xc = c(1,1,1,2,2,2,3,3,3), yc = c(rep(c(0, 1.5, 3),3)))coordinates(df) = ~xc+ycgridded(df) = TRUEimage(df["z"])# draw labels to verify:cc = coordinates(df)z=df[["z"]]zc=as.character(z)zc[is.na(zc)]="NA"text(cc[,1],cc[,2],zc)create objects of class SpatialPoints or SpatialPointsDataFrame
Description
create objects of classSpatialPoints-class orSpatialPointsDataFrame-class fromcoordinates, and from coordinates anddata.frames
Usage
SpatialPoints(coords, proj4string=CRS(as.character(NA)), bbox = NULL)SpatialPointsDataFrame(coords, data, coords.nrs = numeric(0), proj4string = CRS(as.character(NA)), match.ID, bbox = NULL)Arguments
coords | numeric matrix or data.frame with coordinates (each row is a point); in case of SpatialPointsDataFrame an objectof classSpatialPoints-class is also allowed |
proj4string | projection string of classCRS-class |
bbox | bounding box matrix, usually NULL and constructed from the data, but may be passed through for coercion purposes if clearly needed |
data | object of class |
coords.nrs | numeric; if present, records the column positions wherein |
match.ID | logical or character; if missing, and |
Value
SpatialPoints returns an object of classSpatialPoints;SpatialPointsDataFrame returns an object of classSpatialPointsDataFrame;
See Also
coordinates,SpatialPoints-class,SpatialPointsDataFrame-class
Examples
set.seed(1331)pts = cbind(1:5, 1:5)dimnames(pts)[[1]] = letters[1:5]df = data.frame(a = 1:5)row.names(df) = letters[5:1]library(sp)options(warn=1) # show warnings where they occurSpatialPointsDataFrame(pts, df) # warnSpatialPointsDataFrame(pts, df, match.ID = TRUE) # don't warnSpatialPointsDataFrame(pts, df, match.ID = FALSE) # don't warndf$m = letters[5:1]SpatialPointsDataFrame(pts, df, match.ID = "m") # don't warndimnames(pts)[[1]] = letters[5:1]SpatialPointsDataFrame(pts, df) # don't warn: ID matching doesn't reorderClass "SpatialPoints"
Description
Class for (irregularly spaced) points
Objects from the Class
Objects can be created by calls of the formSpatialPoints(x).
Slots
coords:Object of class
"matrix", containing thecoordinates (each row is a point)bbox:Object of class
"matrix", with bounding boxproj4string:Object of class
"CRS", projection string
Extends
Class"Spatial", directly.
Methods
- [
signature(x = "SpatialPoints"): subsets the points; onlyrows (points) can be subsetted- coerce
signature(from = "SpatialPoints", to = "data.frame"): retrieves the data part- coerce
signature(from = "SpatialPoints", to = "SpatialPixels"): equivalent to assigning gridded TRUE for a copy of the object- coerce
signature(from = "SpatialPointsDataFrame", to = "SpatialPixelsDataFrame"): equivalent to assigning gridded TRUE for a copy of the object- coerce
signature(from = "data.frame", to = "SpatialPoints"): setscoordinates, which may be in a data frame- coerce
signature(from = "matrix", to = "SpatialPoints"): setcoordinates, which may be in a matrix- coordinates
signature(obj = "SpatialPoints"): retrievesthe coordinates, as matrix- plot
signature(x = "SpatialPoints", y = "missing"): plot points- summary
signature(object = "SpatialPoints"): summarize object- points
signature(x = "SpatialPoints"): add point symbols to plot- show
signature(object = "SpatialPoints"): prints coordinates- rbind
signature(object = "SpatialPoints"): rbind-like method
plot method arguments
The plot method for “SpatialPoints” objects takes the following arguments:
- x
object of class SpatialPoints
- pch
default 3; either an integer specifying a symbol or a single character to be used as the default in plotting points
- axes
default FALSE; a logical value indicating whether both axes should be drawn
- add
default FALSE; add to existing plot
- xlim
default NULL; the x limits (x1, x2) of the plot
- ylim
default NULL; the y limits of the plot
- ...
passed through
- setParUsrBB
default FALSE; set the
par“usr” bounding box, see note inSpatial-class- cex
default 1; numerical value giving the amount by which plotting text and symbols should be magnified relative to the default
- col
default 1; default plotting color
- lwd
default 1; line width
- bg
default 1; colour to be used for the background of the device region
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
Examples
x = c(1,2,3,4,5)y = c(3,2,5,1,4)S <- SpatialPoints(cbind(x,y))S <- SpatialPoints(list(x,y))S <- SpatialPoints(data.frame(x,y))Splot(S)Class "SpatialPointsDataFrame"
Description
Class for spatial attributes that have spatial point locations
Usage
## S4 method for signature 'SpatialPointsDataFrame'x[i, j, ..., drop = TRUE] ## S4 method for signature 'SpatialPointsDataFrame,SpatialPoints'coerce(from, to, strict=TRUE) ## S4 method for signature 'SpatialPointsDataFrame,data.frame'coerce(from, to, strict=TRUE) ## S4 method for signature 'SpatialPointsDataFrame'coordinates(obj) ## S4 method for signature 'SpatialPointsDataFrame'show(object) ## S4 method for signature 'SpatialPointsDataFrame'points(x) ## S3 method for class 'SpatialPointsDataFrame'rbind(...)Arguments
x,from,obj,object |
|
to | class to which to coerce |
strict | see |
i | row indices |
j | column indices |
drop | see |
... | indices passed through |
Objects from the Class
Objects can be created by calls of the formcoordinates(x) = c("x", "y").or of the formcoordinates(x) = xy; seecoordinates.
Slots
data:Object of class data.frame containingthe attribute data (may or may not contain the coordinates in its columns)
coords:Object of class
"matrix"; the coordinates matrix(points are rows in the matrix)coords.nrsObject of class logical; if TRUE, whenthe object was created the coordinates were retrieved from the data.frame,and hence stripped from it; after coercion to data.frame, e.g. by as.data.frame(x), coordinates will again be added (as first few columns) to the data.frame
bbox:Object of class
"matrix"; bounding boxproj4string:Object of class
"CRS"; projection string
Extends
Class"SpatialPoints", directly.Class"Spatial", by class"SpatialPoints".
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
coordinates,SpatialPoints-class
Examples
data(meuse)xy = meuse[c("x", "y")] # retrieve coordinates as data.frameclass(meuse)data(meuse) # reload data.framecoordinates(meuse) = c("x", "y") # specify column namesclass(meuse)data(meuse) # reload data.framecoordinates(meuse) = c(1, 2) # specify column namesclass(meuse)data(meuse) # reload data.framecoordinates(meuse) = ~x+y # formulaclass(meuse)data(meuse) # reload data.framecoordinates(meuse) = xy # as data frameclass(meuse)data(meuse) # reload data.framecoordinates(meuse) = as.matrix(xy) # as matrixmeuse$log.zn = log(meuse$zinc)class(meuse)dim(meuse)create objects of class SpatialPolygons or SpatialPolygonsDataFrame
Description
create objects of classSpatialPolygons orSpatialPolygonsDataFrame fromlists ofPolygons objects anddata.frames
Usage
Polygon(coords, hole=as.logical(NA))Polygons(srl, ID)SpatialPolygons(Srl, pO, proj4string=CRS(as.character(NA)))SpatialPolygonsDataFrame(Sr, data, match.ID = TRUE)getSpatialPolygonsLabelPoints(SP)Arguments
coords | 2-column numeric matrix with coordinates; first point (row) shouldequal last coordinates (row); if the hole argument is not given, the status of the polygon as a hole or an island will be taken from the ring direction, with clockwise meaning island, and counter-clockwise meaning hole |
hole | logical value for setting polygon as hole or not; if the hole argument is not given, the status of the polygon as a hole or an island will be taken from the ring direction, with clockwise meaning island, and counter-clockwise meaning hole |
proj4string | projection string of classCRS-class |
srl | list withPolygon-class objects |
ID | character vector of length one with identifier |
Srl | list with objects of classPolygons-class |
pO | integer vector; plotting order; if missing in reverse order of Polygons area |
Sr | object of classSpatialPolygons-class |
data | object of class |
match.ID | logical: (default TRUE): match SpatialPolygonsmember Polygons ID slot values with data frame row names, andre-order the data frame rows if necessary. If character: indicatesthe column in |
SP | object of classSpatialPolygons-class |
Details
InPolygon, if the hole argument is not given, the status of the polygon as a hole or an island will be taken from the ring direction, with clockwise meaning island, and counter-clockwise meaning hole. InPolygons, if all of the member Polygon objects are holes, the largest by area will be converted to island status. Until 2010-04-17, version 0.9-61, the area of this converted object was erroneously left at its hole value of zero. Thanks to Patrick Giraudoux for spotting the bug.
The class definitions used for polygons insp do not accord with those ofthe simple features specification of the Open Geospatial Consortium. Thergeos package, an interface to Geometry Engine – Open Source (GEOS), uses thisspecification, in which each hole (interior ring) must be associated withits containing exterior ring. In order to avoid introducing incompatiblechanges into the class definition of Polygons objects, a comment has beenadded as a single character string to each such object. Here we can trustthe data source to assign the hole status correctly, and use round-trip coercion tosf to add such comments to each Polygons member of the polygons slot of this SpatialPolygons object. Exterior rings are codedzero, while interior rings are coded with the 1-based index of theexterior ring to which they belong. SpatialPolygons objects created by reading usingsf have the comments set on input, as OGR also uses SFS.
Refer to Bivand et al. (2013), pages 47-48 and 132-133 for a further discussion.
Value
Polygon returns an object of classPolygon;Polygons returns an object of classPolygons;SpatialPolygons returns object of classSpatialPolygons;SpatialPolygonsDataFrame returns object of classSpatialPolygonsDataFramegetSpatialPolygonsLabelPoints returns an object of classSpatialPoints with label points.
References
Roger Bivand, Edzer Pebesma and Virgilio Gomez-Rubio, 2013. Applied spatial data analysis with R, Second edition. Springer, NY.https://asdar-book.org/
See Also
SpatialPolygons-class,SpatialPolygonsDataFrame-class
Class "SpatialPolygons"
Description
class to hold polygon topology (without attributes)
Objects from the Class
Objects can be created by calls to the functionSpatialPolygons
Slots
polygons:Object of class
"list"; list elements areall of classPolygons-classplotOrder:Object of class
"integer"; integer arraygiving the order in which objects should be plottedbbox:Object of class
"matrix"; seeSpatial-classproj4string:Object of class
"CRS"; seeCRS-class
Extends
Class"Spatial", directly.
Methods
Methods defined with class "SpatialPolygons" in the signature:
- [
signature(obj = "SpatialPolygons"): select subset of (sets of) polygons; NAs are not permitted in the row index- plot
signature(x = "SpatialPolygons", y = "missing"): plot polygons in SpatialPolygons object- summary
signature(object = "SpatialPolygons"): summarize object- rbind
signature(object = "SpatialPolygons"): rbind-like method
plot method arguments
Theplot method for spatial polygons takes the following arguments:
- x
a SpatialPolygons object
- col
a vector of colour values
- border
default
par("fg"); the colour to draw the border- add
default FALSE; if TRUE, add to existing plot
- xlim, ylim
default NULL; ranges for the plotted ‘x’ and ‘y’ values
- xpd
default NULL; controls clipping, see
par- density
default NULL; the density of shading lines, in lines per inch, see
polygon- angle
default 45; the slope of shading lines, given as an angle in degrees (counter-clockwise), see
polygon- pbg
default NULL, set to
par("bg")by default “transparent”; the colour to paint holes- axes
default FALSE; draw axes
- lty
default
par("lty"); border line type- ...
other arguments passed through
- setParUsrBB
default FALSE; see
Spatial-classfor further details- usePolypath
default NULL to set from option value; use
polypathfor hole-handling in plot- rule
default NULL to set from option value; character value specifying the path fill mode, see
polypath
The options forusePolypath andrule may be retrieved withget_Polypath (default TRUE on package load) andget_PolypathRule (default “winding” on package load), and set withset_Polypath andset_PolypathRule
The class definitions used for polygons insp do not accord with those ofthe simple features specification of the Open Geospatial Consortium. Thergeos package, an interface to Geometry Engine – Open Source (GEOS), uses thisspecification, in which each hole (interior ring) must be associated withits containing exterior ring. In order to avoid introducing incompatiblechanges into the class definition of Polygons objects, a comment has beenadded as a single character string to each such object. Here we can trustthe data source to assign the hole status correctly, and use round-trip coercion tosf to add such comments to each Polygons member of the polygons slot of this SpatialPolygons object. Exterior rings are codedzero, while interior rings are coded with the 1-based index of theexterior ring to which they belong. SpatialPolygons objects created by reading usingsf orterra have the comments set on input, as OGR also uses SFS.
Refer to Bivand et al. (2013), pages 47-48 and 132-133 for a further discussion.
Note
rbind calls the functionSpatialPolygons, where it is checked that all IDs are unique. Ifrbind-ingSpatialPolygons without unique IDs, it is possible to set the argumentmakeUniqueIDs = TRUE, althoughit is preferred to change these explicitly withspChFIDs.
Author(s)
Roger Bivand
References
Roger Bivand, Edzer Pebesma and Virgilio Gomez-Rubio, 2013. Applied spatial data analysis with R, Second edition. Springer, NY.https://asdar-book.org/
See Also
Examples
# simple example, from vignette("sp"):Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)Srs1 = Polygons(list(Sr1), "s1")Srs2 = Polygons(list(Sr2), "s2")Srs3 = Polygons(list(Sr3, Sr4), "s3/4")SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)plot(SpP, col = 1:3, pbg="white")grd <- GridTopology(c(1,1), c(1,1), c(10,10))polys <- as(grd, "SpatialPolygons")plot(polys)text(coordinates(polys), labels=row.names(polys))Class "SpatialPolygonsDataFrame"
Description
class to hold polygons with attributes
Objects from the Class
Objects can be created by calls to the functionSpatialPolygonsDataFrame
Slots
data:Object of class
"data.frame"; attribute tablepolygons:Object of class
"list"; seeSpatialPolygons-classplotOrder:Object of class
"integer"; seeSpatialPolygons-classbbox:Object of class
"matrix"; seeSpatial-classproj4string:Object of class
"CRS"; seeCRS-class
Extends
Class"SpatialPolygons", directly.Class"Spatial", by class"SpatialPolygons".
Methods
Methods defined with class "SpatialPolygonsDataFrame" in the signature:
- [
signature(x = "SpatialPolygonsDataFrame"): select subset of (sets of) polygons; NAs are not permitted in the row index- rbind
signature(object = "SpatialPolygonsDataFrame"): rbind-like method, see notes below
Note
SpatialPolygonsDataFrame with default ID matching checks the data frame row names against the Polygons ID slots. They must then agree with each other, and be unique (no Polygons objects can share IDs); the data frame rows will be re-ordered if needed to match the Polygons IDs..
If you want torbind objects with duplicated IDs, seespChFIDs.
Author(s)
Roger Bivand
See Also
Examples
# simple example, from scratch:Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)Srs1 = Polygons(list(Sr1), "s1")Srs2 = Polygons(list(Sr2), "s2")Srs3 = Polygons(list(Sr3, Sr4), "s3/4")SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)plot(SpP, col = 1:3, pbg="white")grd <- GridTopology(c(1,1), c(1,1), c(10,10))polys <- as(grd, "SpatialPolygons")centroids <- coordinates(polys)x <- centroids[,1]y <- centroids[,2]z <- 1.4 + 0.1*x + 0.2*y + 0.002*x*xex_1.7 <- SpatialPolygonsDataFrame(polys, data=data.frame(x=x, y=y, z=z, row.names=row.names(polys)))brks <- quantile(z, seq(0,1,1/7))cols <- grey((length(brks):2)/length(brks))dens <- (2:length(brks))*3plot(ex_1.7, col=cols[findInterval(z, brks, all.inside=TRUE)])plot(ex_1.7, density=dens[findInterval(z, brks, all.inside=TRUE)])constructs SpatialXxxDataFrame from geometry and attributes
Description
constructs SpatialXxxDataFrame from geometry and attributes
Usage
addAttrToGeom(x, y, match.ID, ...)Arguments
x | geometry (locations) of the queries |
y | data.frame object with attributes |
match.ID | logical; if TRUE, the IDs of the geometry and of thedata.frame are matched (possibly swapping records), and an error occurswhen some IDs do not match |
... | (optional) arguments passed to the constructor functions |
Value
an object of class XxxDataFrame, where Xxx is the class of x
Methods
- x = "SpatialPoints", y = "data.frame"
- x = "SpatialPixels", y = "data.frame"
- x = "SpatialGrid", y = "data.frame"
- x = "SpatialLines", y = "data.frame"
- x = "SpatialPolygons", y = "data.frame"
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
aggregation of spatial objects
Description
spatial aggregation of thematic information in spatial objects
Usage
## S3 method for class 'Spatial'aggregate(x, by = list(ID = rep(1, length(x))),FUN, ..., dissolve = TRUE, areaWeighted = FALSE)Arguments
x | object deriving fromSpatial, with attributes |
by | aggregation predicate; if |
FUN | aggregation function, e.g.mean; see details |
... | arguments passed on to function |
dissolve | logical; should, when aggregating based on attributes, theresulting geometries be dissolved? Note that if |
areaWeighted | logical; should the aggregation of |
Details
For as far as these functions use package rgeos, (lines, polygons,dissolve = TRUE), they are deprecated as rgeos will retire; tryusing sf::aggregate instead.
FUN should be a function that takes as first argument avector, and that returns a single number. The canonical examplesaremean andsum. Counting features is obtained whensumming an attribute variable that has the value 1 everywhere.
Value
The aggregation of attribute values ofx either over thegeometry ofby by usingover for spatial matching,or by attribute values, using aggregation functionFUN.
IfareaWeighted isTRUE,FUN is ignored and thearea weighted mean is computed for numerical variables, or if allattributes arefactors, the area dominant factor level (areamode) is returned. This computes the intersection ofxandby; see examples below. As this uses code from packagergeos, it is deprecated as package rgeos will retire.
Ifby is missing, aggregates over all features.
Note
usesover to find spatial match ifby is aSpatial object
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
Examples
data("meuse")coordinates(meuse) <- ~x+ydata("meuse.grid")coordinates(meuse.grid) <- ~x+ygridded(meuse.grid) <- TRUEi = cut(meuse.grid$dist, c(0,.25,.5,.75,1), include.lowest = TRUE)j = sample(1:2, 3103,replace=TRUE)x = aggregate(meuse.grid["dist"], list(i=i,j=j), mean, dissolve = FALSE)spplot(x["j"], col.regions=bpy.colors())Make SpatialPolygons object from GridTopology object
Description
Converts grids of regular rectangles into aSpatialPolygons object, which can be transformed to a different projection or datum withspTransform in packagergdal. The function is not suitable for high-resolution grids. The ordering of the grid cells is as incoordinates() of the same object, and is reported byIDvaluesGridTopology.
Usage
as.SpatialPolygons.GridTopology(grd, proj4string = CRS(as.character(NA)))IDvaluesGridTopology(obj)as.SpatialPolygons.SpatialPixels(obj)IDvaluesSpatialPixels(obj)HexPoints2SpatialPolygons(hex, dx)Arguments
grd |
|
proj4string | object of classCRS-class |
obj |
|
hex |
|
dx | spacing of two horizontally adjacent points; if missing, this will be computedfrom the points |
Value
as.SpatialPolygons.GridTopology andas.SpatialPolygons.SpatialPixels return aSpatialPolygons object;IDvaluesGridTopology andIDvaluesSpatialPixels return a character vector with the object grid indices.
See Also
GridTopology,SpatialPixels,SpatialPolygonsspTransform in packagergdal
Examples
library(lattice)grd <- GridTopology(cellcentre.offset=c(-175,55), cellsize=c(10,10), cells.dim=c(4,4))SpP_grd <- as.SpatialPolygons.GridTopology(grd)plot(SpP_grd)text(coordinates(SpP_grd), sapply(slot(SpP_grd, "polygons"), function(i) slot(i, "ID")), cex=0.5)trdata <- data.frame(A=rep(c(1,2,3,4), 4), B=rep(c(1,2,3,4), each=4), row.names=sapply(slot(SpP_grd, "polygons"), function(i) slot(i, "ID")))SpPDF <- SpatialPolygonsDataFrame(SpP_grd, trdata)spplot(SpPDF)data(meuse.grid)gridded(meuse.grid)=~x+yxx = spsample(meuse.grid, type="hexagonal", cellsize=200)xxpl = HexPoints2SpatialPolygons(xx)image(meuse.grid["dist"])plot(xxpl, add = TRUE)points(xx, cex = .5)## Not run: spplot(aggregate(as(meuse.grid[,1:3], "SpatialPolygonsDataFrame"), xxpl, areaWeighted=TRUE), main = "aggregated meuse.grid")## End(Not run)Making SpatialPolygons objects
Description
This function is used in making SpatialPolygons objects from other formats.
Usage
as.SpatialPolygons.PolygonsList(Srl, proj4string=CRS(as.character(NA)))Arguments
Srl | A list of Polygons objects |
proj4string | Object of class |
Value
The functions return a SpatialPolygons object
Author(s)
Roger Bivand
Examples
grd <- GridTopology(c(1,1), c(1,1), c(10,10))polys <- as.SpatialPolygons.GridTopology(grd)plot(polys)text(coordinates(polys), labels=sapply(slot(polys, "polygons"), function(i) slot(i, "ID")), cex=0.6)retrieve bbox from spatial data
Description
retrieves spatial bounding box from spatial data
Usage
bbox(obj)Arguments
obj | object deriving from class "Spatial", or one of classes: "Line", "Lines", "Polygon" or "Polygons", or ANY, which requires obj to be an array with at least two columns |
Value
two-column matrix; the first column has the minimum,the second the maximum values; rows represent the spatialdimensions
Methods
- obj = "Spatial"
object deriving from class "Spatial"
- obj = "ANY"
an array with at least two columns
- obj = "Line"
object deriving from class "Line"
- obj = "Lines"
object deriving from class "Lines"
- obj = "Polygon"
object deriving from class "Polygon"
- obj = "Polygons"
object deriving from class "Polygons"
Examples
# just 9 points on a grid:x <- c(1,1,1,2,2,2,3,3,3)y <- c(1,2,3,1,2,3,1,2,3)xy <- cbind(x,y)S <- SpatialPoints(xy)bbox(S)# data.framedata(meuse.grid)coordinates(meuse.grid) <- ~x+ygridded(meuse.grid) <- TRUEbbox(meuse.grid)blue-pink-yellow color scheme, which also prints well on black/white printers
Description
Create a vector of ‘n’ “contiguous” colors.
Usage
bpy.colors(n = 100, cutoff.tails = 0.1, alpha = 1.0)Arguments
n | number of colors (>= 1) to be in the palette |
cutoff.tails | tail fraction to be cut off on each side. If 0,this palette runs from black to white; by cutting off the tails, it runsfrom blue to yellow, which looks nicer. |
alpha | numeric; alpha transparency, 0 is fully transparent, 1 is opaque. |
Value
A character vector, ‘cv’, of color names. This can be usedeither to create a user-defined color palette for subsequent graphicsby ‘palette(cv)’, a ‘col=’ specification in graphics functions or in‘par’.
Note
This color map prints well on black-and-white printers.
Author(s)
unknown; the pallette was posted to gnuplot-info a fewdecades ago; R implementation Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
Examples
bpy.colors(10)p <- expand.grid(x=1:30,y=1:30)p$z <- p$x + p$ycoordinates(p) <- c("x", "y")gridded(p) <- TRUEimage(p, col = bpy.colors(100), asp = 1)# require(lattice)# trellis.par.set("regions", list(col=bpy.colors())) # make this default palletteCreate a bubble plot of spatial data
Description
Create a bubble plot of spatial data, with options for bicolourresidual plots (xyplot wrapper)
Usage
bubble(obj, zcol = 1, ..., fill = TRUE, maxsize = 3, do.sqrt = TRUE, pch, col = c("#d01c8b", "#4dac26"), key.entries = quantile(data[,zcol]), main, identify = FALSE, labels = row.names(data.frame(obj)), key.space = "right",scales = list(draw = FALSE), xlab = NULL, ylab = NULL, panel = panel.bubble,sp.layout = NULL, xlim = bbexpand(bbox(obj)[1,], 0.04), ylim = bbexpand(bbox(obj)[2,], 0.04))Arguments
obj | object of, or extending, class SpatialPointsDataFrame or SpatialGridDataFrame, seecoordinates orSpatialPointsDataFrame; the object knows about its spatial coordinates |
zcol | z-variable column name, or column number after removingspatial coordinates from x@data: 1 refers to the first non-coordinatecolumn |
fill | logical; if TRUE, filled circles are plotted (pch = 16), else open circles (pch = 1); the pch argument overrides this |
maxsize |
|
do.sqrt | logical; if TRUE the plotting symbol area (sqrt(diameter)) is proportional to the value of the z-variable; if FALSE, the symbol size(diameter) is proportional to the z-variable |
pch | plotting character |
col | colours to be used; numeric vector of size two: first valueis for negative values, second for positive values. Default colors: 5-class PiYG from colorbrewer.org. |
key.entries | the values that will be plotted in the key; by default the five quantiles min, q.25, median q.75, max |
main | main plotting title |
identify | logical; if true, regular |
labels | labels argument passed to |
... | arguments, passed to |
key.space | location of the key |
scales | scales argument as passed toxyplot |
xlab | x-axis label |
ylab | y-axis label |
panel | panel function used |
sp.layout | possible layout items; seespplot |
xlim | x axis limit |
ylim | y axis limit |
Value
returns (or plots) the bubble plot; ifidentify is TRUE, returnsthe indexes (row numbers) of identified points.
Author(s)
Edzer Pebesma
See Also
Examples
data(meuse)coordinates(meuse) <- c("x", "y") # promote to SpatialPointsDataFramebubble(meuse, "cadmium", maxsize = 2.5, main = "cadmium concentrations (ppm)", key.entries = 2^(-1:4))bubble(meuse, "zinc", main = "zinc concentrations (ppm)", key.entries = 100 * 2^(0:4))Convert character vector to DMS-class object
Description
These two helper functions convert character vectors and decimal degree vectors to the DMS-class representation of degrees, minutes, and decimal seconds. "DMS" objects cannot contain NAs.
Usage
char2dms(from, chd = "d", chm = "'", chs = "\"")dd2dms(dd, NS = FALSE)Arguments
from | character vector of degree, minute, decimal second data |
chd | degree character terminator |
chm | minute character terminator |
chs | second character terminator |
dd | numeric vector of decimal degrees |
NS | logical, TRUE for north/south decimal degrees, FALSE for east/west decimal degrees |
Details
In char2dms, the input data vector should use a regular format, such as that used in the PROJ.4 library, with a trailing capital (NSWE) indicating compass direction.
Value
Both functions return a "DMS" object.
Methods
- from = "DMS", to = "numeric"
coerce a
"DMS"object to a"numeric"vector- from = "DMS", to = "character"
coerce a
"DMS"object to a"character"vector (theas.character.DMSS3 method is also available)
Author(s)
Roger BivandRoger.Bivand@nhh.no
See Also
Examples
data(state)str(state.center$y)stateN <- dd2dms(state.center$y, NS=TRUE)str(attributes(stateN))ch.stateN <- as.character(stateN)str(ch.stateN)stateNa <- char2dms(ch.stateN)str(attributes(stateNa))ch.stateN <- as(stateN, "character")str(ch.stateN)stateNa <- char2dms(ch.stateN)str(attributes(stateNa))Display a compass rose.
Description
Displays a basic compass rose, usually to orient a map.
Usage
compassRose(x,y,rot=0,cex=1)Arguments
x,y | The position of the center of the compass rose in user units. |
rot | Rotation for the compass rose in degrees. See Details. |
cex | The character expansion to use in the display. |
Details
‘compassRose’ displays a conventional compass rose at the positionrequested. The size of the compass rose is determined by the characterexpansion, as the central "rose" is calculated relative to the character size.Rotation is in degrees counterclockwise.
Value
nil
Author(s)
Jim Lemon
set spatial coordinates to create a Spatial object, or retrievespatial coordinates from a Spatial object
Description
set spatial coordinates to create a Spatial object, or retrievespatial coordinates from a Spatial object
Usage
coordinates(obj, ...)coordinates(object) <- valueArguments
obj | object deriving from class "Spatial" |
object | object of class "data.frame" |
value | spatial coordinates; either a matrix, list, or dataframe with numeric data, or column names, column number or areference: a formula (in the form of e.g. |
... | additional arguments that may be used by particular methods |
Value
usually an object of class SpatialPointsDataFrame; if the coordinatesset cover the full set of variables in object, an object of class SpatialPointsis returned
Examples
# data.framedata(meuse.grid)coordinates(meuse.grid) <- ~x+ygridded(meuse.grid) <- TRUEclass(meuse.grid)bbox(meuse.grid)data(meuse)meuse.xy = meuse[c("x", "y")]coordinates(meuse.xy) <- ~x+yclass(meuse.xy)retrieve (or set) spatial coordinates
Description
retrieve (or set) spatial coordinates from (for) spatial data
Methods
- obj = "list"
list with (at least) two numeric components of equal length
- obj = "data.frame"
data.frame with at least two numeric components
- obj = "matrix"
numeric matrix with at least two columns
- obj = "SpatialPoints"
object of, or deriving from, SpatialPoints
- obj = "SpatialPointsDataFrame"
object of, or deriving from, SpatialPointsDataFrame
- obj = "SpatialPolygons"
object of, or deriving from, SpatialPolygons
- obj = "SpatialPolygonsDataFrame"
object of, or deriving from, SpatialPolygonsDataFrame
- obj = "Line"
object of class Line; returned value is matrix
- obj = "Lines"
object of class Lines; returned value is list of matrices
- obj = "SpatialLines"
object of, or deriving from, SpatialLines; returnedvalue is list of lists of matrices
- obj = "GridTopology"
object of, or deriving from, GridTopology
- obj = "GridTopology"
object of, or deriving from, GridTopology
- obj = "SpatialPixels"
object of, or deriving from, SpatialPixels
- obj = "SpatialPixelsDataFrame"
object of, or deriving from, SpatialPixelsDataFrame
- obj = "SpatialGrid"
object of, or deriving from, SpatialGrid
- obj = "SpatialGridDataFrame"
object of, or deriving from, SpatialGridDataFrame
Methods for "coordinates<-"
- object = "data.frame", value="ANY"
promote data.frame to object of classSpatialPointsDataFrame-class, by specifying coordinates; seecoordinates
retrieve or assign coordinate names for classes in sp
Description
retrieve or assign coordinate names for classes insp
Methods for coordnames
- x = "SpatialPoints"
retrieves coordinate names
- x = "SpatialLines"
retrieves coordinate names
- x = "Lines"
retrieves coordinate names
- x = "Line"
retrieves coordinate names
- x = "SpatialPolygons"
retrieves coordinate names
- x = "Polygons"
retrieves coordinate names
- x = "Polygon"
retrieves coordinate names
Methods for "coordnames<-"
- x = "SpatialPoints", value = "character"
replace coordinate names
- x = "SpatialLines", value = "character"
replace coordinate names
- x = "Lines", value = "character"
replace coordinate names
- x = "Line", value = "character"
replace coordinate names
- x = "SpatialPolygons", value = "character"
replace coordinate names
- x = "GridTopology", value = "character"
replace coordinate names
- x = "SpatialGrid", value = "character"
replace coordinate names
- x = "SpatialPixels", value = "character"
replace coordinate names
axis with degrees
Description
draw axes on a plot using degree symbols in numbers
Usage
degAxis(side, at, labels, ...)Arguments
side | integer; seeaxis |
at | numeric; if missing,axTicks is called for nice values; seeaxis |
labels | character; if omitted labels are constructed with degree symbols, endingin N/S/E/W; in case of negative degrees, sign is reversed and S or W is added; seeaxis |
... | passed to the actualaxis call |
Value
axis is plotted on current graph
Note
decimal degrees are used if variation is small, instead of minutes and seconds
Examples
xy = cbind(x = 2 * runif(100) - 1, y = 2 * runif(100) - 1)plot(SpatialPoints(xy, proj4string = CRS("+proj=longlat +ellps=WGS84")),xlim=c(-1,1),ylim=c(-1,1))degAxis(1)degAxis(2, at = c(-1,-0.5,0,0.5,1))#retrieve spatial dimensions from spatial data
Description
retrieves spatial dimensions box from spatial data
Usage
dimensions(obj)Arguments
obj | object deriving from class "Spatial" |
Value
two-column matrix; the first column has the minimum,the second the maximum values; rows represent the spatialdimensions
Methods
- obj = "Spatial"
object deriving from class "Spatial"
Examples
# just 9 points on a grid:x <- c(1,1,1,2,2,2,3,3,3)y <- c(1,2,3,1,2,3,1,2,3)xy <- cbind(x,y)S <- SpatialPoints(xy)dimensions(S)# data.framedata(meuse.grid)coordinates(meuse.grid) <- ~x+ygridded(meuse.grid) <- TRUEdimensions(meuse.grid)disaggregate SpatialLines, SpatialLinesDataFrame, SpatialPolygons, or SpatialPolygonsDataFrame objects
Description
disaggregate SpatialLines, SpatialLinesDataFrame, SpatialPolygons, or SpatialPolygonsDataFrame objects, using functions from rgeos to handle polygon hole nesting
Usage
disaggregate(x, ...)Arguments
x | object of classSpatialLines orSpatialPolygons |
... | ignored |
Value
object of classSpatialLines orSpatialPolygons,where groups ofLine orPolygon are disaggregated tooneLine perLines, or onePolygonperPolygons, respectively.
Author(s)
Robert Hijmans, Edzer Pebesma
Methods for Function elide in Package ‘maptools’
Description
Methods for functionelide to translate and disguise coordinate placing in the real world.
Usage
elide(obj, ...)Arguments
obj | object to be elided |
... | other arguments:
|
Value
The methods return objects of the input class object with elided coordinates; the coordinate reference system is not set. Note that if the input coordinates or centroids are in the data slot data.frame of the input object, they should be removed before the use of these methods, otherwise they will betray the input positions.
Methods
- obj = "SpatialPoints"
elides object
- obj = "SpatialPointsDataFrame"
elides object
- obj = "SpatialLines"
elides object
- obj = "SpatialLinesDataFrame"
elides object
- obj = "SpatialPolygons"
elides object
- obj = "SpatialPolygonsDataFrame"
elides object
Note
Rotation code kindly contributed by Don MacQueen
Examples
data(meuse)coordinates(meuse) <- c("x", "y")proj4string(meuse) <- CRS("+init=epsg:28992")data(meuse.riv)river_polygon <- Polygons(list(Polygon(meuse.riv)),)rivers <- SpatialPolygons(list(river_polygon))proj4string(rivers) <- CRS("+init=epsg:28992")rivers1 <- elide(rivers, reflect=c(TRUE, TRUE), scale=TRUE)meuse1 <- elide(meuse, bb=bbox(rivers), reflect=c(TRUE, TRUE), scale=TRUE)opar <- par(mfrow=c(1,2))plot(rivers, axes=TRUE)plot(meuse, add=TRUE)plot(rivers1, axes=TRUE)plot(meuse1, add=TRUE)par(opar)meuse1 <- elide(meuse, shift=c(10000, -10000))bbox(meuse)bbox(meuse1)rivers1 <- elide(rivers, shift=c(10000, -10000))bbox(rivers)bbox(rivers1)meuse1 <- elide(meuse, rotate=-30, center=apply(bbox(meuse), 1, mean))bbox(meuse)bbox(meuse1)plot(meuse1, axes=TRUE)rearrange data in SpatialPointsDataFrame or SpatialGridDataFrame for plotting with spplot (levelplot/xyplot wrapper)
Description
rearrange SpatialPointsDataFrame for plotting with spplot or levelplot
Usage
flipHorizontal(x)flipVertical(x)Arguments
x | object of class SpatialGridDataFrame |
Value
object of class SpatialGridDataFrame, with pixels flipped horizontallyor vertically. Note that the spatial structure is destroyed (or at least:drastically changed).
Author(s)
Michael Sumner
Examples
data(meuse.grid) # data framegridded(meuse.grid) = c("x", "y") # promotes to fullgrid(meuse.grid) = TRUEd = meuse.grid["dist"]image(d, axes=TRUE)image(flipHorizontal(d), axes=TRUE)image(flipVertical(d), axes=TRUE)Methods for retrieving the geometry from a composite (geometry + attributes) object
Description
geometry retrieves the SpatialXxx object from a SpatialXxxDataFrame object,with Xxx Lines, Points, Polygons, Grid, or Pixels. geometry<- converts adata.frame into a Spatial object.
Usage
geometry(obj) geometry(obj) <- valueArguments
obj | in case of assignment, a data.frame, else an object of class Spatial |
value | object of class Spatial |
Methods
- obj = "Spatial"
- obj = "SpatialPointsDataFrame"
- obj = "SpatialMultiPointsDataFrame"
- obj = "SpatialPolygonsDataFrame"
- obj = "SpatialPixelsDataFrame"
- obj = "SpatialGridDataFrame"
- obj = "SpatialLinesDataFrame"
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
Examples
data(meuse)m = meusecoordinates(m) = meuse[, c("x", "y")]pts = geometry(m)class(pts)geometry(meuse) = ptsclass(meuse)identical(m, meuse) # TRUEcreate neighbourhood (nb) object from grid geometry
Description
create neighbourhood (nb) object from grid geometry
Usage
gridIndex2nb(obj, maxdist = sqrt(2), fullMat = TRUE, ...)Arguments
obj | object of classSpatialGrid orSpatialPixels |
maxdist | maximum distance to be considered (inclusive), expressed in numberof grid cell (sqrt(2) results in queen neighbours) |
fullMat | usedist to compute distances from grid (row/col) indices;FALSE avoids forming the full distance matrix, at a large performance cost |
... | arguments passed on todist |
Value
Object of class nb, which is a list.
The nb object follows the convention of nb objects in package spdep;it is a list with each list element corresponding to a grid cell orpixel; the list element contains the indices of neighbours definedas cells less than maxdist away, measured in cell unit (N/S/E/Wneighbour has distance 1).
Note
Unequal grid cell size is ignored; grid cell row/col indicesare taken to be the coordinates from which distances are computed.
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
plot.nb in package spdep
specify spatial data as being gridded, or find out whether they are
Description
returns logical (TRUE or FALSE) telling whether the object is griddedor not; in assignment promotes a non-gridded structure to a griddedone, or demotes a gridded structure back to a non-structured one.
Usage
gridded(obj)gridded(obj) <- valuefullgrid(obj)fullgrid(obj) <- valuegridparameters(obj)Arguments
obj | object deriving from class "Spatial" (for gridded), orobject of classSpatialGridDataFrame-class (for fullgrid and gridparameters) |
value | logical replacement values, TRUE or FALSE |
Value
if obj derives from class Spatial, gridded(object) will tellwhether it is has topology on a regular grid; if assigned TRUE, if theobject derives from SpatialPoints and has gridded topology,grid topology will be added to object, and the class of the objectwill be promoted toSpatialGrid-class orSpatialGridDataFrame-class
fullgrid returns a logical, telling whether the grid is fulland ordered (i.e., in full matrix form), or whether it is not fullor unordered (i.e. a list of points that happen to lie on a grid. Ifassigned, the way the points are stored may be changed. Changing a setof points to full matrix form and back may change the original order ofthe points, and will remove duplicate points if they were present.
gridparameters returns, ifobj inherits fromSpatialGridDataFrame its grid parameters, else it returns numeric(0). Thereturned value is a data.frame with three columns, named cellcentre.offset("lower left cell centre coordinates"), cellsize, and cells.dim (celldimension); the rows correspond to the spatial dimensions.
Methods
- obj = "Spatial"
object deriving from class "Spatial"
Examples
# just 9 points on a grid:x <- c(1,1,1,2,2,2,3,3,3)y <- c(1,2,3,1,2,3,1,2,3)xy <- cbind(x,y)S <- SpatialPoints(xy)class(S)plot(S)gridded(S) <- TRUEgridded(S)class(S)summary(S)plot(S)gridded(S) <- FALSEgridded(S)class(S)# data.framedata(meuse.grid)coordinates(meuse.grid) <- ~x+ygridded(meuse.grid) <- TRUEplot(meuse.grid) # not much goodsummary(meuse.grid)Create N-S and E-W grid lines over a geographic region
Description
Create N-S and E-W grid lines over a geographic region; create and plot corresponding labels
Usage
gridlines(x, easts = pretty(bbox(x)[1,]), norths = pretty(bbox(x)[2,]), ndiscr = 100) gridat(x, easts = pretty(bbox(x)[1,]), norths = pretty(bbox(x)[2,]), offset = 0.5, side = "WS")## S3 method for class 'SpatialLines'labels(object, labelCRS, side = 1:2, ...)## S3 method for class 'SpatialPointsDataFrame'text(x, ...)Arguments
x | object deriving from classSpatial-class |
easts | numeric; east-west values for vertical lines |
norths | numeric; north-south values for horizontal lines |
ndiscr | integer; number of points used to discretize the line, couldbe set to 2, unless the grid is (re)projected |
offset | offset value to be returned, seetext |
object | SpatialLines-class object, as returned by |
labelCRS | the CRS in which the grid lines were drawn and labels should be printed; if missing, the CRS from |
side | for |
... | for |
Value
gridlines returns an object of classSpatialLines-class, with lines as specified; the returnobject inherits the projection information ofx;gridatreturns a SpatialPointsDataFrame with points at the west and southends of the grid lines created bygridlines, with degreelabels.
Thelabels method forSpatialLines objects returns aSpatialPointsDataFrame-class object with the parameters neededto print labels below and left of the gridlines. The locations forthe labels are those ofproj4string(object) the labels alsounlesslabelCRS is given, in which case they are in that CRS.This object is prepared to be plotted withtext:
Thetext method forSpatialPointsDataFrame puts text labelson its coordinates, and takes care of attributespos,labels,srt andoffset; seetext.
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de, using example codeof Roger Bivand.
See Also
Examples
run <- FALSEif (requireNamespace("sf", quietly=TRUE)) run <- TRUEdata(meuse)coordinates(meuse) = ~x+yplot(meuse)plot(gridlines(meuse), add = TRUE)text(labels(gridlines(meuse)))title("default gridlines within Meuse bounding box")if (run) {proj4string(meuse) <- CRS("+init=epsg:28992")crs.longlat <- CRS("+init=epsg:4326")meuse_ll <- spTransform(meuse, crs.longlat)grd <- gridlines(meuse_ll)grd_x <- spTransform(grd, CRS("+init=epsg:28992"))# labels South and West:plot(meuse)plot(grd_x, add=TRUE, lty=2)grdat_ll <- gridat(meuse_ll)grdat_x <- spTransform(grdat_ll, CRS("+init=epsg:28992"))text(grdat_x)}if (run) {# labels North and East:plot(meuse)plot(grd_x, add=TRUE, lty=2)grdat_ll <- gridat(meuse_ll, side="EN")grdat_x <- spTransform(grdat_ll, CRS("+init=epsg:28992"))text(grdat_x)}if (run) {# now using labels:plot(meuse)plot(grd_x, add=TRUE, lty=2)text(labels(grd_x, crs.longlat))}if (run) {# demonstrate axis labels with angle, both sides:sp = SpatialPoints(rbind(c(-101,9), c(-101,55), c(-19,9), c(-19,55)), crs.longlat)laea = CRS("+proj=laea +lat_0=30 +lon_0=-40")sp.l = spTransform(sp, laea)plot(sp.l, expandBB = c(0, 0.05, 0, .05))gl = spTransform(gridlines(sp), laea)plot(gl, add = TRUE)text(labels(gl, crs.longlat))text(labels(gl, crs.longlat, side = 3:4), col = 'red')title("curved text label demo")}if (run) {# polar:pts=SpatialPoints(rbind(c(-180,-70),c(0,-70),c(180,-89),c(180,-70)), crs.longlat)polar = CRS("+init=epsg:3031")gl = spTransform(gridlines(pts, easts = seq(-180,180,20), ndiscr = 100), polar)plot(spTransform(pts, polar), expandBB = c(.05,0,.05,0))lines(gl)l = labels(gl, crs.longlat, side = 3)l$pos = NULL # pos is too simple, use adj:text(l, adj = c(0.5, -0.5)) l = labels(gl, crs.longlat, side = 4)l$srt = 0 # otherwise they end up upside-downtext(l)title("grid line labels on polar projection, epsg 3031")}## Not run: if (require(maps)) demo(polar) # adds the map of the antarctic## End(Not run)Image or contour method for gridded spatial data; convert to and from image data structure
Description
Create image for gridded data in SpatialGridDataFrame or SpatialPixelsDataFrameobjects.
Usage
## S3 method for class 'SpatialGridDataFrame'image(x, attr = 1, xcol = 1, ycol = 2, col = heat.colors(12), red=NULL, green=NULL, blue=NULL, axes = FALSE, xlim = NULL,ylim = NULL, add = FALSE, ..., asp = NA, setParUsrBB=FALSE, interpolate = FALSE, angle = 0, useRasterImage = !(.Platform$GUI[1] == "Rgui" && getIdentification() == "R Console") && missing(breaks), breaks,zlim = range(as.numeric(x[[attr]])[is.finite(x[[attr]])]))## S3 method for class 'SpatialPixelsDataFrame'image(x, ...) ## S3 method for class 'SpatialPixels'image(x, ...) ## S3 method for class 'SpatialGridDataFrame'contour(x, attr = 1, xcol = 1, ycol = 2,col = 1, add = FALSE, xlim = NULL, ylim = NULL, axes = FALSE, ..., setParUsrBB = FALSE)## S3 method for class 'SpatialPixelsDataFrame'contour(x, ...) as.image.SpatialGridDataFrame(x, xcol = 1, ycol = 2, attr = 1)image2Grid(im, p4 = as.character(NA), digits=10)Arguments
x | object of classSpatialGridDataFrame |
attr | column of attribute variable; this may bethe column name in the data.frame of |
xcol | column number of x-coordinate, in the coordinate matrix |
ycol | column number of y-coordinate, in the coordinate matrix |
col | a vector of colors |
red,green,blue | columns names or numbers given instead of the |
axes | logical; should coordinate axes be drawn? |
xlim | x-axis limits |
ylim | y-axis limits |
zlim | data limits for plotting the (raster, attribute) values |
add | logical; if FALSE, the image is added to the plot layout setupby |
... | arguments passed toimage, see examples |
asp | aspect ratio to be used for plot |
setParUsrBB | default FALSE, see |
useRasterImage | if TRUE, use |
breaks | class breaks for coloured values |
interpolate | default FALSE, a logical vector (or scalar) indicating whether to apply linear interpolation to the image when drawing, see |
angle | default 0, angle of rotation (in degrees, anti-clockwise from positive x-axis, about the bottom-left corner), see |
im | list with components named x, y, and z, as used for |
p4 | CRS object, proj4 string |
digits | default 10, number of significant digits to use for checking equal row/column spacing |
Value
as.image.SpatialGridDataFrame returns the list withelementsx andy, containing the coordinates of the cellcentres of a matrixz, containing the attribute values in matrixform as needed byimage.
Note
Providingxcol andycol attributes seems obsolete,and it is for 2D data, but it may provide opportunities for plottingcertain slices in 3D data. I haven't given this much thought yet.
filled.contour seems to misinterpret the coordinate values,if we take the image.default manual page as the reference.
Author(s)
Edzer Pebesma
See Also
image.default,SpatialGridDataFrame-class,levelplot in packagelattice. Functionimage.plot in packagefields can be used to make a legend for an image, see an example inhttps://stat.ethz.ch/pipermail/r-sig-geo/2007-June/002143.html
Examples
data(meuse.grid)coordinates(meuse.grid) = c("x", "y") # promote to SpatialPointsDataFramegridded(meuse.grid) = TRUE # promote to SpatialGridDataFramedata(meuse)coordinates(meuse) = c("x", "y")image(meuse.grid["dist"], main = "Distance to river Meuse")points(coordinates(meuse), pch = "+")image(meuse.grid["dist"], main = "Distance to river Meuse", useRasterImage=TRUE)points(coordinates(meuse), pch = "+")# color scale:layout(cbind(1,2), c(4,1),1)image(meuse.grid["dist"])imageScale(meuse.grid$dist, axis.pos=4, add.axis=FALSE)axis(4,at=c(0,.2,.4,.8), las=2)data(Rlogo)d = dim(Rlogo)cellsize = abs(c(gt[2],gt[6]))cells.dim = c(d[1], d[2]) # c(d[2],d[1])cellcentre.offset = c(x = gt[1] + 0.5 * cellsize[1], y = gt[4] - (d[2] - 0.5) * abs(cellsize[2]))grid = GridTopology(cellcentre.offset, cellsize, cells.dim)df = as.vector(Rlogo[,,1])for (band in 2:d[3]) df = cbind(df, as.vector(Rlogo[,,band]))df = as.data.frame(df)names(df) = paste("band", 1:d[3], sep="")Rlogo <- SpatialGridDataFrame(grid = grid, data = df)summary(Rlogo)image(Rlogo, red="band1", green="band2", blue="band3")image(Rlogo, red="band1", green="band2", blue="band3", useRasterImage=FALSE)is.na(Rlogo$band1) <- Rlogo$band1 == 255is.na(Rlogo$band2) <- Rlogo$band2 == 255is.na(Rlogo$band3) <- Rlogo$band3 == 255Rlogo$i7 <- 7image(Rlogo, "i7")image(Rlogo, red="band1", green="band2", blue="band3", add=TRUE)Sets or retrieves projection attributes on classes extendingSpatialData
Description
Sets or retrieves projection attributes on classes extendingSpatialData; set or retrieve option value for error or warning on exceedance of geographical coordinate range, set or retrieve option value for exceedance tolerance of geographical coordinate range. Note that only “+proj=longlat +ellps=WGS84” is accepted for geographical coordinates, which must be ordered (eastings, northings); the “+ellps=” definition must be given (or expanded internally from a given “+datum=” value) for recent versions of the PROJ library, and should be set to an appropriate value.
From release 6 of the PROJ library, when used in buildingrgdal with GDAL >= 3, the+datum= key in the Proj.4 string CRS representation is deprecated, and the+towgs84= and+nadgrids= keys may be deprecated soon. For this reason,sp,rgdal andsf are starting to use WKT2 (2019) string representations. Insp, the"CRS" object in itself remains unchanged, but the content of its"projargs" slot may be degraded. To work around the degradation, acomment is added around the"CRS" object containing a WKT2 (2019) string whenrgdal is available and built with PROJ >= 6 and GDAL >=3. Thewkt() accessor function returns the WKT2 (2019) string comment belonging to the"CRS" object.
Usage
is.projected(obj)proj4string(obj)proj4string(obj) <- valuewkt(obj)get_ll_warn()get_ll_TOL()get_ReplCRS_warn()set_ll_warn(value)set_ll_TOL(value)set_ReplCRS_warn(value)Arguments
obj | An object of class or extendingSpatial-class |
value | For |
Details
proj4 strings are operative through CRAN package rgdal. For strings defined as “longlat”, the minimum longitude should be -180, the maximum longitude 360, the minimum latitude -90, and the maximum latitude 90. Note that theproj4string replacement method does not project spatial data - for this usespTransform methods in the rgdal package.
Value
is.projected returns a logical that may beNA;proj4string returns a character vector of length 1.
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
Examples
o <- new("Spatial")proj4string(o) <- CRS("+init=epsg:27700")if (!is.null(comment(slot(o, "proj4string")))) { cat(strsplit(wkt(o), "\n")[[1]], sep="\n") cat(strsplit(wkt(slot(o, "proj4string")), "\n")[[1]], sep="\n")}is.projected(CRS("+proj=longlat"))is.projected(CRS("+proj=geocent"))is.projected(CRS("+proj=geocent +units=km"))deprecated function to load the Meuse data set
Description
deprecated function to load the Meuse data set
Usage
loadMeuse()Value
none; it prints a warning to run demo(meuse)
See Also
Examples
demo(meuse)Calculate aspect ratio for plotting geographic maps;create nice degree axis labels
Description
Calculate aspect ratio for plotting geographic maps;create nice degree axis labels
Usage
mapasp(data, xlim, ylim)degreeLabelsEW(x)degreeLabelsNS(x)Arguments
data | object of class or extending |
xlim | the xlim argument passed (or derived from bounding box) |
ylim | the ylim argument passed (or derived from bounding box) |
x | numeric; values at which tics and marks will be generated |
Value
mapasp is used for the aspect argument in lattice plots and spplot;
let x = dy/dx, with dy and dx the y- and x-size of the map.
let s = 1/cos((My * pi)/180) with My the y coordinate of the middle of the map(the mean of ylim)
for latlong (longlat) data,mapasp returns s * x.for other data, mapasp returns "iso".
Note
the values forx are typically obtained fromaxTicks
See Also
levelplot in packagelattice
Merge a Spatial* object having attributes with a data.frame
Description
Merge a Spatial object having a data.frame (i.e. merging of non-spatial attributes).
Usage
## S4 method for signature 'Spatial,data.frame'merge(x, y, by = intersect(names(x), names(y)), by.x = by, by.y = by, all.x = TRUE, suffixes = c(".x",".y"), incomparables = NULL, duplicateGeoms = FALSE, ...)Arguments
x | object deriving fromSpatial |
y | object of class |
by,by.x,by.y | specifications of the common columns. See 'Details' in (base) |
all.x | logical; if TRUE, then the returned object will have all rows of x, even those that has no matching row in y. These rows will have NAs in those columns that are usually filled with values from y |
suffixes | character(2) specifying the suffixes to be used for making non-by names() unique. |
incomparables | values which cannot be matched. See |
duplicateGeoms | logical; if |
... | arguments to be passed to or from methods. |
Value
a Spatial* object
Author(s)
Robert J. Hijmans
See Also
Meuse river data set
Description
This data set gives locations and topsoil heavy metal concentrations, along with a number of soil and landscape variables at the observation locations, collected in a flood plain of the river Meuse, near the village of Stein (NL). Heavy metal concentrations are from composite samples of an area of approximately 15 m x 15 m.
Usage
data(meuse)Format
This data frame contains the following columns:
- x
a numeric vector; Easting (m) in Rijksdriehoek (RDH)(Netherlands topographical) map coordinates
- y
a numeric vector; Northing (m) in RDH coordinates
- cadmium
topsoil cadmium concentration, mg kg-1 soil ("ppm"); zero cadmiumvalues in the original data set have been shifted to 0.2 (half the lowest non-zero value)
- copper
topsoil copper concentration, mg kg-1 soil ("ppm")
- lead
topsoil lead concentration, mg kg-1 soil ("ppm")
- zinc
topsoil zinc concentration, mg kg-1 soil ("ppm")
- elev
relative elevation above local river bed, m
- dist
distance to the Meuse; obtained from the nearest cell inmeuse.grid, which in turn was derived by a spread (spatial distance)GIS operation, horizontal precision 20 metres; thennormalized to $[0,1]$
- om
organic matter, kg (100 kg)-1 soil (percent)
- ffreq
flooding frequency class: 1 = once in two years; 2 = once in ten years; 3 = one in 50 years
- soil
soil type according to the 1:50 000 soil map of the Netherlands. 1 = Rd10A (Calcareous weakly-developed meadow soils, light sandy clay); 2 = Rd90C/VII (Non-calcareous weakly-developed meadow soils, heavy sandy clay to light clay); 3 = Bkd26/VII (Red Brick soil, fine-sandy, silty light clay)
- lime
lime class: 0 = absent, 1 = present by field test with 5% HCl
- landuse
landuse class: Aa Agriculture/unspecified = , Ab = Agr/sugar beetsm, Ag = Agr/small grains, Ah = Agr/??, Am = Agr/maize, B = woods, Bw = trees in pasture, DEN = ??, Fh = tall fruit trees, Fl = low fruit trees; Fw = fruit trees in pasture, Ga = home gardens, SPO = sport field, STA = stable yard, Tv = ??, W = pasture
- dist.m
distance to river Meuse in metres, as obtained during the field survey
Note
row.names refer to the original sample number.
Soil units were mapped with a minimum delination width of 150 m, and so somewhat generalize the landscape.
Approximate equivalent World Reference Base 2002 for Soil Resources names are: Rd10A Gleyic Fluvisols; Rd90C Haplic Fluvisols; Bkd26 Haplic Luvisols. Units Rd90C and Bkd26 have winter groundwater > 80cm, summer > 120cm depth.
Author(s)
Field data were collected by Ruud van Rijn andMathieu Rikken; compiled for R by Edzer Pebesma; description extended by David Rossiter
References
M G J Rikken and R P G Van Rijn, 1993. Soil pollution with heavy metals - an inquiry into spatial variation, cost of mapping and the risk evaluation of copper, cadmium, lead and zinc in the floodplains of the Meuse west of Stein, the Netherlands. Doctoraalveldwerkverslag, Dept. of Physical Geography, Utrecht University
P.A. Burrough, R.A. McDonnell, 1998. Principles of Geographical Information Systems. Oxford University Press.
Stichting voor Bodemkartering (STIBOKA), 1970. Bodemkaart van Nederland : Blad 59 Peer, Blad 60 West en 60 Oost Sittard: schaal 1 : 50 000. Wageningen, STIBOKA.
Examples
data(meuse)summary(meuse)coordinates(meuse) <- ~x+yproj4string(meuse) <- CRS("+init=epsg:28992")Prediction Grid for Meuse Data Set
Description
Themeuse.grid data frame has 3103 rows and 7 columns;a grid with 40 m x 40 m spacing that covers the Meuse study area (seemeuse)
Usage
data(meuse.grid)Format
This data frame contains the following columns:
- x
a numeric vector; x-coordinate (seemeuse)
- y
a numeric vector; y-coordinate (seemeuse)
- dist
distance to the Meuse river; obtained by a spread(spatial distance) GIS operation, from border of river; normalized to$[0,1]$
- ffreq
flooding frequency class, for definitions see this item inmeuse; it is not known how this map was generated
- part.a
arbitrary division of the area in two areas, a and b
- part.b
see
part.a- soil
soil type, for definitions see this item inmeuse; it is questionable whether these data come from a real soil map, they do not match the published 1:50 000 map
Details
x andy are in RD New, the Dutch topographical mapcoordinate system. Roger Bivand projected this to UTM in theR-Grass interface package.
Source
References
See themeuse documentation
Examples
data(meuse.grid)coordinates(meuse.grid) = ~x+yproj4string(meuse.grid) <- CRS("+init=epsg:28992")gridded(meuse.grid) = TRUEspplot(meuse.grid)Prediction Grid for Meuse Data Set, geographical coordinates
Description
The object contains the meuse.grid data as a SpatialPointsDataFrame after transformation to WGS84 and geographical coordinates.
Usage
data(meuse.grid_ll)Format
The format is:Formal class 'SpatialPointsDataFrame' [package "sp"].
Source
See themeuse documentation
Examples
data(meuse.grid_ll)River Meuse outline
Description
Themeuse.riv data consists of an outline of the Meuseriver in the area a few kilometers around themeusedata set.
Themeuse.area polygon has an outline ofmeuse.grid. Seeexample below how it can be created frommeuse.grid.
Usage
data(meuse.riv)data(meuse.area)Format
meuse.riv: two-column data.frame containing 176 coordinates.
meuse.area: two-column matrix with coordinates of outline.
Details
x andy are in RDM, the Dutch topographical mapcoordinate system. See examples ofspTransform for projection parameters.
References
See themeuse documentation
Examples
data(meuse.riv)plot(meuse.riv, type = "l", asp = 1)data(meuse.grid)coordinates(meuse.grid) = c("x", "y")gridded(meuse.grid) = TRUEimage(meuse.grid, "dist", add = TRUE)data(meuse)coordinates(meuse) = c("x", "y")meuse.sr = SpatialPolygons(list(Polygons(list(Polygon(meuse.riv)),"meuse.riv")))spplot(meuse.grid, col.regions=bpy.colors(), main = "meuse.grid", sp.layout=list(list("sp.polygons", meuse.sr),list("sp.points", meuse, pch="+", col="black") ))spplot(meuse, "zinc", col.regions=bpy.colors(), main = "zinc, ppm", cuts = c(100,200,400,700,1200,2000), key.space = "right", sp.layout= list("sp.polygons", meuse.sr, fill = "lightblue"))consistent spatial overlay for points, grids and polygons
Description
consistent spatial overlay for points, grids andpolygons: at the spatial locations of object x retrieves the indexesor attributes from spatial object y
Usage
over(x, y, returnList = FALSE, fn = NULL, ...)x %over% yArguments
x | geometry (locations) of the queries |
y | layer from which the geometries or attributes are queried |
returnList | logical; see value |
fn | (optional) a function; see value |
... | arguments passed on to function |
Value
Ify is only geometry an object of lengthlength(x).IfreturnList isFALSE, a vector with the (first) indexofy for each geometry (point, grid cell centre, polygonor lines) matchingx. ifreturnList is TRUE, a list oflengthlength(x), with list elementi the vector ofall indices of the geometries iny that correspond to the$i$-th geometry inx.
Ify has attribute data, attribute data arereturned.returnList is FALSE, adata.frame withnumber of rows equal tolength(x) is returned, if it isTRUE a list withlength(x) elements is returned, with a listelement thedata.frame elements of all geometries inythat correspond to that element ofx.
Methods
- x = "SpatialPoints", y = "SpatialPolygons"
returns a numericvector of length equal to the number of points; the number is theindex (number) of the polygon of
yin which a point falls;NA denotes the point does not fall in a polygon; if a point fallsin multiple polygons, the last polygon is recorded.- x = "SpatialPointsDataFrame", y = "SpatialPolygons"
equalto the previous method, except that an argument
fn=xxxisallowed, e.g.fn = meanwhich will then report a data.framewith the mean attribute values of thexpoints falling in each polygon (set) ofy- x = "SpatialPoints", y = "SpatialPolygonsDataFrame"
returnsa data.frame of the second argument with row entries correspondingto the first argument
- x = "SpatialPolygons", y = "SpatialPoints"
returnsthe polygon index of points in
y; ifxisaSpatialPolygonsDataFrame, a data.frame with rows fromxcorresponding to points inyis returned.- x = "SpatialGridDataFrame", y = "SpatialPoints"
returnsobject of class SpatialPointsDataFrame with grid attribute valuesx at spatial point locations y; NA for NA grid cells or pointsoutside grid, and NA values on NA grid cells.
- x = "SpatialGrid", y = "SpatialPoints"
returns grid valuesx at spatial point locations y; NA for NA grid cells or pointsoutside the grid
- x = "SpatialPixelsDataFrame", y = "SpatialPoints"
returnsgrid values x at spatial point locations y; NA for NA grid cellsor points outside the grid
- x = "SpatialPixels", y = "SpatialPoints"
returns gridvalues x at spatial point locations y; NA for NA grid cells orpoints outside the grid
- x = "SpatialPoints", y = "SpatialGrid"
xx
- x = "SpatialPoints", y = "SpatialGridDataFrame"
xx
- x = "SpatialPoints", y = "SpatialPixels"
xx
- x = "SpatialPoints", y = "SpatialPixelsDataFrame"
xx
- x = "SpatialPolygons", y = "SpatialGridDataFrame"
xx
Note
over can be seen as a left outer join in SQL; thematch is a spatial intersection.
points on a polygon boundary and points corresponding to apolygon vertex are considered to be inside the polygon.
These methods assume that pixels and grid cells are neveroverlapping; for objects of classSpatialPixels this isnot guaranteed.
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
See Also
vignette("over") for examples and figures
panel and panel utility functions for spplot
Description
panel functions for spplot functions, and functions that can beuseful within these panel functions
Usage
spplot.key(sp.layout, rows = 1, cols = 1)SpatialPolygonsRescale(obj, offset, scale = 1, fill = "black", col = "black",plot.grid = TRUE, ...)sp.lines(obj, col = 1, ...)sp.points(obj, pch = 3, ...)sp.polygons(obj, col = 1, fill = "transparent", ...)sp.grid(obj, col = 1, alpha = 1,..., at = pretty(obj[[1]]), col.regions = col)sp.text(loc, txt, ...)sp.panel.layout(lst, p.number, ...)bbexpand(x, fraction)Arguments
sp.layout | list; seespplot for definition |
rows | integer; panel row(s) for which the layout should be drawn |
cols | integer; panel column(s) for which the layout should be drawn |
obj | object of classSpatialPolygons-class for |
offset | offset for shifting a Polygons object |
scale | scale for rescaling |
fill | fill color |
col | line color |
plot.grid | logical; plot through grid functions (TRUE), or throughtraditional graphics functions (FALSE) |
pch | plotting character |
at | numeric; values at which colour breaks should occur |
col.regions | colours to fill the grid cells, defaults to col |
loc | numeric vector of two elements |
txt | text to be plotted |
alpha | alpha (transparency) level |
lst | sp.layout argument, seespplot |
p.number | panel number; in a panel, panel.number() should bepassed to this argument |
x | length two numeric vector, containing a range |
fraction | fraction to expand the range by |
... | arguments passed to the underlying panel, lattice or grid functions |
Note
The panel functions ofspplot,panel.gridplot for grids,panel.pointsplot for points, orpanel.polygonsplot for linesor polygons can be called with arguments(x,y,...).Customizing spplot plots can be done by extending the panel function,or by supplying an sp.layout argument; see the documentation forspplot. Inside these panel functions,sp.panel.layoutis called to deal with plotting the items in asp.layout object.
SpatialPolygonsRescale scales and shifts an object of classSpatialPolygons-class; this is useful e.g. for scale bars, or otherlayout items.
sp.lines,sp.points,sp.polygons andsp.textplot lines, points, polygons or text in a panel.
spplot.key draws thesp.layout object at given rows/cols.
sp.pagefn can be passed as apage argument, and willcall functionspplot.key for the last panel drawn on a page.
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
References
https://edzer.github.io/sp/ has a graph gallery withexamples with R code.
See Also
do point(s) fall in a given polygon?
Description
verifies for one or more points whether they fall in a given polygon
Usage
point.in.polygon(point.x, point.y, pol.x, pol.y, mode.checked=FALSE)Arguments
point.x | numerical array of x-coordinates of points |
point.y | numerical array of y-coordinates of points |
pol.x | numerical array of x-coordinates of polygon |
pol.y | numerical array of y-coordinates of polygon |
mode.checked | default FALSE, used internally to save time when all the other argument are known to be of storage mode double |
Value
integer array; values are:0: point is strictly exterior to pol;1: point is strictly interior to pol;2: point lies on the relative interior of an edge of pol;3: point is a vertex of pol.
References
Uses the C function InPoly(). InPoly is Copyright (c) 1998 byJoseph O'Rourke. It may be freely redistributed in its entiretyprovided that this copyright notice is not removed.
Examples
# open polygon:point.in.polygon(1:10,1:10,c(3,5,5,3),c(3,3,5,5))# closed polygon:point.in.polygon(1:10,rep(4,10),c(3,5,5,3,3),c(3,3,5,5,3))sets spatial coordinates to create spatial data, or retrievesspatial coordinates
Description
sets spatial coordinates to create spatial data, or retrievesspatial coordinates
Usage
polygons(obj)polygons(object) <- valueArguments
obj | object of class "SpatialPolygons" or "SpatialPolygonsDataFrame" |
object | object of class "data.frame" |
value | object of class "SpatialPolygons" |
Value
polygons returns the SpatialPolygons of obj; polygons<- promotes adata.frame to a SpatialPolygonsDataFrame object
Examples
grd <- GridTopology(c(1,1), c(1,1), c(10,10))polys <- as.SpatialPolygons.GridTopology(grd)centroids <- coordinates(polys)x <- centroids[,1]y <- centroids[,2]z <- 1.4 + 0.1*x + 0.2*y + 0.002*x*xdf <- data.frame(x=x, y=y, z=z, row.names=row.names(polys))polygons(df) <- polysclass(df)summary(df)Retrieve polygons from SpatialPolygonsDataFrame object
Description
Retrieve polygons from SpatialPolygonsDataFrame object
Methods for polygons
- obj = "SpatialPolygons"
object of, or deriving from, SpatialPolygons
- obj = "SpatialPolygonsDataFrame"
object of, or deriving from, SpatialPolygonsDataFrame
Methods for "polygons<-"
- object = "data.frame", value="SpatialPolygons"
promote data.frame to object of classSpatialPolygonsDataFrame-class, by specifying polygons
read/write to/from (ESRI) asciigrid format
Description
read/write to/from ESRI asciigrid format
Usage
read.asciigrid(fname, as.image = FALSE, plot.image = FALSE, colname = fname, proj4string = CRS(as.character(NA)))write.asciigrid(x, fname, attr = 1, na.value = -9999, ...)Arguments
fname | file name |
as.image | logical; if FALSE, a list is returned, ready to beshown with the |
plot.image | logical; if TRUE, an image of the map is plotted |
colname | alternative name for data column if not file name |
proj4string | A CRS object setting the projection arguments of the Spatial Grid returned |
x | object of classSpatialGridDataFrame |
attr | attribute column; if missing, the firstcolumn is taken; a name or a column number may be given |
na.value | numeric; value given to missing valued cells in theresulting map |
... | arguments passed towrite.table, which is usedto write the numeric data |
Value
read.asciigrid returns the grid map read; either asan object of classSpatialGridDataFrame-class or, ifas.image is TRUE, as list with componentsx,y andz.
Author(s)
Edzer Pebesma
See Also
as.image.SpatialGridDataFrame,image
Examples
x <- read.asciigrid(system.file("external/test.ag", package="sp")[1])class(x)image(x)Methods for Function recenter in Package ‘sp’
Description
Methods for functionrecenter in packagesp to shift or re-center geographical coordinates for a Pacific view. All longitudes < 0 are added to 360, to avoid for instance parts of Alaska being represented on the far left and right of a plot because they have values straddling 180 degrees. In general, using a projected coordinate reference system is to be preferred, but this method permits a geographical coordinate reference system to be used. This idea was suggested by Greg Snow, and corresponds to the two world representations in themaps package.
Methods
- obj = "SpatialPolygons"
recenter a SpatialPolygons object
- obj = "Polygons"
recenter a Polygons object
- obj = "Polygon"
recenter an Polygon object
- obj = "SpatialLines"
recenter a SpatialLines object
- obj = "Lines"
recenter a Lines object
- obj = "Line"
recenter an Line object
Examples
crds <- matrix(c(179, -179, -179, 179, 50, 50, 52, 52), ncol=2)SL <- SpatialLines(list(Lines(list(Line(crds)), "1")), CRS("+proj=longlat +ellps=WGS84"))bbox(SL)SLr <- recenter(SL)bbox(SLr)rcrds <- rbind(crds, crds[1,])SpP <- SpatialPolygons(list(Polygons(list(Polygon(rcrds)),)), proj4string=CRS("+proj=longlat +ellps=WGS84"))bbox(SpP)SpPr <- recenter(SpP)bbox(SpPr)opar <- par(mfrow=c(1,2))plot(SpP)plot(SpPr)par(opar)crds <- matrix(c(-1, 1, 1, -1, 50, 50, 52, 52), ncol=2)SL <- SpatialLines(list(Lines(list(Line(crds)), "1")), CRS("+proj=longlat +ellps=WGS84"))bbox(SL)SLr <- recenter(SL)bbox(SLr)rcrds <- rbind(crds, crds[1,])SpP <- SpatialPolygons(list(Polygons(list(Polygon(rcrds)),)), proj4string=CRS("+proj=longlat +ellps=WGS84"))bbox(SpP)SpPr <- recenter(SpP)bbox(SpPr)opar <- par(mfrow=c(1,2))plot(SpP)plot(SpPr)par(opar)select points spatially
Description
select a number of points by digitizing the area they fall in
Usage
select.spatial(data, digitize = TRUE, pch = "+", rownames = FALSE)Arguments
data | data object of class, or extending |
digitize | logical; if TRUE, points in a digitized polygonare selected; if FALSE, points identified by mouse clicks are selected |
pch | plotting character used for points |
rownames | logical; if FALSE, row (coordinate) numbers are returned;if TRUE and data contains a data.frame part, row.names for selected pointsin the data.frame are returned. |
Value
if rownames == FALSE, array with either indexes (row numbers)of points inside the digitized polygon; if rownames == TRUE, characterarray with corresponding row names in the data.frame part
See Also
point.in.polygon,locator,SpatialPoints-class,SpatialPointsDataFrame-class
Examples
data(meuse)## the following command requires user interaction: left mouse## selects points, right mouse ends digitizingdata(meuse)coordinates(meuse) = c("x", "y")# select.spatial(meuse)A package providing classes and methods for spatial data: points,lines, polygons and grids
Description
This package provides S4 classes for importing, manipulating and exportingspatial data in R, and for methods including print/show, plot, subset,[,[[,\$, names, dim, summary, and a number ofmethods specific to spatial data handling.
Introduction
Several spatial statistical packages have been around for a long while,but no organized set of classes for spatial data has yet been devised.Many of the spatial packages make their own assumptions, or use theirown class definitions for spatial data, making it inconvenient to movefrom one package to another. This package tries to provide a solid setof classes for many different types of spatial data. The idea is thatspatial statistical packages will either support these classes (i.e.,directly read and write them) or will provide conversion to them, so thatwe have a base class set with which any package can exchange. This way,many-to-many conversions can be replace with one-to-many conversions,provided either in this package or the spatial packages. Wherever possibleconversion (coercion) functions are automatic, or provided by sp.
External packages that depend on sp will provide importing and exportingfrom and to external GIS formats, e.g. through GDAL, OGR or shapelib.
In addition, this package tries to provide convenient methods to print,summarize and plot such spatial data.
Dimensions
In principal, geographical data are two-dimensional, on a flat surface (amap) or on a sphere (the earth). This package provides space for dealingwith higher dimensional data where possible; this is e.g. very simplefor points and grids, but hard to do for polygons. Plotting functionsare devised primarily for two-dimensional data, or two-dimensionalprojections of higher dimensional data.
Coordinate reference systems
Central to spatial data is that they have a coordinate reference system,which is coded in object of CRS class. Central to operations on differentspatial data sets is that their coordinate reference system is compatible(i.e., identical).
This CRS can be a character string describing a reference system ina way understood by the PROJ.4 projection library, or a (character)missing value. An interface to the PROJ.4 library is available only ifthe R package rgdal is present.
Class structure
All spatial classes derive from a basic classSpatial, which onlyprovides a bounding box and a CRS. This class has no useful instances, butuseful derived classes.
SpatialPoints extends Spatial and has coordinates. The methodcoordinates extracts the numeric matrix with coordinates from anobject of class SpatialPoints, or from other (possibly derived) classesthat have points.
Objects of class SpatialGrid points on a regular grid. Either a full gridis stored or a partial grid (i.e., only the non-missing valued cells);callingcoordinates on them will give the coordinates for thegrid cells.
SpatialPoints, SpatialPixels and SpatialGrid can be of arbitrarydimension, although most of the effort is in making them work for twodimensional data.
SpatialLines provides lines, and SpatialPolygons provides polygons, i.e.,lines that end where they start and do not intersect with itself.SpatialLines and SpatialPolygons only have two-dimensional data.
SpatialPointsDataFrame extends SpatialPoints with a data slot, havinga data.frame with attribute data. Similarly, SpatialPixelsDataFrame,SpatialLinesDataFrame, SpatialPolygonsDataFrame extend the primaryspatial information with attribute data.
References
PROJ.4:https://github.com/OSGeo/PROJ
GDAL and OGR:https://gdal.org/.
Authors
sp is a collaborative effort of Edzer Pebesma, Roger Bivand, BarryRowlingson and Virgilo G\'omez-Rubio.
Deprecated functions in sp
Description
Deprecated functions is sp: getSpP*, getPolygon*, getLines* getSL*
Usage
set_evolution_status(value)get_evolution_status()Arguments
value | evolution status: only 2L to use sf functions in place of rgdal |
Note
Foroverlay the new implementation is found in theover method; this works slightly different and more consistent.
write map data for Mondrian
Description
The function outputs a SpatialPolygonsDataFrame object to be used by Mondrian
Usage
sp2Mondrian(SP, file, new_format=TRUE)Arguments
SP | a SpatialPolygonsDataFrame object |
file | file where output is written |
new_format | default TRUE, creates a text data file and a separate map file; the old format put both data sets in a single file - the map file is named by inserting "MAP_" into the file= argument after the rightmost directory separator (if any) |
Note
At this release, the function writes out a text file with both data and polygon(s) identified as belonging to each row of data.
Author(s)
Patrick Hausmann and Roger Bivand
References
https://www.theusrus.de/Mondrian/, Ihaka Lecture 1: 28 September 2023, Interactive Graphics and Data Analysis, Antony Unwinhttps://www.auckland.ac.nz/en/science/about-the-faculty/department-of-statistics/ihaka-lecture-series.html
Examples
if (require("sf", quietly=TRUE)) {td <- tempdir()xx <- as(sf::st_read(system.file("shape/nc.shp", package="sf")[1], quiet=TRUE), "Spatial")sp2Mondrian(xx, file=file.path(td, "sids1.txt"))}change feature IDs in spatial objects
Description
When the feature IDs need to be changed in SpatialLines* or SpatialPolygons* objects, these methods may be used. The new IDs should be a character vector of unique IDs of the correct length.
Methods
- obj = "SpatialLines", x = "character"
replace IDs in a SpatialLines object
- obj = "SpatialLinesDataFrame", x = "character"
replace IDs in a SpatialLinesDataFrame object
- obj = "SpatialPolygons", x = "character"
replace IDs in a SpatialPolygons object
- obj = "SpatialPolygonsDataFrame", x = "character"
replace IDs in a SpatialPolygonsDataFrame object
Note
It is usually sensible to keep a copy of the original feature IDs in the object, but this should be done by the user.
Author(s)
Roger Bivand
Examples
## Not run: if(require(sf)) {xx <- as(st_read(system.file("shape/nc.shp", package="sf")[1]), "Spatial")row.names(xx) <- as.character(xx$"FIPSNO")row.names(as(xx, "data.frame"))xx1 <- spChFIDs(xx, as.character(xx$CNTY_ID))row.names(as(xx1, "data.frame"))}## End(Not run)Euclidean or Great Circle distance between points
Description
The function returns a vector of distances between a matrix of 2D points, first column longitude, second column latitude, and a single 2D point, using Euclidean or Great Circle distance (WGS84 ellipsoid) methods.
Usage
spDistsN1(pts, pt, longlat = FALSE)spDists(x, y = x, longlat = FALSE, segments = FALSE, diagonal = FALSE)Arguments
pts | A matrix of 2D points, first column x/longitude, second column y/latitude, or a SpatialPoints or SpatialPointsDataFrame object |
pt | A single 2D point, first value x/longitude, second value y/latitude, or a SpatialPoints or SpatialPointsDataFrame object with one point only |
x | A matrix of n-D points with row denoting points, first column x/longitude, second column y/latitude, or a Spatial object that has acoordinates method |
y | A matrix of n-D points with row denoting points, first column x/longitude, second column y/latitude, or a Spatial object that has acoordinates method |
longlat | logical;if FALSE, Euclidean distance,if TRUE Great Circle (WGS84 ellipsoid) distance; if |
segments | logical; if |
diagonal | logical; if |
Value
spDistsN1 returns a numeric vector of distances in the metric of the points if longlat=FALSE, or in kilometers if longlat=TRUE.
spDists returns a full matrix of distances in the metric of the points if longlat=FALSE, or in kilometers if longlat=TRUE; it usesspDistsN1 in case points are two-dimensional. In case ofspDists(x,x), it will compute all n x n distances, not the sufficient n x (n-1).
Note
The function can also be used to find a local kilometer equivalent to a plot scaled in decimal degrees in order to draw a scale bar.
Author(s)
Roger Bivand, Edzer Pebesma
References
http://www.abecedarical.com/javascript/script_greatcircle.html
See Also
Examples
ll <- matrix(c(5, 6, 60, 60), ncol=2)km <- spDistsN1(ll, ll[1,], longlat=TRUE)zapsmall(km)utm32 <- matrix(c(276.9799, 332.7052, 6658.1572, 6655.2055), ncol=2)spDistsN1(utm32, utm32[1,])dg <- spDistsN1(ll, ll[1,])dgdg[2]/km[2]data(meuse)coordinates(meuse) <- c("x", "y")res <- spDistsN1(meuse, meuse[1,])summary(res)p1 = SpatialPoints(cbind(1:3, 1:3))spDists(p1)spDists(p1, p1)spDists(p1, p1, diagonal = TRUE)try(spDists(p1, p1, segments = TRUE))spDists(p1, segments = TRUE)p2 = SpatialPoints(cbind(5:2, 2:5))spDists(p1, p2)try(spDists(p1, p2, diagonal = TRUE)) # failstry(spDists(p1, p2, segments = TRUE)) # fails# longlat points:proj4string(p1) = "+proj=longlat +ellps=WGS84"proj4string(p2) = "+proj=longlat +ellps=WGS84"is.projected(p1)is.projected(p2)spDists(p1)spDists(p1, p1)spDists(p1, p1, diagonal = TRUE)spDists(p1, p2)try(spDists(p1, p2, diagonal = TRUE)) # failsspDists(p1, p2[1:length(p1),], diagonal = TRUE)spDists(p1, segments = TRUE)spDists(p1[0],p2[0],diagonal=TRUE)spDists(p1[0])p1 = SpatialPoints(cbind(1:3, 1:3, 1:3))spDists(p1)spDists(p1, p1)try(spDists(p1, p1, diagonal = TRUE))try(spDists(p1, p1, segments = TRUE))try(spDists(p1, segments = TRUE))p2 = SpatialPoints(cbind(5:2, 2:5, 3:6))spDists(p1, p2)try(spDists(p1, p2, diagonal = TRUE)) # failstry(spDists(p1, p2, segments = TRUE)) # failsspTransform for map projection and datum transformation
Description
spTransform for map projection and datum transformation
Usage
spTransform(x, CRSobj, ...)Arguments
x | object to be transformed |
CRSobj | object of classCRS, or of class |
... | further arguments (ignored) |
Value
object with coordinates transformed to the new coordinate referencesystem.
Note
Packagesf provides the methods doing actual transformation.
Plot methods for spatial data with attributes
Description
Lattice (trellis) plot methods for spatial data with attributes
Usage
spplot(obj, ...)spplot.grid(obj, zcol = names(obj), ..., names.attr, scales = list(draw = FALSE), xlab = NULL, ylab = NULL, aspect = mapasp(obj,xlim,ylim), panel = panel.gridplot, sp.layout = NULL, formula, xlim = bbox(obj)[1, ], ylim = bbox(obj)[2, ], checkEmptyRC = TRUE, col.regions = get_col_regions())spplot.polygons(obj, zcol = names(obj), ..., names.attr, scales = list(draw = FALSE), xlab = NULL, ylab = NULL, aspect = mapasp(obj,xlim,ylim), panel = panel.polygonsplot, sp.layout = NULL, formula, xlim = bbox(obj)[1, ], ylim = bbox(obj)[2, ], col.regions = get_col_regions())spplot.points(obj, zcol = names(obj), ..., names.attr, scales = list(draw = FALSE), xlab = NULL, ylab = NULL, aspect = mapasp(obj,xlim,ylim), panel = panel.pointsplot, sp.layout = NULL, identify = FALSE, formula, xlim = bbexpand(bbox(obj)[1, ], 0.04), ylim = bbexpand(bbox(obj)[2, ], 0.04), edge.col = "transparent", colorkey = FALSE, col.regions = get_col_regions())mapLegendGrob(obj, widths = unit(1, "cm"), heights = unit(1, "cm"),fill = "black", just = "right")sp.theme(set = FALSE, regions = list(col = bpy.colors(100)), ...)layout.north.arrow(type = 1)layout.scale.bar(height = 0.05)spplot.locator(n = 512, type = "n", ...)set_col_regions(value)get_col_regions()Arguments
obj | object of class extendingSpatial-class |
zcol | character; attribute name(s) or column number(s) in attribute table |
names.attr | names to use in panel, if different from zcol names |
scales | scales argument to be passed to Lattice plots; use |
... | other arguments passed tolevelplot (grids, polygons) orxyplot (points) |
xlab | label for x-axis |
ylab | label for y-axis |
aspect | aspect ratio for spatial axes; defaults to "iso" (one uniton the x-axis equals one unit on the y-axis) but may be set to moresuitable values if the data are e.g. if coordinates are latitude/longitude |
panel | depending on the class of obj,panel.polygonsplot (forpolygons or lines),panel.gridplot (grids) orpanel.pointsplot(points) is used; for further control custom panel functions can besupplied that call one of these panel functions, but do read below how theargument |
sp.layout | NULL or list; see notes below |
identify | if not FALSE, identify plotted objects (currently only workingfor points plots). Labels for identification are the row.names of theattribute table |
formula | optional; may be useful to plot a transformed value. Defaultsto |
xlim | numeric; x-axis limits |
ylim | numeric; y-axis limits |
edge.col | color of symbol edge |
colorkey | if FALSE, use symbol key; if TRUE, use continuous, levelplot-like colorkey; if list, follow syntax of argument |
widths | width of grob |
heights | heights of grob |
fill | fill color of grob |
just | grob placement justification |
set | logical; if TRUE, trellis.par.set is called, else a list is returnedthat can be passed to trellis.par.set() |
regions | color ramp for the theme |
height | height of scale bar; width is 1.0 |
n | see locator |
type | see locator |
checkEmptyRC | logical; if TRUE, a check is done to see ifempty rows or columns are present, and need to be taken care of. Settingto FALSE may improve speed. |
col.regions | vector with fill colours; in case the variableto be plotted is a factor, this vector should have length equal to thenumber of factor levels |
value | vector with color values, default for |
Value
spplot returns a lattice plot of class "trellis", if you fail to "see" it,explicitly callprint(spplot(...)). Ifidentify is TRUE,the plot is plotted and the return value is a vector with row names ofthe selected points.
spplot.locator returns a matrix with identified point locations;usetrellis.focus first to focus on a given panel.
get_col_regions returns the default value forcol.regions
Methods
- obj = "SpatialPixelsDataFrame"
seespplot
- obj = "SpatialGridDataFrame"
seespplot
- obj = "SpatialPolygonsDataFrame"
seespplot
- obj = "SpatialLinesDataFrame"
seespplot
- obj = "SpatialPointsDataFrame"
seespplot
Note
Missing values in the attributes are (currently) not allowed.
spplot.grid,spplot.polygons andspplot.points are S4methods forspplot; seespplot-methods.
Useful arguments that can be passed as... are:
layoutinteger; for the layout of panels (cols,rows)
prettylogical; choose colour breaks at pretty numbers?
atspecify at which values colours change
as.tablelogical; start drawing panels upper-left insteadof lower-left
pageto add marks to each plotted page
for useful values see the appropriate documentation ofxyplot(in case of points), andlevelplot (otherwise).
Ifobj is of SpatialPointsDataFrame, the following options areuseful to pass:
key.spacecharacter: "bottom", "right", "left" or "right" to denotekey location, or list: see argument key in the help forxyplot whatthe options are
legendEntriescharacter; array with key legend (text) entries; suitable defaults obtained from data
cutsnumber of cuts, or, for objects of classSpatialPointsDataFrame only, the actual cuts to use
do.loglogical; if TRUE use log-linear scale to divide range in equal cuts,else use a linear scale if
cutsis only number of cutspchinteger; plotting character to use; defaults to 16 if fill is TRUE, else 1
cexnumeric; character expansion, proportional to default value of 1
filllogical; use filled circles?
layout.north.arrow andlayout.scale.bar can be usedto set a north arrow or scale bar.
Thesp.layout argument is either a single layout item, or a listwith one or more layout items. A layout item is one of
a list with one or more
Spatial*objects, along withstyle arguments likecol,lty,pch,filletc.a list with its first argument the layout function orthe name of the layout function to be called:
sp.pointsforSpatialPoints,sp.polygonsfor SpatialPolygons object,sp.linesfor a SpatialLines object, andsp.textfor text to place. Thesecond argument contains the object (or text) to be plotted; remainingarguments are passed to the correspondingpanel.*functions.
The order of items insp.layout matters; objects are drawn in theorder they appear. With respect toobj, default plot order andprecedence ofsp.layout items is as follows: for points andlines,sp.layout items are drawn over (after)obj; forgrids and polygons,sp.layout items are drawn behind (before)obj. Transparency may further help making multiple thingsvisible. Adding afirst argument to a layout item overrides itsdefault plotting order with respect toobj:
Special control elements ofsp.layout items:
firstlogical; should the layout item be drawn beforethe
obj(TRUE), or after (FALSE)? This overridesthe default order (points and lines in front, polygons and grids behind).whichinteger; controls to which panel a layoutitem should be added. If
whichis present in the main,top-level list it applies to all layout items; in sub-lists withlayout items it denotes the (set of) panel(s) in which the layoutitem should be drawn. Without awhichitem, layout itemsare drawn in each panel.
sp.theme returns a lattice theme; use, after loading packagelattice, the commandtrellis.par.set(sp.theme())after a device is opened or changed to make this work. Currently, this onlysets the colors tobpy.colors.
If the attributes to be plotted are of type factor, spplot triesto create a legend that reflects this. In this case, the color ramppassed needs to be of the same length as the number of factor levels.The factor levels are derived from the first map; subsequent factorswith different factor levels result in an error.
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
References
See Also
xyplot,levelplot,panel.identify to identify objects
Examples
library(lattice)trellis.par.set(sp.theme()) # sets bpy.colors() rampdemo(meuse, ask = FALSE, echo = FALSE)l2 = list("SpatialPolygonsRescale", layout.north.arrow(), offset = c(181300,329800), scale = 400)l3 = list("SpatialPolygonsRescale", layout.scale.bar(), offset = c(180500,329800), scale = 500, fill=c("transparent","black"))l4 = list("sp.text", c(180500,329900), "0")l5 = list("sp.text", c(181000,329900), "500 m")spplot(meuse, c("ffreq"), sp.layout=list(l2,l3,l4,l5), col.regions= "black", pch=c(1,2,3), key.space=list(x=0.1,y=.95,corner=c(0,1)))spplot(meuse, c("zinc", "lead"), sp.layout=list(l2,l3,l4,l5, which = 2),key.space=list(x=0.1,y=.95,corner=c(0,1)))# plotting factors:meuse$f = factor(sample(letters[6:10], 155, replace=TRUE),levels=letters[1:10])meuse$g = factor(sample(letters[1:5], 155, replace=TRUE),levels=letters[1:10])spplot(meuse, c("f","g"), col.regions=bpy.colors(10))if (require(RColorBrewer)) {spplot(meuse, c("ffreq"), sp.layout=list(l2,l3,l4,l5),col.regions=brewer.pal(3, "Set1"))}meuse.grid$g = factor(sample(letters[1:5], 3103, replace=TRUE),levels=letters[1:10])meuse.grid$f = factor(sample(letters[6:10], 3103, replace=TRUE),levels=letters[1:10])spplot(meuse.grid, c("f","g"), col.regions=bpy.colors(10))# example modifying colorkey for points:spplot(meuse["dist"], colorkey = list(right = list( # see ?levelplot in package trellis, argument colorkey:fun = draw.colorkey, args = list(key = list(at = seq(0, 1, .1), # colour breakscol = bpy.colors(11), # colourslabels = list(at = c(0, .2, .4, .6, .8, 1), labels = c("0x", "20x", "40x", "60x", "80x", "100x")))))))l6 = list(meuse.grid["dist"], col = grey(seq(.5,.9,length.out=10)))spplot(meuse, c("zinc", "lead"), sp.layout = l6)spplot(meuse, c("zinc", "lead"), sp.layout = list(meuse.grid, meuse.riv, col = 'grey'))# Custom legend placement, taken from # http://stackoverflow.com/questions/29344692/custom-placement-of-spplot-legend-in-the-maps <- spplot(meuse.grid[,'dist'], colorkey = list(space = "left", height = 0.4))args <- s$legend$left$args$key## Prepare list of arguments needed by `legend=` argument (as described in ?xyplot)library(lattice) # draw.colorkeylegendArgs <- list(fun = draw.colorkey, args = list(key = args), corner = c(0.05,.75))## Call spplot() again, this time passing in to legend the arguments## needed to print a color keyspplot(meuse.grid[,'dist'], colorkey = FALSE, legend = list(inside = legendArgs))sample point locations in (or on) a spatial object
Description
sample point locations within a square area, a grid,a polygon, or on a spatial line, using regular or random samplingmethods; the methods used assume that the geometry used is not spherical, so objects should be in planar coordinates
Usage
spsample(x, n, type, ...)makegrid(x, n = 10000, nsig = 2, cellsize, offset = rep(0.5, nrow(bb)),pretty = TRUE)Arguments
x | Spatial object; |
... | optional arguments, passed to the appropriate |
n | (approximate) sample size |
type | character; |
bb | bounding box of the sampled domain; setting this to a smallervalue leads to sub-region sampling |
offset | for square cell-based sampling types (regular, stratified, nonaligned, hexagonal): the offset (position) of the regulargrid; the default for |
cellsize | if missing, a cell size is derived from the sample size |
nsig | for "pretty" cell size; |
pretty | logical; if |
Value
an object of classSpatialPoints-class. The number ofpoints is only guaranteed to equaln when sampling is done in asquare box, i.e. (sample.Spatial). Otherwise, the obtained numberof points will have expected valuen.
Whenx is of a class deriving fromSpatial-class for whichnospsample-methods exists, sampling is done in the bounding boxof the object, usingspsample.Spatial. An overlay usingover may be necessary to select the features inside the geometryafterwards.
Sampling type"nonaligned" is not implemented for line objects.
Some methods may return NULL if no points could be successfully placed.
makegrid makes a regular grid that coversx; whencellsize is not given it derives one from the number of gridpoints requested (approximating the number of cells). It tries tochoose pretty cell size and grid coordinates.
Methods
- x = "Spatial"
sample in the bbox of
x- x = "Line"
sample on a line
- x = "Polygon"
sample in a Polygon
- x = "Polygons"
sample in a Polygons object, consisting of possiblymultiple Polygon objects (holes must be correctly defined, use
checkPolygonsHolesif need be)- x = "SpatialPolygons"
sample in an SpatialPolygons object; samplingtakes place over all Polygons objects present, use subsetting to varysampling intensity (density); holes must be correctly defined, use
checkPolygonsHolesif need be- x = "SpatialGrid"
sample in an SpatialGrid object
- x = "SpatialPixels"
sample in an SpatialPixels object
Note
If anPolygon-class object has zero area (i.e. is a line),samples on this line element are returned. If the area is very closeto zero, the algorithm taken here (generating points in a squarearea, selecting those inside the polygon) may be very resourceintensive. When numbers of points per polygon are small andtype="random", the number searched for is inflated to ensure hits,and the points returned sampled among these.
The following two arguments can be further specified:
nclusters Number of clusters (strata) to sample from.
iter(default = 4) number of times to try to place sample pointsin a polygon before giving up and returning NULL - this may occur whentrying to hit a small and awkwardly shaped polygon in a large boundingbox with a small number of points
Author(s)
Edzer Pebesma,edzer.pebesma@uni-muenster.de
References
Chapter 3 in B.D. Ripley, 1981. Spatial Statistics, Wiley
Fibonacci sampling: Alvaro Gonzalez, 2010. Measurement of Areas on aSphere Using Fibonacci and Latitude-Longitude Lattices. MathematicalGeosciences 42(1), p. 49-64
See Also
Examples
data(meuse.riv)meuse.sr = SpatialPolygons(list(Polygons(list(Polygon(meuse.riv)), "x")))plot(meuse.sr)points(spsample(meuse.sr, n = 1000, "regular"), pch = 3)plot(meuse.sr)points(spsample(meuse.sr, n = 1000, "random"), pch = 3)plot(meuse.sr)points(spsample(meuse.sr, n = 1000, "stratified"), pch = 3)plot(meuse.sr)points(spsample(meuse.sr, n = 1000, "nonaligned"), pch = 3)plot(meuse.sr)points(spsample(meuse.sr@polygons[[1]], n = 100, "stratified"), pch = 3, cex=.5)data(meuse.grid)gridded(meuse.grid) = ~x+yimage(meuse.grid)points(spsample(meuse.grid,n=1000,type="random"), pch=3, cex=.5)image(meuse.grid)points(spsample(meuse.grid,n=1000,type="stratified"), pch=3, cex=.5)image(meuse.grid)points(spsample(meuse.grid,n=1000,type="regular"), pch=3, cex=.5)image(meuse.grid)points(spsample(meuse.grid,n=1000,type="nonaligned"), pch=3, cex=.5)fullgrid(meuse.grid) = TRUEimage(meuse.grid)points(spsample(meuse.grid,n=1000,type="stratified"), pch=3,cex=.5)rearrange data in SpatialPointsDataFrame or SpatialGridDataFrame for plotting with spplot (levelplot/xyplot wrapper)
Description
rearrange SpatialPointsDataFrame for plotting with spplot or levelplot
Usage
spmap.to.lev(data, zcol = 1:n, n = 2, names.attr)## S3 method for class 'SpatialPointsDataFrame'stack(x, select, ...)## S3 method for class 'SpatialGridDataFrame'stack(x, select, ...)Arguments
data | object of class (or extending) SpatialPointsDataFrame orSpatialGridDataFrame |
zcol | z-coordinate column name(s), or a column number (range) (afterremoving the spatial coordinate columns: 1 refers to the first non-coordinatecolumn, etc. ) |
names.attr | names of the set of z-columns (these nameswill appear in the plot); if omitted, column names of |
n | number of columns to be stacked |
x | same as |
select | same as |
... | ignored |
Value
spmap.to.lev returns a data frame with the following elements:
x | x-coordinate for each row |
y | y-coordinate for each row |
z | column vector with each of the elements in columns |
name | factor; name of each of the stacked |
stack is an S3 method: it return a data.frame with a columnvalues that has the stacked coordinates and attributes, and acolumnind that indicates the variable stacked; it alsoreplicates the coordinates.
See Also
Examples
library(lattice)data(meuse.grid) # data framecoordinates(meuse.grid) = c("x", "y") # promotes to SpatialPointsDataFramemeuse.grid[["idist"]] = 1 - meuse.grid[["dist"]] # add variable# the following is made much easier by spplot:levelplot(z~x+y|name, spmap.to.lev(meuse.grid, z=c("dist","idist"), names.attr =c("distance", "inverse of distance")), aspect = "iso")levelplot(values~x+y|ind, as.data.frame(stack(meuse.grid)),aspect = "iso")gridded(meuse.grid) = TRUElevelplot(z~x+y|name, spmap.to.lev(meuse.grid, z=c("dist","idist"), names.attr =c("distance", "inverse of distance")), aspect = "iso")levelplot(values~x+y|ind, as.data.frame(stack(meuse.grid)), asp = "iso")Compute surface area of a digital elevation model.
Description
It is often said that if Wales was flattened out it would havean area bigger than England. This function computes the surfacearea of a grid of heights taking into account the sloping natureof the surface.
Usage
surfaceArea(m, ...)surfaceArea.matrix(m, cellx = 1, celly = 1, byCell = FALSE)Arguments
m | a matrix of height values, or an object of classSpatialPixelsDataFrame orSpatialGridDataFrame. |
cellx | the size of the grid cells in the x-direction, in the same units as the height values. |
celly | the size of the grid cells in the y-direction, in the same units asthe height values. |
byCell | return single value or matrix of values |
... | ignored |
Value
Either a single value of the total area if byCell=FALSE, or a matrixthe same shape as m of individual cell surface areas ifbyCell=TRUE. In this case, the sum of the returned matrix should bethe same value as that which is returned if byCell=FALSE.
Missing values (NA) in the input matrix are allowed. They will producean NA in the output matrix for byCell=TRUE, and contribute zero to thetotal area. They also have an effect on adjacent cells - see codecomments for details.
Methods
- obj = "matrix"
takes a matrix as input, requires cellx and celly to be set
- obj = "SpatialGridDataFrame"
takes an object of classSpatialGridDataFrame as input, and retrieves cellx and celly from this
- obj = "SpatialPixelsDataFrame"
takes an object of classSpatialPixelsDataFrame as input, and retrieves cellx and celly from this
Author(s)
Barry Rowlingson <b.rowlingson@lancaster.ac.uk>, integration in sp EdzerPebesma.
References
Calculating Landscape Surface Area from Digital Elevation Models, Jeff S. JennessWildlife Society Bulletin, Vol. 32, No. 3 (Autumn, 2004), pp. 829-839
Examples
surfaceArea(volcano)image(surfaceArea(volcano,byCell=TRUE))data(meuse.grid)gridded(meuse.grid) = ~x+yimage(surfaceArea(meuse.grid["dist"], byCell=TRUE))surfaceArea(meuse.grid["dist"])find point pairs with equal spatial coordinates
Description
find point pairs with equal spatial coordinates
Usage
zerodist(obj, zero = 0.0, unique.ID = FALSE, memcmp = TRUE) zerodist2(obj1, obj2, zero = 0.0, memcmp = TRUE) remove.duplicates(obj, zero = 0.0, remove.second = TRUE, memcmp = TRUE)Arguments
obj | object of, or extending, classSpatialPoints |
obj1 | object of, or extending, classSpatialPoints |
obj2 | object of, or extending, classSpatialPoints |
zero | distance values less than or equal to this threshold value areconsidered to have zero distance (default 0.0);units are those of the coordinates for projected data or unknown projection,or km if coordinates are defined to be longitude/latitude |
unique.ID | logical; if TRUE, return an ID (integer) for each point that is different only when two points do not share the same location |
memcmp | use |
remove.second | logical; if TRUE, the second of each pair of duplicatepoints is removed, if FALSE remove the first |
Value
zerodist andzerodist2 return a two-column matrixwith in each row pairs of row numbers with identical coordinates;a matrix with zero rows is returned if no such pairs are found. Forzerodist, row number pairs refer to row pairs inobj. Forzerodist2, row number pairs refer to rows inobj andobj2, respectively.remove.duplicates removes duplicateobservations if present, and else returnsobj.
Note
When using kriging, duplicate observations sharing identicalspatial locations result in singular covariance matrices.This function may help identify and remove spatial duplices.The full matrix with all pair-wise distances is not stored; thedouble loop is done at the C level.
Whenunique.ID=TRUE is used, an integer index is returned. sp1.0-14 returned the highest index, sp 1.0-15 and later return thelowest index.
Whenzero is 0.0 andmemcmp is notFALSE,zerodist usesmemcmp to evaluate exact equality ofcoordinates; there may be cases where this results in a differentevaluation compared to doing the double arithmetic of computingdistances.
Examples
data(meuse)summary(meuse)# pick 10 rowsn <- 10ran10 <- sample(nrow(meuse), size = n, replace = TRUE)meusedup <- rbind(meuse, meuse[ran10, ])coordinates(meusedup) <- c("x", "y")zd <- zerodist(meusedup)sum(abs(zd[1:n,1] - sort(ran10))) # 0!# remove the duplicate rows:meusedup2 <- meusedup[-zd[,2], ]summary(meusedup2)meusedup3 <- subset(meusedup, !(1:nrow(meusedup) %in% zd[,2]))summary(meusedup3)coordinates(meuse) <- c("x", "y")zerodist2(meuse, meuse[c(10:33,1,10),])