Debian Codegraph @

vignettes/csdacm.Rnw

raw
1 %% $Id: csdacm.Rnw,v 1.44 2008-04-06 20:47:04 roger Exp $
2 % -*- mode: noweb; noweb-default-code-mode: R-mode; -*-
3
4 % merge all depth coefficients!!
5
6 % Customising spatial data analysis classes and methods
7
8 %\SweaveOpts{echo=TRUE}
9 %*Intro and plan*
10
11 %motivate spatial data handling
12 \documentclass{article}
13 % \VignetteIndexEntry{Customising spatial data classes and methods}
14
15 \usepackage{graphicx}
16 \usepackage[colorlinks=true,urlcolor=blue]{hyperref}
17
18 \usepackage{color}
19
20 \usepackage{Sweave}
21 \SweaveOpts{keep.source=FALSE}
22 \usepackage{natbib}
23
24 \newcommand{\strong}[1]{{\normalfont\fontseries{b}\selectfont #1}}
25 \let\pkg=\strong
26
27 \newcommand\code{\bgroup\@codex}
28 \def\@codex#1{\small {\normalfont\ttfamily\hyphenchar\font=45 #1}\egroup}
29
30 \usepackage{xspace}
31 \def\RR{\textsf{R}\xspace}
32 \def\SP{\texttt{S-PLUS}\texttrademark\xspace}
33 \def\SS{\texttt{S}\xspace}
34 \def\SIII{\texttt{S3}\xspace}
35 \def\SIV{\texttt{S4}\xspace}
36
37 \title{{\bf Customising spatial data classes and methods}\footnote{This vignette formed pp. 127--148 of the first edition of Bivand, R. S.,
38 Pebesma, E. and G\'{o}mez-Rubio V. (2008) Applied Spatial Data Analysis with R,
39 Springer-Verlag, New York. It was retired from the second edition (2013) to
40 accommodate material on other topics, and is made available in this form
41 with the understanding of the publishers. It has been updated to the 2013
42 state of the software, e.g. using \code{over}.} }
43 \author{Edzer Pebesma\footnote{Institute for Geoinformatics,
44 University of Muenster, Weseler Strasse 253, 48151 M\"{u}nster, Germany.
45 {\tt [email protected]}}}
46 \date{Feb 2008}
47
48 \begin{document}
49
50 \maketitle
51 \tableofcontents
52
53 <<echo=FALSE>>=
54 owidth <- getOption("width")
55 options("width"=90)
56 .PngNo <- 0
57 @
58
59 <<label=figreset,echo=FALSE,eval=FALSE>>=
60 .iwidth <- 5
61 .iheight <- 6
62 .ipointsize <- 12
63 @
64
65 <<echo=FALSE,results=hide>>=
66 <<figreset>>
67 @
68 <<label=afig,echo=FALSE,eval=FALSE>>=
69 .PngNo <- .PngNo + 1; file <- paste("Fig-bitmap-", .PngNo, ".pdf", sep="")
70 pdf(file=file, width = .iwidth, height = .iheight, pointsize = .ipointsize)
71 opar <- par(mar=c(3,3,1,1)+0.1)
72 @
73
74 <<label=zfig,echo=FALSE,eval=FALSE>>=
75 dev.null <- dev.off()
76 cat("\\includegraphics[width=0.95\\textwidth]{", file, "}\n\n", sep="")
77 @
78
79 Although the classes defined in the \pkg{sp} package cover many needs,
80 they do not go far beyond the most typical GIS data models. In applied
81 research, it often happens that customised classes would suit the
82 actual data coming from the instruments better. Since \SIV classes have
83 mechanisms for inheritance, it may be attractive to build on the \pkg{sp}
84 classes, so as to utilise their methods where appropriate. Here, we will
85 demonstrate a range of different settings in which \pkg{sp} classes can
86 be extended. Naturally, this is only useful for researchers with specific
87 and clear needs, so our goal is to show how (relatively) easy it may be
88 to prototype classes extending \pkg{sp} classes for specific purposes.
89
90 \section{Programming with classes and methods}
91 \label{sect:cls}
92
93 This section will explain the elementary basics of programming with
94 classes and methods in \RR. The \SS language (implemented in \RR and
95 \SP) contains two mechanisms for creating classes and methods: the
96 traditional \SIII system and the more recent \SIV system (see Section 2.2 in
97 \cite{bivand}, in which classes were described for the use{\RR} ---
98 here they are described for the develope{\RR}). This chapter is not a
99 full introduction to \RR programming \citep[see][for more details]{braun+murdoch:07}, but it will try to give some
100 feel of how the \code{Spatial} classes in package \pkg{sp} can be
101 extended to be used for wider classes of problems. For full details,
102 the interested reader is referred to e.g.\ \cite{R:Venables+Ripley:2000}
103 and \cite{R:Chambers:1998}, the latter being a reference for new-style
104 \SIV classes and methods. Example code is for example found in the source
105 code for package \pkg{sp}, available from CRAN.
106
107 Suppose we define myfun as
108 \begin{footnotesize}
109 << >>=
110 myfun <- function(x) {
111 x + 2
112 }
113 @
114 \end{footnotesize}
115 then, calling it with the numbers 1, 2 and 3 results in
116 \begin{footnotesize}
117 << >>=
118 myfun(1:3)
119 @
120 \end{footnotesize}
121 or alternatively using a named argument:
122 \begin{footnotesize}
123 << >>=
124 myfun(x=1:3)
125 @
126 \end{footnotesize}
127 The return value of the function is the last expression evaluated.
128 Often, we want to wrap existing functions, such as a plot function:
129 \begin{footnotesize}
130 << >>=
131 plotXplus2Yminus3 <- function(x, y, ...) {
132 plot(x = x + 2, y = y - 3, ...)
133 }
134 @
135 \end{footnotesize}
136 In this case, the \code{...} is used to pass information to the
137 \code{plot} function without explicitly anticipating what it will be:
138 named arguments \code{x} and \code{y}, or the first two arguments if they
139 are unnamed are processed, remaining arguments are passed on.
140 The plot function is a generic method, with
141 an instance that depends on the class of its first (\SIII) or first $n$
142 arguments (\SIV). The available instances of \code{plot} are shown for
143 \SIII-type methods by
144
145 \begin{footnotesize}
146 << >>=
147 methods("plot")
148 @
149 \end{footnotesize}
150 and for \SIV-type methods by
151 \begin{footnotesize}
152 << >>=
153 library(sp)
154 showMethods("plot")
155 @
156 \end{footnotesize}
157 where we first loaded \pkg{sp} to make sure there are some \SIV plot
158 methods to show.
159
160 \subsection{\SIII-style classes and methods}
161
162 Building \SIII-style classes is simple. Suppose we want to
163 build an object of class \code{foo}:
164 \begin{footnotesize}
165 << >>=
166 x <- rnorm(10)
167 class(x) <- "foo"
168 x
169 @
170 \end{footnotesize}
171 If we plot this object, e.g., by \code{plot(x)} we get the same plot as
172 when we would not have set the class to \code{foo}. If we know, however, that
173 objects of class \code{foo} need to be plotted without symbols but with
174 connected lines, we can write a plot method for this class:
175
176 \begin{footnotesize}
177 << >>=
178 plot.foo <- function(x, y, ...) {
179 plot.default(x, type = 'l', ...)
180 }
181 @
182 \end{footnotesize}
183 after which \code{plot(x)} will call this particular method, rather than
184 a default plot method.
185
186 Class inheritance is obtained in \SIII when an object is given multiple
187 classes, as in
188 \begin{footnotesize}
189 << >>=
190 class(x) <- c("foo", "bar")
191 @
192 <<eval=FALSE>>=
193 plot(x)
194 @
195 \end{footnotesize}
196
197 For this plot, first function \code{plot.foo} will be looked for, and
198 if not found the second option \code{plot.bar} will be looked for. If
199 none of them is found, the default \code{plot.default} will be used.
200
201 The \SIII class mechanism is simple and powerful. Much of \RR works with
202 it, including key functions such as \code{lm}.
203 \begin{footnotesize}
204 << >>=
205 data(meuse)
206 class(meuse)
207 class(lm(log(zinc)~sqrt(dist), meuse))
208 @
209 \end{footnotesize}
210
211 There is, however, no checking that a class with a particular name does
212 indeed contain the elements that a certain method for it expects.
213 It also has design flaws, as method specification by dot separation
214 is ambiguous in case of names such as \code{as.data.frame}, where one
215 cannot tell whether it means that the method \code{as.data} acts on
216 objects of class \code{frame}, or the method \code{as} acts on objects
217 of class \code{data.frame}, or none of them (the answer is: none). For
218 such reasons, \SIV-style classes and methods were designed.
219
220 \subsection{\SIV-style classes and methods}
221
222 \SIV-style classes are formally defined, using \code{setClass}. As an example,
223 somewhat simplified versions of classes \code{CRS} and \code{Spatial}
224 in \pkg{sp} are
225 \begin{footnotesize}
226 <<echo=FALSE>>=
227 options("width"=60)
228 @
229 <<eval=FALSE>>=
230 setClass("CRS", representation(projargs = "character"))
231 setClass("Spatial",
232 representation(bbox = "matrix", proj4string = "CRS"),
233 # NOT TOO WIDE
234 validity <- function(object) {
235 bb <- bbox(object)
236 if (!is.matrix(bb))
237 return("bbox should be a matrix")
238 n <- dimensions(object)
239 if (n < 2)
240 return("spatial.dimension should be 2 or more")
241 if (any(is.na(bb)))
242 return("bbox should never contain NA values")
243 if (any(!is.finite(bb)))
244 return("bbox should never contain infinite values")
245 if (any(bb[,"max"] < bb[,"min"]))
246 return("invalid bbox: max < min")
247 TRUE
248 }
249 )
250 @
251 <<echo=FALSE>>=
252 options("width"=70)
253 @
254 \end{footnotesize}
255
256 The command \code{setClass} defines a class name as a formal class, gives
257 the names of the class elements (called slots), and their type---type
258 checking will happen upon construction of an instance of the class. Further
259 checking, e.g., on valid dimensions and data ranges can be done in the
260 \code{validity} function. Here, the validity function retrieves the
261 bounding box using the generic \code{bbox} method.
262 Generics, if not defined in the base R system, e.g.,
263 \begin{footnotesize}
264 << >>=
265 isGeneric("show")
266 @
267 \end{footnotesize}
268 can be defined with \code{setGeneric}. Defining a specific instance of a
269 generic is done by \code{setMethod}:
270 \begin{footnotesize}
271 <<eval=FALSE>>=
272 setGeneric("bbox", function(obj) standardGeneric("bbox"))
273 setMethod("bbox", signature = "Spatial", function(obj) obj@bbox)
274 @
275 \end{footnotesize}
276 where the signature tells the class of the first (or first $n$) arguments.
277 Here, the \code{@} operator is used to access the \code{bbox} slot in
278 an \SIV object, not to be confused with the \code{\$} operator to access
279 list elements.
280
281 We will now illustrate this mechanism by providing a few examples of
282 classes, building on those available in package \pkg{sp}.
283
284 \section{Animal track data in package \pkg{trip}}
285
286 CRAN Package \pkg{trip}, written by Michael Sumner
287 \citep{kirkwood06,page06}, provides a class for animal tracking
288 data. Animal tracking data consist of sets of ($x,y,t$) stamps,
289 grouped by an identifier pointing to an individual animal, sensor or
290 perhaps isolated period of monitoring. A strategy for this
291 (slightly simplified from that of \pkg{trip}) is to extend the {\tt
292 SpatialPointsDataFrame} class by a length 2 character vector carrying
293 the names of the time column and the trip identifier column in the {\tt
294 SpatialPointsDataFrame} attribute table.
295
296 Package \pkg{trip} does a lot of work to read and analyse tracking
297 data from data formats typical for tracking data (Argos DAT), removing
298 duplicate observations and validating the objects, e.g., checking that
299 time stamps increase and movement speeds are realistic. We ignore this
300 and stick to the bare bones.
301
302 We now define a class called \code{trip} that extends \code{SpatialPointsDataFrame}:
303 \begin{footnotesize}
304 << >>=
305 library(sp)
306 setClass("trip", representation("SpatialPointsDataFrame", TOR.columns = "character"),
307 validity <- function(object) {
308 if (length([email protected]) != 2)
309 stop("Time/id column names must be of length 2")
310 if (!all([email protected] %in% names(object@data)))
311 stop("Time/id columns must be present in attribute table")
312 TRUE
313 }
314 )
315 showClass("trip")
316 @
317 \end{footnotesize}
318 that checks, upon creation of objects, that indeed two variable names
319 are passed and that these names refer to variables present in the
320 attribute table.
321
322
323 \subsection{Generic and constructor functions}
324 It would be nice to have a constructor function, just like \code{data.frame} or
325 \code{SpatialPoints}, so we now create it and set it as the generic function to
326 be called in case the first argument is of class \code{SpatialPointsDataFrame}.
327 \begin{footnotesize}
328 << >>=
329 trip.default <- function(obj, TORnames) {
330 if (!is(obj, "SpatialPointsDataFrame"))
331 stop("trip only supports SpatialPointsDataFrame")
332 if (is.numeric(TORnames))
333 TORnames <- names(obj)[TORnames]
334 new("trip", obj, TOR.columns = TORnames)
335 }
336
337 if (!isGeneric("trip"))
338 setGeneric("trip", function(obj, TORnames)
339 standardGeneric("trip"))
340
341 setMethod("trip", signature(obj = "SpatialPointsDataFrame", TORnames = "ANY"), trip.default)
342 @
343 \end{footnotesize}
344
345 We can now try it out, with turtle data:
346
347 \begin{footnotesize}
348 << >>=
349 turtle <- read.csv(system.file("external/seamap105_mod.csv", package="sp"))
350 @
351 << >>=
352 timestamp <- as.POSIXlt(strptime(as.character(turtle$obs_date), "%m/%d/%Y %H:%M:%S"), "GMT")
353 turtle <- data.frame(turtle, timestamp = timestamp)
354 turtle$lon <- ifelse(turtle$lon < 0, turtle$lon+360, turtle$lon)
355 turtle <- turtle[order(turtle$timestamp),]
356 coordinates(turtle) <- c("lon", "lat")
357 proj4string(turtle) <- CRS("+proj=longlat +ellps=WGS84")
358 turtle$id <- c(rep(1, 200), rep(2, nrow(coordinates(turtle)) - 200))
359 turtle_trip <- trip(turtle, c("timestamp", "id"))
360 summary(turtle_trip)
361 @
362 \end{footnotesize}
363
364 \subsection{Methods for trip objects}
365
366 The summary method here is not defined for \code{trip}, but is the
367 default summary inherited from class \code{Spatial}. As can be seen,
368 nothing special about the trip features is mentioned, such as what the
369 time points are and what the identifiers. We could alter this by writing a
370 class-specific summary method
371 \begin{footnotesize}
372 << >>=
373 summary.trip <- function(object, ...) {
374 cat("Object of class \"trip\"\nTime column: ")
375 print([email protected][1])
376 cat("Identifier column: ")
377 print([email protected][2])
378 print(summary(as(object, "Spatial")))
379 print(summary(object@data))
380 }
381 setMethod("summary", "trip", summary.trip)
382 summary(turtle_trip)
383 @
384 \end{footnotesize}
385
386 As \code{trip} extends \code{SpatialPointsDataFrame},
387 subsetting using {\small \verb+"["+}
388 and column selection or replacement using {\small \verb+"[["+}
389 or {\small \verb+"$"+} all work,
390 as these are inherited. Creating invalid trip objects can be prohibited by
391 adding checks to the validity function in the class definition, e.g.,
392 %<<eval=FALSE,echo=TRUE>>=
393 %x <- turtle_trip[1]
394 %@
395 will not work because the time and/or id column are not present any more.
396
397 A custom plot method for trip could be written, for example
398 using colour to denote a change in identifier:
399 \begin{footnotesize}
400 << >>=
401 setGeneric("lines", function(x, ...) standardGeneric("lines"))
402 setMethod("lines", signature(x = "trip"),
403 function(x, ..., col = NULL) {
404 # NOT TOO WIDE
405 tor <- [email protected]
406 if (is.null(col)) {
407 l <- length(unique(x[[tor[2]]]))
408 col <- hsv(seq(0, 0.5, length = l))
409 }
410 coords <- coordinates(x)
411 lx <- split(1:nrow(coords), x[[tor[2]]])
412 for (i in 1:length(lx))
413 lines(coords[lx[[i]], ], col = col[i], ...)
414 }
415 )
416 @
417 \end{footnotesize}
418 Here, the \code{col} argument is added to the function header so that a
419 reasonable default can be overridden, e.g., for black/white plotting.
420
421 \section{Multi-point data: \texttt{SpatialMultiPoints}}
422
423 One of the feature types of the OpenGeospatial Consortium (OGC) simple feature
424 specification that has
425 not been implemented in \pkg{sp} is the \code{MultiPoint} object. In a
426 \code{MultiPoint} object, each feature refers to a {\em set of} points. The
427 \pkg{sp} classes \code{SpatialPointsDataFrame} only provide reference to a
428 single point. Instead of building a new class up from scratch, we'll try
429 to re-use code and build a class \code{SpatialMultiPoint} from the {\tt
430 SpatialLines} class. After all, lines are just sets of ordered points.
431
432 In fact, the \code{SpatialLines} class implements the \code{MultiLineString}
433 simple feature, where each feature can refer to multiple lines. A special
434 case is formed if each feature only has a single line:
435 \begin{footnotesize}
436 <<echo=FALSE>>=
437 options("width"=50)
438 @
439 << >>=
440 setClass("SpatialMultiPoints", representation("SpatialLines"),
441 validity <- function(object) {
442 if (any(unlist(lapply(object@lines, function(x) length(x@Lines))) != 1))
443 # NOT TOO WIDE
444 stop("Only Lines objects with one Line element")
445 TRUE
446 }
447 )
448 SpatialMultiPoints <- function(object) new("SpatialMultiPoints", object)
449 @
450 <<echo=FALSE>>=
451 options("width"=70)
452 @
453 \end{footnotesize}
454
455 As an example, we can create an instance of this class for two MultiPoint
456 features each having three locations:
457 \begin{footnotesize}
458 << >>=
459 n <- 5
460 set.seed(1)
461 x1 <- cbind(rnorm(n),rnorm(n, 0, 0.25))
462 x2 <- cbind(rnorm(n),rnorm(n, 0, 0.25))
463 x3 <- cbind(rnorm(n),rnorm(n, 0, 0.25))
464 L1 <- Lines(list(Line(x1)), ID="mp1")
465 L2 <- Lines(list(Line(x2)), ID="mp2")
466 L3 <- Lines(list(Line(x3)), ID="mp3")
467 s <- SpatialLines(list(L1,L2,L3))
468 smp <- SpatialMultiPoints(s)
469 @
470 \end{footnotesize}
471
472 If we now plot object \code{smp}, we get the same plot as when we plot
473 \code{s}, showing the two lines. The \code{plot} method for a
474 \code{SpatialLines} object is not suitable, so we write a new one:
475
476 \begin{footnotesize}
477 << >>=
478 plot.SpatialMultiPoints <- function(x, ..., pch = 1:length(x@lines), col = 1, cex = 1) {
479 n <- length(x@lines)
480 if (length(pch) < n)
481 pch <- rep(pch, length.out = n)
482 if (length(col) < n)
483 col <- rep(col, length.out = n)
484 if (length(cex) < n)
485 cex <- rep(cex, length.out = n)
486 plot(as(x, "Spatial"), ...)
487 for (i in 1:n)
488 points(x@lines[[i]]@Lines[[1]]@coords, pch = pch[i], col = col[i], cex = cex[i])
489 }
490 setMethod("plot", signature(x = "SpatialMultiPoints", y = "missing"),
491 function(x, y, ...) plot.SpatialMultiPoints(x, ...))
492 @
493 \end{footnotesize}
494
495 Here we chose to pass any named \code{...} arguments to the plot method
496 for a \code{Spatial} object. This function sets up the axes and controls the
497 margins, aspect ratio, etc. All arguments that need to be passed
498 to \code{points} (\code{pch} for symbol type, \code{cex} for symbol size and
499 \code{col} for symbol colour) need explicit naming and sensible defaults,
500 as they are passed explicitly to the consecutive calls to \code{points}.
501 According to the documentation of \code{points}, in addition to \code{pch},
502 \code{cex} and \code{col}, the arguments \code{bg} and \code{lwd} (symbol
503 fill colour and symbol line width) would need a similar treatment to
504 make this plot method completely transparent with the base \code{plot}
505 method---something an end user would hope for.
506
507 Having \code{pch}, \code{cex} and \code{col} arrays the length of the number
508 of \code{MultiPoints} {\em sets} rather than the number of points to be
509 plotted is useful for two reasons. First, the whole point of {\tt
510 MultiPoints} object is to distinguish {\em sets} of points. Second,
511 when we extend this class to \code{SpatialMultiPointsDataFrame}, e.g., by
512 \begin{footnotesize}
513 << >>=
514 cName <- "SpatialMultiPointsDataFrame"
515 setClass(cName, representation("SpatialLinesDataFrame"),
516 validity <- function(object) {
517 lst <- lapply(object@lines, function(x) length(x@Lines))
518 if (any(unlist(lst) != 1))
519 stop("Only Lines objects with single Line")
520 TRUE
521 }
522 )
523 SpatialMultiPointsDataFrame <- function(object) {
524 new("SpatialMultiPointsDataFrame", object)
525 }
526 @
527 \end{footnotesize}
528 then we can pass symbol characteristics by (functions of) columns in the attribute table:
529
530 \begin{footnotesize}
531 <<fig=FALSE>>=
532 df <- data.frame(x1 = 1:3, x2 = c(1,4,2), row.names = c("mp1", "mp2", "mp3"))
533 smp_df <- SpatialMultiPointsDataFrame(SpatialLinesDataFrame(smp, df))
534 setMethod("plot", signature(x = "SpatialMultiPointsDataFrame", y = "missing"),
535 function(x, y, ...) plot.SpatialMultiPoints(x, ...))
536 grys <- c("grey10", "grey40", "grey80")
537 @
538 <<eval=FALSE>>=
539 plot(smp_df, col = grys[smp_df[["x1"]]], pch = smp_df[["x2"]], cex = 2, axes = TRUE)
540 @
541 \end{footnotesize}
542 for which the plot is shown in Figure \ref{fig:smpdf}.
543
544 \begin{figure}
545 %<<fig=TRUE,echo=FALSE>>=
546 <<echo=FALSE,results=tex>>=
547 .iwidth <- 6
548 .iheight <- 2.5
549 .ipointsize <- 10
550 <<afig>>
551 plot(smp_df, col = grys[smp_df[["x1"]]], pch = smp_df[["x2"]], cex = 2, axes = TRUE)
552 <<zfig>>
553 <<figreset>>
554 @
555 \caption{Plot of the \code{SpatialMultiPointsDataFrame} object.}
556 \label{fig:smpdf}
557 \end{figure}
558
559 Hexagonal grids are like square grids, where grid points are centres
560 of matching hexagons, rather than squares. Package \pkg{sp} has no
561 classes for hexagonal grids, but does have some useful functions for
562 generating and plotting them. This could be used to build a class. Much
563 of this code in \pkg{sp} is based on postings to the R-sig-geo mailing
564 list by Tim Keitt, used with permission.
565
566 The spatial sampling method \code{spsample} has a method for sampling points
567 on a hexagonal grid:
568 \begin{footnotesize}
569 <<>>=
570 data(meuse.grid)
571 gridded(meuse.grid)=~x+y
572 xx <- spsample(meuse.grid, type="hexagonal", cellsize=200)
573 class(xx)
574 @
575 \end{footnotesize}
576 gives the points shown in the left side of Figure \ref{fig:hex}. Note
577 that an alternative hexagonal representation is obtained by rotating
578 this grid 90 degrees; we will not further consider that here.
579
580 \begin{footnotesize}
581 <<fig=FALSE>>=
582 HexPts <- spsample(meuse.grid, type="hexagonal", cellsize=200)
583 @
584 <<eval=FALSE>>=
585 spplot(meuse.grid["dist"], sp.layout = list("sp.points", HexPts, col = 1))
586 @
587 <<fig=FALSE>>=
588 HexPols <- HexPoints2SpatialPolygons(HexPts)
589 df <- over(HexPols, meuse.grid)
590 HexPolsDf <- SpatialPolygonsDataFrame(HexPols, df, match.ID = FALSE)
591 @
592 <<eval=FALSE>>=
593 spplot(HexPolsDf["dist"])
594 @
595 \end{footnotesize}
596 for which the plots are shown in Figure \ref{fig:hex}.
597
598 \begin{figure}
599 <<echo=FALSE,results=tex>>=
600 .iwidth <- 6
601 .iheight <- 4
602 <<afig>>
603 library(lattice)
604 # RSB quietening greys
605 grys <- grey.colors(11, 0.95, 0.55, 2.2)
606 print(spplot(meuse.grid["dist"], cuts=10, col.regions=grys, sp.layout = list("sp.points", HexPts, col = 1)),
607 split = c(1, 1, 2, 1), more = TRUE)
608 print(spplot(HexPolsDf["dist"], cuts=10, col.regions=grys),
609 split = c(2, 1, 2, 1), more = FALSE)
610 <<zfig>>
611 <<figreset>>
612 @
613 \caption{Hexagonal points (left) and polygons (right).}
614 \label{fig:hex}
615 \end{figure}
616 We can now generate and plot hexagonal grids, but need to deal with two
617 representations: as points and as polygons, and both representations do
618 not tell by themselves that they represent a hexagonal grid.
619
620 For designing a hexagonal grid class we will extend \code{SpatialPoints},
621 assuming that computation of the polygons can be done when needed without
622 a prohibitive overhead.
623 \begin{footnotesize}
624 << >>=
625 setClass("SpatialHexGrid", representation("SpatialPoints", dx = "numeric"),
626 validity <- function(object) {
627 if (object@dx <= 0)
628 stop("dx should be positive")
629 TRUE
630 }
631 )
632 @
633 <<echo=FALSE>>=
634 options("width"=40)
635 @
636 << >>=
637 setClass("SpatialHexGridDataFrame", representation("SpatialPointsDataFrame", dx = "numeric"),
638 # NOT TOO WIDE
639 validity <- function(object) {
640 if (object@dx <= 0)
641 stop("dx should be positive")
642 TRUE
643 }
644 )
645 @
646 <<echo=FALSE>>=
647 options("width"=70)
648 @
649 \end{footnotesize}
650 Note that these class definitions do not check that instances actually do
651 form valid hexagonal grids; a more robust implementation could provide
652 a test that distances between points with equal $y$ coordinate are
653 separated by a multiple of \code{dx}, that the $y$-separations are
654 correct and so on.
655
656 It might make sense to adapt the generic \code{spsample} method in
657 package \pkg{sp} to return \code{SpatialHexGrid} objects; we can also
658 add \code{plot} and \code{spsample} methods for them. Method \code{over}
659 should work with a \code{SpatialHexGrid} as its first argument,
660 by inheriting from \code{SpatialPoints}. Let us first see
661 how to create the new classes. Without a constructor function we can use
662
663 \begin{footnotesize}
664 << >>=
665 HexPts <- spsample(meuse.grid, type="hexagonal", cellsize=200)
666 Hex <- new("SpatialHexGrid", HexPts, dx = 200)
667 df <- over(Hex, meuse.grid)
668 spdf <- SpatialPointsDataFrame(HexPts, df)
669 HexDf <- new("SpatialHexGridDataFrame", spdf, dx = 200)
670 @
671 \end{footnotesize}
672 Because of the route taken to define both HexGrid classes, it is not
673 obvious that the second extends the first. We can tell the \SIV system
674 this by \code{setIs}:
675 \begin{footnotesize}
676 << >>=
677 is(HexDf, "SpatialHexGrid")
678 setIs("SpatialHexGridDataFrame", "SpatialHexGrid")
679 is(HexDf, "SpatialHexGrid")
680 @
681 \end{footnotesize}
682 to make sure that methods for \code{SpatialHexGrid} objects work as well
683 for objects of class \code{SpatialHexGridDataFrame}.
684
685 When adding methods, several of them will need conversion to the
686 polygon representation, so it makes sense to add the conversion
687 function such that e.g. \code{as(x, "SpatialPolygons")} will work:
688 \begin{footnotesize}
689 <<echo=FALSE>>=
690 options("width"=50)
691 @
692 << >>=
693 # NOT TOO WIDE
694 setAs("SpatialHexGrid", "SpatialPolygons",
695 function(from)
696 HexPoints2SpatialPolygons(from, from@dx)
697 )
698 setAs("SpatialHexGridDataFrame", "SpatialPolygonsDataFrame",
699 function(from)
700 SpatialPolygonsDataFrame(as(obj, "SpatialPolygons"), obj@data, match.ID = FALSE)
701 )
702 @
703 <<echo=FALSE>>=
704 options("width"=70)
705 @
706 \end{footnotesize}
707
708 We can now add \code{plot}, \code{spplot}, \code{spsample} and
709 \code{over} methods for these classes:
710 \begin{footnotesize}
711 << >>=
712 setMethod("plot", signature(x = "SpatialHexGrid", y = "missing"),
713 function(x, y, ...) plot(as(x, "SpatialPolygons"), ...)
714 )
715 setMethod("spplot", signature(obj = "SpatialHexGridDataFrame"),
716 function(obj, ...)
717 spplot(SpatialPolygonsDataFrame( as(obj, "SpatialPolygons"), obj@data, match.ID = FALSE), ...)
718 )
719 setMethod("spsample", "SpatialHexGrid", function(x, n, type, ...)
720 spsample(as(x, "SpatialPolygons"), n = n, type = type, ...)
721 )
722 setMethod("over", c("SpatialHexGrid", "SpatialPoints"), function(x, y, ...)
723 over(as(x, "SpatialPolygons"), y)
724 )
725 @
726 \end{footnotesize}
727 After this, the following will work:
728
729 \begin{footnotesize}
730 <<eval=FALSE>>=
731 spplot(meuse.grid["dist"], sp.layout = list("sp.points", Hex, col = 1))
732 spplot(HexDf["dist"])
733 @
734 \end{footnotesize}
735
736 Coercion to a data frame is done by
737
738 \begin{footnotesize}
739 <<eval=FALSE>>=
740 as(HexDf, "data.frame")
741 @
742 \end{footnotesize}
743
744 Another detail not mentioned is that the bounding box of the hexgrid
745 objects only match the grid centre points, not the hexgrid cells:
746 \begin{footnotesize}
747 << >>=
748 bbox(Hex)
749 bbox(as(Hex, "SpatialPolygons"))
750 @
751 \end{footnotesize}
752 One solution for this is to correct for this in a constructor function,
753 and check for it in the validity test. Explicit coercion functions
754 to the points representation would have to set the bounding box back
755 to the points ranges. Another solution is to write a bbox method for
756 the hexgrid classes, taking the risk that someone still looks at the
757 incorrect bbox slot.
758
759 \section{Spatio-temporal grids}
760 Spatio-temporal data can be represented in different ways. One simple
761 option is when observations (or model-results, or predictions) are given
762 on a regular space-time grid.
763
764 Objects of class or extending \code{SpatialPoints}, \code{SpatialPixels}
765 and \code{SpatialGrid} do not have the constraint that they represent a
766 two-dimensional space; they may have arbitrary dimension; an example for
767 a three-dimensional grid is
768
769 \begin{footnotesize}
770 << >>=
771 n <- 10
772 x <- data.frame(expand.grid(x1 = 1:n, x2 = 1:n, x3 = 1:n), z = rnorm(n^3))
773 coordinates(x) <- ~x1+x2+x3
774 gridded(x) <- TRUE
775 fullgrid(x) <- TRUE
776 summary(x)
777 @
778 \end{footnotesize}
779 We might assume here that the third dimension, \code{x3}, represents
780 time. If we are happy with time somehow represented by a real number
781 (in double precision), then we are done. A simple representation is that of
782 decimal year, with e.g. 1980.5 meaning the 183rd day of 1980, or
783 e.g. relative time in seconds after the start of some event.
784
785 When we want to use the \code{POSIXct} or \code{POSIXlt} representations,
786 we need to do some more work to see the readable version. We will now
787 devise a simple three-dimensional space-time grid with the \code{POSIXct}
788 representation.
789
790 \begin{footnotesize}
791 <<echo=FALSE>>=
792 options("width"=50)
793 @
794 << >>=
795 # NOT TOO WIDE
796 setClass("SpatialTimeGrid", "SpatialGrid",
797 validity <- function(object) {
798 stopifnot(dimensions(object) == 3)
799 TRUE
800 }
801 )
802 @
803 <<echo=FALSE>>=
804 options("width"=70)
805 @
806 \end{footnotesize}
807 Along the same line, we can extend the \code{SpatialGridDataFrame}
808 for space-time:
809
810 \begin{footnotesize}
811 << >>=
812 setClass("SpatialTimeGridDataFrame", "SpatialGridDataFrame",
813 validity <- function(object) {
814 stopifnot(dimensions(object) == 3)
815 TRUE
816 }
817 )
818 setIs("SpatialTimeGridDataFrame", "SpatialTimeGrid")
819 x <- new("SpatialTimeGridDataFrame", x)
820 @
821 \end{footnotesize}
822 A crude summary for this class could be written along these lines:
823 \begin{footnotesize}
824 << >>=
825 summary.SpatialTimeGridDataFrame <- function(object, ...) {
826 cat("Object of class SpatialTimeGridDataFrame\n")
827 x <- gridparameters(object)
828 t0 <- ISOdate(1970,1,1,0,0,0)
829 t1 <- t0 + x[3,1]
830 cat(paste("first time step:", t1, "\n"))
831 t2 <- t0 + x[3,1] + (x[3,3] - 1) * x[3,2]
832 cat(paste("last time step: ", t2, "\n"))
833 cat(paste("time step: ", x[3,2], "\n"))
834 summary(as(object, "SpatialGridDataFrame"))
835 }
836 @
837 <<echo=FALSE>>=
838 options("width"=50)
839 @
840 << >>=
841 # NOT TOO WIDE
842 setMethod("summary", "SpatialTimeGridDataFrame", summary.SpatialTimeGridDataFrame)
843 summary(x)
844 @
845 <<echo=FALSE>>=
846 options("width"=70)
847 @
848 \end{footnotesize}
849
850 Next, suppose we need a subsetting method that selects on the time.
851 When the first subset argument is allowed to be a time range, this is done by
852 \begin{footnotesize}
853 << >>=
854 subs.SpatialTimeGridDataFrame <- function(x, i, j, ..., drop=FALSE) {
855 t <- coordinates(x)[,3] + ISOdate(1970,1,1,0,0,0)
856 if (missing(j))
857 j <- TRUE
858 sel <- t %in% i
859 if (! any(sel))
860 stop("selection results in empty set")
861 fullgrid(x) <- FALSE
862 if (length(i) > 1) {
863 x <- x[i = sel, j = j,...]
864 fullgrid(x) <- TRUE
865 as(x, "SpatialTimeGridDataFrame")
866 } else {
867 gridded(x) <- FALSE
868 x <- x[i = sel, j = j,...]
869 cc <- coordinates(x)[,1:2]
870 p4s <- CRS(proj4string(x))
871 # NOT TOO WIDE
872 SpatialPixelsDataFrame(cc, x@data, proj4string = p4s)
873 }
874 }
875 setMethod("[", c("SpatialTimeGridDataFrame", "POSIXct", "ANY"),
876 subs.SpatialTimeGridDataFrame)
877 t1 <- as.POSIXct("1970-01-01 0:00:03", tz = "GMT")
878 t2 <- as.POSIXct("1970-01-01 0:00:05", tz = "GMT")
879 summary(x[c(t1,t2)])
880 summary(x[t1])
881 @
882 \end{footnotesize}
883 The reason to only convert back to \code{SpatialTimeGridDataFrame} when
884 multiple time steps are present is that the time step (``cell size''
885 in time direction) cannot be found when there is only a single step. In
886 that case, the current selection method returns an object of class
887 \code{SpatialPixelsDataFrame} for that time slice.
888
889
890 Plotting a set of slices could be done using levelplot, or writing
891 another \code{spplot} method:
892 \begin{footnotesize}
893 << >>=
894 spplot.stgdf <- function(obj, zcol = 1, ..., format = NULL) {
895 # NOT TOO WIDE
896 if (length(zcol) != 1)
897 stop("can only plot a single attribute")
898 if (is.null(format)) format <- "%Y-%m-%d %H:%M:%S"
899 cc <- coordinates(obj)
900 df <- unstack(data.frame(obj[[zcol]], cc[,3]))
901 ns <- format(coordinatevalues(getGridTopology(obj))[[3]] + ISOdate(1970,1,1,0,0,0), format = format)
902 cc2d <- cc[cc[,3] == min(cc[,3]), 1:2]
903 obj <- SpatialPixelsDataFrame(cc2d, df)
904 spplot(obj, names.attr = ns,...)
905 }
906 setMethod("spplot", "SpatialTimeGridDataFrame", spplot.stgdf)
907 @
908 \end{footnotesize}
909
910 \begin{figure}
911 \begin{center}
912 <<echo=FALSE,results=tex>>=
913 .iwidth <- 6
914 .iheight <- 4
915 <<afig>>
916 #print(spplot(x, format = "%H:%M:%S", as.table=TRUE))
917 print(spplot(x, as.table=TRUE))
918 <<zfig>>
919 <<figreset>>
920 @
921 \end{center}
922 \caption{ \code{spplot} for an object of class \code{SpatialTimeGridDataFrame},
923 filled with random numbers.}
924 \label{fig:stgdf}
925 \end{figure}
926 Now, the result of
927 \begin{footnotesize}
928 <<eval=FALSE>>=
929 library(lattice)
930 trellis.par.set(canonical.theme(color = FALSE))
931 spplot(x, format = "%H:%M:%S", as.table=TRUE, cuts=6,
932 col.regions=grey.colors(7, 0.55, 0.95, 2.2))
933 # RSB quietening greys
934 @
935 \end{footnotesize}
936 is shown in Figure \ref{fig:stgdf}. The format argument passed controls the
937 way time is printed; one can refer to the help of
938 \begin{footnotesize}
939 <<eval=FALSE>>=
940 ?as.character.POSIXt
941 @
942 \end{footnotesize}
943 for more details about the \code{format} argument.
944
945 \section{Analysing spatial Monte Carlo simulations}
946 \label{sec:simquant}
947
948 Quite often, spatial statistical analysis results in a large number
949 of spatial realisations or a random field, using some Monte Carlo
950 simulation approach. Regardless whether individual values refer to
951 points, lines, polygons or grid cells, we would like to write some
952 methods or functions that aggregate over these simulations, to get
953 summary statistics such as the mean value, quantiles, or cumulative
954 distributions values. Such aggregation can take place in two ways.
955 Either we aggregate over the probability space, and compute summary
956 statistics for each geographical feature over the set of realisations
957 (i.e., the rows of the attribute table), or for each realisation we
958 aggregate over the complete geographical layer or a subset of it (i.e.,
959 aggregate over the columns of the attribute table).
960
961 Let us first generate, as an example, a set of 100 conditional Gaussian
962 simulations for the zinc variable in the meuse data set:
963 \begin{footnotesize}
964 <<eval=TRUE,echo=TRUE>>=
965 data(meuse)
966 coordinates(meuse) <- ~x+y
967 if (require(gstat, quietly = TRUE)) {
968 v <- vgm(.5, "Sph", 800, .05)
969 sim <- krige(log(zinc)~1, meuse, meuse.grid, v, nsim=100, nmax=30)
970 sim@data <- exp(sim@data)
971 }
972 @
973 \end{footnotesize}
974
975 where the last statement back-transforms the simulations from the log scale
976 to the observation scale. A quantile method for Spatial object attributes
977 can be written as
978 \begin{footnotesize}
979 << >>=
980 quantile.Spatial <- function(x, ..., byLayer = FALSE) {
981 stopifnot("data" %in% slotNames(x))
982 apply(x@data, ifelse(byLayer, 2, 1), quantile, ...)
983 }
984 @
985 \end{footnotesize}
986 after which we can find the sample lower and upper 95\%
987 confidence limits by
988 \begin{footnotesize}
989 << >>=
990 if (require(gstat, quietly = TRUE)) {
991 sim$lower <- quantile.Spatial(sim[1:100], probs = 0.025)
992 sim$upper <- quantile.Spatial(sim[1:100], probs = 0.975)
993 }
994 @
995 \end{footnotesize}
996
997 To get the sample distribution of the areal median, we can aggregate over
998 layers:
999 \begin{footnotesize}
1000 << >>=
1001 if (require(gstat, quietly = TRUE)) {
1002 medians <- quantile.Spatial(sim[1:100], probs = 0.5, byLayer = TRUE)
1003 }
1004 @
1005 <<eval=FALSE>>=
1006 hist(medians)
1007 @
1008 \end{footnotesize}
1009
1010 It should be noted that in these particular cases, the quantities computed
1011 by simulations could have been obtained faster and exact by working
1012 analytically with ordinary (block) kriging and the normal distribution
1013 (Section 8.7.2 in \cite{bivand}).
1014
1015 A statistic that cannot be obtained analytically is the sample distribution
1016 of the area fraction that exceeds a threshold. Suppose that 500 is a
1017 crucial threshold, and we want to summarise the sampling distribution of
1018 the area fraction where 500 is exceeded:
1019 \begin{footnotesize}
1020 <<echo=FALSE>>=
1021 options("width"=50)
1022 @
1023 << >>=
1024 fractionBelow <- function(x, q, byLayer = FALSE) {
1025 stopifnot(is(x, "Spatial") || !("data" %in% slotNames(x)))
1026 apply(x@data < q, ifelse(byLayer, 2, 1), function(r) sum(r)/length(r))
1027 # NOT TOO WIDE
1028 }
1029 @
1030 <<echo=FALSE>>=
1031 options("width"=70)
1032 @
1033 << >>=
1034 if (require(gstat, quietly = TRUE)) {
1035 over500 <- 1 - fractionBelow(sim[1:100], 200, byLayer = TRUE)
1036 summary(over500)
1037 quantile(over500, c(0.025, 0.975))
1038 }
1039 @
1040 \end{footnotesize}
1041
1042
1043 For space-time data, we could write methods that aggregate over space,
1044 over time or over space and time.
1045
1046
1047 This chapter has sketched developments beyond the base \pkg{sp} classes
1048 and methods used otherwise in this book. Although we think that the base
1049 classes cater for many standard kinds of spatial data analysis, it is
1050 clear that specific research problems will call for specific solutions,
1051 and that the \RR environment provides the high-level abstractions needed
1052 to help busy researchers get their work done.
1053
1054
1055 <<echo=FALSE>>=
1056 options("width"=owidth)
1057 @
1058
1059
1060 \begin{thebibliography}{}
1061
1062 \bibitem[Bivand et al., 2008]{bivand}
1063 Roger S. Bivand, Edzer J. Pebesma and Virgilio Gomez-Rubio (2008).
1064 \newblock {\em Applied spatial data analysis with {\RR}}
1065 \newblock Springer, NY
1066
1067 \bibitem[Braun and Murdoch, 2007]{braun+murdoch:07}
1068 Braun, W.~J. and Murdoch, D.~J. (2007).
1069 \newblock {\em A first course in statistical programming with {\RR}}.
1070 \newblock Cambridge University Press, Cambridge.
1071
1072 \bibitem[Chambers, 1998]{R:Chambers:1998}
1073 Chambers, J.M. (1998).
1074 \newblock {\em Programming with Data}.
1075 \newblock Springer, New York.
1076
1077 \bibitem[Kirkwood et al., 2006]{kirkwood06}
1078 Kirkwood, R., Lynch, M., Gales, N., Dann, P., and Sumner, M. (2006).
1079 \newblock At-sea movements and habitat use of adult male {A}ustralian fur seals
1080 ({A}rctocephalus pusillus doriferus).
1081 \newblock {\em Canadian Journal of Zoology}, 84:1781--1788.
1082
1083 \bibitem[Page et al., 2006]{page06}
1084 Page, B., McKenzie, J., Sumner, M., Coyne, M., and Goldsworthy, S. (2006).
1085 \newblock Spatial separation of foraging habitats among {N}ew {Z}ealand fur
1086 seals.
1087 \newblock {\em Marine Ecology Progress Series}, 323:263--279.
1088
1089 \bibitem[Venables and Ripley, 2000]{R:Venables+Ripley:2000}
1090 Venables, W. N. and Ripley, B. D. (2000).
1091 \newblock {\em {\SS} Programming}.
1092 \newblock Springer, New York.
1093
1094 \end{thebibliography}
1095
1096 \end{document}
1097