Debian Codegraph @

vignettes/intro_sp.Rnw

raw
1 % dimensions(x) returns number of spatial dimensions
2 % y = transform(x, "proj4string")
3 % bbox(x)
4 % coordinates(x) ; <-
5 % rings(x) ; <-
6 % method to retrieve lines? --> Lines()?
7 % gridded(x) ; <-
8 %
9 \documentclass{article}
10 % \VignetteIndexEntry{sp: classes and methods for spatial data}
11
12 \usepackage{graphicx}
13 \usepackage[colorlinks=true,urlcolor=blue]{hyperref}
14
15 \usepackage{color}
16
17 \usepackage{Sweave}
18 \newcommand{\strong}[1]{{\normalfont\fontseries{b}\selectfont #1}}
19 \let\pkg=\strong
20 \newcommand{\code}[1]{{\tt #1}}
21 \newcommand{\proglang}[1]{{\bf #1}}
22
23 \title{ Classes and Methods for Spatial Data:\\
24 the \pkg{sp} Package }
25 \author{Edzer Pebesma\footnote{Institute for Geoinformatics,
26 University of Muenster, Heisenbergstra{\ss}e 2, 48149 M\"{u}nster, Germany.
27 \code{[email protected]}}
28 \and
29 Roger S.\ Bivand\footnote{Economic Geography Section, Department of Economics, %
30 Norwegian School of Economics and Business Administration, %
31 Breiviksveien 40, N-5045 Bergen, Norway; \code{[email protected]}}}
32 \date{Feb 2005}
33
34 \begin{document}
35
36 \maketitle
37 \tableofcontents
38
39 \section{Introduction}
40
41 The \pkg{sp} package provides classes and methods for dealing
42 with spatial data in \proglang{R}\footnote{
43 The motivation to write this package was born on a
44 pre-conference spatial data workshop during DSC 2003.
45 At that time, the advantage of having multiple R packages for spatial
46 statistics seemed to be hindered by a lack of a uniform interface for
47 handling spatial data. Each package had its own conventions on how
48 spatial data were stored and returned. With this package, and packages
49 supporting the classes provided here, we hope that \proglang{R} with its extension
50 packages becomes more coherent for analyzing different types of spatial data.
51 }. The spatial data structures implemented
52 include points, lines, polygons and grids; each of them with or
53 without attribute data. We have chosen to use S4 classes and
54 methods style (Chambers, 1998) to allow validation of objects
55 created. Although we mainly aim at using spatial data in the
56 geographical (two-dimensional) domain, the data structures that
57 have a straightforward implementation in higher dimensions (points,
58 grids) do allow this.
59
60 From the package home page on CRAN,
61 \url{https://cran.r-project.org/package=sp}, links to a graph
62 gallery with R code, and the development source tree are found.
63
64 This vignette describes the classes, methods and functions provided
65 by \pkg{sp}. Instead of manipulating the class slots (components)
66 directly\footnote{which is possible, but not recommended because
67 validity of resulting objects is no longer verified}, we provide
68 methods and functions to create or modify the classes from elementary
69 types such as matrices, {\tt data.frame}s or lists and convert them back
70 to any of these types. Also, coercion (type casting) from one class
71 to the other is provided, where relevant.
72
73 Package \pkg{sp} is loaded by
74 <<>>=
75 library(sp)
76 @
77
78 <<echo=FALSE,print=FALSE>>=
79 set.seed(13331)
80 # library(lattice)
81 @
82
83 \section{Spatial data classes}
84
85 The spatial data classes implemented are points, grids, lines,
86 rings and polygons. Package \pkg{sp} provides classes for the
87 spatial-only information (the topology), e.g. \code{SpatialPoints},
88 and extensions for the case where attribute information stored in
89 a \code{data.frame} is available for each spatial entity (e.g. for
90 points, the \code{SpatialPointsDataFrame}). The available data
91 classes are:
92
93 \begin{center}
94 \begin{tabular}{lllll}
95 data type & class & attributes & contains \\ \hline
96 points & \code{SpatialPoints} & No &\code{Spatial} \\
97 points & \code{SpatialPointsDataFrame} & \code{data.frame} &\code{SpatialPoints} \\
98 multipoints & \code{SpatialMultiPoints} & No &\code{Spatial} \\
99 multipoints & \code{SpatialMultiPointsDataFrame} & \code{data.frame} &\code{SpatialMultiPoints} \\
100 pixels & \code{SpatialPixels} & No &\code{SpatialPoints} \\
101 pixels & \code{SpatialPixelsDataFrame} & \code{data.frame} &\code{SpatialPixels} \\
102 & & &\code{SpatialPointsDataFrame} \\
103 full grid & \code{SpatialGrid } & No &\code{SpatialPixels} \\
104 full grid & \code{SpatialGridDataFrame} & \code{data.frame} &\code{SpatialGrid} \\
105 line & \code{Line} & No & \\
106 lines & \code{Lines} & No & \code{Line} list \\
107 lines & \code{SpatialLines} & No & \code{Spatial}, \code{Lines} list \\
108 lines & \code{SpatialLinesDataFrame} & \code{data.frame} &\code{SpatialLines} \\
109 polygons & \code{Polygon} & No &\code{Line} \\
110 polygons & \code{Polygons} & No &\code{Polygon} list \\
111 polygons & \code{SpatialPolygons} & No &\code{Spatial}, \code{Polygons} list \\
112 polygons & \code{SpatialPolygonsDataFrame} & \code{data.frame} &\code{SpatialPolygons} \\
113 \end{tabular}
114 \end{center}
115
116 The class \code{Spatial} only holds metadata common to all derived
117 classes (bounding box, coordinate reference system), and is of
118 convenient for defining methods that are common to all derived
119 classes. In the following sections we will show how we can create
120 objects of these classes from scratch or from other objects, and
121 which methods and functions are available to them.
122
123 \section{Manipulating spatial objects}
124
125 Although entries in spatial objects are in principle accessible through
126 their slot name, e.g. \code{x@coords} contains the coordinates of an object
127 of class or extending \code{SpatialPoints}, we strongly encourage users
128 to access the data by using functions and methods, in this case {\tt
129 coordinates(x)} to retrieve the coordinates.
130
131 \subsection{Standard methods}
132
133 Selecting, retrieving or replacing certain attributes in spatial objects
134 with attributes is done using standard methods
135 \begin{itemize}
136 \item \verb|[| select "rows" (features) and/or columns in the data attribute
137 table; e.g. \code{meuse[1:2, "zinc"]} returns a \code{SpatialPointsDataFrame}
138 with the first two points and an attribute table with only variable "zinc".
139 \item \verb|[[| extracts a column from the data attribute table
140 \item \verb|[[<-| assign or replace a column in the data attribute
141 table.
142 \end{itemize}
143 Other methods available are: \code{plot}, \code{summary}, \code{print},
144 \code{dim} and \code{names} (operate on the data.frame part), {\tt
145 as.data.frame}, \code{as.matrix} and \code{image} (for gridded data),
146 \code{lines} (for line data), \code{points} (for point data), \code{subset}
147 (points and grids), \code{stack} (point and grid data.frames), \code{over}
148 for spatial joins,
149 \code{spplot}, and \code{length} (number of features).
150
151 \subsection{Spatial methods}
152 A number of spatial methods are available for the classes in \pkg{sp}:
153 \begin{itemize}
154 \item \code{dimensions(x)} returns number of spatial dimensions
155 \item \code{y = spTransform(x, CRS("+proj=longlat +datum=WGS84"))}
156 convert or transform from one coordinate reference system (geographic projection)
157 to another (requires package rgdal to be installed)
158 \item \code{bbox(x)} returns a matrix with the coordinates bounding box;
159 the dimensions form rows, min/max form the columns
160 \item \code{coordinates(x)} returns a matrix with the spatial coordinates
161 %\item \code{rings(x)} retrieve the spatial rings (polygons) of an
162 %object deriving from \code{SpatialPolygons}
163 % \item \code{method to retrieve lines? --> Lines()?
164 \item \code{gridded(x)} tells whether \code{x} derives from SpatialPixels, or when
165 used in assignment, coerces a \code{SpatialPoints} object into a \code{SpatialPixels} object.
166 \item \code{spplot(x)} plots attributes, possibly in combination with
167 other types of data (points, lines, grids, polygons), and possibly in
168 as a conditioning plot for multiple attributes
169 \item \code{over(x, y)} retrieve index or attributes of \code{y} corresponding
170 (intersecting) with spatial locations of \code{x}.
171 \item \code{spsample(x)} samples point coordinates in the continuous space
172 of \code{SpatialPolygons}, a gridded area, or along a \code{SpatialLines}. Subsetting
173 and \code{sample} can be used to randomly subsample full spatial entities.
174 \item \code{geometry(x)} strips the \code{data.frame}, and returns the geometry-only
175 object
176 \end{itemize}
177
178 \section{Spatial points}
179
180 \subsection{Points without attributes}
181
182 We can generate a set of 10 points on the unit square $[0,1] \times
183 [0,1]$ by
184 <<echo=TRUE,print=FALSE>>=
185 xc = round(runif(10), 2)
186 yc = round(runif(10), 2)
187 xy = cbind(xc, yc)
188 xy
189 @
190 this $10 \times 2$ matrix can be converted into a \code{SpatialPoints}
191 object by
192
193 <<echo=TRUE,print=FALSE,fig=FALSE>>=
194 xy.sp = SpatialPoints(xy)
195 xy.sp
196 plot(xy.sp, pch = 2)
197 @
198 The plot is shown in figure \ref{fig:points}.
199
200 \begin{figure}
201 \begin{center}
202 <<echo=FALSE,print=FALSE,fig=TRUE>>=
203 plot(xy.sp, pch = 2)
204 @
205 \end{center}
206 \caption{plot of \code{SpatialPoints} object; aspect ratio of x and y axis units is 1}
207 \label{fig:points}
208 \end{figure}
209
210 We can retrieve the coordinates from \code{xy.sp} by
211 <<echo=TRUE>>=
212 xy.cc = coordinates(xy.sp)
213 class(xy.cc)
214 dim(xy.cc)
215 @
216 and other methods retrieve the bounding box, the dimensions, select points
217 (not dimensions or columns), coerce to a data.frame, or print a summary:
218 <<echo=TRUE>>=
219 bbox(xy.sp)
220 dimensions(xy.sp)
221 xy.sp[1:2]
222 xy.df = as.data.frame(xy.sp)
223 class(xy.df)
224 dim(xy.df)
225 summary(xy.sp)
226 @
227
228 \subsection{Points with attributes}
229
230 One way of creating a \code{SpatialPointsDataFrame} object is by building
231 it from a a \code{SpatialPoints} object and a data.frame containing
232 the attributes:
233 <<echo=TRUE>>=
234 df = data.frame(z1 = round(5 + rnorm(10), 2), z2 = 20:29)
235 df
236 xy.spdf = SpatialPointsDataFrame(xy.sp, df)
237 xy.spdf
238 summary(xy.spdf)
239 dimensions(xy.spdf)
240 xy.spdf[1:2, ] # selects row 1 and 2
241 xy.spdf[1] # selects attribute column 1, along with the coordinates
242 xy.spdf[1:2, "z2"] # select row 1,2 and attribute "z2"
243 xy.df = as.data.frame(xy.spdf)
244 xy.df[1:2,]
245 xy.cc = coordinates(xy.spdf)
246 class(xy.cc)
247 dim(xy.cc)
248 @
249 A note on selection with \verb|[|: the behaviour is as much as possible
250 copied from that of \code{data.frame}s, but coordinates are always
251 sticky and a \code{SpatialPointsDataFrame} is always returned; {\tt
252 drop=FALSE} is not allowed. If coordinates should be dropped, use the
253 \code{as.data.frame} method and select the non-coordinate data, or use
254 \verb|[[| to select a single attribute column (example below).
255
256 \code{SpatialPointsDataFrame} objects can be created directly from
257 data.frames by specifying which columns contain the coordinates:
258 <<echo=TRUE>>=
259 df1 = data.frame(xy, df)
260 coordinates(df1) = c("xc", "yc")
261 df1
262 @
263 or
264 <<echo=TRUE>>=
265 df2 = data.frame(xy, df)
266 coordinates(df2) = ~xc+yc
267 df2[1:2,]
268 as.data.frame(df2)[1:2,]
269 @
270 Note that in this form, \code{coordinates} by setting (specifying) the
271 coordinates promotes its argument, an object of class \code{data.frame}
272 to an object of class \code{SpatialPointsDataFrame}. The method {\tt
273 as.data.frame} coerces back to the original \code{data.frame}. When used
274 on a right-hand side of an equation, \code{coordinates} {\em retrieves}
275 the matrix with coordinates:
276 <<>>=
277 coordinates(df2)[1:2,]
278 @
279 Elements (columns) in the data.frame part of an object can be manipulated
280 (retrieved, assigned) directly:
281 <<>>=
282 df2[["z2"]]
283 df2[["z2"]][10] = 20
284 df2[["z3"]] = 1:10
285 summary(df2)
286 @
287 Plotting attribute data can be done by using either \code{spplot} to
288 colour symbols, or \code{bubble} which uses symbol size:
289 <<eval=FALSE,echo=TRUE,print=FALSE>>=
290 bubble(df2, "z1", key.space = "bottom")
291 spplot(df2, "z1", key.space = "bottom")
292 @
293 the resulting plots are shown in figure \ref{fig:spdf}.
294
295 \begin{figure}
296 \begin{center}
297 <<echo=FALSE,print=FALSE,fig=TRUE>>=
298 print(bubble(df2, "z1", key.space = "bottom"), split = c(1,1,2,1), more=TRUE)
299 print(spplot(df2, "z1", key.space = "bottom"), split = c(2,1,2,1), more=FALSE)
300 @
301 \end{center}
302 \caption{plot of \code{SpatialPointsDataFrame} object, using symbol
303 size (\code{bubble}, top) or colour (\code{spplot}, bottom) }
304 \label{fig:spdf}
305 \end{figure}
306
307 \section{Grids}
308 Package \pkg{sp} has two classes for grid topology: \code{SpatialPixels}
309 and \code{SpatialGrid}. The pixels form stores coordinates and is for
310 partial grids, or unordered points; the \code{SpatialGrid} form does not
311 store coordinates but holds full grids (i.e., \code{SpatialGridDataFrame}
312 holds attribute values for each grid cell). Objects can be coerced from
313 one representation to the other.
314
315 \subsection{Creating grids from topology}
316 When we know the offset, the cell sizes and the dimensions of a grid, we
317 can specify this by using the function \code{GridTopology}:
318 <<>>=
319 gt = GridTopology(cellcentre.offset = c(1,1,2), cellsize=c(1,1,1), cells.dim = c(3,4,6))
320 grd = SpatialGrid(gt)
321 summary(grd)
322 @
323
324 The grid parameters can be retrieved by the function
325 <<>>=
326 gridparameters(grd)
327 @
328
329 \subsection{Creating grids from points}
330 In the following example a three-dimensional grid is constructed from
331 a set of point coordinates:
332 <<>>=
333 pts = expand.grid(x = 1:3, y = 1:4, z=2:7)
334 grd.pts = SpatialPixels(SpatialPoints(pts))
335 summary(grd.pts)
336 grd = as(grd.pts, "SpatialGrid")
337 summary(grd)
338 @
339 Note that when passed a points argument, SpatialPixels accepts a tolerance
340 (default 10 * .Machine\$double.eps) to specify how close the points have
341 to be to being exactly on a grid. For very large coordinates, this value
342 may have to be increased. A warning is issued if full rows and/or columns
343 are missing.
344
345 \subsection{Gridded data with attributes}
346
347 Spatial, gridded data are data with coordinates on a regular lattice.
348 To form such a grid we can go from coordinates:
349 <<>>=
350 attr = expand.grid(xc = 1:3, yc = 1:3)
351 grd.attr = data.frame(attr, z1 = 1:9, z2 = 9:1)
352 coordinates(grd.attr) = ~xc+yc
353 gridded(grd.attr)
354 gridded(grd.attr) = TRUE
355 gridded(grd.attr)
356 summary(grd.attr)
357 @
358
359 Package \pkg{raster} provides dedicated methods to deal with raster data,
360 and can deal with grids that are too large to be stored in memory.
361
362 \subsection{Are grids stored as points or as matrix/array?}
363
364 The form in which gridded data comes depends on whether the grid was
365 created from a set of points or from a matrix or external grid format
366 (e.g. read through rgdal). Retrieving the form, or conversion to another
367 can be done by \code{as(x, "class")}, or by using the function \code{fullgrid}:
368 <<>>=
369 fullgrid(grd)
370 fullgrid(grd.pts)
371 fullgrid(grd.attr)
372 fullgrid(grd.pts) = TRUE
373 fullgrid(grd.attr) = TRUE
374 fullgrid(grd.pts)
375 fullgrid(grd.attr)
376 @
377
378 The advantage of having grids in cell form is that when a large part
379 of the grid contains missing values, these cells are not
380 stored. In addition, no ordering of grid cells is required. For plotting by
381 a grid with \code{levelplot}, this form is required and \code{spplot}
382 (for grids a front-end to \code{levelplot}) will convert grids that are
383 not in this form. In contrast, \code{image} requires a slightly altered
384 version of the the full grid form. A disadvantage of the cell form is
385 that the coordinates for each point have to be stored, which may be
386 prohibitive for large grids. Grids in cell form do have an index to
387 allow for fast transformation to the full grid form.
388
389 Besides \code{print}, \code{summary}, \code{plot},
390 objects of class \code{SpatialGridDataFrame} have methods for
391 \begin{itemize}
392 \item \verb|[| select rows (points) and/or columns (variables)
393 \item \verb|[[| extract a column from the attribute table
394 \item \verb|[[<-| assign or replace a column in the attribute table
395 \item \code{coordinates} retrieve the coordinates of grid cells
396 \item \code{as.matrix}, \code{as.array} retrieve the data as a matrix or array. The first index (rows) is the
397 x-column, the second index (columns) the y-coordinate, different attributes the third index. Row index 1 is the smallest
398 x-coordinate; column index 1 is the larges y-coordinate (top-to-bottom).
399 \item \code{as} coercion methods for \code{data.frame}, \code{SpatialPointsDataFrame}
400 \item\code{image} plot an image of the grid
401 \end{itemize}
402 Finally, \code{spplot}, a front-end to \code{levelplot} allows the
403 plotting of a single grid plot or a lattice of grid plots.
404
405 \subsection{Row and column selection of a region}
406 Rows/columns selection can be done when gridded data is in the full grid
407 form (as \code{SpatialGridDataFrame}). In this form also rows and/or columns
408 can be de-selected (in which case a warning is issued):
409 <<>>=
410 fullgrid(grd.attr) = FALSE
411 grd.attr[1:5, "z1"]
412 fullgrid(grd.attr) = TRUE
413 grd.attr[1:2,-2, c("z2","z1")]
414 @
415
416 \section{Lines}
417
418 \subsection{Building line objects from scratch}
419 In many instances, line coordinates will be retrieved from external
420 sources. The following example shows how to build an object of class
421 \code{SpatialLines} from scratch. Note that the \code{Lines} objects have to be given character ID values, and that these values must be unique for \code{Lines} objects combined in a \code{SpatialLines} object.
422
423 % build line objects
424 <<fig=TRUE>>=
425 l1 = cbind(c(1,2,3),c(3,2,2))
426 l1a = cbind(l1[,1]+.05,l1[,2]+.05)
427 l2 = cbind(c(1,2,3),c(1,1.5,1))
428 Sl1 = Line(l1)
429 Sl1a = Line(l1a)
430 Sl2 = Line(l2)
431 S1 = Lines(list(Sl1, Sl1a), ID="a")
432 S2 = Lines(list(Sl2), ID="b")
433 Sl = SpatialLines(list(S1,S2))
434 summary(Sl)
435 plot(Sl, col = c("red", "blue"))
436 @
437
438 \subsection{Building line objects with attributes}
439
440 The class \code{SpatialLinesDataFrame} is designed for holding
441 lines data that have an attribute table (data.frame) attached
442 to it:
443 <<>>=
444 df = data.frame(z = c(1,2), row.names=sapply(slot(Sl, "lines"), function(x) slot(x, "ID")))
445 Sldf = SpatialLinesDataFrame(Sl, data = df)
446 summary(Sldf)
447 @
448 Not many useful methods for it are available yet. The \code{plot} method
449 only plots the lines, ignoring attribute table values. Suggestions for
450 useful methods are welcome.
451
452 \section{Polygons}
453
454 \subsection{Building from scratch}
455 The following example shows how a set of polygons are built from scratch.
456 Note that \code{Sr4} has the opposite direction (anti-clockwise) as the other three (clockwise);
457 it is meant to represent a hole in the \code{Sr3} polygon. The default value for the hole colour \code{pbg} is \code{"transparent}, which will not show, but which often does not matter, because another polygon fills the hole --- here it is set to \code{"white"}. Note that the \code{Polygons} objects have to be given character ID values, and that these values must be unique for \code{Polygons} objects combined in a \code{SpatialPolygons} object.
458 <<fig=TRUE>>=
459 Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
460 Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
461 Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
462 Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)
463
464 Srs1 = Polygons(list(Sr1), "s1")
465 Srs2 = Polygons(list(Sr2), "s2")
466 Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
467 SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)
468 plot(SpP, col = 1:3, pbg="white")
469 # plot(SpP)
470 @
471
472 \subsection{Polygons with attributes}
473 Polygons with attributes, objects of class \code{SpatialPolygonsDataFrame},
474 are built from the \code{SpatialPolygons} object (topology) and the attributes
475 (data.frame). The \code{row.names} of the attributes data frame are matched with the ID slots of the \code{SpatialPolygons} object, and the rows of the data frame will be re-ordered if necessary.
476 <<>>=
477 attr = data.frame(a=1:3, b=3:1, row.names=c("s3/4", "s2", "s1"))
478 SrDf = SpatialPolygonsDataFrame(SpP, attr)
479 as(SrDf, "data.frame")
480 spplot(SrDf)
481 @
482
483 <<fig=TRUE,echo=FALSE>>=
484 print(spplot(SrDf))
485 @
486
487 or, as another way to create the \code{SpatialPolygonsDataFrame} object:
488 <<>>=
489 SrDf = attr
490 polygons(SrDf) = SpP
491 @
492
493 \section{Importing and exporting data}
494
495 Data import and export from external data sources and file formats
496 is handled inthe \pkg{rgdal} package in the first instance, using the
497 available OGR/GDAL drivers for vector and raster data. This keeps the
498 range of drivers up to date, and secures code maintenance through working
499 closely with the open source geospatial community. Mac OSX users unable
500 or unwilling to install \pkg{rgdal} from source after installing its
501 external dependencies will find some functions in the \pkg{maptools}
502 package to import and export a limited range of formats.
503
504
505 \section*{References}
506 \begin{description}
507 \item Chambers, J.M., 1998, Programming with data, a guide to the S language.
508 Springer, New York.
509 \end{description}
510
511 \end{document}
512
513 % vim:syntax=tex