0% found this document useful (0 votes)
50 views657 pages

Spatstat Manual for Spatial Analysis

This document provides information about the R package 'spatstat' which contains functions for spatial point pattern analysis, model fitting, simulation, and tests. It allows for analyzing spatial data including point patterns, line segment patterns, spatial windows, pixel images and tessellations. The package can fit point process models to point pattern data and provides tools for formal inference and model diagnostics. It was authored by Adrian Baddeley and others and is released under the GPL license.

Uploaded by

Carolina Garzón
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views657 pages

Spatstat Manual for Spatial Analysis

This document provides information about the R package 'spatstat' which contains functions for spatial point pattern analysis, model fitting, simulation, and tests. It allows for analyzing spatial data including point patterns, line segment patterns, spatial windows, pixel images and tessellations. The package can fit point process models to point pattern data and provides tools for formal inference and model diagnostics. It was authored by Adrian Baddeley and others and is released under the GPL license.

Uploaded by

Carolina Garzón
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Package ‘spatstat’

November 11, 2009


Version 1.17-2

Date 10 november 2009

Title Spatial Point Pattern analysis, model-fitting, simulation, tests

Author Adrian Baddeley <adrian@[Link]> and Rolf Turner


<[Link]@[Link]>, with substantial contributions of code by Marie-Colette
van Lieshout, Rasmus Waagepetersen, Kasper Klitgaard Berthelsen and Dominic
Schuhmacher. Additional contributions by Ang Qi Wei, C. Beale, R. Bernhardt, B.
Biggerstaff, R. Bivand, F. Bonneu, J. Burgos, J.B. Chen, Y.C. Chin, B. Christensen, M.
de la Cruz, P.J. Diggle, S. Eglen, A. Gault, M. Genton, P. Grabarnik, C. Graf, J.
Franklin, U. Hahn, M. Hering, M.B. Hansen, M. Hazelton, J. Heikkinen, K. Hornik, R.
Ihaka, R. John-Chandran, D. Johnson, J. Laake, R. Mark, J. Mateu, P. McCullagh, S.
Meyer, X.C. Mi, J. Moller, L.S. Nielsen, F. Nunes, E. Parilov, J. Picka, M. Reiter, B.D.
Ripley, B. Rowlingson, E. Rubak, J. Rudge, A. Sarkka, K. Schladitz, B.T. Scott, I.-M.
Sintorn, M. Spiess, M. Stevenson, P. Surovy, B. Turlach, A. van Burgel, T. Verbeke, A.
Villers, H. Wang, H. Wendrock and S. Wong.

Maintainer Adrian Baddeley <adrian@[Link]>

Depends R (>= 2.10.0), stats, graphics, utils, mgcv, deldir (>= 0.0-7)

Suggests gpclib, sm, maptools, rpanel, tkrplot, scatterplot3d

Description A package for analysing spatial data, mainly Spatial Point Patterns, including
multitype/marked points and spatial covariates, in any two-dimensional spatial region.
Also supports three-dimensional point patterns. Contains functions for plotting spatial
data, exploratory data analysis, model-fitting, simulation, spatial sampling, model
diagnostics, and formal inference. Data types include point patterns, line segment
patterns, spatial windows, pixel images and tessellations. Point process models can be
fitted to point pattern data. Cluster type models are fitted by the method of minimum
contrast. Very general Gibbs point process models can be fitted to point pattern data
using a function ppm similar to lm or glm. Models may include dependence on
covariates, interpoint interaction and dependence on marks. Fitted models can be
simulated automatically. Also provides facilities for formal inference (such as chi-squared
tests) and model diagnostics (including simulation envelopes, residuals, residual plots
and Q-Q plots).

License GPL (>= 2)

URL [Link]

1
2 R topics documented:

R topics documented:
spatstat-package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
affine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
allstats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
alltypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
amacrine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
anemones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
ants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
applynbd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
areaGain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
AreaInter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
areaLoss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
as.box3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
BadGey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
bei . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
bermantest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
betacells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
blur . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
border . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
box3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
bramblecanes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
bronzefilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
R topics documented: 3

[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
chorley . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
clarkevans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
clickpoly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
clickppp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
closing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
colourmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
concatxy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
connected . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
convexhull . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
coords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
copper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
corners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
crossdist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
delaunay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
deltametric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
demopat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
diameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
diameter.box3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
DiggleGratton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
dilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
dirichlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
disc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
discpartarea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
discretise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
distfun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
distmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
4 R topics documented:

[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
eem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
effectfun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Emark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
envelope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
erosion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
ewcdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
F3est . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Fest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
finpines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
fryplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
G3est . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
ganglia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Gcross . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Gdot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Gest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Geyer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Gmulti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
gpc2owin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
gridcentres . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
gridweights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
hamster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
harmonic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
heather . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Hest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
humberside . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
hyperframe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Iest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
im . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
R topics documented: 5

incircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
infline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
iplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
istat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
japanesepines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Jcross . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Jdot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Jest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Jmulti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
K3est . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Kcross . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Kdot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Kest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Kinhom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Kmeasure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Kmulti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
kppm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
lansing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Lcross . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
Ldot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
LennardJones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Lest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
letterR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
levelset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
6 R topics documented:

Linhom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
localK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
longleaf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
lurking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
lut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
markconnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
markcorr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
markcorrint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
markstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
marktable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
markvario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
matchingdist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
methods.box3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
methods.pp3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
mincontrast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
miplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
MultiStrauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
MultiStraussHard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
murchison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
nbfires . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
nearestsegment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
nncorr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
nncross . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
nndist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
nnwhich . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
nztrees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
opening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Ord . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
OrdThresh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
owin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
pairdist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
PairPiece . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Pairwise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
pcf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
R topics documented: 7

[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
pcfcross . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
perimeter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
pixellate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
pixelquad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
plot.pp3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
pointsOnLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Poisson . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
ponderosa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
pp3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
ppm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
ppp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
pppdist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
pppmatching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
ppx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
profilepl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
progressreport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
project2segment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
psp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
8 R topics documented:

[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
quadratcount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
quadratresample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
quadrats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
quadscheme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
raster.x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
rcell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
reach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
redwood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
redwoodfull . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
rescale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
residualspaper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
rGaussPoisson . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
ripras . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
rjitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
rlabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
rlinegrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
rMatClust . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
rMaternI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
rMaternII . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
rmh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
rmhcontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
rmhmodel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
rmhstart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
rMosaicField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
rMosaicSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
rmpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
rmpoispp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
rNeymanScott . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
rotate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
rpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
R topics documented: 9

rpoisline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
rpoislinetess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
rpoispp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
rpoispp3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
rpoisppOnLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
rshift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
rSSI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
rstrat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
rStrauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
rsyst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
rthin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
rThomas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
runifdisc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
runifpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
runifpoint3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
runifpointOnLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
SatPiece . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
Saturated . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
scanpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
setcov . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
setmarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
shapley . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
shift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
simdat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
Softcore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
solutionset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
spokes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
spruces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
square . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
stieltjes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
Strauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
StraussHard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
suffstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
10 spatstat-package

[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
superimpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
superimposePSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
swedishpines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
tess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
tiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
unitname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
unmark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
urkiola . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
vertices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630

spatstat-package The Spatstat Package

Description
This is a summary of the features of spatstat, a package in R for the statistical analysis of
spatial point patterns.

Details
spatstat is a package for the statistical analysis of spatial data. Currently, it deals mainly
with the analysis of patterns of points in the plane. The points may carry ‘marks’, and the
spatial region in which the points were recorded may have arbitrary shape.
The package supports
ˆ creation, manipulation and plotting of point patterns
ˆ exploratory data analysis
ˆ simulation of point process models
ˆ parametric model-fitting
ˆ hypothesis tests and diagnostics
The point process models to be fitted may be quite general Gibbs/Markov models; they
may include spatial trend, dependence on covariates, and interpoint interactions of any
order (i.e. not restricted to pairwise interactions). Models are specified by a formula in
the R language, and are fitted using a single function ppm analogous to lm and glm. It is
also possible to fit cluster process models by the method of minimum contrast.
Apart from two-dimensional point patterns and point processes, spatstat also supports
patterns of line segments in two dimensions, point patterns in three dimensions, and mul-
tidimensional space-time point patterns. It also supports spatial tessellations and random
sets.
spatstat-package 11

Getting Started
For a quick introduction to spatstat, see the paper by Baddeley and Turner (2005a). For
a complete 2-day course on using spatstat, see the workshop notes by Baddeley (2008).
Both of these documents are available on the internet.
Type demo(spatstat) for a demonstration of the package’s capabilities. Type demo(data)
to see all the datasets available in the package.

FUNCTIONS AND DATASETS


Following is a summary of the main functions and datasets in the spatstat package. Al-
ternatively an alphabetical list of all functions and datasets is available by typing li-
brary(help=spatstat).
For further information on any of these, type help(name) where name is the name of the
function or dataset.

CONTENTS:

I. Creating and manipulating data


II. Exploratory Data Analysis
III. Model fitting (cluster models)
IV. Model fitting (Gibbs models)
V. Simulation
VI. Tests and diagnostics
VII. Documentation

I. CREATING AND MANIPULATING DATA


Types of spatial data:
The main types of spatial data supported by spatstat are:

ppp point pattern


owin window (spatial region)
im pixel image
psp line segment pattern
tess tessellation
pp3 three-dimensional point pattern

To create a point pattern:

ppp create a point pattern from (x, y) and window information


ppp(x, y, xlim, ylim) for rectangular window
ppp(x, y, poly) for polygonal window
ppp(x, y, mask) for binary image window
[Link] convert other types of data to a ppp object
clickppp interactively add points to a plot
setmarks, %mark% attach/reassign marks to a point pattern

To simulate a random point pattern:


12 spatstat-package

runifpoint generate n independent uniform random points


rpoint generate n independent random points
rmpoint generate n independent multitype random points
rpoispp simulate the (in)homogeneous Poisson point process
rmpoispp simulate the (in)homogeneous multitype Poisson point process
runifdisc generate n independent uniform random points in disc
rstrat stratified random sample of points
rsyst systematic random sample of points
rjitter apply random displacements to points in a pattern
rMaternI simulate the Mat\’ern Model I inhibition process
rMaternII simulate the Mat\’ern Model II inhibition process
rSSI simulate Simple Sequential Inhibition process
rStrauss simulate Strauss process (perfect simulation)
rNeymanScott simulate a general Neyman-Scott process
rMatClust simulate the Mat\’ern Cluster process
rThomas simulate the Thomas process
rGaussPoisson simulate the Gauss-Poisson cluster process
rthin random thinning
rcell simulate the Baddeley-Silverman cell process
rmh simulate Gibbs point process using Metropolis-Hastings
[Link] simulate Gibbs point process using Metropolis-Hastings
runifpointOnLines generate n random points along specified line segments
rpoisppOnLines generate Poisson random points along specified line segments

To randomly change an existing point pattern:

rlabel random (re)labelling of a multitype point pattern


rshift random shift (including toroidal shifts)

Standard point pattern datasets:


Remember to say data(amacrine) etc. Type demo(data) to see all the datasets installed
with the package.

amacrine Austin Hughes’ rabbit amacrine cells


anemones Upton-Fingleton sea anemones data
ants Harkness-Isham ant nests data
bei Tropical rainforest trees
betacells Waessle et al. cat retinal ganglia data
bramblecanes Bramble Canes data
bronzefilter Bronze Filter Section data
cells Crick-Ripley biological cells data
chorley Chorley-Ribble cancer data
copper Berman-Huntington copper deposits data
demopat Synthetic point pattern
finpines Finnish Pines data
hamster Aherne’s hamster tumour data
humberside North Humberside childhood leukaemia data
japanesepines Japanese Pines data
lansing Lansing Woods data
longleaf Longleaf Pines data
murchison Murchison gold deposits
nbfires New Brunswick fires data
spatstat-package 13

nztrees Mark-Esler-Ripley trees data


ponderosa Getis-Franklin ponderosa pine trees data
redwood Strauss-Ripley redwood saplings data
redwoodfull Strauss redwood saplings data (full set)
residualspaper Data from Baddeley et al (2005)
shapley Galaxies in an astronomical survey
simdat Simulated point pattern (inhomogeneous, with interaction)
spruces Spruce trees in Saxonia
swedishpines Strand-Ripley swedish pines data
urkiola Urkiola Woods data

To manipulate a point pattern:

[Link] plot a point pattern (e.g. plot(X))


iplot plot a point pattern interactively
[.ppp extract or replace a subset of a point pattern
pp[subset] or pp[subwindow]
superimpose combine several point patterns
[Link] apply a function to sub-patterns of a point pattern
[Link] classify the points in a point pattern
unmark remove marks
setmarks attach marks or reset marks
[Link] divide pattern into sub-patterns
rotate rotate pattern
shift translate pattern
affine apply affine transformation
[Link] kernel smoothing
[Link] interactively identify points
[Link] remove duplicate points
[Link] determine which points are duplicates
dirichlet compute Dirichlet-Voronoi tessellation
delaunay compute Delaunay triangulation
convexhull compute convex hull
[Link] approximate point pattern by pixel image
[Link] approximate point pattern by pixel image

See [Link] to control plotting behaviour.


To create a window:
An object of class "owin" describes a spatial region (a window of observation).

owin Create a window object


owin(xlim, ylim) for rectangular window
owin(poly) for polygonal window
owin(mask) for binary image window
[Link] Convert other data to a window object
square make a square window
disc make a circular window
ripras Ripley-Rasson estimator of window, given only the points
convexhull compute convex hull of something
letterR polygonal window in the shape of the R logo
14 spatstat-package

To manipulate a window:

[Link] plot a window.


plot(W)
[Link] Find a tight bounding box for the window
erosion erode window by a distance r
dilation dilate window by a distance r
closing close window by a distance r
opening open window by a distance r
border difference between window and its erosion/dilation
[Link] invert (swap inside and outside)
[Link] approximate a window by a simple polygon
rotate rotate window
shift translate window
affine apply affine transformation

Digital approximations:

[Link] Make a discrete pixel approximation of a given window


[Link] convert window to pixel image
[Link] convert window to pixel image
[Link] map continuous coordinates to raster locations
raster.x raster x coordinates
raster.y raster y coordinates
[Link] convert pixel mask to polygonal window

See [Link] to control the approximation


Geometrical computations with windows:

[Link] intersection of two windows


[Link] union of two windows
[Link] set subtraction of two windows
[Link] determine whether a point is inside a window
[Link] compute area
perimeter compute perimeter length
diameter compute diameter
incircle find largest circle inside a window
connected find connected components of window
[Link] compute areas of eroded windows
[Link] compute areas of dilated windows
[Link] compute distances from data points to window boundary
[Link] compute distances from all pixels to window boundary
[Link] boundary distance for each tile in tessellation
[Link] distance transform image
[Link] compute centroid (centre of mass) of window
[Link] determine whether one window contains another
[Link] determine whether a window is convex
convexhull compute convex hull
[Link] pixel approximation of window
[Link] polygonal approximation of window
spatstat-package 15

Pixel images: An object of class "im" represents a pixel image. Such objects are returned
by some of the functions in spatstat including Kmeasure, setcov and [Link].

im create a pixel image


[Link] convert other data to a pixel image
pixellate convert other data to a pixel image
[Link] convert pixel image to matrix
[Link] plot a pixel image on screen as a digital image
[Link] draw contours of a pixel image
[Link] draw perspective plot of a pixel image
[.im extract a subset of a pixel image
[<-.im replace a subset of a pixel image
[Link] apply vector shift to pixel image
X print very basic information about image X
summary(X) summary of image X
[Link] histogram of image
[Link] mean pixel value of image
[Link] quantiles of image
[Link] convert numeric image to factor image
[Link] test whether an object is a pixel image
[Link] interpolate a pixel image
blur apply Gaussian blur to image
connected find connected components
[Link] test whether two images have compatible dimensions
[Link] evaluate any expression involving images
levelset level set of an image
solutionset region where an expression is true

Line segment patterns


An object of class "psp" represents a pattern of straight line segments.

psp create a line segment pattern


[Link] convert other data into a line segment pattern
[Link] determine whether a dataset has class "psp"
[Link] plot a line segment pattern
[Link] print basic information
[Link] print summary information
[.psp extract a subset of a line segment pattern
[Link] convert line segment pattern to data frame
[Link] extract marks of line segments
marks<-.psp assign new marks to line segments
[Link] delete marks from line segments
[Link] compute the midpoints of line segments
[Link] extract the endpoints of line segments
[Link] compute the lengths of line segments
[Link] compute the orientation angles of line segments
[Link] rotate a line segment pattern
[Link] shift a line segment pattern
[Link] apply an affine transformation
[Link] compute the distance map of a line segment pattern
[Link] kernel smoothing of line segments
[Link] find crossing points between line segments
16 spatstat-package

[Link] find crossing points between two line segment patterns


nncross find distance to nearest line segment from a given point
nearestsegment find line segment closest to a given point
project2segment find location along a line segment closest to a given point
pointsOnLines generate points evenly spaced along line segment
rpoisline generate a realisation of the Poisson line process inside a window
rlinegrid generate a random array of parallel lines through a window

Tessellations
An object of class "tess" represents a tessellation.

tess create a tessellation


quadrats create a tessellation of rectangles
[Link] convert other data to a tessellation
[Link] plot a tessellation
tiles extract all the tiles of a tessellation
[.tess extract some tiles of a tessellation
[<-.tess change some tiles of a tessellation
[Link] intersect two tessellations
or restrict a tessellation to a window
[Link] subdivide a tessellation by a line
dirichlet compute Dirichlet-Voronoi tessellation of points
delaunay compute Delaunay triangulation of points
rpoislinetess generate tessellation using Poisson line process

Three-dimensional point patterns


An object of class "pp3" represents a three-dimensional point pattern in a rectangular box.
The box is represented by an object of class "box3".

pp3 create a 3-D point pattern


plot.pp3 plot a 3-D point pattern
coords extract coordinates
[Link] extract coordinates
unitname.pp3 name of unit of length
runifpoint3 generate uniform random points in 3-D
rpoispp3 generate Poisson random points in 3-D
box3 create a 3-D rectangular box
as.box3 convert data to 3-D rectangular box
unitname.box3 name of unit of length
diameter.box3 diameter of box
volume.box3 volume of box
shortside.box3 shortest side of box
[Link] volumes of erosions of box

Hyperframes
A hyperframe is like a data frame, except that the entries may be objects of any kind.

hyperframe create a hyperframe


[Link] convert data to hyperframe
[Link] plot hyperframe
[Link] evaluate expression using each row of hyperframe
spatstat-package 17

II. EXPLORATORY DATA ANALYSIS


Inspection of data:

summary(X) print useful summary of point pattern X


X print basic description of point pattern X
any(duplicated(X)) check for duplicated points in pattern X
istat(X) Interactive exploratory analysis

Classical exploratory tools:

clarkevans Clark and Evans aggregation index


fryplot Fry plot
miplot Morishita Index plot

Summary statistics for a point pattern:

quadratcount Quadrat counts


Fest empty space function F
Gest nearest neighbour distribution function G
Kest Ripley’s K-function
Lest Ripley’s L-function
Jest J-function J = (1 − G)/(1 − F )
localL Getis-Franklin neighbourhood density function
localK neighbourhood K-function
pcf pair correlation function
Kinhom K for inhomogeneous point patterns
Linhom L for inhomogeneous point patterns
[Link] fast K-function using FFT for large datasets
Kmeasure reduced second moment measure
allstats all four functions F , G, J, K
envelope simulation envelopes for a summary function

Related facilities:

[Link] plot a summary function


[Link] evaluate any expression involving summary functions
[Link] evaluate any expression involving an array of functions
[Link] evaluate an expression for a summary function
nndist nearest neighbour distances
nnwhich find nearest neighbours
pairdist distances between all pairs of points
crossdist distances between points in two patterns
nncross nearest neighbours between two point patterns
exactdt distance from any location to nearest data point
distmap distance map image
[Link] kernel smoothed density
[Link] spatial interpolation of marks

Summary statistics for a multitype point pattern: A multitype point pattern is


represented by an object X of class "ppp" with a component X$marks which is a factor.
18 spatstat-package

Gcross,Gdot,Gmulti multitype nearest neighbour distributions Gij , Gi•


Kcross,Kdot, Kmulti multitype K-functions Kij , Ki•
Lcross,Ldot multitype L-functions Lij , Li•
Jcross,Jdot,Jmulti multitype J-functions Jij , Ji•
pcfcross multitype pair correlation function gij
markconnect marked connection function pij
alltypes estimates of the above for all i, j pairs
Iest multitype I-function
[Link],[Link] inhomogeneous counterparts of Kcross, Kdot
[Link],[Link] inhomogeneous counterparts of Lcross, Ldot

Summary statistics for a marked point pattern: A marked point pattern is repre-
sented by an object X of class "ppp" with a component X$marks. The entries in the vector
X$marks may be numeric, complex, string or any other atomic type. For numeric marks,
there are the following functions:

markmean smoothed local average of marks


markvar smoothed local variance of marks
markcorr mark correlation function
markvario mark variogram
markcorrint mark correlation integral
Emark mark independence diagnostic E(r)
Vmark mark independence diagnostic V (r)
nnmean nearest neighbour mean index
nnvario nearest neighbour mark variance index

For marks of any type, there are the following:

Gmulti multitype nearest neighbour distribution


Kmulti multitype K-function
Jmulti multitype J-function

Alternatively use [Link] to convert a marked point pattern to a multitype point pattern.
Programming tools:

applynbd apply function to every neighbourhood in a point pattern


markstat apply function to the marks of neighbours in a point pattern
marktable tabulate the marks of neighbours in a point pattern
pppdist find the optimal match between two point patterns

Summary statistics for a three-dimensional point pattern:


These are for 3-dimensional point pattern objects (class pp3).

F3est empty space function F


G3est nearest neighbour function G
K3est K-function

III. MODEL FITTING (CLUSTER MODELS)


Cluster process models (with homogeneous or inhomogeneous intensity) can be fitted by
the function kppm. Its result is an object of class "kppm". The fitted model can be printed,
spatstat-package 19

plotted, predicted, simulated and updated.

[Link] Plot the fitted model


[Link] Compute fitted intensity
[Link] Update the model
[Link] Generate simulated realisations

Lower-level fitting functions include:

[Link] fit the Thomas process model


[Link] fit the Matern Cluster process model
[Link] fit a log-Gaussian Cox process model
mincontrast low-level algorithm for fitting models
by the method of minimum contrast

The Thomas and Matern models can also be simulated, using rThomas and rMatClust
respectively.

IV. MODEL FITTING (GIBBS MODELS)


For a detailed explanation of how to fit Gibbs models to point pattern data using spatstat,
see Baddeley and Turner (2005b) or Baddeley (2008).
To fit a Gibbs point process model:
Model fitting in spatstat is performed mainly by the function ppm. Its result is an object of
class "ppm".
Manipulating the fitted model:

[Link] Plot the fitted model


[Link] Compute the spatial trend and conditional intensity
of the fitted point process model
[Link] Extract the fitted model coefficients
[Link] Extract the trend formula
[Link] Compute fitted conditional intensity at quadrature points
[Link] Compute point process residuals at quadrature points
[Link] Update the fit
[Link] Variance-covariance matrix of estimates
[Link] Simulate from fitted model
[Link] Simulate from fitted model
[Link] Print basic information about a fitted model
[Link] Summarise a fitted model
effectfun Compute the fitted effect of one covariate
[Link] log-likelihood or log-pseudolikelihood
[Link] Analysis of deviance

For model selection, you can also use the generic functions step, drop1 and AIC on fitted
point process models.
See [Link] to control plotting of fitted model.
To specify a point process model:
The first order “trend” of the model is determined by an R language formula. The formula
specifies the form of the logarithm of the trend.
20 spatstat-package

~1 No trend (stationary)
~x Loglinear trend λ(x, y) = exp(α + βx)
where x, y are Cartesian coordinates
~polynom(x,y,3) Log-cubic polynomial trend
~harmonic(x,y,2) Log-harmonic polynomial trend

The higher order (“interaction”) components are described by an object of class "interact".
Such objects are created by:

Poisson() the Poisson point process


Strauss() the Strauss process
StraussHard() the Strauss/hard core point process
Softcore() pairwise interaction, soft core potential
PairPiece() pairwise interaction, piecewise constant
DiggleGratton() Diggle-Gratton potential
LennardJones() Lennard-Jones potential
Pairwise() pairwise interaction, user-supplied potential
AreaInter() Area-interaction process
Geyer() Geyer’s saturation process
BadGey() multiscale Geyer process
SatPiece() Saturated pair model, piecewise constant potential
Saturated() Saturated pair model, user-supplied potential
OrdThresh() Ord process, threshold potential
Ord() Ord model, user-supplied potential
MultiStrauss() multitype Strauss process
MultiStraussHard() multitype Strauss/hard core process

Finer control over model fitting:


A quadrature scheme is represented by an object of class "quad". To create a quadrature
scheme, typically use quadscheme.

quadscheme default quadrature scheme


using rectangular cells or Dirichlet cells
pixelquad quadrature scheme based on image pixels
quad create an object of class "quad"

To inspect a quadrature scheme:

plot(Q) plot quadrature scheme Q


print(Q) print basic information about quadrature scheme Q
summary(Q) summary of quadrature scheme Q

A quadrature scheme consists of data points, dummy points, and weights. To generate
dummy points:

[Link] default pattern of dummy points


gridcentres dummy points in a rectangular grid
rstrat stratified random dummy pattern
spokes radial pattern of dummy points
corners dummy points at corners of the window
spatstat-package 21

To compute weights:

gridweights quadrature weights by the grid-counting rule


[Link] quadrature weights are Dirichlet tile areas

Simulation and goodness-of-fit for fitted models:

[Link] simulate realisations of a fitted model


[Link] simulate realisations of a fitted model
envelope compute simulation envelopes for a fitted model

V. SIMULATION
There are many ways to generate a random point pattern, line segment pattern, pixel image
or tessellation in spatstat.
Random point patterns:

runifpoint generate n independent uniform random points


rpoint generate n independent random points
rmpoint generate n independent multitype random points
rpoispp simulate the (in)homogeneous Poisson point process
rmpoispp simulate the (in)homogeneous multitype Poisson point process
runifdisc generate n independent uniform random points in disc
rstrat stratified random sample of points
rsyst systematic random sample (grid) of points
rMaternI simulate the Mat\’ern Model I inhibition process
rMaternII simulate the Mat\’ern Model II inhibition process
rSSI simulate Simple Sequential Inhibition process
rStrauss simulate Strauss process (perfect simulation)
rNeymanScott simulate a general Neyman-Scott process
rMatClust simulate the Mat\’ern Cluster process
rThomas simulate the Thomas process
rGaussPoisson simulate the Gauss-Poisson cluster process
rcell simulate the Baddeley-Silverman cell process
runifpointOnLines generate n random points along specified line segments
rpoisppOnLines generate Poisson random points along specified line segments

Resampling a point pattern:

quadratresample block resampling


rjitter apply random displacements to points in a pattern
rshift random shifting of (subsets of) points
rthin random thinning

Fitted point process models:


If you have fitted a point process model to a point pattern dataset, the fitted model can be
simulated.
Cluster process models are fitted by the function kppm yielding an object of class "kppm".
To generate one or more simulated realisations of this fitted model, use [Link].
Gibbs point process models are fitted by the function ppm yielding an object of class "ppm".
To generate a simulated realisation of this fitted model, use rmh. To generate one or more
22 spatstat-package

simulated realisations of the fitted model, use [Link].


Other random patterns:

rlinegrid generate a random array of parallel lines through a window


rpoisline simulate the Poisson line process within a window
rpoislinetess generate random tessellation using Poisson line process
rMosaicSet generate random set by selecting some tiles of a tessellation
rMosaicField generate random pixel image by assigning random values in each tile of a tessellation

Simulation-based inference

envelope critical envelope for Monte Carlo test of goodness-of-fit


[Link] diagnostic plot for interpoint interaction

VI. TESTS AND DIAGNOSTICS


Classical hypothesis tests:

[Link] χ2 goodness-of-fit test on quadrat counts


kstest Kolmogorov-Smirnov goodness-of-fit test
bermantest Berman’s goodness-of-fit tests
envelope critical envelope for Monte Carlo test of goodness-of-fit
[Link] Analysis of Deviance for point process models

Diagnostic plots:
Residuals for a fitted point process model, and diagnostic plots based on the residuals, were
introduced in Baddeley et al (2005).
Type demo(diagnose) for a demonstration of the diagnostics features.

[Link] diagnostic plots for spatial trend


[Link] diagnostic plot for interpoint interaction
residualspaper examples from Baddeley et al (2005)

Resampling and randomisation procedures


You can build your own tests based on randomisation and resampling using the following
capabilities:

quadratresample block resampling


rjitter apply random displacements to points in a pattern
rshift random shifting of (subsets of) points
rthin random thinning

VII. DOCUMENTATION
The online manual entries are quite detailed and should be consulted first for information
about a particular function.
The paper by Baddeley and Turner (2005a) is a brief overview of the package. Baddeley and
Turner (2005b) is a more detailed explanation of how to fit point process models to data.
Baddeley (2008) is a complete set of notes from a 2-day workshop on the use of spatstat.
Type citation("spatstat") to get these references.
[Link] 23

Licence
This library and its documentation are usable under the terms of the ”GNU General Public
License”, a copy of which is distributed with the package.

Acknowledgements
Marie-Colette van Lieshout, Rasmus Waagepetersen, Dominic Schuhmacher and Kasper
Klitgaard Berthelsen made substantial contributions of code. Additional contributions by
Ang Qi Wei, Colin Beale, Ricardo Bernhardt, Brad Biggerstaff, Roger Bivand, Florent
Bonneu, Julian Burgos, Jianbao Chen, Y.C. Chin, Bjarke Christensen, Marcelino de la
Cruz, Peter Diggle, Stephen Eglen, Agnes Gault, Marc Genton, Pavel Grabarnik, C. Graf,
Janet Franklin, Ute Hahn, Mandy Hering, Martin Bogsted Hansen, Martin Hazelton, Juha
Heikkinen, Kurt Hornik, Ross Ihaka, Robert John-Chandran, Devin Johnson, Jeff Laake,
Robert Mark, Jorge Mateu, Peter McCullagh, Sebastian Wastl Meyer, Mi Xiangcheng, Jes-
per Moller, Linda Stougaard Nielsen, Felipe Nunes, Evgeni Parilov, Jeff Picka, Matt Reiter,
Brian Ripley, Barry Rowlingson, Ege Rubak, John Rudge, Aila Sarkka, Katja Schladitz,
Bryan Scott, Ida-Maria Sintorn, Malte Spiess, Mark Stevenson, P. Surovy, Berwin Turlach,
Andrew van Burgel, Tobias Verbeke, Alexendre Villers, Hao Wang, H. Wendrock and Selene
Wong.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A. (2008) Analysing spatial point patterns in R. Workshop notes. CSIRO online
technical publication. URL: [Link]/resources/[Link]
Baddeley, A. and Turner, R. (2005a) Spatstat: an R package for analyzing spatial point
patterns. Journal of Statistical Software 12:6, 1–42. URL: [Link], ISSN:
1548-7660.
Baddeley, A. and Turner, R. (2005b) Modelling spatial point patterns in R. In: A. Baddeley,
P. Gregori, J. Mateu, R. Stoica, and D. Stoyan, editors, Case Studies in Spatial Point
Pattern Modelling, Lecture Notes in Statistics number 185. Pages 23–74. Springer-Verlag,
New York, 2006. ISBN: 0-387-28311-0.
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial
point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

[Link] Intensity Estimate of Point Pattern Using Tessellation

Description
Computes an adaptive estimate of the intensity function of a point pattern.

Usage
[Link](X, f = 0.1, ..., nrep = 1)
24 [Link]

Arguments

X Point pattern dataset (object of class "ppp").


f Fraction (between 0 and 1) of the data points that will be removed from
the data and used to determine a tessellation for the intensity estimate.
... Arguments passed to [Link] determining the pixel resolution of the result.
nrep Number of independent repetitions of the randomised procedure.

Details

This function is an alternative to [Link]. It computes an estimate of the intensity


function of a point pattern dataset.
The dataset X is randomly split into two patterns A and B containing a fraction f and
1-f, respectively, of the original data. The subpattern A is used to construct a Dirichlet
tessellation (see dirichlet). The subpattern B is retained for counting. For each tile of
the Dirichlet tessellation, we count the number of points of B falling in the tile, and divide
by the area of the same tile, to obtain an estimate of the intensity of the pattern B in the
tile. This estimate is divided by 1-f to obtain an estimate of the intensity of X in the tile.
The result is a pixel image of intensity estimates which are constant on each tile of the
tessellation.
If nrep is greater than 1, this randomised procedure is repeated nrep times, and the results
are averaged.
This technique has been used by Ogata et al. (2003), Ogata (2004) and Baddeley (2007).

Value

A pixel image (object of class "im") whose values are estimates of the intensity of X.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Baddeley, A. (2007) Validation of statistical models for spatial point patterns. In J.G.
Babu and E.D. Feigelson (eds.) SCMA IV: Statistical Challenges in Modern Astronomy
IV, volume 317 of Astronomical Society of the Pacific Conference Series, San Francisco,
California USA, 2007. Pages 22–38.
Ogata, Y. (2004) Space-time model for regional seismicity and detection of crustal stress
changes. Journal of Geophysical Research, 109, 2004.
Ogata, Y., Katsura, K. and Tanemura, M. (2003). Modelling heterogeneous space-time
occurrences of earthquake and its residual analysis. Applied Statistics 52 499–509.

See Also

[Link], dirichlet, [Link].


affine 25

Examples
## Not run:
data(nztrees)
plot([Link](nztrees))

## End(Not run)

affine Apply Affine Transformation

Description

Applies any affine transformation of the plane (linear transformation plus vector shift) to
a plane geometrical object, such as a point pattern or a window.

Usage

affine(X, ...)

Arguments

X Any suitable dataset representing a two-dimensional object, such as a


point pattern (object of class "ppp"), or a window (object of class "owin").
... Arguments determining the affine transformation.

Details

This is generic. Methods are provided for point patterns ([Link]) and windows
([Link]).

Value

Another object of the same type, representing the result of applying the affine transforma-
tion.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [Link], rotate, shift


26 [Link]

[Link] Apply Affine Transformation To Window

Description
Applies any affine transformation of the plane (linear transformation plus vector shift) to
a window.

Usage
## S3 method for class 'owin':
affine(X, mat=diag(c(1,1)), vec=c(0,0), ...)

Arguments
X Window (object of class "owin").
mat Matrix representing a linear transformation.
vec Vector of length 2 representing a translation.
... Ignored

Details
The window is subjected first to the linear transformation represented by mat (multiplying
on the left by mat), and then the result is translated by the vector vec.
The argument mat must be a nonsingular 2 × 2 matrix.
This is a method for the generic function affine.

Value
Another window (of class "owin") representing the result of applying the affine transfor-
mation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
affine, [Link], rotate, shift

Examples
# shear transformation
X <- affine(owin(), matrix(c(1,0,0.6,1),ncol=2))
## Not run:
plot(X)

## End(Not run)
[Link] 27

[Link] Apply Affine Transformation To Point Pattern

Description
Applies any affine transformation of the plane (linear transformation plus vector shift) to
a point pattern.

Usage
## S3 method for class 'ppp':
affine(X, mat=diag(c(1,1)), vec=c(0,0), ...)

Arguments
X Point pattern (object of class "ppp").
mat Matrix representing a linear transformation.
vec Vector of length 2 representing a translation.
... Ignored

Details
The point pattern, and its window, are subjected first to the linear transformation rep-
resented by mat (multiplying on the left by mat), and are then translated by the vector
vec.
The argument mat must be a nonsingular 2 × 2 matrix.
This is a method for the generic function affine.

Value
Another point pattern (of class "ppp") representing the result of applying the affine trans-
formation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
affine, [Link], rotate, shift

Examples
data(cells)
# shear transformation
X <- affine(cells, matrix(c(1,0,0.6,1),ncol=2))
## Not run:
plot(X)
# rescale y coordinates by factor 1.3
plot(affine(cells, diag(c(1,1.3))))

## End(Not run)
28 [Link]

[Link] Apply Affine Transformation To Line Segment Pattern

Description
Applies any affine transformation of the plane (linear transformation plus vector shift) to
a line segment pattern.

Usage
## S3 method for class 'psp':
affine(X, mat=diag(c(1,1)), vec=c(0,0), ...)

Arguments
X Line Segment pattern (object of class "psp").
mat Matrix representing a linear transformation.
vec Vector of length 2 representing a translation.
... Ignored

Details
The line segment pattern, and its window, are subjected first to the linear transformation
represented by mat (multiplying on the left by mat), and are then translated by the vector
vec.
The argument mat must be a nonsingular 2 × 2 matrix.
This is a method for the generic function affine.

Value
Another line segment pattern (of class "psp") representing the result of applying the affine
transformation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
affine, [Link], [Link], rotate, shift

Examples
oldpar <- par(mfrow=c(2,1))
X <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
plot(X, main="original")
# shear transformation
Y <- affine(X, matrix(c(1,0,0.6,1),ncol=2))
plot(Y, "transformed")
par(oldpar)
#
allstats 29

# rescale y coordinates by factor 0.2


affine(X, diag(c(1,0.2)))

allstats Calculate four standard summary functions of a point pattern.

Description
Calculates the F , G, J, and K summary functions for an unmarked point pattern. Returns
them as a function array (of class "fasp", see [Link]).

Usage
allstats(pp, ..., dataname=NULL, verb=FALSE)

Arguments
pp The observed point pattern, for which summary function estimates are
required. An object of class "ppp". It must not be marked.
... Optional arguments passed to the summary functions Fest, Gest, Jest
and Kest.
dataname A character string giving an optional (alternative) name for the point
pattern.
verb A logical value meaning “verbose”. If TRUE, progress reports are printed
during calculation.

Details
This computes four standard summary statistics for a point pattern: the empty space func-
tion F (r), nearest neighbour distance distribution function G(r), van Lieshout-Baddeley
function J(r) and Ripley’s function K(r). The real work is done by Fest, Gest, Jest and
Kest respectively. Consult the help files for these functions for further information about
the statistical interpretation of F , G, J and K.
If verb is TRUE, then “progress reports” (just indications of completion) are printed out
when the calculations are finished for each of the four function types.
The overall title of the array of four functions (for plotting by [Link]) will be formed
from the argument dataname. If this is not given, it defaults to the expression for pp given
in the call to allstats.

Value
A list of length 4 containing the F , G, J and K functions respectively.
The list can be plotted directly using plot (which dispatches to [Link]).
Each list entry retains the format of the output of the relevant estimating routine Fest,
Gest, Jest or Kest. Thus each entry in the list is a function value table (object of class
"fv", see [Link]).
The default formulae for plotting these functions are cbind(km,theo) ~ r for F, G, and
J, and cbind(trans,theo) ~ r for K.
30 alltypes

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link], Fest, Gest, Jest, Kest

Examples
data(swedishpines)
a <- allstats(swedishpines,dataname="Swedish Pines")
## Not run:
plot(a)
plot(a, subset=list("r<=15","r<=15","r<=15","r<=50"))

## End(Not run)

alltypes Calculate Summary Statistic for All Types in a Multitype Point


Pattern

Description
Given a marked point pattern, this computes the estimates of a selected summary function
(F ,G, J, K etc) of the pattern, for all possible combinations of marks, and returns these
functions in an array.

Usage
alltypes(X, fun="K", ..., dataname=NULL,verb=FALSE,envelope=FALSE)

Arguments
X The observed point pattern, for which summary function estimates are
required. An object of class "ppp".
fun The summary function. Either an R function, or a character string indi-
cating the summary function required. Options for strings are "F", "G",
"J", "K", "L", "pcf", "Gcross", "Jcross", "Kcross", "Lcross", "Gdot",
"Jdot", "Kdot", "Ldot".
... Arguments passed to the summary function (and to the function envelope
if appropriate)
dataname Character string giving an optional (alternative) name to the point pat-
tern, different from what is given in the call. This name, if supplied, may
be used by [Link]() in forming the title of the plot. If not supplied
it defaults to the parsing of the argument supplied as X in the call.
verb Logical value. If verb is true then terse “progress reports” (just the val-
ues of the mark indices) are printed out when the calculations for that
combination of marks are completed.
envelope Logical value. If envelope is true, then simulation envelopes of the sum-
mary function will also be computed. See Details.
alltypes 31

Details
This routine is a convenient way to analyse the dependence between types in a multitype
point pattern. It computes the estimates of a selected summary function of the pattern,
for all possible combinations of marks. It returns these functions in an array (an object of
class "fasp") amenable to plotting by [Link]().
The argument fun specifies the summary function that will be evaluated for each type of
point, or for each pair of types. It may be either an R function or a character string.
Suppose that the points have possible types 1, 2, . . . , m and let Xi denote the pattern of
points of type i only.
If fun="F" then this routine calculates, for each possible type i, an estimate of the Empty
Space Function Fi (r) of Xi . See Fest for explanation of the empty space function. The
estimate is computed by applying Fest to Xi with the optional arguments ....
If fun is "Gcross", "Jcross", "Kcross" or "Lcross", the routine calculates, for each pair
of types (i, j), an estimate of the “i-toj” cross-type function Gij (r), Jij (r), Kij (r) or Lij (r)
respectively describing the dependence between Xi and Xj . See Gcross, Jcross, Kcross
or Lcross respectively for explanation of these functions. The estimate is computed by
applying the relevant function (Gcross etc) to X using each possible value of the arguments
i,j, together with the optional arguments ....
If fun is "pcf" the routine calculates the cross-type pair correlation function pcfcross
between each pair of types.
If fun is "Gdot", "Jdot", "Kdot" or "Ldot", the routine calculates, for each type i, an
estimate of the “i-to-any” dot-type function Gi• (r), Ji• (r) or Ki• (r) or Li• (r) respectively
describing the dependence between Xi and X. See Gdot, Jdot, Kdot or Ldot respectively for
explanation of these functions. The estimate is computed by applying the relevant function
(Gdot etc) to X using each possible value of the argument i, together with the optional
arguments ....
The letters "G", "J", "K" and "L" are interpreted as abbreviations for Gcross, Jcross,
Kcross and Lcross respectively, assuming the point pattern is marked. If the point pattern
is unmarked, the appropriate function Fest, Jest, Kest or Lest is invoked instead.
If envelope=TRUE, then as well as computing the value of the summary function for each
combination of types, the algorithm also computes simulation envelopes of the summary
function for each combination of types. The arguments ... are passed to the function
envelope to control the number of simulations, the random process generating the simula-
tions, the construction of envelopes, and so on.

Value
A function array (an object of class "fasp", see [Link]). This can be plotted using
[Link].
If the pattern is not marked, the resulting “array” has dimensions 1 × 1. Otherwise the
following is true:
If fun="F", the function array has dimensions m × 1 where m is the number of different
marks in the point pattern. The entry at position [i,1] in this array is the result of
applying Fest to the points of type i only.
If fun is "Gdot", "Jdot", "Kdot" or "Ldot", the function array again has dimensions m× 1.
The entry at position [i,1] in this array is the result of Gdot(X, i), Jdot(X, i) Kdot(X,
i) or Ldot(X, i) respectively.
If fun is "Gcross", "Jcross", "Kcross" or "Lcross" (or their abbreviations "G", "J", "K"
or "L"), the function array has dimensions m × m. The [i,j] entry of the function array
32 alltypes

(for i 6= j) is the result of applying the function Gcross, Jcross, Kcross orLcross to the
pair of types (i,j). The diagonal [i,i] entry of the function array is the result of applying
the univariate function Gest, Jest, Kest or Lest to the points of type i only.
If envelope=FALSE, then each function entry fns[[i]] retains the format of the output
of the relevant estimating routine Fest, Gest, Jest, Kest, Lest, Gcross, Jcross ,Kcross,
Lcross, Gdot, Jdot, Kdot or Ldot The default formulae for plotting these functions are
cbind(km,theo) ~ r for F, G, and J functions, and cbind(trans,theo) ~ r for K and L
functions.
If envelope=TRUE, then each function entry fns[[i]] has the same format as the output
of the envelope command.

Note
Sizeable amounts of memory may be needed during the calculation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], Fest, Gest, Jest, Kest, Lest, Gcross, Jcross, Kcross, Lcross,
Gdot, Jdot, Kdot, envelope.

Examples
# bramblecanes (3 marks).
data(bramblecanes)

bF <- alltypes(bramblecanes,"F",verb=TRUE)
plot(bF)
plot(alltypes(bramblecanes,"G"))
plot(alltypes(bramblecanes,"Gdot"))

# Swedishpines (unmarked).
data(swedishpines)

plot(alltypes(swedishpines,"K"))

data(amacrine)
plot(alltypes(amacrine, "pcf"), ylim=c(0,1.3))

# A setting where you might REALLY want to use dataname:


## Not run:
xxx <- alltypes(ppp(Melvin$x,Melvin$y,
window=[Link](c(5,20,15,50)),marks=clyde),
fun="F",verb=TRUE,dataname="Melvin")

## End(Not run)

# envelopes
bKE <- alltypes(bramblecanes,"K",envelope=TRUE,nsim=19)
## Not run:
bFE <- alltypes(bramblecanes,"F",envelope=TRUE,nsim=19,global=TRUE)
amacrine 33

## End(Not run)

# extract one entry


[Link](bKE[1,1])

amacrine Hughes’ Amacrine Cell Data

Description
Austin Hughes’ data: a point pattern of displaced amacrine cells in the retina of a rabbit.
A marked point pattern.

Usage
data(amacrine)

Format
An object of class "ppp" representing the point pattern of cell locations. Entries include

x Cartesian x-coordinate of cell


y Cartesian y-coordinate of cell
marks factor with levels off and on
indicating “off” and “on” cells

See [Link] for details of the format.

Notes

Austin Hughes’ data: a point pattern of displaced amacrine cells in the retina of a rabbit.
152 “on” cells and 142 “off” cells in a rectangular sampling frame.
The true dimensions of the rectangle are 1060 by 662 microns. The coordinates here are
scaled to a rectangle of height 1 and width 1060/662 = 1.601 so the unit of measurement
is approximately 662 microns.
The data were analysed by Diggle (1986).

Source

Peter Diggle, personal communication

References

Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit: analysis of a bivariate
spatial point pattern. J. Neurosci. Meth. 18, 115–125.
34 anemones

anemones Beadlet Anemones Data

Description
These data give the spatial locations and diameters of sea anemones (beadlet anemone
Actinia equina) in a sample plot on the north face of a boulder, well above low tide level,
at Quiberon (Bretagne, France) in May 1976.
The data were originally described and discussed by Kooijman (1979a). Kooijman (1979b)
shows a hand-drawn plot of the original data. The data are discussed by Upton and Fin-
gleton (1985) as Example 1.8 on pages 64–67.
The anemones dataset is taken directly from Table 1.11 of Upton and Fingleton (1985).
The coordinates and diameters are integer multiples of an idiosyncratic unit of length. The
boundary is a rectangle 280 by 180 units.

Usage
data(anemones)

Format
anemones is an object of class "ppp" representing the point pattern of anemone locations.
It is a marked point pattern with numeric marks representing anemone diameter. See
[Link] for details of the format.

Units
There is some confusion about the correct physical scale for these data. According to
Upton and Fingleton (1985), one unit in the dataset is approximately 0.475 cm. According
to Kooijman (1979a, 1979b) and also quoted by Upton and Fingleton (1985), the physical
size of the sample plot was 14.5 by 9.75 cm. However if the data are plotted at this scale,
they are too small for a rectangle of this size, and the appearance of the plot does not
match the original hand-drawn plot in Kooijman (1979b). To avoid confusion, we have not
assigned a unit scale to this dataset.

Source
Table 1.11 on pages 62–63 of Upton and Fingleton (1985), who acknowledge Kooijman
(1979a) as the source.

References
Kooijman, S.A.L.M. (1979a) The description of point patterns. In Spatial and temporal
analysis in ecology (ed. R.M. Cormack and J.K. Ord), International Cooperative Publishing
House, Fairland, Maryland, USA. Pages 305–332.
Kooijman, S.A.L.M. (1979b) Inference about dispersal patterns. Acta Biotheoretica 28,
149–189.
Upton, G.J.G. and Fingleton, B. (1985) Spatial data analysis by example. Volume 1: Point
pattern and quantitative data. John Wiley and Sons, Chichester.
[Link] 35

Examples
data(anemones)
# plot diameters on same scale as x, y
plot(anemones, markscale=0.5)

[Link] Orientation Angles of Line Segments

Description
Computes the orientation angle of each line segment in a line segment pattern.

Usage
[Link](x, directed=FALSE)

Arguments
x A line segment pattern (object of class "psp").
directed Logical flag. See details.

Details
For each line segment, the angle of inclination to the x-axis (in radians) is computed, and
the angles are returned as a numeric vector.
If directed=TRUE, the directed angle of orientation is computed. The angle respects the
sense of direction from (x0,y0) to (x1,y1). The values returned are angles in the full
range from −π to π. The angle is computed as atan2(y1-y0,x1-x0). See atan2.
If directed=FALSE, the undirected angle of orientation is computed. Angles differing by pi
are regarded as equivalent. The values returned are angles in the range from 0 to π. These
angles are computed by first computing the directed angle, then adding π to any negative
angles.

Value
Numeric vector.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
b <- [Link](a)
36 [Link]

[Link] ANOVA for Fitted Point Process Models

Description
Performs analysis of deviance for two or more fitted point process models.

Usage
## S3 method for class 'ppm':
anova(object, ..., test=NULL, override=FALSE)

Arguments
object A fitted point process model (object of class "ppm").
... One or more fitted point process models.
test Character string, partially matching one of "Chisq", "F" or "Cp".
override Logical flag indicating whether to proceed even when there is no statistical
theory to support the calculation.

Details
This is a method for anova for fitted point process models (objects of class "ppm", usually
generated by the model-fitting function ppm).
If the fitted models are all Poisson point processes, then this function performs an Analysis
of Deviance of the fitted models. The output shows the deviance differences (i.e. 2 times log
likelihood ratio), the difference in degrees of freedom, and (if test="Chi") the two-sided
p-values for the chi-squared tests. Their interpretation is very similar to that in [Link].
If some of the fitted models are not Poisson point processes, then there is no statistical
theory available to support a similar analysis. The function issues a warning, and (by
default) returns a NULL value.
However if override=TRUE, then a kind of analysis of deviance table will be printed. The
‘deviance’ differences in this table are equal to 2 times the differences in the maximised
values of the log pseudolikelihood (see ppm). At the time of writing, there is no statistical
theory to support inferential interpretation of log pseudolikelihood ratios. The override
option is provided for research purposes only!

Value
An object of class "anova", or NULL.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm
ants 37

Examples
data(swedishpines)
mod0 <- ppm(swedishpines, ~1, Poisson())
modx <- ppm(swedishpines, ~x, Poisson())
[Link](mod0, modx, test="Chi")

ants Harkness-Isham ants’ nests data

Description
These data give the spatial locations of nests of two species of ants, Messor wasmanni and
Cataglyphis bicolor, recorded by Professor R.D.\ Harkness at a site in northern Greece, and
described in Harkness \& Isham (1983). The full dataset (supplied here) has an irregular
polygonal boundary, while most analyses have been confined to two rectangular subsets of
the pattern (also supplied here).
The harvester ant M. wasmanni collects seeds for food and builds a nest composed mainly
of seed husks. C. bicolor is a heat-tolerant desert foraging ant which eats dead insects and
other arthropods. Interest focuses on whether there is evidence in the data for intra-species
competition between Messor nests (i.e. competition for resources) and for preferential
placement of Cataglyphis nests in the vicinity of Messor nests.
The full dataset is displayed in Figure 1 of Harkness \& Isham (1983). See Usage below
to produce a comparable plot. It comprises 97 nests (68 Messor and 29 Cataglyphis) inside
an irregular convex polygonal boundary, together with annotations showing a foot track
through the region, the boundary between field and scrub areas inside the region, and
indicating the two rectangular subregions A and B used in their analysis.
Rectangular subsets of the data were analysed by Harkness \& Isham (1983), Isham (1984),
Takacs \& Fiksel (1986), S\”arkk\”a (1993, section 5.3), H\”ogmander and S\”arkk\”a
(1999) and Baddeley \& Turner (2000). The full dataset (inside its irregular boundary)
was first analysed by Baddeley \& Turner (2005b).
The dataset ants is the full point pattern enclosed by the irregular polygonal boundary.
The x and y coordinates are eastings (E-W) and northings (N-S) scaled so that 1 unit equals
0.5 feet. This is a multitype point pattern object, each point carrying a mark indicating
the ant species (with levels Cataglyphis and Messor).
The dataset [Link] is a list of auxiliary information:

A and B The subsets of the pattern within the rectangles A and B demarcated in Figure 1
of Harkness \& Isham (1983). These are multitype point pattern objects.
[Link] and [Link] coordinates of two straight lines bounding the foot track.
[Link] The endpoints of a straight line separating the regions of ‘field’ and
‘scrub’: scrub to the North and field to the South.
plot A function, with no arguments, which produces a plot of the full dataset.

Usage
data(ants)
38 ants

Format
ants is an object of class "ppp" representing the full point pattern of ants’ nests. See
[Link] for details of the format. The coordinates are scaled so that 1 unit equals 0.5
feet. The points are marked by species (with levels Cataglyphis and Messor).
[Link] is a list with entries

A point pattern of class "ppp"


B point pattern of class "ppp"
trackNE data in format list(x=numeric(2),y=numeric(2)) giving the two endpoints of
line markings
trackSW data in format list(x=numeric(2),y=numeric(2)) giving the two endpoints
of line markings
fieldscrub data in format list(x=numeric(2),y=numeric(2)) giving the two endpoints
of line markings
plot Function with no arguments

Source
Harkness and Isham (1983). Nest coordinates kindly provided by Prof Valerie Isham. Poly-
gon coordinates digitised by Adrian Baddeley from a reprint of Harkness \& Isham (1983).

References
Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283–322.
Baddeley, A. and Turner, R. (2005a) Spatstat: an R package for analyzing spatial point
patterns. Journal of Statistical Software 12:6, 1–42. URL: [Link], ISSN:
1548-7660.
Baddeley, A. and Turner, R. (2005b) Modelling spatial point patterns in R. In: A. Baddeley,
P. Gregori, J. Mateu, R. Stoica, and D. Stoyan, editors, Case Studies in Spatial Point
Pattern Modelling, Lecture Notes in Statistics number 185. Pages 23–74. Springer-Verlag,
New York, 2006. ISBN: 0-387-28311-0.
Harkness, R.D. and Isham, V. (1983) A bivariate spatial point pattern of ants’ nests. Applied
Statistics 32, 293–303.
H\”ogmander, H. and S\”arkk\”a, A. (1999) Multitype spatial point patterns with hierar-
chical interactions. Biometrics 55, 1051–1058.
Isham, V.S. (1984) Multitype Markov point processes: some approximations. Proceedings
of the Royal Society of London, Series A, 391, 39–53.
Takacs, R. and Fiksel, T. (1986) Interaction pair-potentials for a system of ants’ nests.
Biometrical Journal 28, 1007–1013.
S\”arkk\”a, A. (1993) Pseudo-likelihood approach for pair potential estimation of Gibbs pro-
cesses. Number 22 in Jyv\”askyl\”a Studies in Computer Science, Economics and Statistics.
University of Jyv\”askyl\”a, Finland.

Examples

# Equivalent to Figure 1 of Harkness and Isham (1983)


[Link] 39

data(ants)
[Link]$plot()

# Data in subrectangle A, rotated


# Approximate data used by Sarkka (1993)

angle <- atan(diff([Link]$fieldscrub$y)/diff([Link]$fieldscrub$x))


plot(rotate([Link]$A, -angle))

# Approximate window used by Takacs and Fiksel (1986)

tfwindow <- [Link](ants$window)


antsTF <- ppp(ants$x, ants$y, window=tfwindow)
plot(antsTF)

[Link] Combine Two Line Segment Patterns

Description
Combine two line segment patterns into a single pattern.

Usage
[Link](A, B)

Arguments
A,B Line segment patterns (objects of class "psp").

Details
This function is used to superimpose two line segment patterns A and B.
The two patterns must have identical windows. If one pattern has marks, then the other
must also have marks of the same type.
(To combine two point patterns, see superimpose).

Value
Another line segment pattern (object of class "psp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
psp, [Link], superimpose,

Examples
X <- psp(runif(20), runif(20), runif(20), runif(20), window=owin())
Y <- psp(runif(5), runif(5), runif(5), runif(5), window=owin())
[Link](X,Y)
40 applynbd

applynbd Apply Function to Every Neighbourhood in a Point Pattern

Description
Visit each point in a point pattern, find the neighbouring points, and apply a given function
to them.

Usage
applynbd(X, FUN, N, R, criterion, exclude=FALSE, ...)

Arguments
X Point pattern. An object of class "ppp", or data which can be converted
into this format by [Link].
FUN Function to be applied to each neighbourhood. The arguments of FUN are
described under Details.
N Integer. If this argument is present, the neighbourhood of a point of X
is defined to consist of the N points of X which are closest to it. This
argument is incompatible with R and criterion.
R Nonnegative numeric value. If this argument is present, the neighbour-
hood of a point of X is defined to consist of all points of X which lie within
a distance R of it. This argument is incompatible with N and criterion.
criterion Function. If this argument is present, the neighbourhood of a point of
X is determined by evaluating this function. See under Details. This
argument is incompatible with N and R.
exclude Logical. If TRUE then the point currently being visited is excluded from
its own neighbourhood.
... extra arguments passed to the function FUN. They must be given in the
form name=value.

Details
This is an analogue of apply for point patterns. It visits each point in the point pattern
X, determines which points of X are “neighbours” of the current point, applies the function
FUN to this neighbourhood, and collects the values returned by FUN.
The definition of “neighbours” depends on the arguments N, R and criterion, exactly one
of which must be given. Also the argument exclude determines whether the current point
is excluded from its own neighbourhood.

ˆ If N is given, then the neighbours of the current point are the N points of X which are
closest to the current point (including the current point itself unless exclude=TRUE).
ˆ If R is given, then the neighbourhood of the current point consists of all points of X
which lie closer than a distance R from the current point.
ˆ If criterion is given, then it must be a function with two arguments dist and drank
which will be vectors of equal length. The interpretation is that dist[i] will be the
distance of a point from the current point, and drank[i] will be the rank of that
distance (the three points closest to the current point will have rank 1, 2 and 3). This
applynbd 41

function must return a logical vector of the same length as dist and drank whose i-th
entry is TRUE if the corresponding point should be included in the neighbourhood. See
the examples below.

When applynbd is executed, each point of X is visited, and the following happens for each
point:
ˆ the neighbourhood of the current point is determined according to the chosen rule,
and stored as a point pattern Y;
ˆ the function FUN is called as:
FUN(Y=Y, current=current, dists=dists, dranks=dranks, ...)
where current is the location of the current point (in a format explained below),
dists is a vector of distances from the current point to each of the points in Y, dranks
is a vector of the ranks of these distances with respect to the full point pattern X, and
... are the arguments passed from the call to applynbd;
ˆ The result of the call to FUN is stored.

The results of each call to FUN are collected and returned according to the usual rules for
apply and its relatives. See the Value section of this help file.
The format of the argument current is as follows. If X is an unmarked point pattern, then
current is a vector of length 2 containing the coordinates of the current point. If X is
marked, then current is a point pattern containing exactly one point, so that current$x
is its x-coordinate and current$marks is its mark value. In either case, the coordinates of
the current point can be referred to as current$x and current$y.
Note that FUN will be called exactly as described above, with each argument named ex-
plicitly. Care is required when writing the function FUN to ensure that the arguments will
match up. See the Examples.
See markstat for a common use of this function.
To simply tabulate the marks in every R-neighbourhood, use marktable.

Value
Similar to the result of apply. If each call to FUN returns a single numeric value, the result
is a vector of dimension X$n, the number of points in X. If each call to FUN returns a vector of
the same length m, then the result is a matrix of dimensions c(m,n); note the transposition
of the indices, as usual for the family of apply functions. If the calls to FUN return vectors
of different lengths, the result is a list of length X$n.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], apply, markstat, marktable

Examples
data(redwood)

# count the number of points within radius 0.2 of each point of X


nneighbours <- applynbd(redwood, R=0.2, function(Y, ...){Y$n-1})
42 applynbd

# equivalent to:
nneighbours <- applynbd(redwood, R=0.2, function(Y, ...){Y$n}, exclude=TRUE)

# compute the distance to the second nearest neighbour of each point


secondnndist <- applynbd(redwood, N = 2,
function(dists, ...){max(dists)},
exclude=TRUE)

# marked point pattern


data(longleaf)

# compute the median of the marks of all neighbours of a point


# (see also 'markstat')
[Link] <- applynbd(longleaf, R=90, exclude=TRUE,
function(Y, ...) { median(Y$marks)})

# ANIMATION explaining the definition of the K function


# (arguments `fullpicture' and 'rad' are passed to FUN)

## Not run:
showoffK <- function(Y, current, dists, dranks, fullpicture,rad) {
plot(fullpicture, main="")
points(Y, cex=2)
u <- current
points(u$x,u$y,pch="+",cex=3)
theta <- seq(0,2*pi,length=100)
polygon(u$x+ rad * cos(theta),u$y+rad*sin(theta))
text(u$x+rad/3,u$y+rad/2,Y$n,cex=3)
[Link](if(runif(1) < 0.1) 1.5 else 0.3)
return(Y$n - 1)
}
applynbd(redwood, R=0.2, showoffK, fullpicture=redwood, rad=0.2, exclude=TRUE)

# animation explaining the definition of the G function

showoffG <- function(Y, current, dists, dranks, fullpicture) {


plot(fullpicture, main="")
points(Y, cex=2)
u <- current
points(u[1],u[2],pch="+",cex=3)
v <- c(Y$x[1],Y$y[1])
segments(u[1],u[2],v[1],v[2],lwd=2)
w <- (u + v)/2
nnd <- dists[1]
text(w[1],w[2],round(nnd,3),cex=2)
[Link](if(runif(1) < 0.1) 1.5 else 0.3)
return(nnd)
}

data(cells)
applynbd(cells, N=1, showoffG, exclude=TRUE, fullpicture=cells)

## End(Not run)
[Link] 43

[Link] Area of a Window

Description
Computes the area of a window

Usage
[Link](w)

Arguments
w A window, whose area will be computed. This should be an object of
class owin, or can be given in any format acceptable to [Link]().

Details
If the window W is of type "rectangle" or "polygonal", the area of this rectangular
window is computed by analytic geometry. If W is of type "mask" the area of the discrete
raster approximation of the window is computed by summing the binary image values and
adjusting for pixel size.

Value
A numerical value giving the area of the window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
perimeter, diameter, [Link], [Link]

Examples
w <- [Link]()
[Link](w)
# returns 1.00000

k <- 6
theta <- 2 * pi * (0:(k-1))/k
co <- cos(theta)
si <- sin(theta)
mas <- owin(c(-1,1), c(-1,1), poly=list(x=co, y=si))
[Link](mas)
# returns approx area of k-gon

mas <- [Link](square(2), eps=0.01)


X <- raster.x(mas)
Y <- raster.y(mas)
mas$m <- ((X - 1)^2 + (Y - 1)^2 <= 1)
44 areaGain

[Link](mas)
# returns 3.14 approx

areaGain Difference of Disc Areas

Description
Computes the area of that part of a disc that is not covered by other discs.

Usage
areaGain(u, X, r, W=NULL, ngrid=[Link]("[Link]"))

Arguments
u Coordinates of the centre of the disc of interest. A vector of length 2.
Alternatively, a point pattern (object of class "ppp").
X Locations of the centres of other discs. A point pattern (object of class
"ppp").
r Disc radius, or vector of disc radii.
W Optional. Window (object of class "owin") in which the area should be
computed.
ngrid Dimensions of the ngrid * ngrid array of test points that will be used
to estimate the uncovered area.

Details
This function computes the area of that part of the disc of radius r centred at the location u
that is not covered by any of the discs of radius r centred at the points of the pattern X. This
area is important in some calculations related to the area-interaction model AreaInter.
If u is a point pattern and r is a vector, the result is a matrix, with one row for each point
in u and one column for each entry of r. The [i,j] entry in the matrix is the area of that
part of the disc of radius r[j] centred at the location u[i] that is not covered by any of
the discs of radius r[j] centred at the points of the pattern X.
If W is not NULL, then the areas are computed only inside the window W. Currently this is
implemented only for rectangular windows.
The area is calculated by discrete approximation, using an ngrid * ngrid grid of test
points.

Value
A matrix with one row for each point in u and one column for each value in r.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
AreaInter 45

See Also
AreaInter, areaLoss

Examples
data(cells)
u <- c(0.5,0.5)
areaGain(u, cells, 0.1)

AreaInter The Area Interaction Point Process Model

Description
Creates an instance of the Area Interaction point process model (Widom-Rowlinson pene-
trable spheres model) which can then be fitted to point pattern data.

Usage
AreaInter(r)

Arguments
r The radius of the discs in the area interaction process

Details
This function defines the interpoint interaction structure of a point process called the
Widom-Rowlinson penetrable sphere model or area-interaction process. It can be used
to fit this model to point pattern data.
The function ppm(), which fits point process models to point pattern data, requires an
argument of class "interact" describing the interpoint interaction structure of the model
to be fitted. The appropriate description of the area interaction structure is yielded by the
function AreaInter(). See the examples below.
In standard form, the area-interaction process (Widom and Rowlinson, 1970; Baddeley
and Van Lieshout, 1995) with disc radius r, intensity parameter κ and interaction parameter
γ is a point process with probability density

f (x1 , . . . , xn ) = ακn(x) γ −A(x)

where x1 , . . . , xn represent the points of the pattern, n(x) is the number of points in the
pattern, and A(x) is the area of the region formed by the union of discs of radius r centred
at the points x1 , . . . , xn . Here α is a normalising constant.
The interaction parameter γ can be any positive number. If γ = 1 then the model reduces
to a Poisson process with intensity κ. If γ < 1 then the process is regular, while if γ > 1 the
process is clustered. Thus, an area interaction process can be used to model either clustered
or regular point patterns. Two points interact if the distance between them is less than 2r.
The standard form of the model, shown above, is a little complicated to interpret in practical
2
applications. For example, each isolated point of the pattern x contributes a factor κγ −πr
to the probability density.
46 AreaInter

In spatstat, the model is parametrised in a different form, which is easier to interpret. In


canonical scale-free form, the probability density is rewritten as

f (x1 , . . . , xn ) = αβ n(x) η −C(x)

where β is the new intensity parameter, η is the new interaction parameter, and C(x) =
B(x) − n(x) is the interaction potential. Here
A(x)
B(x) =
πr2
is the normalised area (so that the discs have unit area). In this formulation, each isolated
point of the pattern contributes a factor β to the probability density (so the first order
trend is β). The quantity C(x) is a true interaction potential, in the sense that C(x) = 0 if
the point pattern x does not contain any points that lie close together (closer than 2r units
apart).
The old parameters κ, γ of the standard form are related to the new parameters β, η of the
canonical scale-free form, by
2
β = κγ −πr = κ/η
and 2
η = γ πr
provided γ and κ are positive and finite.
In the canonical scale-free form, the parameter η can take any nonnegative value. The value
η = 1 again corresponds to a Poisson process, with intensity β. If η < 1 then the process is
regular, while if η > 1 the process is clustered. The value η = 0 corresponds to a hard core
process with hard core radius r (interaction distance 2r).
The nonstationary area interaction process is similar except that the contribution of each
individual point xi is a function β(xi ) of location, rather than a constant beta.
Note the only argument of AreaInter() is the disc radius r. When r is fixed, the model
becomes an exponential family. The canonical parameters log(β) and log(η) are estimated
by ppm(), not fixed in AreaInter().

Value
An object of class "interact" describing the interpoint interaction structure of the area-
interaction process with disc radius r.

Warnings
The interaction distance of this process is equal to 2 * r. Two discs of radius r overlap if
their centres are closer than 2 * r units apart.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A.J. and Van Lieshout, M.N.M. (1995). Area-interaction point processes. Annals
of the Institute of Statistical Mathematics 47 (1995) 601–619.
Widom, B. and Rowlinson, J.S. (1970). New model for the study of liquid-vapor phase
transitions. The Journal of Chemical Physics 52 (1970) 1670–1684.
areaLoss 47

See Also

ppm, [Link], [Link]

Examples

# prints a sensible description of itself


AreaInter(r=0.1)

# Note the reach is twice the radius


reach(AreaInter(r=1))

# Fit the stationary area interaction process to Swedish Pines data


data(swedishpines)
ppm(swedishpines, ~1, AreaInter(r=7))

# Fit the stationary area interaction process to `cells'


data(cells)
ppm(cells, ~1, AreaInter(r=0.06))
# eta=0 indicates hard core process.

# Fit a nonstationary area interaction with log-cubic polynomial trend


## Not run:
ppm(swedishpines, ~polynom(x/10,y/10,3), AreaInter(r=7))

## End(Not run)

areaLoss Difference of Disc Areas

Description

Computes the area of that part of a disc that is not covered by other discs.

Usage

areaLoss(X, r, ngrid=[Link]("[Link]"), subset=NULL)

Arguments

X Locations of the centres of discs. A point pattern (object of class "ppp").


r Disc radius, or vector of disc radii.
ngrid Dimensions of the ngrid * ngrid array of test points that will be used
to estimate the uncovered area.
subset Optional. Index identifying a subset of the points of X for which the area
difference should be computed.
48 as.box3

Details

This function computes, for each point X[i] in X and for each radius r, the area of that part
of the disc of radius r centred at the location X[i] that is not covered by any of the other
discs of radius r centred at the points X[j] for j not equal to i. This area is important in
some calculations related to the area-interaction model AreaInter.
The result is a matrix, with one row for each point in X and one column for each entry of
r.
The area is calculated by discrete approximation, using an ngrid * ngrid grid of test
points.

Value

A matrix with one row for each point in X (or X[subset]) and one column for each value
in r.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

AreaInter, areaGain

Examples
data(cells)
areaLoss(cells, 0.1, 32)

as.box3 Convert Data to Three-Dimensional Box

Description

Interprets data as the dimensions of a three-dimensional box.

Usage

as.box3(...)

Arguments

... Data that can be interpreted as giving the dimensions of a three-dimensional


box. See Details.
[Link] 49

Details
This function converts data in various formats to an object of class "box3" representing a
three-dimensional box (see box3). The arguments ... may be

ˆ an object of class "box3"


ˆ arguments acceptable to box3
ˆ a numeric vector of length 6, interpreted as c(xrange[1],xrange[2],yrange[1],yrange[2],zrange[1],
ˆ an object of class "pp3" representing a three-dimensional point pattern contained in
a box.

Value
Object of class "box3".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
box3, pp3

Examples
X <- c(0,10,0,10,0,5)
as.box3(X)
X <- pp3(runif(42),runif(42),runif(42), box3(c(0,1)))
as.box3(X)

[Link] Coerce Point Pattern to a Data Frame

Description
Extracts the coordinates of the points in a point pattern, and their marks if any, and returns
them in a data frame.

Usage
## S3 method for class 'ppp':
[Link](x, [Link] = NULL, ...)

Arguments
x Point pattern (object of class "ppp").
[Link] Optional character vector of row names.
... Ignored.
50 [Link]

Details
This is a method for the generic function [Link] for the class "ppp" of point
patterns.
It extracts the coordinates of the points in the point pattern, and returns them as columns
named x and y in a data frame. If the points were marked, the marks are returned as a
column named marks with the same type as in the point pattern dataset.

Value
A data frame.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
data(amacrine)
df <- [Link](amacrine)
df[1:5,]

[Link] Coerce Line Segment Pattern to a Data Frame

Description
Extracts the coordinates of the endpoints in a line segment pattern, and their marks if any,
and returns them in a data frame.

Usage
## S3 method for class 'psp':
[Link](x, [Link] = NULL, ...)

Arguments
x Line segment pattern (object of class "psp").
[Link] Optional character vector of row names.
... Ignored.

Details
This is a method for the generic function [Link] for the class "psp" of line segment
patterns.
It extracts the coordinates of the endpoints of the line segments, and returns them as
columns named x0, y0, x1 and y1 in a data frame. If the line segments were marked, the
marks are returned as a column named marks in the data frame, with the same type as in
the line segment pattern dataset.
[Link] 51

Value
A data frame with 4 or 5 columns.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
data(copper)
df <- [Link](copper$Lines)

[Link] Convert Data to Hyperframe

Description
Converts data from any suitable format into a hyperframe.

Usage
[Link](x, ...)
## Default S3 method:
[Link](x, ...)
## S3 method for class '[Link]':
[Link](x, ...)
## S3 method for class 'hyperframe':
[Link](x, ...)
## S3 method for class 'listof':
[Link](x, ...)

Arguments
x Data in some other format.
... Ignored.

Details
A hyperframe is like a data frame, except that its entries can be objects of any kind.
The generic function [Link] converts any suitable kind of data into a hyperframe.
There are methods for the classes [Link] and listof, and a default method, all of
which convert data that is like a hyperframe into a hyperframe object. (The method for
the class listof converts a list of objects, of arbitrary type, into a hyperframe with one
column.) These methods do not discard any information.
There are also methods for other classes (see [Link]) which extract the coor-
dinates from a spatial dataset. These methods do discard some information.

Value
An object of class "hyperframe" created by hyperframe.
52 [Link]

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
hyperframe

Examples
df <- [Link](x=runif(4),y=letters[1:4])
[Link](df)

sims <- list()


for(i in 1:3) sims[[i]] <- rpoispp(42)
[Link]([Link](sims))

[Link] Extract coordinates and marks of multidimensional point pattern

Description
Given any kind of spatial or space-time point pattern, extract the coordinates and marks
of the points.

Usage
## S3 method for class 'ppx':
[Link](x, ...)
## S3 method for class 'ppx':
[Link](x, ...)

Arguments
x A general multidimensional space-time point pattern (object of class "ppx").
... Ignored.

Details
An object of class "ppx" (see ppx) represents a marked point pattern in multidimensional
space and/or time. There may be any number of spatial coordinates, any number of tem-
poral coordinates, and any number of mark variables. The individual marks may be atomic
(numeric values, factor values, etc) or objects of any kind.
The function [Link] extracts the coordinates and the marks as a "hyperframe"
(see hyperframe) with one row of data for each point in the pattern. This is a method for
the generic function [Link].
The function [Link] discards those mark variables which are not atomic val-
ues, and extracts the coordinates and the remaining marks as a [Link] with one row of
data for each point in the pattern. This is a method for the generic function [Link].
[Link] 53

Value
A hyperframe or [Link] as appropriate.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppx, hyperframe, [Link].

Examples
df <- [Link](x=runif(4),y=runif(4),t=runif(4))
X <- ppx(data=df, temporal="t")
[Link](X)
val <- runif(4)
E <- lapply(val, function(s) { rpoispp(s) })
hf <- hyperframe(t=val, e=[Link](E))
Z <- ppx(data=hf, domain=c(0,1))
[Link](Z)
[Link](Z)

[Link] Convert to Pixel Image

Description
Converts various kinds of data to a pixel image

Usage
[Link](X, ...)
## S3 method for class 'im':
[Link](X, W=NULL, ...,
eps=NULL, dimyx=NULL, xy=NULL,
[Link]=NULL)
## S3 method for class 'owin':
[Link](X, W=NULL, ...,
eps=NULL, dimyx=NULL, xy=NULL,
[Link]=NULL, value=1)
## S3 method for class 'tess':
[Link](X, W=NULL, ...,
eps=NULL, dimyx=NULL, xy=NULL,
[Link]=NULL)
## S3 method for class 'function':
[Link](X, W=NULL, ...,
eps=NULL, dimyx=NULL, xy=NULL,
[Link]=NULL)
## Default S3 method:
[Link](X, W=NULL, ...,
54 [Link]

eps=NULL, dimyx=NULL, xy=NULL,


[Link]=NULL)

Arguments
X Data to be converted to a pixel image.
W Window object which determines the spatial domain and pixel array ge-
ometry.
... Additional arguments passed to X when X is a function.
eps,dimyx,xy Optional parameters passed to [Link] which determine the pixel array
geometry. See [Link].
[Link] Optional value to replace NA entries in the output image.
value Optional. The value to be assigned to pixels inside the window, if X is a
window.

Details
This function converts the data X into a pixel image object of class "im" (see [Link]).
The function [Link] is generic, with methods for the classes listed above.
Currently X may be any of the following:
ˆ a pixel image object, of class "im".
ˆ a window object, of class "owin" (see [Link]). The result is an image with all
pixel entries equal to value inside the window X, and NA outside.
ˆ a tessellation (object of class "tess"). The result is a factor-valued image, with one
factor level corresponding to each tile of the tessellation. Pixels are classified according
to the tile of the tessellation into which they fall.
ˆ a single number (or a single logical, complex, factor or character value). The result is
an image with all pixel entries equal to this constant value inside the window W (and
NA outside, unless the argument [Link] is given). Argument W is required.
ˆ a function of the form function(x, y, ...) which is to be evaluated to yield the
image pixel values. In this case, the additional argument W must be present. This
window will be converted to a binary image mask. Then the function X will be eval-
uated in the form X(x, y, ...) where x and y are vectors containing the x and
y coordinates of all the pixels in the image mask, and ... are any extra arguments
given. This function must return a vector or factor of the same length as the input
vectors, giving the pixel values.
ˆ a list with entries x, y, z in the format expected by the standard R functions [Link]
and [Link]. That is, z is a matrix of pixel values, x and y are vectors
of x and y coordinates respectively, and z[i,j] is the pixel value for the location
(x[i],y[j]).
ˆ a point pattern (object of class "ppp"). See the separate documentation for [Link].

The spatial domain (enclosing rectangle) of the pixel image is determined by the argument
W. If W is absent, the spatial domain is determined by X. When X is a function or a single
numerical value, W is required.
The pixel array dimensions of the final resulting image are determined by (in priority order)
ˆ the argument eps, dimyx or xy if present;
ˆ the pixel dimensions of the window W, if it is present and if it is a binary mask;
[Link] 55

ˆ the pixel dimensions of X if it is an image, a binary mask, or a list(x,y,z);


ˆ the default pixel dimensions, controlled by [Link].

Note that if eps, dimyx or xy is given, this will override the pixel dimensions of X if it has
them. Thus, [Link] can be used to change an image’s pixel dimensions.
If the argument [Link] is given, then all NA entries in the image will be replaced by
this value. The resulting image is then defined everwhere on the full rectangular domain,
instead of a smaller window. Here [Link] should be a single value, of the same type
as the other entries in the image.

Value
An image object of class "im".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
Separate documentation for [Link]

Examples
data(demopat)
# window object
W <- demopat$window
plot(W)
Z <- [Link](W)
image(Z)
# function
Z <- [Link](function(x,y) {x^2 + y^2}, [Link]())
image(Z)
# function with extra arguments
f <- function(x, y, x0, y0) {
sqrt((x - x0)^2 + (y-y0)^2)
}
Z <- [Link](f, [Link](), x0=0.5, y0=0.5)
image(Z)
# Revisit the Sixties
data(letterR)
Z <- [Link](f, letterR, x0=2.5, y0=2)
image(Z)
# usual convention in S
stuff <- list(x=1:10, y=1:10, z=matrix(1:100, nrow=10))
Z <- [Link](stuff)
# convert to finer grid
Z <- [Link](Z, dimyx=256)

# pixellate the Dirichlet tessellation


Di <- dirichlet(runifpoint(10))
plot([Link](Di))
plot(Di, add=TRUE)
56 [Link]

[Link] Pixel Image Approximation of a Window

Description
Obtain a discrete (pixel image) approximation of a given window

Usage
[Link](w, eps=NULL, dimyx=NULL, xy=NULL)

Arguments
w A window (object of class "owin") or data acceptable to [Link].
eps (optional) width and height of pixels.
dimyx (optional) pixel array dimensions
xy (optional) pixel coordinates

Details
This function generates a rectangular grid of locations in the plane, tests whether each of
these locations lies inside the window w, and stores the results as a binary pixel image or
‘mask’ (an object of class "owin", see [Link]).
The most common use of this function is to approximate the shape of another window w by
a binary pixel image. In this case, we will usually want to have a very fine grid of pixels.
This function can also be used to generate a coarsely-spaced grid of locations inside a
window, for purposes such as subsampling and prediction.
The grid spacing and location are controlled by the arguments eps, dimyx and xy, which
are mutually incompatible.
If eps is given, then the grid spacing will be approximately eps in both the x and y
directions.
If dimyx is given, then the pixel grid will be an m × n rectangular grid where m, n are given
by dimyx[2], dimyx[1] respectively. Warning: dimyx[1] is the number of pixels in the y
direction, and dimyx[2] is the number in the x direction.
If xy is given, then this should be a structure containing two elements x and y which are
the vectors of x and y coordinates of the margins of the grid. The pixel coordinates will be
generated from these two vectors. In this case w may be omitted.
If neither eps nor dimyx nor xy is given, the pixel raster dimensions are obtained from
[Link]("npixel").
There is no inverse of this function. However, the function [Link] will compute a
polygonal approximation of a binary mask.

Value
A window (object of class "owin") of type "mask" representing a binary pixel image.
[Link] 57

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link], [Link]

Examples
w <- owin(c(0,10),c(0,10), poly=list(x=c(1,2,3,2,1), y=c(2,3,4,6,7)))
## Not run: plot(w)
m <- [Link](w)
## Not run: plot(m)
x <- 1:9
y <- seq(0.25, 9.75, by=0.5)
m <- [Link](w, xy=list(x=x, y=y))

[Link] Convert Pixel Image to Matrix

Description
Convert a pixel image to a matrix

Usage
## S3 method for class 'im':
[Link](x, ...)

Arguments
x A pixel image (object of class "im").
... Ignored.

Details
This function takes the pixel image x and returns a matrix containing the pixel values.
It is handy when you want to extract a summary of the pixel values. See the Examples.

Value
A matrix.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
58 [Link]

Examples
# artificial image
Z <- setcov(square(1))

M <- [Link](Z)

median(M)

## Not run:
# plot the cumulative distribution function of pixel values
plot(ecdf([Link](Z)))

## End(Not run)

[Link] Convert Data To Class owin

Description
Converts data specifying an observation window in any of several formats, into an object
of class "owin".

Usage
[Link](W, ..., fatal=TRUE)
## S3 method for class 'owin':
[Link](W, ..., fatal=TRUE)
## S3 method for class 'ppp':
[Link](W, ..., fatal=TRUE)
## S3 method for class 'ppm':
[Link](W, ..., fatal=TRUE)
## S3 method for class 'psp':
[Link](W, ..., fatal=TRUE)
## S3 method for class 'quad':
[Link](W, ..., fatal=TRUE)
## S3 method for class 'tess':
[Link](W, ..., fatal=TRUE)
## S3 method for class 'im':
[Link](W, ..., fatal=TRUE)
## S3 method for class '[Link]':
[Link](W, ..., fatal=TRUE)
## S3 method for class '[Link]':
[Link](W, ..., fatal=TRUE)
## Default S3 method:
[Link](W, ..., fatal=TRUE)

Arguments
W Data specifying an observation window, in any of several formats de-
scribed under Details below.
fatal Logical flag determining what to do if the data cannot be converted to an
observation window. See Details.
... Ignored.
[Link] 59

Details
The class "owin" is a way of specifying the observation window for a point pattern. See
[Link] for an overview.
This function converts data in any of several formats into an object of class "owin" for use
by the spatstat package. The argument W may be

ˆ an object of class "owin"


ˆ a structure with entries xrange, yrange specifying the x and y dimensions of a rect-
angle
ˆ a four-element vector (interpreted as (xmin, xmax, ymin, ymax)) specifying the x
and y dimensions of a rectangle
ˆ a structure with entries xl, xu, yl, yu specifying the x and y dimensions of a rectan-
gle as (xmin, xmax) = (xl, xu) and (ymin, ymax) = (yl, yu). This will accept
objects of class spp used in the Venables and Ripley spatial library.
ˆ an object of class "[Link]" from the gpclib package, representing a polygonal win-
dow.
ˆ an object of class "ppp" representing a point pattern. In this case, the object’s window
structure will be extracted.
ˆ an object of class "psp" representing a line segment pattern. In this case, the object’s
window structure will be extracted.
ˆ an object of class "tess" representing a tessellation. In this case, the object’s window
structure will be extracted.
ˆ an object of class "quad" representing a quadrature scheme. In this case, the window
of the data component will be extracted.
ˆ an object of class "im" representing a pixel image. In this case, a window of type
"mask" will be returned, with the same pixel raster coordinates as the image. An image
pixel value of NA, signifying that the pixel lies outside the window, is transformed into
the logical value FALSE, which is the corresponding convention for window masks.
ˆ an object of class "ppm" representing a fitted point process model. In this case, [Link]
extracts the original point pattern data to which the model was fitted, and returns the
observation window of this point pattern.
ˆ A [Link] with exactly three columns. Each row of the data frame corresponds
to one pixel. Each row contains the x and y coordinates of a pixel, and a logical value
indicating whether the pixel lies inside the window.

If the argument W is not in one of these formats and cannot be converted to a window,
then an error will be generated (if fatal=TRUE) or a value of NULL will be returned (if
fatal=FALSE).
The function [Link] is generic, with methods for "owin", "im" and "ppp" as well as the
default method.

Value
An object of class "owin" (see [Link]) specifying an observation window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
60 [Link]

See Also
[Link], owin

Examples
w <- [Link](c(0,1,0,1))
w <- [Link](list(xrange=c(0,5),yrange=c(0,10)))
# point pattern
data(demopat)
w <- [Link](demopat)
# image
Z <- [Link](function(x,y) { x + 3}, [Link]())
w <- [Link](Z)

# Venables & Ripley 'spatial' package


require(spatial)
towns <- ppinit("[Link]")
w <- [Link](towns)
detach(package:spatial)

[Link] Convert a Window to a Polygonal Window

Description
Given a window W of any geometric type (rectangular, polygonal or binary mask), this
function returns a polygonal window that represents the same spatial domain.

Usage
[Link](W)

Arguments
W A window (object of class "owin").

Details
Given a window W of any geometric type (rectangular, polygonal or binary mask), this
function returns a polygonal window that represents the same spatial domain.
If W is already polygonal, it is returned without change.
If W is a rectangle, it is converted to a polygon with 4 vertices.
If W is a binary mask, then each pixel in the mask is replaced by a small square or rectangle,
and the union of these squares or rectangles is computed. The result is a polygonal window
that has only horizontal and vertical edges. (Use [Link] to remove the staircase
appearance, if desired).

Value
A polygonal window (object of class "owin" and of type "polygonal").
[Link] 61

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link], [Link], [Link]

Examples
data(letterR)
m <- [Link](letterR, dimyx=32)
p <- [Link](m)
if(interactive()) {
plot(m)
plot(p, add=TRUE, lwd=2)
}

[Link] Convert Data To Class ppp

Description
Tries to coerce any reasonable kind of data to a point pattern (an object of class "ppp")
for use by the spatstat package).

Usage

[Link](X, ..., fatal=TRUE)


\bsl{}method\{[Link]\}\{ppp\}(X, ..., fatal=TRUE)
\bsl{}method\{[Link]\}\{quad\}(X, ..., fatal=TRUE)
\bsl{}method\{[Link]\}\{matrix\}(X, W=NULL, ..., fatal=TRUE)
\bsl{}method\{[Link]\}\{[Link]\}(X, W=NULL, ..., fatal=TRUE)
\bsl{}method\{[Link]\}\{default\}(X, W=NULL, ..., fatal=TRUE)

Usage
[Link](X, ..., fatal=TRUE)
[Link](X, W, ..., fatal=TRUE)

Arguments
X Data which will be converted into a point pattern
W Data which define a window for the pattern when X does not contain a
window
... Ignored.
fatal Logical value. See Details.
62 [Link]

Details
Converts the dataset X to a point pattern (an object of class "ppp"; see [Link] for an
overview).
This function is normally used to convert an existing point pattern dataset, stored in another
format, to the "ppp" format. To create a new point pattern from raw data such as x, y
coordinates, it is normally easier to use the creator function ppp.
The dataset X may be:
ˆ an object of class "ppp"
ˆ an object of class "spp" as defined in the spatial library
ˆ an object of class "quad" representing a quadrature scheme (see [Link])
ˆ a two-column or three-column matrix or data frame
ˆ a structure with entries x, y which are numeric vectors of equal length
ˆ a numeric vector of length 2, interpreted as the coordinates of a single point.
In the last three cases, we need the second argument W which is converted to a window
object by the function [Link]. In the first three cases, W will be ignored.
If X is a three-column matrix or data frame, the third column will be interpreted as con-
taining marks, and the result will be a marked point pattern.
The argument fatal indicates what to do when W is missing and X contains no information
about the window. If fatal=TRUE, a fatal error will be generated; if fatal=FALSE, the
value NULL is returned.
An spp object is the representation of a point pattern in the spatial library. Our imple-
mentation recognises the following formats:
ˆ a structure with entries x, y xl, xu, yl, yu
ˆ a structure with entries x, y and area, where area is a structure with entries xl, xu,
yl, yu
(used in spatial versions 1 to 6 and version 7.1 respectively) where x and y are vectors
of equal length giving the point coordinates, and xl, xu, yl, yu are numbers giving the
dimensions of a rectangular window.
The function [Link] is generic, with methods for the classes "ppp", "quad", "matrix" and
a default method.
Point pattern datasets can also be created by the function ppp.

Value
An object of class "ppp" (see [Link]) describing the point pattern and its window of
observation. The value NULL may also be returned; see Details.

Warnings
If the format of spp objects is changed in future versions of the spatial library, then
[Link] may not be able to interpret them. It currently handles all versions of spatial up
to 7.1-4.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
[Link] 63

See Also

ppp, [Link], [Link], [Link]

Examples
## Not run:
plot(c(0,1),c(0,1),type="n")
xy <- locator(20) # click on 20 points in plot window
pp <- [Link](xy, c(0,1,0,1))

w <- owin(c(0,1),c(0,1))
plot(w) # neater
xy <- locator(20) # click on 20 points in plot window
pp <- [Link](xy, w)

## End(Not run)

xy <- matrix(runif(40), ncol=2)


pp <- [Link](xy, c(0,1,0,1))

# Venables-Ripley format
require(spatial)
towns <- ppinit("[Link]")
pp <- [Link](towns) # converted to our format
detach(package:spatial)

[Link] Convert Data To Class psp

Description

Tries to coerce any reasonable kind of data to a line segment pattern (an object of class
"psp") for use by the spatstat package.

Usage

[Link](x, ..., from=NULL, to=NULL)


## S3 method for class 'psp':
[Link](x, ..., check=[Link]("checksegments"), fatal=TRUE)
## S3 method for class '[Link]':
[Link](x, ..., window=NULL, marks=NULL, check=[Link]("checksegments"), fatal=TRUE)
## S3 method for class 'matrix':
[Link](x, ..., window=NULL, marks=NULL, check=[Link]("checksegments"),
fatal=TRUE)
## S3 method for class 'owin':
[Link](x, ..., check=[Link]("checksegments"), fatal=TRUE)
## Default S3 method:
[Link](x, ..., window=NULL, marks=NULL,
check=[Link]("checksegments"), fatal=TRUE)
64 [Link]

Arguments
x Data which will be converted into a line segment pattern
window Data which define a window for the pattern when x does not contain a
window
... Ignored.
marks (Optional) vector of marks for the pattern
check Logical value indicating whether to check the validity of the data, e.g. to
check that the line segments lie inside the window.
fatal Logical value. See Details.
from,to Point patterns (object of class "ppp") containing the first and second
endpoints (respectively) of each segment. Incompatible with x.

Details
Converts the dataset x to a line segment pattern (an object of class "psp"; see [Link]
for an overview).
This function is normally used to convert an existing line segment pattern dataset, stored
in another format, to the "psp" format. To create a new point pattern from raw data such
as x, y coordinates, it is normally easier to use the creator function psp.
The dataset x may be:

ˆ an object of class "psp"


ˆ a data frame with columns named x0, y0, x1, y1 that will be interpreted as the
coordinates of the endpoints of the segments.
ˆ a data frame or matrix with exactly 4 columns that will be interpreted as the coordi-
nates x0, y0, x1, y1 of the endpoints of the segments
ˆ a data frame with columns named xmid, ymid, length, angle that will be inter-
preted as the coordinates of the segment midpoints, the lengths of the segments, and
the orientations of the segments in radians
ˆ a structure with elements named x0, y0, x1, y1 or elements named xmid, ymid,
length, angle which will be interpreted as above.
ˆ an object of class "owin" representing a spatial window; it must be of type "rectangle"
or "polygonal". The boundary edges of the window will be extracted as a line segment
pattern.

If the argument marks is missing or NULL, then x may also be:

ˆ a data frame with columns named x0, y0, x1, y1, marks
ˆ a data frame or matrix with exactly 5 columns; the first 4 columns will be interpreted
as the coordinates x0, y0, x1, y1 of the endpoints of the segments, and the last
column will be interpreted as the marks.
ˆ a structure with elements named x0, y0, x1, y1, marks which will be interpreted
as above.

Alternatively, you may specify two point patterns from and to containing the first and
second endpoints of the line segments.
The argument window is converted to a window object by the function [Link].
[Link] 65

The argument fatal indicates what to do when the data cannot be converted to a line
segment pattern. If fatal=TRUE, a fatal error will be generated; if fatal=FALSE, the value
NULL is returned.
The function [Link] is generic, with methods for the classes "psp", "[Link]", "matrix"
and a default method.
Point pattern datasets can also be created by the function psp.

Value
An object of class "psp" (see [Link]) describing the line segment pattern and its
window of observation. The value NULL may also be returned; see Details.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
psp, [Link], [Link], [Link]

Examples
mat <- matrix(runif(40), ncol=4)
a <- [Link](mat, window=owin())
stuff <- list(xmid=runif(10),
ymid=runif(10),
length=rep(0.1, 10),
angle=runif(10, 0, 2 * pi))
a <- [Link](stuff, window=owin())
b <- [Link](from=runifpoint(10), to=runifpoint(10))

[Link] Window Frame

Description
Extract the window frame of a window or other spatial dataset

Usage
[Link](w, ...)

Arguments
w A window, or a dataset that has a window. Either a window (object of
class "owin"), a pixel image (object of class "im") or other data deter-
mining such a window.
... Optional. Auxiliary data to help determine the window. If w does not
belong to a recognised class, the arguments w and ... are passed to
[Link] to determine the window.
66 [Link]

Details
This function is the quickest way to determine a bounding rectangle for a spatial dataset.
If w is a window, the function just extracts the outer bounding rectangle of w as given by
its elements xrange,yrange.
The function can also be applied to any spatial dataset that has a window: for example, a
point pattern (object of class "ppp") or a line segment pattern (object of class "psp"). The
bounding rectangle of the window of the dataset is extracted.
Use the function [Link] to compute the smallest bounding rectangle of a dataset.

Value
A window (object of class "owin") of type "rectangle" representing a rectangle.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link], [Link]

Examples
w <- owin(c(0,10),c(0,10), poly=list(x=c(1,2,3,2,1), y=c(2,3,4,6,7)))
r <- [Link](w)
# returns a 10 x 10 rectangle

data(lansing)
[Link](lansing)

data(copper)
[Link](copper$SouthLines)

[Link] Convert Data To Tessellation

Description
Converts data specifying a tessellation, in any of several formats, into an object of class
"tess".

Usage
[Link](X)
## S3 method for class 'tess':
[Link](X)
## S3 method for class 'im':
[Link](X)
## S3 method for class 'owin':
[Link](X)
## S3 method for class 'quadratcount':
[Link] 67

[Link](X)
## S3 method for class 'quadrattest':
[Link](X)
## S3 method for class 'list':
[Link](X)

Arguments
X Data to be converted to a tessellation.

Details
A tessellation is a collection of disjoint spatial regions (called tiles) that fit together to form
a larger spatial region. This command creates an object of class "tess" that represents a
tessellation.
This function converts data in any of several formats into an object of class "tess" for use
by the spatstat package. The argument X may be
ˆ an object of class "tess". The object will be stripped of any extraneous attributes
and returned.
ˆ a pixel image (object of class "im") with pixel values that are logical or factor values.
Each level of the factor will determine a tile of the tessellation.
ˆ a window (object of class "owin"). The result will be a tessellation consisting of a
single tile.
ˆ a set of quadrat counts (object of class "quadratcount") returned by the command
quadratcount. The quadrats used to generate the counts will be extracted and re-
turned as a tessellation.
ˆ a quadrat test (object of class "quadrattest") returned by the command [Link].
The quadrats used to perform the test will be extracted and returned as a tessellation.
ˆ a list of windows (objects of class "owin") giving the tiles of the tessellation.

The function [Link] is generic, with methods for various classes, as listed above.

Value
An object of class "tess" specifying a tessellation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
tess

Examples
# pixel image
v <- [Link](function(x,y){factor(round(5 * (x^2 + y^2)))}, W=owin())
levels(v) <- letters[seq(length(levels(v)))]
[Link](v)
# quadrat counts
data(nztrees)
68 BadGey

qNZ <- quadratcount(nztrees, nx=4, ny=3)


[Link](qNZ)

BadGey Hybrid Geyer Point Process Model

Description
Creates an instance of the Baddeley-Geyer point process model, defined as a hybrid of
several Geyer interactions. The model can then be fitted to point pattern data.

Usage
BadGey(r, sat)

Arguments
r vector of interaction radii
sat vector of saturation parameters, or a single common value of saturation
parameter

Details
This is Baddeley’s generalisation of the Geyer saturation point process model, described in
Geyer, to a process with multiple interaction distances.
The BadGey point process with interaction radii r1 , . . . , rk , saturation thresholds s1 , . . . , sk ,
intensity parameter β and interaction parameters γ1 , . . . , gammak , is the point process in
which each point xi in the pattern X contributes a factor
v (xi ,X) v (xi ,X)
βγ1 1 . . . gammakk

to the probability density of the point pattern, where

vj (xi , X) = min(sj , tj (xi , X))

where tj (xi , X) denotes the number of points in the pattern X which lie within a distance
rj from the point xi .
BadGey is used to fit this model to data. The function ppm(), which fits point process
models to point pattern data, requires an argument of class "interact" describing the
interpoint interaction structure of the model to be fitted. The appropriate description of
the piecewise constant Saturated pairwise interaction is yielded by the function BadGey().
See the examples below.
The argument r specifies the vector of interaction distances. The entries of r must be
strictly increasing, positive numbers.
The argument sat specifies the vector of saturation parameters that are applied to the
point counts tj (xi , X). It should be a vector of the same length as r, and its entries should
be nonnegative numbers. Thus sat[1] is applied to the count of points within a distance
r[1], and sat[2] to the count of points within a distance r[2], etc. Alternatively sat may
be a single number, and this saturation value will be applied to every count.
Infinite values of the saturation parameters are also permitted; in this case vj (xi , X) =
tj (xi , X) and there is effectively no ‘saturation’ for the distance range in question. If all
[Link] 69

the saturation parameters are set to Inf then the model is effectively a pairwise interaction
process, equivalent to PairPiece (however the interaction parameters γ obtained from
BadGey have a complicated relationship to the interaction parameters γ obtained from
PairPiece).
If r is a single number, this model is virtually equivalent to the Geyer process, see Geyer.

Value
An object of class "interact" describing the interpoint interaction structure of a point
process.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]> in collaboration with Hao Wang and Jeff
Picka

See Also
ppm, [Link], Geyer, PairPiece, SatPiece

Examples
BadGey(c(0.1,0.2), c(1,1))
# prints a sensible description of itself
BadGey(c(0.1,0.2), 1)
data(cells)

# fit a stationary Baddeley-Geyer model


ppm(cells, ~1, BadGey(c(0.07, 0.1, 0.13), 2))

# nonstationary process with log-cubic polynomial trend


## Not run:
ppm(cells, ~polynom(x,y,3), BadGey(c(0.07, 0.1, 0.13), 2))

## End(Not run)

[Link] Distance to Boundary of Window

Description
Computes the distances from each pixel in a window to the boundary of the window.

Usage
[Link](w, ..., style="image")

Arguments
w A window (object of class "owin").
... Arguments passed to [Link] to determine the pixel resolution.
style Character string determining the format of the output: either "matrix",
"coords" or "image".
70 [Link]

Details
This function computes, for each pixel u in the window w, the shortest distance d(u, W c )
from u to the boundary of W .
If the window is not of type "mask" then it is first converted to that type. The arguments
"..." are passed to [Link] to determine the pixel resolution.

Value
If style="image", a pixel image (object of class "im") containing the distances from each
pixel in the image raster to the boundary of the window.
If style="matrix", a matrix giving the distances from each pixel in the image raster to the
boundary of the window. Rows of this matrix correspond to the y coordinate and columns
to the x coordinate.
If style="coords", a list with three components x,y,z, where x,y are vectors of length
m, n giving the x and y coordinates respectively, and z is an m × n matrix such that
z[i,j] is the distance from (x[i],y[j]) to the boundary of the window. Rows of this
matrix correspond to the x coordinate and columns to the y coordinate. This result can be
plotted with persp, image or contour.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], erosion, [Link], [Link].

Examples
u <- owin(c(0,1),c(0,1))
d <- [Link](u, eps=0.01)
image(d)
d <- [Link](u, eps=0.01, style="matrix")
mean(d >= 0.1)
# value is approx (1 - 2 * 0.1)^2 = 0.64

[Link] Distance to Boundary of Window

Description
Computes the distances from each point of a point pattern to the boundary of the window.

Usage
[Link](X)

Arguments
X A point pattern (object of class "ppp").
[Link] 71

Details
This function computes, for each point xi in the point pattern X, the shortest distance
d(xi , W c ) from xi to the boundary of the window W of observation.
If the window X$window is of type "rectangle" or "polygonal", then these distances are
computed by analytic geometry and are exact, up to rounding errors. If the window is
of type "mask" then the distances are computed using the real-valued distance transform,
which is an approximation with maximum error equal to the width of one pixel in the mask.

Value
A numeric vector, giving the distances from each point of the pattern to the boundary of
the window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link], erosion

Examples
data(cells)
d <- [Link](cells)

[Link] Distance to Boundary of Window

Description
Computes the shortest distances from each tile in a tessellation to the boundary of the
window.

Usage
[Link](X)

Arguments
X A tessellation (object of class "tess").

Details
This function computes, for each tile si in the tessellation X, the shortest distance from si
to the boundary of the window W containing the tessellation.

Value
A numeric vector, giving the shortest distance from each tile in the tessellation to the
boundary of the window. Entries of the vector correspond to the entries of tiles(X).
72 bei

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
tess, [Link], [Link]

Examples
P <- runifpoint(15)
X <- dirichlet(P)
plot(X, col="red")
B <- [Link](X)
# identify tiles that do not touch the boundary
plot(X[B > 0], add=TRUE, col="green", lwd=3)

bei Tropical rain forest trees

Description
A point pattern giving the locations of 3605 trees in a tropical rain forest. Accompanied
by covariate data giving the elevation (altitude) and slope of elevation in the study region.

Usage
data(bei)

Format
bei is an object of class "ppp" representing the point pattern of tree locations. See
[Link] for details of the format.
[Link] is a list containing two pixel images, elev (elevation in metres) and grad (norm
of elevation gradient). These pixel images are objects of class "im", see [Link].

Notes
The dataset bei gives the positions of 3605 trees of the species Beilschmiedia pendula
(Lauraceae) in a 1000 by 500 metre rectangular sampling region in the tropical rainforest
of Barro Colorado Island.
The accompanying dataset [Link] gives information about the altitude (elevation) in
the study region. It is a list containing two pixel images, elev (elevation in metres) and
grad (norm of elevation gradient).
These data are part of a much larger dataset containing the positions of hundreds of thou-
sands of trees belong to thousands of species; see Hubbell and Foster (1983), Condit, Hubbell
and Foster (1996) and Condit (1998).
The present data were analysed by Moller and Waagepetersen (2006).
bermantest 73

Source
Hubbell and Foster (1983), Condit, Hubbell and Foster (1996) and Condit (1998). Data
files kindly supplied by Rasmus Waagepetersen. The data were collected in the forest
dynamics plot of Barro Colorado Island. The study was made possible through the generous
support of the U.S. National Science Foundation, the John D. and Catherine T. MacArthur
Foundation, and the Smithsonian Tropical Research Institute.

References
Condit, R. (1998) Tropical Forest Census Plots. Springer-Verlag, Berlin and R.G. Landes
Company, Georgetown, Texas.
Condit, R., Hubbell, S.P and Foster, R.B. (1996) Changes in tree species abundance in a
neotropical forest: impact of climate change. Journal of Tropical Ecology 12, 231–256.
Hubbell, S.P and Foster, R.B. (1983) Diversity of canopy trees in a neotropical forest and
implications for conservation. In: Tropical Rain Forest: Ecology and Management (eds.
S.L. Sutton, T.C. Whitmore and A.C. Chadwick), Blackwell Scientific Publications, Oxford,
25–41.
Moller, J. and Waagepetersen, R.P. (2006) Modern statistics for spatial point processes. Re-
search report R-2006-12, Department of Mathematical Sciences, Aalborg University, Den-
mark. ISSN 1601-7811. URL <[Link]>

bermantest Berman’s Tests for Point Process Model

Description
Tests the goodness-of-fit of a Poisson point process model using methods of Berman (1986).

Usage
bermantest(...)
## S3 method for class 'ppp':
bermantest(X, covariate,
which = c("Z1", "Z2"),
alternative = c("[Link]", "less", "greater"), ...)
## S3 method for class 'ppm':
bermantest(model, covariate,
which = c("Z1", "Z2"),
alternative = c("[Link]", "less", "greater"), ...)

Arguments
X A point pattern (object of class "ppp").
model A fitted point process model (object of class "ppm").
covariate The spatial covariate on which the test will be based. An image (object
of class "im") or a function.
which Character string specifying the choice of test.
alternative Character string specifying the alternative hypothesis.
... Ignored.
74 bermantest

Details
These functions perform a goodness-of-fit test of a Poisson point process model fitted to
point pattern data. The observed distribution of the values of a spatial covariate at the data
points, and the predicted distribution of the same values under the model, are compared
using either of two test statistics Z1 and Z2 proposed by Berman (1986).
The function bermantest is generic, with methods for point patterns ("ppp") and point
process models ("ppm").

ˆ If X is a point pattern dataset (object of class "ppp"), then bermantest(X, ...)


performs a goodness-of-fit test of the uniform Poisson point process (Complete Spatial
Randomness, CSR) for this dataset.
ˆ If model is a fitted point process model (object of class "ppm") then bermantest(model,
...) performs a test of goodness-of-fit for this fitted model. In this case, model should
be a Poisson point process.

The test is performed by comparing the observed distribution of the values of a spatial
covariate at the data points, and the predicted distribution of the same covariate under the
model. Thus, you must nominate a spatial covariate for this test.
The argument covariate should be either a function(x,y) or a pixel image (object of
class "im" containing the values of a spatial function. If covariate is an image, it should
have numeric values, and its domain should cover the observation window of the model.
If covariate is a function, it should expect two arguments x and y which are vectors of
coordinates, and it should return a numeric vector of the same length as x and y.
First the original data point pattern is extracted from model. The values of the covariate
at these data points are collected.
Next the values of the covariate at all locations in the observation window are evaluated.
The point process intensity of the fitted model is also evaluated at all locations in the
window.

ˆ If which="Z1", the test statistic Z1 is computed as follows. The sum S of the covariate
values at all data points is evaluated. The predicted mean µ and variance σ 2 of S are
computed from the values of the covariate at all locations in the window. Then we
compute Z1 = (S − µ)/σ.
ˆ If which="Z2", the test statistic Z2 is computed as follows. The values of the covariate
at all locations in the observation window, weighted by the point process intensity, are
compiled into a cumulative distribution function F . The probability integral transfor-
mation is then applied: the values of the covariate at the original data points are
transformed by the predicted cumulative distribution function F into numbers between
0 and 1. If the model is correct, these numbers are i.i.d. uniform random numbers.
The standardised sample mean of these numbers is the statistic Z2 .

In both cases the null distribution of the test statistic is the standard normal distribution,
approximately.
The return value is an object of class "htest" containing the results of the hypothesis test.
The print method for this class gives an informative summary of the test outcome.

Value
An object of class "htest" (hypothesis test) and also of class "bermantest", containing
the results of the test. The return value can be plotted (by [Link]) or printed
to give an informative summary of the test.
betacells 75

Warning
The meaning of a one-sided test must be carefully scrutinised: see the printed output.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Berman, M. (1986) Testing for spatial association between a point process and another
stochastic process. Applied Statistics 35, 54–62.

See Also
kstest, [Link], ppm

Examples
# Berman's data
data(copper)
X <- copper$SouthPoints
L <- copper$SouthLines
D <- distmap(L, eps=1)
# test of CSR
bermantest(X, D)
bermantest(X, D, "Z2")

betacells Beta Ganglion Cells in Cat Retina

Description
Point pattern of cells in the retina, each cell classified as ‘on’ or ‘off’. A bivariate point
pattern.

Usage
data(betacells)

Format
betacells is an object of class "ppp" representing the point pattern of cell locations.
Entries include

x Cartesian x-coordinate of cell


y Cartesian y-coordinate of cell
marks factor with levels off and on
indicating “off” and “on” cells

See [Link] for details of the format. Cartesian coordinates are given in microns.
[Link] is a list with one component area which is the vector of areas (in square
76 betacells

microns) of the cells in the pattern.

Notes
This is a new, corrected version of the old dataset ganglia. See below.
These data represent a pattern of beta-type ganglion cells in the retina of a cat recorded
by W\”assle et al. (1981). Beta cells are associated with the resolution of fine detail in the
cat’s visual system. They can be classified anatomically as “on” or “off”.
Statistical independence of the arrangement of the “on”- and“off”-components would strengthen
the evidence for Hering’s (1878) ‘opponent theory’ that there are two separate channels for
sensing “brightness” and “darkness”. See W\”assle et al (1981). There is considerable cur-
rent interest in the arrangement of cell mosaics in the retina, see Rockhill et al (2000).
The dataset is a multitype point pattern giving the locations and types (“on” or “off”) of
beta cells observed in a rectangle of dimensions 750 × 990 microns. Coordinates are given
in microns (thousandths of a millimetre).
The original source is Figure 6 of W\”assle et al (1981), which is a manual drawing of the
beta mosaic observed in a microscope field-of-view of a whole mount of the retina. Thus,
all beta cells in the retina were effectively projected onto the same two-dimensional plane.
The data were scanned in 2004 by Stephen Eglen from Figure 6(a) of W\”assle et al (1981).
Image analysis software was used to identify the soma (cell body). The x, y location of
each cell was taken to be the centroid of the soma. The type of each cell (“on” or ‘off”) was
identified by referring to Figures 6(b) and 6(d).
The area of each soma (in square microns) was also computed, and is provided in the dataset
[Link].
Note that this is a corrected version of the ganglia dataset provided in earlier versions of
spatstat. The earlier data ganglia were not faithful to the scale in the original paper and
contain some scanning errors.

Source
W\”assle et al (1981), Figure 6(a), scanned and processed by Stephen Eglen <[Link]@[Link]>

References
Hering, E. (1878) Zur Lehre von Lichtsinn. Vienna.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.
Rockhill, R.L., Euler, T. and Masland, R.H. (2000) Spatial order within but not between
types of retinal neurons. Proc. Nat. Acad. Sci. USA 97(5), 2303–2307.
W\”assle, H., Boycott, B. B. & Illing, R.-B. (1981). Morphology and mosaic of on- and
off-beta cells in the cat retina and some functional considerations. Proc. Roy. Soc. London
Ser. B 212, 177–195.

Examples
data(betacells)
plot(betacells)
plot(betacells$window, main="beta cells")
symbols(betacells$x, betacells$y,
circles=sqrt([Link]$area/pi),
inches=FALSE, add=TRUE)
blur 77

blur Apply Gaussian Blur to a Pixel Image

Description
Applies a Gaussian blur to a pixel image.

Usage
blur(x, sigma = NULL, ..., normalise=FALSE, bleed = TRUE, varcov=NULL)

Arguments
x The pixel image. An object of class "im".
sigma Standard deviation of isotropic Gaussian smoothing kernel.
... Ignored.
normalise Logical flag indicating whether the output values should be divided by
the corresponding blurred image of the window itself. See Details.
bleed Logical flag indicating whether to allow blur to extend outside the original
domain of the image. See Details.
varcov Variance-covariance matrix of anisotropic Gaussian kernel. Incompatible
with sigma.

Details
This command applies a Gaussian blur to the pixel image x.
The blurring kernel is the isotropic Gaussian kernel with standard deviation sigma, or
the anisotropic Gaussian kernel with variance-covariance matrix varcov. The arguments
sigma and varcov are incompatible. Also sigma may be a vector of length 2 giving the
standard deviations of two independent Gaussian coordinates, thus equivalent to varcov =
diag(sigma^2).
If the pixel values of x include some NA values (meaning that the image domain does not
completely fill the rectangular frame) then these NA values are first reset to zero.
The algorithm then computes the convolution x ∗ G of the (zero-padded) pixel image x with
the specified Gaussian kernel G.
If normalise=FALSE, then this convolution x ∗ G is returned. If normalise=TRUE, then the
convolution x ∗ G is normalised by dividing it by the convolution w ∗ G of the image domain
w with the same Gaussian kernel. Normalisation ensures that the result can be interpreted
as a weighted average of input pixel values, without edge effects due to the shape of the
domain.
If bleed=FALSE, then pixel values outside the original image domain are set to NA. Thus the
output is a pixel image with the same domain as the input. If bleed=TRUE, then no such
alteration is performed, and the result is a pixel image defined everywhere in the rectangular
frame containing the input image.
Computation is performed using the Fast Fourier Transform.

Value
A pixel image with the same pixel array as the input image x.
78 border

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link] for interpolating a pixel image to a finer resolution, [Link] for blurring a
point pattern, [Link] for interpolating marks attached to points.

Examples
data(letterR)
Z <- [Link](function(x,y) { 4 * x^2 + 3 * y }, letterR)
par(mfrow=c(1,3))
plot(Z)
plot(letterR, add=TRUE)
plot(blur(Z, 0.3, bleed=TRUE))
plot(letterR, add=TRUE)
plot(blur(Z, 0.3, bleed=FALSE))
plot(letterR, add=TRUE)
par(mfrow=c(1,1))

border Border Region of a Window

Description
Computes the border region of a window, that is, the region lying within a specified distance
of the boundary of a window.

Usage
border(w, r, outside=FALSE, ...)

Arguments
w A window (object of class "owin") or something acceptable to [Link].
r Numerical value.
outside Logical value determining whether to compute the border outside or inside
w.
... Optional arguments passed to erosion (if outside=FALSE) or to dilation
(if outside=TRUE).

Details
By default (if outside=FALSE), the border region is the subset of w lying within a distance
r of the boundary of w. It is computed by eroding w by the distance r (using erosion) and
subtracting this eroded window from the original window w.
If outside=TRUE, the border region is the set of locations outside w lying within a distance
r of w. It is computed by dilating w by the distance r (using dilation) and subtracting
the original window w from the dilated window.
[Link] 79

Value
A window (object of class "owin").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
erosion, dilation

Examples
# rectangle
u <- [Link]()
border(u, 0.1)
border(u, 0.1, outside=TRUE)
# polygon
data(letterR)
plot(letterR)
plot(border(letterR, 0.1), add=TRUE)
plot(border(letterR, 0.1, outside=TRUE), add=TRUE)

[Link] Bounding Box of a Window or Point Pattern

Description
Find the smallest rectangle containing a given window(s) or point pattern(s).

Usage
[Link](...)

Arguments
... One or more windows (objects of class "owin"), pixel images (objects of
class "im") or point patterns (objects of class "ppp").

Details
This function finds the smallest rectangle (with sides parallel to the coordinate axes) that
contains all the given objects.
For a window (object of class "owin"), the bounding box is the smallest rectangle that
contains all the vertices of the window (this is generally smaller than the enclosing frame,
which is returned by [Link]).
For a point pattern (object of class "ppp"), the bounding box is the smallest rectangle that
contains all the points of the pattern, and is computed by [Link].
For a pixel image (object of class "im"), the image will be converted to a window using
[Link], and the bounding box of this window is obtained.
If the argument is a list of several objects, then this function finds the smallest rectangle
that contains all the bounding boxes of the objects.
80 [Link]

Value
A window (object of class "owin") of type "rectangle" representing a rectangle.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link], [Link] [Link]

Examples
w <- owin(c(0,10),c(0,10), poly=list(x=c(1,2,3,2,1), y=c(2,3,4,6,7)))
r <- [Link](w)
# returns rectangle [1,3] x [2,7]

w2 <- [Link]()
r <- [Link](w, w2)
# returns rectangle [0,3] x [0,7]

[Link] Convex Hull of Points

Description
Computes the smallest rectangle containing a set of points.

Usage
[Link](x, y=NULL)

Arguments
x vector of x coordinates of observed points, or a 2-column matrix giving
x,y coordinates, or a list with components x,y giving coordinates (such
as a point pattern object of class "ppp".)
y (optional) vector of y coordinates of observed points, if x is a vector.

Details
Given an observed pattern of points with coordinates given by x and y, this function finds
the smallest rectangle, with sides parallel to the coordinate axes, that contains all the points,
and returns it as a window.

Value
A window (an object of class "owin").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
box3 81

See Also
owin, [Link], [Link], ripras

Examples
x <- runif(30)
y <- runif(30)
w <- [Link](x,y)
plot(owin(), main="[Link](x,y)")
plot(w, add=TRUE)
points(x,y)

X <- rpoispp(30)
plot(X, main="[Link](X)")
plot([Link](X), add=TRUE)

box3 Three-Dimensional Box

Description
Creates an object representing a three-dimensional box.

Usage
box3(xrange = c(0, 1), yrange = xrange, zrange = yrange, unitname = NULL)

Arguments
xrange, yrange, zrange
Dimensions of the box in the x, y, z directions. Each of these arguments
should be a numeric vector of length 2.
unitname Optional. Name of the unit of length. See Details.

Details
This function creates an object representing a three-dimensional rectangular parallelepiped
(box) with sides parallel to the coordinate axes.
The object can be used to specify the domain of a three-dimensional point pattern (see pp3)
and in various geometrical calculations (see volume.box3, diameter.box3, [Link]).
The optional argument unitname specifies the name of the unit of length. See unitname
for valid formats.
The function as.box3 can be used to convert other kinds of data to this format.

Value
An object of class "box3". There is a print method for this class.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
82 bramblecanes

See Also
as.box3, pp3, volume.box3, diameter.box3, [Link].

Examples
box3()
box3(c(0,10),c(0,10),c(0,5), unitname=c("metre","metres"))
box3(c(-1,1))

bramblecanes Hutchings’ Bramble Canes data

Description
Data giving the locations and ages of bramble canes in a field. A marked point pattern.

Usage
data(bramblecanes)

Format
An object of class "ppp" representing the point pattern of plant locations. Entries include

x Cartesian x-coordinate of plant


y Cartesian y-coordinate of plant
marks factor with levels 0,1, 2 indicating age

See [Link] for details of the format.

Notes
These data record the (x, y) locations and ages of bramble canes in a field 9 metres square,
rescaled to the unit square. The canes were classified according to age as either newly
emergent, one or two years old. These are encoded as marks 0, 1 and 2 respectively in the
dataset.
The data were recorded and analysed by Hutchings (1979) and further analysed by Diggle
(1981a, 1981b, 1983), Diggle and Milne (1983), and Van Lieshout and Baddeley (1999).
All analyses found that the pattern of newly emergent canes exhibits clustering, which
Hutchings attributes to “vigorous vegetative reproduction”.

Source
Hutchings (1979), data published in Diggle (1983)

References
Diggle, P. J. (1981a) Some graphical methods in the analysis of spatial point patterns. In
Interpreting multivariate data, V. Barnett (Ed.) John Wiley and Sons.
Diggle, P. J. (1981b). Statistical analysis of spatial point patterns. N.Z. Statist. 16, 22–41.
Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.
bronzefilter 83

Diggle, P. J. and Milne, R. K. (1983) Bivariate Cox processes: some models for bivariate
spatial point patterns. Journal of the Royal Statistical Soc. Series B 45, 11–21.
Hutchings, M. J. (1979) Standing crop and pattern in pure stands of Mercurialis perennis
and Rubus fruticosus in mixed deciduous woodland. Oikos 31, 351–357.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

bronzefilter Bronze gradient filter data

Description
These data represent a spatially inhomogeneous pattern of circular section profiles of par-
ticles, observed in a longitudinal plane section through a gradient sinter filter made from
bronze powder, prepared by Ricardo Bernhardt, Dresden.
The material was produced by sedimentation of bronze powder with varying grain diameter
and subsequent sintering, as described in Bernhardt et al. (1997).
The data are supplied as a marked point pattern of circle centres marked by circle radii.
The coordinates of the centres and the radii are recorded in mm. The field of view is an
18 × 7 mm rectangle.
The data were first analysed by Hahn et al. (1999).

Usage
data(bronzefilter)

Format
An object of class "ppp" representing the point pattern of cell locations. Entries include

x Cartesian x-coordinate of bronze grain profile centre


y Cartesian y-coordinate of bronze grain profile centre
marks radius of bronze grain profile

See [Link] for details of the format. All coordinates are recorded in mm.

Source
R.\ Bernhardt (section image), H.\ Wendrock (coordinate measurement). Adjusted, for-
matted and communicated by U.\ Hahn.

References
Bernhardt, R., Meyer-Olbersleben, F. and Kieback, B. (1997) Fundamental investigation
on the preparation of gradient structures by sedimentation of different powder fractions
under gravity. Proc. of the 4th Int. Conf. On Composite Engineering, July 6–12 1997,
ICCE/4, Hawaii, Ed. David Hui, 147–148.
Hahn U., Micheletti, A., Pohlink, R., Stoyan D. and Wendrock, H.(1999) Stereological
analysis and modelling of gradient structures. Journal of Microscopy, 195, 113–124.
84 [Link]

Examples
data(bronzefilter)
plot(bronzefilter, markscale=1)

[Link] Apply Function to Image Broken Down by Factor

Description
Splits a pixel image into sub-images and applies a function to each sub-image.

Usage
## S3 method for class 'im':
by(data, INDICES, FUN, ...)

Arguments
data A pixel image (object of class "im").
INDICES Grouping variable. Either a tessellation (object of class "tess") or a
factor-valued pixel image.
FUN Function to be applied to each sub-image of data.
... Extra arguments passed to FUN.

Details
This is a method for the generic function by for pixel images (class "im").
The pixel image data is first divided into sub-images according to INDICES. Then the
function FUN is applied to each subset. The results of each computation are returned in a
list.
The grouping variable INDICES may be either

ˆ a tessellation (object of class "tess"). Each tile of the tessellation delineates a subset
of the spatial domain.
ˆ a pixel image (object of class "im") with factor values. The levels of the factor deter-
mine subsets of the spatial domain.

Value
A list containing the results of each evaluation of FUN.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], tess, im
[Link] 85

Examples
W <- square(1)
X <- [Link](function(x,y){sqrt(x^2+y^2)}, W)
Y <- dirichlet(runifpoint(12, W))
# mean pixel value in each subset
unlist(by(X, Y, mean))
# trimmed mean
unlist(by(X, Y, mean, trim=0.05))

[Link] Apply a Function to a Point Pattern Broken Down by Factor

Description
Splits a point pattern into sub-patterns, and applies the function to each sub-pattern.

Usage
## S3 method for class 'ppp':
by(data, INDICES=marks(data), FUN, ...)

Arguments
data Point pattern (object of class "ppp").
INDICES Grouping variable. Either a factor, a pixel image with factor values, or a
tessellation.
FUN Function to be applied to subsets of data.
... Additional arguments to FUN.

Details
This is a method for the generic function by for point patterns (class "ppp").
The point pattern data is first divided into subsets according to INDICES. Then the function
FUN is applied to each subset. The results of each computation are returned in a list.
The argument INDICES may be

ˆ a factor, of length equal to the number of points in data. The levels of INDICES
determine the destination of each point in data. The ith point of data will be placed
in the sub-pattern [Link](data)$l where l = f[i].
ˆ a pixel image (object of class "im") with factor values. The pixel value of INDICES at
each point of data will be used as the classifying variable.
ˆ a tessellation (object of class "tess"). Each point of data will be classified according
to the tile of the tessellation into which it falls.

If INDICES is missing, then data must be a multitype point pattern (a marked point pattern
whose marks vector is a factor). Then the effect is that the points of each type are separated
into different point patterns.
86 cells

Value
A list (also of class "listof") containing the results returned from FUN for each of the
subpatterns.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppp, [Link], [Link], tess, im.

Examples
# multitype point pattern, broken down by type
data(amacrine)
by(amacrine, FUN=density)
by(amacrine, FUN=function(x) { min(nndist(x)) } )

# how to pass additional arguments to FUN


by(amacrine, FUN=clarkevans, correction=c("Donnelly","cdf"))

# point pattern broken down by tessellation


data(swedishpines)
tes <- quadrats(swedishpines, 5, 5)
B <- by(swedishpines, tes, clarkevans, correction="Donnelly")
unlist(lapply(B, [Link]))

cells Biological Cells Point Pattern

Description
The data record the locations of the centres of 42 biological cells observed under optical
microscopy in a histological section. The microscope field-of-view has been rescaled to the
unit square.
The data were recorded by F.H.C. Crick and B.D. Ripley, and analysed in Ripley (1977,
1981) and Diggle (1983). They are often used as a canonical example of an ‘ordered’ point
pattern.

Usage
data(cells)

Format
An object of class "ppp" representing the point pattern of cell centres. See [Link] for
details of the format.

Source
Crick and Ripley, see Ripley (1977)
[Link] 87

References

Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.
Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal
Statistical Society, Series B 39, 172–212.
Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.

[Link] Centroid of a window

Description

Computes the centroid (centre of mass) of a window

Usage

[Link](w)

Arguments

w A window

Details

The centroid of the window w is computed. The centroid (“centre of mass”) is the point
whose x and y coordinates are the mean values of the x and y coordinates of all points in
the window.
The argument w should be a window (an object of class "owin", see [Link] for details)
or can be given in any format acceptable to [Link]().
The calculation uses an exact analytic formula for the case of polygonal windows.
Note that the centroid of a window is not necessarily inside the window. If the window is
convex then it does contain its centroid.

Value

A list with components x, y giving the coordinates of the centroid of the window w.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

owin, [Link]
88 [Link]

Examples
w <- owin(c(0,1),c(0,1))
[Link](w)
# returns 0.5, 0.5

data(demopat)
w <- demopat$window
# an irregular window
## Not run:
plot(w)
# plot the window
points([Link](w))
# mark its centroid

## End(Not run)

wapprox <- [Link](w)


# pixel approximation of window
## Not run:
points([Link](wapprox))
# should be indistinguishable

## End(Not run)

[Link] Subdivide a Window or Tessellation using a Set of Lines

Description
Divide a given window into tiles delineated by a set of infinite straight lines, obtaining
a tessellation of the window. Alternatively, given a tessellation, divide each tile of the
tessellation into sub-tiles delineated by the lines.

Usage
[Link](X, L)

Arguments
X A window (object of class "owin") or tessellation (object of class "tess")
to be subdivided by lines.
L A set of infinite straight lines (object of class "infline")

Details
The argument L should be a set of infinite straight lines in the plane (stored in an object L
of class "infline" created by the function infline).
If X is a window, then it is divided into tiles delineated by the lines in L.
If X is a tessellation, then each tile of X is subdivided into sub-tiles delineated by the lines
in L.
The result is a tessellation.
chorley 89

Value
A tessellation (object of class "tess").

Warning
If X is a non-convex window, or a tessellation containing non-convex tiles, then [Link](X,L)
may contain a tile which consists of several unconnected pieces.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
infline, [Link]

Examples
L <- infline(p=1:3, theta=pi/4)
W <- square(4)
[Link](W, L)

chorley Chorley-Ribble Cancer Data

Description
Spatial locations of cases of cancer of the larynx and cancer of the lung, and the location
of a disused industrial incinerator. A marked point pattern.

Usage
data(chorley)

Format
The dataset chorley is an object of class "ppp" representing a marked point pattern.
Entries include

x Cartesian x-coordinate of home address


y Cartesian y-coordinate of home address
marks factor with levels larynx and lung
indicating whether this is a case of cancer of the larynx
or cancer of the lung.

See [Link] for details of the format.


The dataset [Link] is a list with two components. The first component plotit is
a function which will plot the data in a sensible fashion. The second component incin is a
list with entries x and y giving the location of the industrial incinerator.
Coordinates are given in kilometres, and the resolution is 100 metres (0.1 km)
90 clarkevans

Notes
The data give the precise domicile addresses of new cases of cancer of the larynx (58
cases) and cancer of the lung (978 cases), recorded in the Chorley and South Ribble Health
Authority of Lancashire (England) between 1974 and 1983. The supplementary data give
the location of a disused industrial incinerator.
The data were first presented and analysed by Diggle (1990). They have subsequently been
analysed by Diggle and Rowlingson (1994) and Baddeley et al. (2005).
The aim is to assess evidence for an increase in the incidence of cancer of the larynx in the
vicinity of the now-disused industrial incinerator. The lung cancer cases serve as a surrogate
for the spatially-varying density of the susceptible population.
The data are represented as a marked point pattern, with the points giving the spatial
location of each individual’s home address and the marks identifying whether each point is
a case of laryngeal cancer or lung cancer.
Coordinates are in kilometres, and the resolution is 100 metres (0.1 km).
The dataset chorley has a polygonal window with 132 edges which closely approximates
the boundary of the Chorley and South Ribble Health Authority.

Source
Coordinates of cases were provided by the Chorley and South Ribble Health Authority, and
were kindly supplied by Professor Peter Diggle. Region boundary was digitised by Adrian
Baddeley, 2005, from a photograph of an Ordnance Survey map.

References
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial
point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.
Diggle, P. (1990) A point process modelling approach to raised incidence of a rare phe-
nomenon in the vicinity of a prespecified point. Journal of the Royal Statistical Soc. Series
A 153, 349-362.
Diggle, P. and Rowlingson, B. (1994) A conditional approach to point process modelling of
elevated risk. Journal of the Royal Statistical Soc. Series A 157, 433-440.

Examples
data(chorley)
[Link]$plotit()

clarkevans Clark and Evans Aggregation Index

Description
Computes the Clark and Evans aggregation index R for a spatial point pattern.

Usage
clarkevans(X, correction=c("none", "Donnelly", "cdf"),
clipregion=NULL)
clarkevans 91

Arguments
X A spatial point pattern (object of class "ppp").
correction Character vector. The type of edge correction(s) to be applied.
clipregion Clipping region for the guard area correction. A window (object of class
"owin"). See Details.

Details
The Clark and Evans (1954) aggregation index R is a crude measure of clustering or ordering
of a point pattern. It is the ratio of the observed mean nearest neighbour distance in the
pattern to that expected for a Poisson point process of the same intensity. A value R > 1
suggests ordering, while R < 1 suggests clustering.
Without correction for edge effects, the value of R will be positively biased. Edge effects
arise because, for a point of X close to the edge of the window, the true nearest neighbour
may actually lie outside the window. Hence observed nearest neighbour distances tend to
be larger than the true nearest neighbour distances.
The argument correction specifies an edge correction or several edge corrections to be
applied. It is a character vector containing one or more of the options "none", "Donnelly",
"guard" and "cdf" (which are recognised by partial matching). These edge corrections are:

”none”: No edge correction is applied.


”Donnelly”: Edge correction of Donnelly (1978), available for rectangular windows only.
The theoretical expected value of mean nearest neighbour distance under a Poisson
process is adjusted for edge effects by the edge correction of Donnelly (1978). The
value of R is the ratio of the observed mean nearest neighbour distance to this adjusted
theoretical mean.
”guard”: Guard region or buffer area method. The observed mean nearest neighbour
distance for the point pattern X is re-defined by averaging only over those points of X
that fall inside the sub-window clipregion.
”cdf”: Cumulative Distribution Function method. The nearest neighbour distance distri-
bution function G(r) of the stationary point process is estimated by Gest using the
Kaplan-Meier type edge correction. Then the mean of the distribution is calculated
from the cdf.

If the argument clipregion is given, then the selected edge corrections will be assumed to
include correction="guard".

Value
A numeric value or numeric vector, with named components

naive R without edge correction


Donnelly R using Donnelly edge correction
guard R using guard region
cdf R using cdf method

(as selected by correction). The value of the Donnelly component will be NA if the window
of X is not a rectangle.
92 clickpoly

Author(s)
John Rudge <rudge@[Link]> with modifications by Adrian Baddeley <adrian@[Link]>
[Link]

References
Clark, P.J. and Evans, F.C. (1954) Distance to nearest neighbour as a measure of spatial
relationships in populations Ecology 35, 445–453.
Donnelly, K. (1978) Simulations to determine the variance and edge-effect of total nearest
neighbour distance. In Simulation methods in archaeology, Cambridge University Press, pp
91–95.

See Also
nndist, Gest

Examples
# Example of a clustered pattern
data(redwood)
clarkevans(redwood)

# Example of an ordered pattern


data(cells)
clarkevans(cells)

# Random pattern
X <- rpoispp(100)
clarkevans(X)

# How to specify a clipping region


clip1 <- owin(c(0.1,0.9),c(0.1,0.9))
clip2 <- erosion(cells$window, 0.1)
clarkevans(cells, clipregion=clip1)
clarkevans(cells, clipregion=clip2)

clickpoly Interactively Define a Polygon

Description
Allows the user to create a polygon by point-and-click in the display.

Usage
clickpoly(add=FALSE, nv=NULL, np=1, ...)

Arguments
add Logical value indicating whether to create a new plot (add=FALSE) or draw
over the existing plot (add=TRUE).
nv Number of vertices of the polygon (if this is predetermined).
np Number of polygons to create.
... Arguments passed to locator to control the interactive plot.
clickppp 93

Details
This function allows the user to create a polygonal window by interactively clicking on the
screen display.
The user is prompted to point the mouse at any desired locations for the polygon vertices,
and click the left mouse button to add each point. Interactive input stops after nv clicks
(if nv was given) or when the middle mouse button is pressed.
The return value is a window (object of class "owin") representing the polygon.
This function uses the R command locator to input the mouse clicks. It only works on
screen devices such as ‘X11’, ‘windows’ and ‘quartz’. Arguments that can be passed to
locator through ... include pch (plotting character), cex (character expansion factor)
and col (colour). See locator and par.
Multiple polygons can also be drawn, by specifying np > 1. The polygons must be disjoint.
The result is a single window object consisting of all the polygons.

Value
A window (object of class "owin") representing the polygon.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], clickppp, locator

clickppp Interactively Add Points

Description
Allows the user to create a point pattern by point-and-click in the display.

Usage
clickppp(n=NULL, win=square(1), types=NULL, ..., add=FALSE,
main=NULL, hook=NULL)

Arguments
n Number of points to be added (if this is predetermined).
win Window in which to create the point pattern. An object of class "owin".
types Vector of types, when creating a multitype point pattern.
... Optional extra arguments to be passed to locator to control the display.
add Logical value indicating whether to create a new plot (add=FALSE) or draw
over the existing plot (add=TRUE).
main Main heading for plot.
hook For internal use only. Do not use this argument.
94 [Link]

Details
This function allows the user to create a point pattern by interactively clicking on the screen
display.
First the window win is plotted on the current screen device. Then the user is prompted to
point the mouse at any desired locations and click the left mouse button to add each point.
Interactive input stops after n clicks (if n was given) or when the middle mouse button is
pressed.
The return value is a point pattern containing the locations of all the clicked points inside
the original window win, provided that all of the clicked locations were inside this window.
Otherwise, the window is expanded to a box large enough to contain all the points (as well
as containing the original window).
If the argument types is given, then a multitype point pattern will be created. The user
is prompted to input the locations of points of type type[i], for each successive index i.
(If the argument n was given, there will be n points of each type.) The return value is a
multitype point pattern.
This function uses the R command locator to input the mouse clicks. It only works on
screen devices such as ‘X11’, ‘windows’ and ‘quartz’. Arguments that can be passed to
locator through ... include pch (plotting character), cex (character expansion factor)
and col (colour). See locator and par.

Value
A point pattern (object of class "ppp").

Author(s)
Original by Dominic Schuhmacher. Adapted by Adrian Baddeley <adrian@[Link]>
[Link] and Rolf Turner <[Link]@[Link]>

See Also
[Link], locator, clickpoly

[Link] Intersect Infinite Straight Lines with a Window

Description
Take the intersection between a set of infinite straight lines and a window, yielding a set of
line segments.

Usage
[Link](L, win)

Arguments
L Object of class "infline" specifying a set of infinite straight lines in the
plane.
win Window (object of class "owin").
closing 95

Details
This function computes the intersection between a set of infinite straight lines in the plane
(stored in an object L of class "infline" created by the function infline) and a window
win. The result is a pattern of line segments.

Value
A line segment pattern (object of class "psp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
infline,psp.
To divide a window into pieces using infinite lines, use [Link].

Examples
L <- infline(p=1:3, theta=pi/4)
W <- square(4)
[Link](L, W)

closing Morphological Closing

Description
Perform morphological closing of a window, a line segment pattern or a point pattern.

Usage
closing(w, r, ...)
## S3 method for class 'owin':
closing(w, r, ..., polygonal=NULL)
## S3 method for class 'ppp':
closing(w, r, ..., polygonal=TRUE)
## S3 method for class 'psp':
closing(w, r, ..., polygonal=TRUE)

Arguments
w A window (object of class "owin" or a line segment pattern (object of
class "psp") or a point pattern (object of class "ppp").
r positive number: the radius of the closing.
... extra arguments passed to [Link] controlling the pixel resolution, if a
pixel approximation is used
polygonal Logical flag indicating whether to compute a polygonal approximation to
the erosion (polygonal=TRUE) or a pixel grid approximation (polygonal=FALSE).
96 [Link]

Details
The morphological closing (Serra, 1982) of a set W by a distance r > 0 is the set of all
points that cannot be separated from W by any circle of radius r. That is, a point x belongs
to the closing W ∗ if it is impossible to draw any circle of radius r that has x on the inside
and W on the outside. The closing W ∗ contains the original set W .
For a small radius r, the closing operation has the effect of smoothing out irregularities in
the boundary of W . For larger radii, the closing operation smooths out concave features in
the boundary. For very large radii, the closed set W ∗ becomes more and more convex.
The algorithm applies dilation followed by erosion.

Value
If r > 0, an object of class "owin" representing the closed region. If r=0, the result is
identical to w.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Serra, J. (1982) Image analysis and mathematical morphology. Academic Press.

See Also
opening for the opposite operation.
dilation, erosion for the basic operations.
owin, [Link] for information about windows.

Examples
data(letterR)
v <- closing(letterR, 0.25, dimyx=256)
plot(v, main="closing")
plot(letterR, add=TRUE)

[Link] Coefficients of Fitted Point Process Model

Description
Given a point process model fitted to a point pattern, extract the coefficients of the fitted
model. A method for coef.

Usage
## S3 method for class 'ppm':
coef(object, ...)
[Link] 97

Arguments
object The fitted point process model (an object of class "ppm")
... Ignored.

Details
This function is a method for the generic function coef.
The argument object must be a fitted point process model (object of class "ppm"). Such
objects are produced by the maximum pseudolikelihood fitting algorithm ppm).
This function extracts the vector of coefficients of the fitted model. This is the estimate of
the parameter vector θ such that the conditional intensity of the model is of the form

λ(u, x) = exp(θS(u, x))

where S(u, x) is a (vector-valued) statistic.


For example, if the model object is the uniform Poisson process, then coef(object) will
yield a single value (named "(Intercept)") which is the logarithm of the fitted intensity
of the Poisson process.
Use [Link] to print a more useful description of the fitted model.

Value
A vector containing the fitted coefficients.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], ppm

Examples
data(cells)

poi <- ppm(cells, ~1, Poisson())


coef(poi)
# This is the log of the fitted intensity of the Poisson process

stra <- ppm(cells, ~1, Strauss(r=0.07))


coef(stra)

# The two entries "(Intercept)" and "Interaction"


# are respectively log(beta) and log(gamma)
# in the usual notation for Strauss(beta, gamma, r)
98 colourmap

colourmap Colour Lookup Tables

Description
Create a colour map (colour lookup table).

Usage
colourmap(col, ..., breaks=NULL, inputs=NULL)

Arguments
col Character vector specifying colours
... Ignored.
inputs Values to which the colours are associated. A factor or vector of the same
length as col. Incompatible with breaks.
breaks Breakpoints for the colour map. A numeric vector of length equal to
length(col)+1.

Details
A colour map is a mechanism for associating colours with data. It can be regarded as a
function, mapping data to colours.
The command colourmap creates an object representing a colour map, which can then be
used to control the plot commands in the spatstat package. It can also be used to compute
the colour assigned to any data value.
The argument col specifies the colours to which data values will be mapped. It should be
a character vector whose entries can be interpreted as colours.
Exactly one of the arguments inputs and breaks must be specified by name.
If inputs is given, then it should be a vector or factor, of the same length as col. The
entries of inputs can be any atomic type (e.g. numeric, logical, character, complex) or
factor values. The resulting colour map associates the value inputs[i] with the colour
col[i].
If breaks is given, then it determines intervals of the real number line which are mapped
to each colour. It should be a numeric vector, of length at least 2, with entries that are in
increasing order. Infinite values are allowed. Any number in the range between breaks[i]
and breaks[i+1] will be mapped to the colour col[i].
The result is an object of class "colourmap". There are print and plot methods for this
class. Some plot commands in the spatstat package accept an object of this class as a
specification of the colour map.
The result is also a function f which can be used to compute the colour assigned to any
data value. That is, f(x) returns the character value of the colour assigned to x. This also
works for vectors of data values.

Value
A function, which is also an object of class "colourmap".
[Link] 99

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
The plot method [Link].
See colours for information about the colours that R recognises, and how to manipulate
them.
See lut for lookup tables.

Examples
# colour map for real numbers, using breakpoints
cr <- colourmap(c("red", "blue", "green"), breaks=c(0,5,10,15))
cr
cr(3.2)
cr(c(3,5,7))
# a large colour map
co <- colourmap(rainbow(100), breaks=seq(-1,1,length=101))
co(0.2)
# colour map for discrete set of values
ct <- colourmap(c("red", "green"), inputs=c(FALSE, TRUE))
ct(TRUE)

[Link] Test Whether Two Function Arrays Are Compatible

Description
Tests whether two function arrays (class "fasp") are compatible.

Usage
[Link](A, B)

Arguments
A,B Function arrays (object of class "fasp").

Details
An object of class "fasp" can be regarded as an array of functions. Such objects are
returned by the command alltypes.
This function tests whether two such objects are compatible (so that, for example, they
could be added or subtracted).
The functions are compatible if the arrays have the same dimensions, and the corresponding
functions in each cell of the array are compatible as defined by [Link].

Value
Logical value: TRUE if the objects are compatible, and FALSE if they are not.
100 [Link]

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

[Link] Test Whether Two Function Objects Are Compatible

Description
Tests whether two function objects (class "fv") are compatible.

Usage
[Link](A, B)

Arguments
A,B Function value objects (class "fv").

Details
An object of class "fv" is essentially a data frame containing several different statistical
estimates of the same function. Such objects are returned by Kest and its relatives.
This function tests whether two such objects are compatible (so that, for example, they
could be added or subtracted).
The functions are compatible if they have been evaluated at the same sequence of values of
the argument r, and if the statistical estimates have the same names.

Value
Logical value: TRUE if the objects are compatible, and FALSE if they are not.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

[Link] Test Whether Two Pixel Images Are Compatible

Description
Tests whether two pixel image objects have compatible dimensions.

Usage
[Link](A, B, tol=1e-6)
[Link] 101

Arguments
A,B Pixel images (objects of class "im").
tol Tolerance factor

Details
This function tests whether the pixel images A and B have compatible pixel dimensions.
They are compatible if they have the same number of rows and columns, the same physical
pixel dimensions, and occupy the same rectangle in the plane.
The argument tol specifies the maximum tolerated error in the pixel coordinates, expressed
as a fraction of the dimensions of a single pixel.

Value
Logical value: TRUE if the images are compatible, and FALSE if they are not.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

[Link] Take Complement of a Window

Description
Take the set complement of a window, within its enclosing rectangle or in a larger rectangle.

Usage
[Link](w, frame=[Link](w))

Arguments
w an object of class "owin" describing a window of observation for a point
pattern.
frame Optional. The enclosing rectangle, with respect to which the set comple-
ment is taken.

Details
This yields a window object (of class "owin", see [Link]) representing the set com-
plement of w with respect to the rectangle frame.
By default, frame is the enclosing box of w (originally specified by the arguments xrange
and yrange given to owin when w was created). If frame is specified, it must be a rectangle
(an object of class "owin" whose type is "rectangle") and it must be larger than the
enclosing box of w. This rectangle becomes the enclosing box for the resulting window.
If w is a rectangle, then frame must be specified. Otherwise an error will occur (since the
complement of w in itself is empty).
For rectangular and polygonal windows, the complement is computed by reversing the sign
of each boundary polygon, while for binary masks it is computed by negating the pixel
values.
102 concatxy

Value
Another object of class "owin" representing the complement of the window, i.e. the inside
of the window becomes the outside.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link]

Examples
# rectangular
a <- owin(c(0,1),c(0,1))
b <- owin(c(-1,2),c(-1,2))
bmina <- [Link](a, frame=b)
# polygonal
data(demopat)
w <- demopat$window
outside <- [Link](w)
# mask
w <- [Link](demopat$window)
outside <- [Link](w)

concatxy Concatenate x,y Coordinate Vectors

Description
Concatenate any number of pairs of x and y coordinate vectors.

Usage
concatxy(...)

Arguments
... Any number of arguments, each of which is a structure containing ele-
ments x and y.

Details
This function can be used to superimpose two or more point patterns of unmarked points
(but see also superimpose which is recommended).
It assumes that each of the arguments in ... is a structure containing (at least) the elements
x and y. It concatenates all the x elements into a vector x, and similarly for y, and returns
these concatenated vectors.
connected 103

Value
A list with two components x and y, which are the concatenations of all the corresponding
x and y vectors in the argument list.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
superimpose, quadscheme

Examples
dat <- runifrect(30)
xy <- list(x=runif(10),y=runif(10))
new <- concatxy(dat, xy)

connected Connected components of an image or window

Description
Finds the topologically-connected clumps of pixels in an image or window.

Usage
connected(X, background = NA, method="C")

Arguments
X Image (object of class "im") or window (object of class "owin").
background Optional. Treat pixels with this value as being part of the background.
method String indicating the algorithm to be used. Either "C" or "interpreted".
See Details.

Details
This function computes the connected component transform (Rosenfeld and Pfalz, 1966)
of a binary image or binary mask. The argument X is first converted into a pixel image
with logical values. Then the algorithm identifies the connected components (topologically-
connected clumps of pixels) in the foreground.
Two pixels belong to the same connected component if they have the value TRUE and if
they are neighbours (in the 8-connected sense). This rule is applied repeatedly until it
terminates. Then each connected component contains all the pixels that can be reached by
stepping from neighbour to neighbour.
If method="C", the computation is performed by a compiled C language implementation
of the classical algorithm of Rosenfeld and Pfalz (1966). If method="interpreted", the
computation is performed by an R implementation of the algorithm of Park et al (2000).
The result is a factor-valued image, with levels that correspond to the connected compo-
nents. The Examples show how to extract each connected component as a separate window
object.
104 connected

Value

A pixel image (object of class "im") with factor values. The levels of the factor correspond
to the connected components.

Warnings

It may be hard to distinguish different components in the default plot because the colours
of nearby components may be very similar. See the Examples for a randomised colour map.
The algorithm for method="interpreted" can be very slow for large images (or images
where the connected components include a large number of pixels).

Author(s)

Original R code by Julian Burgos, University of Washington. Adapted for spatstat by


Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References

Park, J.-M., Looney, C.G. and Chen, H.-C. (2000) Fast connected component labeling al-
gorithm using a divide and conquer technique. Pages 373-376 in S.Y. Shin (ed) Computers
and Their Applications: Proceedings of the ISCA 15th International Conference on Com-
puters and Their Applications, March 29-31, 2000, New Orleans, Louisiana USA. ISCA
2000, ISBN 1-880843-32-3.
Rosenfeld, A. and Pfalz, J.L. (1966) Sequential operations in digital processing. Journal of
the Association for Computing Machinery 13 471-494.

See Also

[Link], tess

Examples
data(cells)
d <- distmap(cells, dimyx=256)
X <- levelset(d, 0.06)
plot(X)
Z <- connected(X)
plot(Z)

# number of components
nc <- length(levels(Z))
# plot with randomised colour map
plot(Z, col=hsv(h=sample(seq(0,1,length=nc), nc)))

# how to extract the components as a list of windows


W <- tiles(tess(image=Z))
[Link] 105

[Link] Contour plot of pixel image

Description
Generates a contour plot of a pixel image.

Usage
## S3 method for class 'im':
contour(x, ..., main, axes=TRUE, add=FALSE)

Arguments
x Pixel image to be plotted. An object of class "im".
main Character string to be displayed as the main title.
axes Logical. If TRUE, coordinate axes are plotted (with tick marks) around
a region slightly larger than the image window. If FALSE, no axes are
plotted, and a box is drawn tightly around the image window. Ignored if
add=TRUE.
add Logical. If FALSE, a new plot is created. If TRUE, the contours are drawn
over the existing plot.
... Other arguments passed to [Link] controlling the contour plot;
see Details.

Details
This is a method for the generic contour function, for objects of the class "im".
An object of class "im" represents a pixel image; see [Link].
This function displays the values of the pixel image x as a contour plot on the current plot
device, using equal scales on the x and y axes.
The appearance of the plot can be modified using any of the arguments listed in the help
for [Link]. Useful ones include:

nlevels Number of contour levels to plot.


drawlabels Whether to label the contour lines with text.
col,lty,lwd Colour, type, and width of contour lines.

See [Link] for a full list of these arguments.


The defaults for any of the abovementioned arguments can be reset using [Link].

Value
none.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
106 convexhull

See Also
[Link], [Link], [Link]

Examples
# an image
Z <- setcov(owin())
contour(Z)
contour(Z, axes=FALSE)

convexhull Convex Hull

Description
Computes the convex hull of a spatial object.

Usage
convexhull(x)

Arguments
x a window (object of class "owin"), a point pattern (object of class "ppp"),
a line segment pattern (object of class "psp"), or an object that can be
converted to a window by [Link].

Details
This function computes the convex hull of the spatial object x.

Value
A window (an object of class "owin").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link], [Link]

Examples
data(demopat)
W <- demopat$window
plot(convexhull(W), col="lightblue", border=NA)
plot(W, add=TRUE, lwd=2)
[Link] 107

[Link] Convex Hull of Points

Description
Computes the convex hull of a set of points in two dimensions.

Usage
[Link](x, y=NULL)

Arguments
x vector of x coordinates of observed points, or a 2-column matrix giving
x,y coordinates, or a list with components x,y giving coordinates (such
as a point pattern object of class "ppp".)
y (optional) vector of y coordinates of observed points, if x is a vector.

Details
Given an observed pattern of points with coordinates given by x and y, this function com-
putes the convex hull of the points, and returns it as a window.

Value
A window (an object of class "owin").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link], convexhull, [Link], ripras

Examples
x <- runif(30)
y <- runif(30)
w <- [Link](x,y)
plot(owin(), main="[Link](x,y)", lty=2)
plot(w, add=TRUE)
points(x,y)

X <- rpoispp(30)
plot(X, main="[Link](X)")
plot([Link](X), add=TRUE)
108 coords

coords Extract Coordinates of a Spatial or Spatiotemporal Point Pattern

Description
Given any kind of spatial or space-time point pattern, this function extracts the (space
and/or time) coordinates of the points and returns them as a data frame.

Usage
coords(x, ...)
## S3 method for class 'ppp':
coords(x, ...)
## S3 method for class 'ppx':
coords(x, ..., spatial = TRUE, temporal = TRUE)

Arguments
x A point pattern: either a two-dimensional point pattern (object of class
"ppp"), a three-dimensional point pattern (object of class "pp3"), or a
general multidimensional space-time point pattern (object of class "ppx").
... Further arguments passed to methods.
spatial,temporal
Logical values indicating whether to extract spatial and temporal coor-
dinates, respectively. The default is to return both spatial and temporal
coordinates.

Details
The function coords is generic, with methods for the classes "ppp") and "ppx". An object
of class "pp3" also inherits from "ppx" and is handled by the method for "ppx".

Value
A [Link] with one row for each point, containing the coordinates.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppx, pp3, ppp, [Link], [Link].

Examples
df <- [Link](x=runif(4),y=runif(4),t=runif(4))
X <- ppx(data=df, temporal="t")
coords(X)
coords(X, temporal=FALSE)
copper 109

copper Berman-Huntington points and lines data

Description
These data come from an intensive geological survey of a 70 x 158 km region in central
Queensland, Australia. They consist of 67 points representing copper ore deposits, and 146
line segments representing geological ‘lineaments’. Lineaments are linear features, visible
on a satellite image, that are believed to consist largely of geological faults (Berman, 1986,
p. 55). It would be of great interest to predict the occurrence of copper deposits from the
lineament pattern, since the latter can easily be observed on satellite images.
These data were introduced and analysed by Berman (1986). They have also been studied
by Berman and Diggle (1989), Berman and Turner (1992), Baddeley and Turner (2000,
2005), Foxall and Baddeley (2002) and Baddeley et al (2005).
Many analyses have been performed on the southern half of the data only. This subset is
also provided.

Usage
data(copper)

Format
copper is a list with the following entries:

Points a point pattern (object of class "ppp") representing the full point pattern of copper
deposits. See [Link] for details of the format.
Lines a line segment pattern (object of class "psp") representing the lineaments in the full
dataset. See [Link] for details of the format.
SouthWindow the window delineating the southern half of the study region. An object
of class "owin".
SouthPoints the point pattern of copper deposits in the southern half of the study region.
An object of class "ppp".
SouthLines the line segment pattern of the lineaments in the southern half of the study
region. An object of class "psp".

Source
Dr J. Huntington. Coordinates kindly provided by Dr. Mark Berman and Dr. A. Green,
CSIRO, Sydney, Australia.

References
Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283–322.
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial
point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.
Baddeley, A. and Turner, R. (2005) Modelling spatial point patterns in R. In: A. Baddeley,
P. Gregori, J. Mateu, R. Stoica, and D. Stoyan, editors, Case Studies in Spatial Point
110 corners

Pattern Modelling, Lecture Notes in Statistics number 185. Pages 23–74. Springer-Verlag,
New York, 2006. ISBN: 0-387-28311-0.
Berman, M. (1986). Testing for spatial association between a point process and another
stochastic process. Applied Statistics 35, 54–62.
Berman, M. and Diggle, P.J. (1989) Estimating Weighted Integrals of the Second-order
Intensity of a Spatial Point Process. Journal of the Royal Statistical Society, series B 51,
81–92.
Berman, M. and Turner, T.R. (1992) Approximating point process likelihoods with GLIM.
Applied Statistics 41, 31–38.
Foxall, R. and Baddeley, A. (2002) Nonparametric measures of association between a spatial
point process and a random set, with geological applications. Applied Statistics 51, 165–
182.

Examples

data(copper)

# Plot full dataset

plot(copper$Points)
plot(copper$Lines, add=TRUE)

# Plot southern half of data


plot(copper$SouthPoints)
plot(copper$SouthLines, add=TRUE)

## Not run:
Z <- distmap(copper$SouthLines)
plot(Z)
X <- copper$SouthPoints
ppm(X, ~D, covariates=list(D=Z))

## End(Not run)

corners Corners of a rectangle

Description
Returns the four corners of a rectangle

Usage
corners(window)

Arguments
window A window. An object of class owin, or data in any format acceptable to
[Link]().
crossdist 111

Details
This trivial function is occasionally convenient. If window is of type "rectangle" this re-
turns the four corners of the window itself; otherwise, it returns the corners of the bounding
rectangle of the window.

Value
A list with two components x and y, which are numeric vectors of length 4 giving the
coordinates of the four corner points of the (bounding rectangle of the) window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], quadscheme

Examples
w <- [Link]()
corners(w)
# returns list(x=c(0,1,0,1),y=c(0,0,1,1))

crossdist Pairwise distances

Description
Computes the distances between pairs of ‘things’ taken from two different datasets.

Usage
crossdist(X, Y, ...)

Arguments
X,Y Two objects of the same class.
... Additional arguments depending on the method.

Details
Given two datasets X and Y (representing either two point patterns or two line segment
patterns) crossdist computes the Euclidean distance from each thing in the first dataset
to each thing in the second dataset, and returns a matrix containing these distances.
The function crossdist is generic, with methods for point patterns (objects of class "ppp"),
line segment patterns (objects of class "psp"), and a default method. See the documentation
for [Link], [Link] or [Link] for further details.
112 [Link]

Value
A matrix whose [i,j] entry is the distance from the i-th thing in the first dataset to the
j-th thing in the second dataset.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]

See Also
[Link], [Link], [Link], pairdist, nndist

[Link] Pairwise distances between two different sets of points

Description
Computes the distances between each pair of points taken from two different sets of points.

Usage
## Default S3 method:
crossdist(X, Y, x2, y2, ..., period=NULL, method="C")

Arguments
X,Y Numeric vectors of equal length specifying the coordinates of the first set
of points.
x2,y2 Numeric vectors of equal length specifying the coordinates of the second
set of points.
... Ignored.
period Optional. Dimensions for periodic edge correction.
method String specifying which method of calculation to use. Values are "C" and
"interpreted".

Details
Given two sets of points, this function computes the Euclidean distance from each point in
the first set to each point in the second set, and returns a matrix containing these distances.
This is a method for the generic function crossdist.
This function expects X and Y to be numeric vectors of equal length specifying the coordi-
nates of the first set of points. The arguments x2,y2 specify the coordinates of the second
set of points.
Alternatively if period is given, then the distances will be computed in the ‘periodic’ sense
(also known as ‘torus’ distance). The points will be treated as if they are in a rectangle of
width period[1] and height period[2]. Opposite edges of the rectangle are regarded as
equivalent.
The argument method is not normally used. It is retained only for checking the validity of the
software. If method = "interpreted" then the distances are computed using interpreted
R code only. If method="C" (the default) then C code is used. The C code is faster by a
factor of 4.
[Link] 113

Value
A matrix whose [i,j] entry is the distance from the i-th point in the first set of points to
the j-th point in the second set of points.

Author(s)
Pavel Grabarnik <[Link]@[Link]> and Adrian Baddeley <adrian@[Link]>
[Link]

See Also
crossdist, [Link], [Link], pairdist, nndist, Gest

Examples
d <- crossdist(runif(7), runif(7), runif(12), runif(12))
d <- crossdist(runif(7), runif(7), runif(12), runif(12), period=c(1,1))

[Link] Pairwise distances between two different point patterns

Description
Computes the distances between pairs of points taken from two different point patterns.

Usage
## S3 method for class 'ppp':
crossdist(X, Y, ..., periodic=FALSE, method="C")

Arguments
X,Y Point patterns (objects of class "ppp").
... Ignored.
periodic Logical. Specifies whether to apply a periodic edge correction.
method String specifying which method of calculation to use. Values are "C" and
"interpreted".

Details
Given two point patterns, this function computes the Euclidean distance from each point
in the first pattern to each point in the second pattern, and returns a matrix containing
these distances.
This is a method for the generic function crossdist for point patterns (objects of class
"ppp").
This function expects two point patterns X and Y, and returns the matrix whose [i,j]
entry is the distance from X[i] to Y[j].
Alternatively if periodic=TRUE, then provided the windows containing X and Y are identical
and are rectangular, then the distances will be computed in the ‘periodic’ sense (also known
114 [Link]

as ‘torus’ distance): opposite edges of the rectangle are regarded as equivalent. This is
meaningless if the window is not a rectangle.
The argument method is not normally used. It is retained only for checking the validity of the
software. If method = "interpreted" then the distances are computed using interpreted
R code only. If method="C" (the default) then C code is used. The C code is faster by a
factor of 4.

Value
A matrix whose [i,j] entry is the distance from the i-th point in X to the j-th point in Y.

Author(s)
Pavel Grabarnik <[Link]@[Link]> and Adrian Baddeley <adrian@[Link]>
[Link]

See Also
crossdist, [Link], [Link], pairdist, nndist, Gest

Examples
data(cells)
d <- crossdist(cells, runifpoint(6))
d <- crossdist(cells, runifpoint(6), periodic=TRUE)

[Link] Pairwise distances between two different line segment patterns

Description
Computes the distances between all pairs of line segments taken from two different line
segment patterns.

Usage
## S3 method for class 'psp':
crossdist(X, Y, ..., method="Fortran", type="Hausdorff")

Arguments
X,Y Line segment patterns (objects of class "psp").
... Ignored.
method String specifying which method of calculation to use. Values are "Fortran"
and "interpreted".
type Type of distance to be computed. Options are "Hausdorff" and "separation".
Partial matching is used.
[Link] 115

Details
This is a method for the generic function crossdist.
Given two line segment patterns, this function computes the distance from each line seg-
ment in the first pattern to each line segment in the second pattern, and returns a matrix
containing these distances.
The distances between line segments are measured in one of two ways:

ˆ if type="Hausdorff", distances are computed in the Hausdorff metric. The Hausdorff


distance between two line segments is the maximum distance from any point on one
of the segments to the nearest point on the other segment.
ˆ if type="separation", distances are computed as the minimum distance from a point
on one line segment to a point on the other line segment. For example, line segments
which cross over each other have separation zero.

The argument method is not normally used. It is retained only for checking the validity of the
software. If method = "interpreted" then the distances are computed using interpreted
R code only. If method="Fortran" (the default) then Fortran code is used. The Fortran
code is several times faster.

Value
A matrix whose [i,j] entry is the distance from the i-th line segment in X to the j-th line
segment in Y.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
pairdist, nndist, Gest

Examples
L1 <- psp(runif(5), runif(5), runif(5), runif(5), owin())
L2 <- psp(runif(10), runif(10), runif(10), runif(10), owin())
D <- crossdist(L1, L2)
#result is a 5 x 10 matrix
S <- crossdist(L1, L2, type="sep")

[Link] Crossing Points of Two Line Segment Patterns

Description
Finds any crossing points between two line segment patterns.

Usage
[Link](A,B)
116 [Link]

Arguments
A,B Line segment patterns (objects of class "psp").

Details
This function finds any crossing points between the line segment patterns A and B.
A crossing point occurs whenever one of the line segments in A intersects one of the line
segments in B, at a nonzero angle of intersection.

Value
Point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link].

Examples
a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
b <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
plot(a, col="green", main="[Link]")
plot(b, add=TRUE, col="blue")
P <- [Link](a,b)
plot(P, add=TRUE, col="red")

[Link] Convert Pixel Image from Numeric to Factor

Description
Transform the values of a pixel image from numeric values into a factor.

Usage
## S3 method for class 'im':
cut(x, ...)

Arguments
x A pixel image. An object of class "im".
... Arguments passed to [Link]. They determine the breakpoints for
the mapping from numerical values to factor values. See [Link].
[Link] 117

Details
This simple function applies the generic cut operation to the pixel values of the image x.
The range of pixel values is divided into several intervals, and each interval is associated
with a level of a factor. The result is another pixel image, with the same window and pixel
grid as x, but with the numeric value of each pixel discretised by replacing it by the factor
level.
This function is a convenient way to inspect an image and to obtain summary statistics.
See the examples.
To select a subset of an image, use the subset operator [.im instead.

Value
A pixel image (object of class "im") with pixel values that are a factor. See [Link].

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also
cut, [Link]

Examples
# artificial image data
Z <- setcov(square(1))

Y <- cut(Z, 3)
Y <- cut(Z, breaks=seq(0,1,length=5))

# cut at the quartiles


# (divides the image into 4 equal areas)
Y <- cut(Z, quantile(Z))

[Link] Classify Points in a Point Pattern

Description

Classifies the points in a point pattern into distinct types according to the numerical marks
in the pattern, or according to another variable.

Usage
## S3 method for class 'ppp':
cut(x, z=marks(x), ...)
118 [Link]

Arguments

x A two-dimensional point pattern. An object of class "ppp".


z Data determining the classification. A numeric vector, a factor, a pixel
image, or a tessellation. Defaults to the vector of marks of the point
pattern.
... Arguments passed to [Link]. They determine the breakpoints for
the mapping from numerical values in z to factor values in the output.
See [Link].

Details

This function has the effect of classifying each point in the point pattern x into one of
several possible types. The classification is based on the dataset z, which may be either

ˆ a factor (of length equal to the number of points in z) determining the classification
of each point in x. Levels of the factor determine the classification.
ˆ a numeric vector (of length equal to the number of points in z). The range of values
of z will be divided into bands (the number of bands is determined by ...) and z will
be converted to a factor using [Link].
ˆ a pixel image (object of class "im"). The value of z at each point of x will be used as
the classifying variable.
ˆ a tessellation (object of class "tess", see tess). Each point of x will be classified
according to the tile of the tessellation into which it falls.

The default is to take z to be the vector of marks in x. If the marks are numeric, then the
range of values of the numerical marks is divided into several intervals, and each interval
is associated with a level of a factor. The result is a marked point pattern, with the same
window and point locations as x, but with the numeric mark of each point discretised by
replacing it by the factor level. This is a convenient way to transform a marked point
pattern which has numeric marks into a multitype point pattern, for example to plot it or
analyse it. See the examples.
To select some points from a point pattern, use the subset operator [.ppp instead.

Value

A multitype point pattern, that is, a point pattern object (of class "ppp") with a marks
vector that is a factor.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

cut, [Link], tess


[Link] 119

Examples
# (1) cutting based on numeric marks of point pattern

data(longleaf)
# Longleaf Pines data
# the marks are positive real numbers indicating tree diameters.

## Not run:
plot(longleaf)

## End(Not run)

# cut the range of tree diameters into three intervals


long3 <- cut(longleaf, breaks=3)
## Not run:
plot(long3)

## End(Not run)

# adult trees defined to have diameter at least 30 cm


long2 <- cut(longleaf, breaks=c(0,30,100), labels=c("Sapling", "Adult"))
plot(long2)
plot(long2, cols=c("green","blue"))

# (2) cutting based on another numeric vector


# Divide Swedish Pines data into 3 classes
# according to nearest neighbour distance

data(swedishpines)
plot(cut(swedishpines, nndist(swedishpines), breaks=3))

# (3) cutting based on tessellation


# Divide Swedish Pines study region into a 4 x 4 grid of rectangles
# and classify points accordingly

tes <- tess(xgrid=seq(0,96,length=5),ygrid=seq(0,100,length=5))


plot(cut(swedishpines, tes))
plot(tes, lty=2, add=TRUE)

[Link] Extract Original Data from a Fitted Point Process Model

Description
Given a fitted point process model, this function extracts the original point pattern dataset
to which the model was fitted.

Usage
[Link](object)

Arguments
object fitted point process model (an object of class "ppm").
120 [Link]

Details
An object of class "ppm" represents a point process model that has been fitted to data.
It is typically produced by the model-fitting algorithm ppm. The object contains complete
information about the original data point pattern to which the model was fitted. This
function extracts the original data pattern.
See [Link] for a list of all operations that can be performed on objects of class "ppm".

Value
A point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
data(cells)
fit <- ppm(cells, ~1, Strauss(r=0.1))
X <- [Link](fit)
# 'X' is identical to 'cells'

[Link] Generate a Default Pattern of Dummy Points

Description
Generates a default pattern of dummy points for use in a quadrature scheme.

Usage
[Link](X, nd, random=FALSE, ntile=NULL, npix=NULL, ..., verbose=FALSE)

Arguments
X The observed data point pattern. An object of class "ppp" or in a format
recognised by [Link]()
nd Optional. Integer, or integer vector of length 2, specifying an nd * nd or
nd[1] * nd[2] rectangular array of dummy points.
random Logical value. If TRUE, the dummy points are randomised.
ntile Optional. Integer or pair of integers specifying the number of rows and
columns of tiles used in the counting rule.
npix Optional. Integer or pair of integers specifying the number of rows and
columns of pixels used in computing approximate areas.
... Ignored.
verbose If TRUE, information about the construction of the quadrature scheme is
printed.
delaunay 121

Details
This function provides a sensible default for the dummy points in a quadrature scheme.
A quadrature scheme consists of the original data point pattern, an additional pattern of
dummy points, and a vector of quadrature weights for all these points. See [Link]
for further information about quadrature schemes.
If random is false (the default), then the function creates dummy points in an nd[1] by
nd[1] rectangular grid. If random is true, then the frame of the window is divided into an
nd[1] by nd[1] array of tiles, and one dummy point is generated at random inside each
tile. In either case, the four corner points of the frame of the window are added. Then if
the window is not rectangular, any dummy points lying outside it are deleted.
If nd is missing, a default value (depending on the data pattern X) is computed by [Link].
Alternative functions for creating dummy patterns include corners, gridcentres, stratrand
and spokes.

Value
A point pattern (an object of class "ppp", see [Link]) containing the dummy points.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], quadscheme, corners, gridcentres, stratrand, spokes

Examples
data(simdat)
P <- simdat
D <- [Link](P, 100)
## Not run: plot(D)
Q <- quadscheme(P, D, "grid")
## Not run: plot([Link](Q))

delaunay Delaunay Triangulation of Point Pattern

Description
Computes the Delaunay triangulation of a spatial point pattern.

Usage
delaunay(X)

Arguments
X Spatial point pattern (object of class "ppp").
122 deltametric

Details
The Delaunay triangulation of a spatial point pattern X is defined as follows. First the
Dirichlet/Voronoi tessellation of X computed; see dirichlet. Then two points of X are
defined to be Delaunay neighbours if their Dirichlet/Voronoi tiles share a common boundary.
Every pair of Delaunay neighbours is joined by a straight line. The result is a tessellation,
consisting of disjoint triangles. The union of these triangles is the convex hull of X.

Value
A tessellation (object of class "tess"). The window of the tessellation is the convex hull of
X, not the original window of X.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
tess, dirichlet, [Link], ppp

Examples
X <- runifpoint(42)
plot(delaunay(X))
plot(X, add=TRUE)

deltametric Delta Metric

Description
Computes the discrepancy between two sets A and B according to Baddeley’s delta-metric.

Usage
deltametric(A, B, p = 2, c = Inf, ...)

Arguments
A,B The two sets which will be compared. Windows (objects of class "owin"),
point patterns (objects of class "ppp") or line segment patterns (objects
of class "psp").
p Index of the Lp metric. Either a positive numeric value, or Inf.
c Distance threshold. Either a positive numeric value, or Inf.
... Arguments passed to [Link] to determine the pixel resolution of the
distance maps computed by distmap.
deltametric 123

Details
Baddeley (1992a, 1992b) defined a distance between two sets A and B contained in a space
W by
 Z 1/p
1
∆(A, B) = |min(c, d(x, A)) − min(c, d(x, B))|p dx
|W | W
where c ≥ 0 is a distance threshold parameter, 0 < p ≤ ∞ is the exponent parameter, and
d(x, A) denotes the shortest distance from a point x to the set A. Also |W| denotes the
area or volume of the containing space W .
This is defined so that it is a metric, i.e.

ˆ ∆(A, B) = 0 if and only if A = B


ˆ ∆(A, B) = ∆(B, A)
ˆ ∆(A, C) ≤ ∆(A, B) + ∆(B, C)

It is topologically equivalent to the Hausdorff metric (Baddeley, 1992a) but has better
stability properties in practical applications (Baddeley, 1992b).
If p = ∞ and c = ∞ the Delta metric is equal to the Hausdorff metric.
The algorithm uses distmap to compute the distance maps d(x, A) and d(x, B), then ap-
proximates the integral numerically. The accuracy of the computation depends on the pixel
resolution which is controlled through the extra arguments ... passed to [Link].

Value
A numeric value.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A.J. (1992a) Errors in binary images and an Lp version of the Hausdorff metric.
Nieuw Archief voor Wiskunde 10, 157–183.
Baddeley, A.J. (1992b) An error metric for binary images. In W. Foerstner and S. Ruwiedel
(eds) Robust Computer Vision. Karlsruhe: Wichmann. Pages 59–78.

See Also
distmap

Examples
X <- runifpoint(20)
Y <- runifpoint(10)
deltametric(X, Y, p=1,c=0.1)
124 [Link]

demopat Artificial Data Point Pattern

Description
This is an artificial dataset, for use in testing and demonstrating the capabilities of the
spatstat package. It is a multitype point pattern in an irregular polygonal window. There
are two types of points. The window contains a polygonal hole.

Usage
data(demopat)

Format
An object of class "ppp" representing the point pattern.
See [Link] for details of the format of a point pattern object.

Source
Adrian Baddeley

[Link] Kernel Smoothed Intensity of Point Pattern

Description
Compute a kernel smoothed intensity function from a point pattern.

Usage
## S3 method for class 'ppp':
density(x, sigma, ...,
weights, edge=TRUE, varcov=NULL,
at="pixels", leaveoneout=TRUE)

Arguments
x Point pattern (object of class "ppp").
sigma Standard deviation of isotropic Gaussian smoothing kernel.
weights Optional vector of weights to be attached to the points. May include
negative values.
... Arguments passed to [Link] to determine the pixel resolution.
edge Logical flag: if TRUE, apply edge correction.
varcov Variance-covariance matrix of anisotropic Gaussian kernel. Incompatible
with sigma.
at String specifying whether to compute the intensity values at a grid of
pixel locations (at="pixels") or only at the points of x (at="points").
leaveoneout Logical value indicating whether to compute a leave-one-out estimator.
Applicable only when at="points".
[Link] 125

Details
This is a method for the generic function density.
It computes a fixed-bandwidth kernel estimate (Diggle, 1985) of the intensity function of
the point process that generated the point pattern x.
By default it computes the convolution of the isotropic Gaussian kernel of standard deviation
sigma with point masses at each of the data points in x. Each point has unit weight, unless
the argument weights is given (it should be a numeric vector; weights can be negative or
zero).
If edge=TRUE, the intensity estimate is corrected for edge effect bias by dividing it by the
convolution of the Gaussian kernel with the window of observation.
Instead of the isotropic Gaussian kernel with standard deviation sigma, the smoothing
kernel may be chosen to be any Gaussian kernel, by giving the variance-covariance matrix
varcov. The arguments sigma and varcov are incompatible. Also sigma may be a vector
of length 2 giving the standard deviations of two independent Gaussian coordinates, thus
equivalent to varcov = diag(sigma^2).
Thus the intensity value at a point u is
X
λ̂(u) = e(u) k(xi − u)wi
i

where k is the Gaussian smoothing kernel, e(u) is an edge correction factor, and xi are the
weights.
By default the intensity values are computed at every location u in a fine grid, and are
returned as a pixel image. Computation is performed using the Fast Fourier Transform.
Accuracy depends on the pixel resolution, controlled by the arguments ... passed to
[Link].
If at="points", the intensity values are computed to high accuracy at the points of x
only. Computation is performed by directly evaluating and summing the Gaussian kernel
contributions without discretising the data. The result is a numeric vector giving the density
values. The intensity value at a point xi is
X
λ̂(xi ) = e(xi ) k(xj − xi )wi
j

If leaveoneout=TRUE (the default), then the sum in the equation is taken over all j not
equal to i, so that the intensity value at a data point is the sum of kernel contributions
from all other data points. If leaveoneout=FALSE then the sum is taken over all j, so that
the intensity value at a data point includes a contribution from the same point.
To perform spatial interpolation of values that were observed at the points of a point
pattern, use [Link].
For adaptive nonparametric estimation, see [Link].

Value
By default, the result is a pixel image (object of class "im"). Pixel values are estimated
intensity values, expressed in “points per unit area”.
If at="points", the result is a numeric vector of length equal to the number of points in
x. Values are estimated intensity values at the points of x.
126 [Link]

Note
This function is often misunderstood.
The result of [Link] is not a spatial smoothing of the marks or weights attached
to the point pattern. To perform spatial interpolation of values that were observed at the
points of a point pattern, use [Link].
The result of [Link] is not a probability density. It is an estimate of the intensity
function of the point process that generated the point pattern data. Intensity is the expected
number of random points per unit area. The units of intensity are “points per unit area”.
Intensity is usually a function of spatial location, and it is this function which is estimated
by [Link]. The integral of the intensity function over a spatial region gives the
expected number of points falling in this region.
Inspecting an estimate of the intensity function is usually the first step in exploring a spatial
point pattern dataset. For more explanation, see the workshop notes (Baddeley, 2008) or
Diggle (2003).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A. (2008) Analysing spatial point patterns in R. Workshop notes. CSIRO online
technical publication. URL: [Link]/resources/[Link]
Diggle, P.J. (1985) A kernel method for smoothing point process data. Applied Statistics
(Journal of the Royal Statistical Society, Series C) 34 (1985) 138–147.
Diggle, P.J. (2003) Statistical analysis of spatial point patterns, Second edition. Arnold.

See Also
[Link], [Link], [Link], [Link]

Examples
data(cells)
Z <- density(cells, 0.05)
plot(Z)
density(cells, 0.05, at="points")

[Link] Kernel Smoothing of Line Segment Pattern

Description
Compute a kernel smoothed intensity function from a line segment pattern.

Usage
## S3 method for class 'psp':
density(x, sigma, ..., edge=TRUE)
[Link] 127

Arguments
x Line segment pattern (object of class "psp") to be smoothed.
sigma Standard deviation of isotropic Gaussian smoothing kernel.
... Extra arguments passed to [Link] which determine the resolution of the
resulting image.
edge Logical flag indicating whether to apply edge correction.

Details
This is a method for the generic function density.
A kernel estimate of the intensity of the line segment pattern is computed. The result is
the convolution of the isotropic Gaussian kernel, of standard deviation sigma, with the line
segments. Computation is performed analytically.
If edge=TRUE this result is adjusted for edge effects by dividing it by the convolution of the
same Gaussian kernel with the observation window.

Value
A pixel image (object of class "im").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], density

Examples
L <- psp(runif(20),runif(20),runif(20),runif(20), window=owin())
D <- density(L, sigma=0.03)
plot(D, main="density(L)")
plot(L, add=TRUE)

[Link] Kernel Smoothed Intensity of Split Point Pattern

Description
Compute a kernel smoothed intensity function for each of the components of a split point
pattern.

Usage
## S3 method for class 'splitppp':
density(x, ...)
128 [Link]

Arguments

x Split point pattern (object of class "splitppp" created by [Link]) to


be smoothed.
... Arguments passed to [Link] to control the smoothing, pixel reso-
lution, edge correction etc.

Details

This is a method for the generic function density.


The argument x should be an object of class "splitppp", effectively a list of point patterns.
Typically x is obtained by applying the function [Link] to a point pattern y by calling
split(y). This splits the points of y into several sub-patterns.
A kernel estimate of the intensity function of each of the point patterns is computed using
[Link].
The return value is a list, each of whose entries is a pixel image (object of class "im"). The
return value also belongs to the class "listof" and can be plotted or printed.

Value

A list of pixel images (objects of class "im"). Can be plotted or printed.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [Link]

Examples
data(amacrine)
Z <- density(split(amacrine), 0.05)
plot(Z)

[Link] Diagnostic Plots for Fitted Point Process Model

Description

Given a point process model fitted to a point pattern, produce diagnostic plots based on
residuals.
[Link] 129

Usage
[Link](object, ..., type="raw", which="all", sigma=NULL,
rbord=reach(object), cumulative=TRUE,
[Link]=TRUE, rv = NULL, [Link]=TRUE,
[Link]=TRUE, typename, check=TRUE, repair=TRUE,
oldstyle=FALSE)
## S3 method for class 'diagppm':
plot(x, ..., which,
[Link]="image", [Link]="imagecontour",
[Link]=TRUE, spacing=0.1,
srange=NULL, monochrome=FALSE, main=NULL)

Arguments
object The fitted point process model (an object of class "ppm") for which diag-
nostics should be produced. This object is usually obtained from ppm.
type String indicating the type of residuals or weights to be used. Current
options are "eem" for the Stoyan-Grabarnik exponential energy weights,
"raw" for the raw residuals, "inverse" for the inverse-lambda residuals,
and "pearson" for the Pearson residuals. A partial match is adequate.
which Character string or vector indicating the choice(s) of plots to be generated.
Options are "all", "marks", "smooth", "x", "y" and "sum". Multiple
choices may be given but must be matched exactly. See Details.
sigma Bandwidth for kernel smoother in "smooth" option.
rbord Width of border to avoid edge effects. The diagnostic calculations will
be confined to those points of the data pattern which are at least rbord
units away from the edge of the window.
cumulative Logical flag indicating whether the lurking variable plots for the x and y
coordinates will be the plots of cumulative sums of marks (cumulative=TRUE)
or the plots of marginal integrals of the smoothed residual field (cumulative=FALSE).
[Link] Logical value indicating whether plots should be shown. If [Link]=FALSE,
the computed diagnostic quantities are returned without plotting them.
[Link] One of "discrete" or "image" indicating how the density part of the
residual measure should be plotted.
[Link] One of "image", "persp", "contour" or "imagecontour" indicating how
the smoothed residual field should be plotted.
[Link],[Link]
Logical values indicating whether error bounds should be computed and
added to the "x" and "y" plots. The default is TRUE for Poisson models
and FALSE for non-Poisson models. See Details.
rv Usually absent. If this argument is present, the values of the residuals
will not be calculated from the fitted model object but will instead be
taken directly from this vector.
spacing The spacing between plot panels (when a four-panel plot is generated)
expressed as a fraction of the width of the window of the point pattern.
srange Vector of length 2 that will be taken as giving the range of values of the
smoothed residual field, when generating an image plot of this field. This
is useful if you want to generate diagnostic plots for two different fitted
models using the same colour map.
130 [Link]

monochrome Flag indicating whether images should be displayed in greyscale (suitable


for publication) or in colour (suitable for the screen). The default is to
display in colour.
check Logical value indicating whether to check the internal format of object.
If there is any possibility that this object has been restored from a dump
file, or has otherwise lost track of the environment where it was originally
computed, set check=TRUE.
repair Logical value indicating whether to repair the internal format of object,
if it is found to be damaged.
oldstyle Logical flag indicating whether error bounds should be plotted using the
approximation given in the original paper (oldstyle=TRUE), or using the
correct asymptotic formula (oldstyle=FALSE).
x The value returned from a previous call to [Link]. An object of
class "diagppm".
typename String to be used as the name of the residuals.
main Main title for the plot.
... Extra arguments, controlling either the resolution of the smoothed image
(passed from [Link] to [Link]) or the appearance of the
plots (passed from [Link] to [Link] and from [Link]
to [Link]).
[Link] Advanced use only.

Details
This function generates several diagnostic plots for a fitted point process model. The
plots display the residuals from the fitted model (Baddeley et al, 2005) or alternatively
the ‘exponential energy marks’ (Stoyan and Grabarnik, 1991). These plots can be used to
assess goodness-of-fit, to identify outliers in the data, and to reveal departures from the
fitted model. See also the companion function [Link].
The argument object must be a fitted point process model (object of class "ppm") typically
produced by the maximum pseudolikelihood fitting algorithm ppm).
The argument type selects the type of residual or weight that will be computed. Current
options are:

"eem": exponential energy marks (Stoyan and Grabarnik, 1991) computed by eem. These
are positive weights attached to the data points (i.e. the points of the point pattern
dataset to which the model was fitted). If the fitted model is correct, then the sum of
these weights for all data points in a spatial region B has expected value equal to the
area of B. See eem for further explanation.
"raw", "inverse" or "pearson": point process residuals (Baddeley et al, 2005) computed
by the function [Link]. These are residuals attached both to the data points
and to some other points in the window of observation (namely, to the dummy points
of the quadrature scheme used to fit the model). If the fitted model is correct, then
the sum of the residuals in a spatial region B has mean zero. The options are
ˆ "raw": the raw residuals;
ˆ "inverse": the ‘inverse-lambda’ residuals, a counterpart of the exponential energy
weights;
ˆ "pearson": the Pearson residuals.
See [Link] for further explanation.
[Link] 131

The argument which selects the type of plot that is produced. Options are:
"marks": plot the residual measure. For the exponential energy weights (type="eem") this
displays circles centred at the points of the data pattern, with radii proportional to
the exponential energy weights. For the residuals (type="raw", type="inverse" or
type="pearson") this again displays circles centred at the points of the data pattern
with radii proportional to the (positive) residuals, while the plotting of the negative
residuals depends on the argument [Link]. If [Link]="image" then the neg-
ative part of the residual measure, which is a density, is plotted as a colour image.
If [Link]="discrete" then the discretised negative residuals (obtained by approx-
imately integrating the negative density using the quadrature scheme of the fitted
model) are plotted as squares centred at the dummy points with side lengths propor-
tional to the (negative) residuals. [To control the size of the circles and squares, use
the argument maxsize.]
"smooth": plot a kernel-smoothed version of the residual measure. Each data or dummy
point is taken to have a ‘mass’ equal to its residual or exponential energy weight.
(Note that residuals can be negative). This point mass is then replaced by a bivariate
isotropic Gaussian density with standard deviation sigma. The value of the smoothed
residual field at any point in the window is the sum of these weighted densities. If
the fitted model is correct, this smoothed field should be flat, and its height should
be close to 0 (for the residuals) or 1 (for the exponential energy weights). The field
is plotted either as an image, contour plot or perspective view of a surface, according
to the argument [Link]. The range of values of the smoothed field is printed if
the option which="sum" is also selected.
"x": produce a ‘lurking variable’ plot for the x coordinate. This is a plot of h(x) against x
(solid lines) and of E(h(x)) against x (dashed lines), where h(x) is defined below, and
E(h(x)) denotes the expectation of h(x) assuming the fitted model is true.
ˆ if cumulative=TRUE then h(x) is the cumulative sum of the weights or residuals
for all points which have X coordinate less than or equal to x. For the residuals
E(h(x)) = 0, and for the exponential energy weights E(h(x)) = area of the subset
of the window to the left of the line X = x.
ˆ if cumulative=FALSE then h(x) is the marginal integral of the smoothed resid-
ual field (see the case which="smooth" described above) on the x axis. This is
approximately the derivative of the plot for cumulative=TRUE. The value of h(x)
is computed by summing the values of the smoothed residual field over all pixels
with the given x coordinate. For the residuals E(h(x)) = 0, and for the exponen-
tial energy weights E(h(x)) = length of the intersection between the observation
window and the line X = x.
If [Link] = TRUE, then superimposed on the lurking variable plot are the pointwise
two-standard-deviation error limits for h(x) calculated for the inhomogeneous Poisson
process. The default is [Link] = TRUE for Poisson models and [Link] = FALSE for
non-Poisson models.
"y": produce a similar lurking variable plot for the y coordinate.
"sum": print the sum of the weights or residuals for all points in the window (clipped by
a margin rbord if required) and the area of the same window. If the fitted model is
correct the sum of the exponential energy weights should equal the area of the window,
while the sum of the residuals should equal zero. Also print the range of values of the
smoothed field displayed in the "smooth" case.
"all": All four of the diagnostic plots listed above are plotted together in a two-by-two
display. Top left panel is "marks" plot. Bottom right panel is "smooth" plot. Bottom
left panel is "x" plot. Top right panel is "y" plot, rotated 90 degrees.
132 [Link]

The argument rbord ensures there are no edge effects in the computation of the residuals.
The diagnostic calculations will be confined to those points of the data pattern which are at
least rbord units away from the edge of the window. The value of rbord should be greater
than or equal to the range of interaction permitted in the model.
By default, the two-standard-deviation limits are calculated from the exact formula for the
asymptotic variance of the residuals under the asymptotic normal approximation, equation
(37) of Baddeley et al (2006). However, for compatibility with the original paper of Baddeley
et al (2005), if oldstyle=TRUE, the two-standard-deviation limits are calculated using the
innovation variance, an over-estimate of the true variance of the residuals.
The argument rv would normally be used only by experts. It enables the user to substitute
arbitrary values for the residuals or marks, overriding the usual calculations. If rv is
present, then instead of calculating the residuals from the fitted model, the algorithm takes
the entries of the vector rv to be the values of the residuals or marks, and plots them in
the manner appropriate to the type of residual or mark selected by type. The length of
rv must equal the number of points in the original data point pattern (if type="eem") or
the number of quadrature (data and dummy) points used to fit the model (if type="raw",
type="inverse" or type="pearson").
The return value is an object of class "diagppm". There are methods for plot and print
for such objects. See the Examples.
See also the companion functions [Link], which produces a Q-Q plot of the residuals,
and lurking, which produces lurking variable plots for any spatial covariate.

Value
An object of class "diagppm" which contains the coordinates needed to reproduce the se-
lected plots. This object can be plotted using [Link] and printed using [Link].

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial
point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.
Baddeley, A., Moller, J. and Pakes, A.G. (2006) Properties of residuals for spatial point
processes. To appear.
Stoyan, D. and Grabarnik, P. (1991) Second-order characteristics for stochastic structures
connected with Gibbs point processes. Mathematische Nachrichten, 151:95–100.

See Also
[Link], eem, [Link], [Link], lurking, ppm

Examples
data(cells)
fit <- ppm(cells, ~x, Strauss(r=0.15))
[Link](fit)
## Not run:
[Link](fit, type="pearson")
diameter 133

## End(Not run)
[Link](fit, which="marks")
[Link](fit, type="raw", [Link]="discrete")

# save the diagnostics and plot them later


u <- [Link](fit, rbord=0.15, [Link]=FALSE)
## Not run:
plot(u)
plot(u, which="marks")

## End(Not run)

diameter Diameter of a Window

Description
Computes the diameter of a window

Usage
diameter(w)

Arguments
w A window, whose diameter will be computed.

Details
This function computes the diameter of a window of arbitrary shape, i.e. the maximum
distance between any two points in the window.
The argument w should be a window (an object of class "owin", see [Link] for details)
or can be given in any format acceptable to [Link]().

Value
The numerical value of the diameter of the window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], perimeter, owin, [Link]

Examples
w <- owin(c(0,1),c(0,1))
diameter(w)
# returns sqrt(2)
data(letterR)
diameter(letterR)
134 diameter.box3

diameter.box3 Geometrical Calculations for Three-Dimensional Box

Description
Calculates the volume, diameter, shortest side, or eroded volume of a three-dimensional
box.

Usage
diameter.box3(x)
volume.box3(x)
shortside.box3(x)
[Link](x, r)

Arguments
x Three-dimensional box (object of class "box3").
r Numeric value or vector of numeric values for which eroded volumes
should be calculated.

Details
diameter.box3 computes the diameter of the box. volume.box3 computes the volume of
the box. shortside.box3 finds the shortest of the three side lengths of the box.
[Link] computes, for each entry r[i], the volume of the smaller box obtained by
removing a slab of thickness r[i] from each face of the box. This smaller box is the subset
consisting of points that lie at least r[i] units away from the boundary of the box.

Value
For diameter.box3, shortside.box3 and volume.box3, a single numeric value. For [Link],
a numeric vector of the same length as r.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
as.box3

Examples
X <- box3(c(0,10),c(0,10),c(0,5))
diameter.box3(X)
volume.box3(X)
shortside.box3(X)
hd <- shortside.box3(X)/2
[Link](X, seq(0,hd, length=10))
DiggleGratton 135

DiggleGratton Diggle-Gratton model

Description
Creates an instance of the Diggle-Gratton pairwise interaction point process model, which
can then be fitted to point pattern data.

Usage
DiggleGratton(delta, rho)

Arguments
delta lower threshold δ
rho upper threshold ρ

Details
Diggle and Gratton (1984, pages 208-210) introduced the pairwise interaction point process
with pair potential h(t) of the form
 κ
t−δ
h(t) = if δ ≤ t ≤ ρ
ρ−δ
with h(t) = 0 for t < δ and h(t) = 1 for t > ρ. Here δ, ρ and κ are parameters.
Note that we use the symbol κ where Diggle and Gratton (1984) and Diggle, Gates and
Stibbard (1987) use β, since in spatstat we reserve the symbol β for an intensity parameter.
The parameters must all be nonnegative, and must satisfy δ ≤ ρ.
The potential is inhibitory, i.e.\ this model is only appropriate for regular point patterns.
The strength of inhibition increases with κ. For κ = 0 the model is a hard core process
with hard core radius δ. For κ = ∞ the model is a hard core process with hard core radius
ρ.
The irregular parameters δ, ρ must be given in the call to DiggleGratton, while the regular
parameter κ will be estimated.

Value
An object of class "interact" describing the interpoint interaction structure of a point
process.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Diggle, P.J., Gates, D.J. and Stibbard, A. (1987) A nonparametric estimator for pairwise-
interaction point processes. Biometrika 74, 763 – 770.
Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statis-
tical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.
136 [Link]

See Also
ppm, [Link], Pairwise

Examples
data(cells)
ppm(cells, ~1, DiggleGratton(0.05, 0.1))

[Link] Areas of Morphological Dilations

Description
Computes the areas of successive morphological dilations.

Usage
[Link](X, r, W=NULL, ..., exact = FALSE)

Arguments
X Object to be dilated. A point pattern (object of class "ppp"), a line
segment pattern (object of class "psp"), or a window (object of class
"owin").
r Numeric vector of radii for the dilations.
W Optional. Window (object of class "owin") inside which the areas will be
computed, or NULL indicating the entire area should be computed.
... Ignored.
exact Logical flag indicating whether areas should be computed using analytic
geometry (which is slower but more accurate). Currently available only
when X is a point pattern.

Details
This function computes the areas of the dilations of X by each of the radii r[i]. Areas may
also be computed inside a specified window W.
The morphological dilation of a set X by a distance r > 0 is the subset consisting of all
points x such that the distance from x to X is less than or equal to r.
When X is a point pattern, the dilation by a distance r is the union of discs of radius r
centred at the points of X.
The argument r should be a vector of nonnegative numbers.
If exact=TRUE and if X is a point pattern, then the areas are computed using analytic
geometry, which is slower but much more accurate. Otherwise the computation is performed
using distmap.
To compute the dilated object itself, use dilation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
dilation 137

See Also
owin, [Link], dilation, [Link]

Examples
X <- runifpoint(10)
a <- [Link](X, c(0.1,0.2), W=square(1), exact=TRUE)

dilation Morphological Dilation

Description
Perform morphological dilation of a window, a line segment pattern or a point pattern

Usage
dilation(w, r, ...)
## S3 method for class 'owin':
dilation(w, r, ..., polygonal=NULL, tight=TRUE)
## S3 method for class 'ppp':
dilation(w, r, ..., polygonal=TRUE, tight=TRUE)
## S3 method for class 'psp':
dilation(w, r, ..., polygonal=TRUE, tight=TRUE)

Arguments
w A window (object of class "owin" or a line segment pattern (object of
class "psp") or a point pattern (object of class "ppp").
r positive number: the radius of dilation.
... extra arguments passed to [Link] controlling the pixel resolution, if the
pixel approximation is used.
polygonal Logical flag indicating whether to compute a polygonal approximation to
the erosion (polygonal=TRUE) or a pixel grid approximation (polygonal=FALSE).
tight Logical flag indicating whether the bounding frame of the window should
be taken as the smallest rectangle enclosing the dilated region (tight=TRUE),
or should be the dilation of the bounding frame of w (tight=FALSE).

Details
The morphological dilation of a set W by a distance r > 0 is the set consisting of all points
lying at most r units away from W . Effectively, dilation adds a margin of width r onto the
set W .
If polygonal=TRUE then a polygonal approximation to the dilation is computed. If polygonal=FALSE
then a pixel approximation to the dilation is computed from the distance map of w. The
arguments "..." are passed to [Link] to control the pixel resolution.
When w is a window, the default (when polygonal=NULL) is to compute a polygonal ap-
proximation if w is a rectangle or polygonal window, and to compute a pixel approximation
if w is a window of type "mask".
138 dirichlet

Value
If r > 0, an object of class "owin" representing the dilated region. If r=0, the result is
identical to w.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
erosion for the opposite operation.
owin, [Link]

Examples
w <- owin(c(0,1),c(0,1))
v <- dilation(w, 0.1)

dirichlet Dirichlet Tessellation of Point Pattern

Description
Computes the Dirichlet/Voronoi tessellation of a spatial point pattern.

Usage
dirichlet(X)

Arguments
X Spatial point pattern (object of class "ppp").

Details
In a spatial point pattern X, the Dirichlet/Voronoi tile associated with a particular point
X[i] is the region of space that is closer to X[i] than to any other point in X. The Dirichlet
tiles divide the two-dimensional plane into disjoint regions, forming a tessellation.
This function computes the Dirichlet tessellation (within the original window of X).

Value
A tessellation (object of class "tess").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
tess, delaunay, ppp
[Link] 139

Examples
X <- runifpoint(42)
plot(dirichlet(X))
plot(X, add=TRUE)

[Link] Compute Quadrature Weights Based on Dirichlet Tessellation

Description
Computes quadrature weights for a given set of points, using the areas of tiles in the Dirichlet
tessellation.

Usage
[Link](X, window=NULL, exact=TRUE, ...)

Arguments
X Data defining a point pattern.
window Default window for the point pattern
exact Logical value. If TRUE, compute exact areas using the package deldir. If
FALSE, compute approximate areas using a pixel raster.
... Ignored.

Details
This function computes a set of quadrature weights for a given pattern of points (typically
comprising both “data” and ‘dummy” points). See [Link] for an explanation of
quadrature weights and quadrature schemes.
The weights are computed using the Dirichlet tessellation. First X and (optionally) window
are converted into a point pattern object. Then the Dirichlet tessellation of the points of
X is computed. The weight attached to a point of X is the area of its Dirichlet tile (inside
the window X$window).
If exact=TRUE the Dirichlet tessellation is computed exactly by the Lee-Schachter algorithm
using the package deldir. Otherwise a pixel raster approximation is constructed and the
areas are approximations to the true weights. In all cases the sum of the weights is equal
to the area of the window.

Value
Vector of nonnegative weights for each point in X.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], gridweights
140 disc

Examples
Q <- quadscheme(runifpoispp(10))
X <- [Link](Q) # data and dummy points together
w <- [Link](X, exact=FALSE)

disc Circular Window

Description
Creates a circular window

Usage
disc(radius=1, centre=c(0,0), ..., mask=FALSE, npoly=128)

Arguments
radius Radius of the circle.
centre Coordinates of the centre of the circle.
mask Logical flag controlling the type of approximation to a perfect circle. See
Details.
npoly Number of edges of the polygonal approximation, if mask=FALSE.
... Arguments passed to [Link] determining the pixel resolution, if mask=TRUE.

Details
This command creates a window object representing a disc, with the given radius and
centre.
By default, the circle is approximated by a polygon with npoly edges.
If mask=TRUE, then the disc is approximated by a binary pixel mask. The resolution of the
mask is controlled by the arguments ... which are passed to [Link].

Value
An object of class "owin" (see [Link]) specifying a window.

Note
This function can also be used to generate regular polygons, by setting npoly to a small
integer value. For example npoly=5 generates a pentagon and npoly=13 a triskaidecagon.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], owin, [Link]
discpartarea 141

Examples
# unit disc
W <- disc()
# disc of radius 3 centred at x=10, y=5
W <- disc(3, c(10,5))
#
plot(disc())
plot(disc(mask=TRUE))
# nice smooth circle
plot(disc(npoly=256))
# how to control the resolution of the mask
plot(disc(mask=TRUE, dimyx=256))
# check accuracy of approximation
[Link](disc())/pi
[Link](disc(mask=TRUE))/pi

discpartarea Area of Part of Disc

Description
Compute area of intersection between a disc and a window

Usage
discpartarea(X, r, W=[Link](X))

Arguments
X Point pattern (object of class "ppp") specifying the centres of the discs.
Alternatively, X may be in any format acceptable to [Link].
r Matrix, vector or numeric value specifying the radii of the discs.
W Window (object of class "owin") with which the discs should be inter-
sected.

Details
This algorithm computes the exact area of the intersection between a window W and a disc
(or each of several discs). The centres of the discs are specified by the point pattern X, and
their radii are specified by r.
If r is a single numeric value, then the algorithm computes the area of intersection between
W and the disc of radius r centred at each point of X, and returns a one-column matrix
containing one entry for each point of X.
If r is a vector of length m, then the algorithm returns an n * m matrix in which the entry
on row i, column j is the area of the intersection between W and the disc centred at X[i]
with radius r[j].
If r is a matrix, it should have one row for each point in X. The algorithm returns a matrix
in which the entry on row i, column j is the area of the intersection between W and the disc
centred at X[i] with radius r[i,j].
Areas are computed by analytic geometry.
142 discretise

Value
Numeric matrix, with one row for each point of X.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, disc

Examples
data(letterR)
X <- runifpoint(3, letterR)
discpartarea(X, 0.2)

discretise Safely Convert Point Pattern Window to Binary Mask

Description
Given a point pattern, discretise its window by converting it to a binary pixel mask, ad-
justing the mask so that it still contains all the points.

Usage
discretise(X, eps = NULL, dimyx = NULL, xy = NULL)

Arguments
X A point pattern (object of class "ppp") to be converted.
eps (optional) width and height of each pixel
dimyx (optional) pixel array dimensions
xy (optional) pixel coordinates

Details
This function modifies the point pattern X by converting its observation window X$window
to a binary pixel image (a window of type "mask"). It ensures that no points of X are
deleted by the discretisation.
The window is first discretised using [Link]. It can happen that points of X that were
inside the original window may fall outside the new mask. The discretise function corrects
this by augmenting the mask (so that the mask includes any pixel that contains a point of
the pattern).
The arguments eps, dimyx and xy control the fineness of the pixel array. They are passed
to [Link].
If eps, dimyx and xy are all absent or NULL, and if the window of X is of type "mask" to
start with, then discretise(X) returns X unchanged.
See [Link] for further details about the arguments eps, dimyx, and xy, and the process
of converting a window to one of type mask.
distfun 143

Value
A point pattern (object of class "ppp"), identical to X, except that its observation window
has been converted to one of type mask.

Error checking
Before doing anything, discretise checks that all the points of the pattern are actually
inside the original window. This is guaranteed to be the case if the pattern was constructed
using ppp or [Link]. However anomalies are possible if the point pattern was created or
manipulated inappropriately. These will cause an error.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link]

Examples
data(demopat)
X <- demopat
plot(X, main="original pattern")
Y <- discretise(X, dimyx=50)
plot(Y, main="discretise(X)")
stopifnot(X$n == Y$n)

# what happens if we just convert the window to a mask?


W <- X$window
M <- [Link](W, dimyx=50)
plot(M, main="window of X converted to mask")
plot(X, add=TRUE, pch=16)
plot(X[M], add=TRUE, pch=1, cex=1.5)
XM <- X[M]
cat(paste(X$n - XM$n, "points of X lie outside M\n"))

distfun Distance Map as a Function

Description
Compute the distance function of an object, and return it as a function.

Usage
distfun(X, ...)
## S3 method for class 'ppp':
distfun(X, ...)
## S3 method for class 'psp':
distfun(X, ...)
## S3 method for class 'owin':
distfun(X, ..., invert=FALSE)
144 distmap

Arguments
X Any suitable dataset representing a two-dimensional object, such as a
point pattern (object of class "ppp"), a window (object of class "owin")
or a line segment pattern (object of class "psp").
... Extra arguments are ignored.
invert If TRUE, compute the distance transform of the complement of X.

Details
The “distance function” of a set of points A is the mathematical function f such that, for any
two-dimensional spatial location (x, y), the function value f(x,y) is the shortest distance
from (x, y) to A.
The command f <- distfun(X) returns a function in the R language, with arguments
x,y, that represents the distance function of X. Evaluating the function f in the form v <-
f(x,y), where x and y are any numeric vectors of equal length containing coordinates of
spatial locations, yields the values of the distance function at these locations.
This should be contrasted with the related command distmap which computes the distance
function of X on a grid of locations, and returns the distance values in the form of a pixel
image.

Value
A function with arguments x,y. The function also belongs to the class "distfun" for
which there is a print method and a plot method.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
distmap

Examples
data(letterR)
f <- distfun(letterR)
f(0.2, 0.3)

distmap Distance Map

Description
Compute the distance map of an object, and return it as a pixel image. Generic.

Usage
distmap(X, ...)
[Link] 145

Arguments
X Any suitable dataset representing a two-dimensional object, such as a
point pattern (object of class "ppp"), a window (object of class "owin")
or a line segment pattern (object of class "psp").
... Arguments passed to [Link] to control pixel resolution.

Details
The “distance map” of a set of points A is the function f whose value f(x) is defined for
any two-dimensional location x as the shortest distance from x to A.
This function computes the distance map of the set X and returns the distance map as a
pixel image.
This is generic. Methods are provided for point patterns ([Link]), line segment
patterns ([Link]) and windows ([Link]).

Value
A pixel image (object of class "im") whose grey scale values are the values of the distance
map.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link], distfun

Examples
data(cells)
U <- distmap(cells)
data(letterR)
V <- distmap(letterR)
## Not run:
plot(U)
plot(V)

## End(Not run)

[Link] Distance Map of Window

Description
Computes the distance from each pixel to the nearest point in the given window.

Usage
## S3 method for class 'owin':
distmap(X, ..., discretise=FALSE, invert=FALSE)
146 [Link]

Arguments
X A window (object of class "owin").
... Arguments passed to [Link] to control pixel resolution.
discretise Logical flag controlling the choice of algorithm when X is a polygonal
window. See Details.
invert If TRUE, compute the distance transform of the complement of the window.

Details
The “distance map” of a window W is the function f whose value f(u) is defined for any
two-dimensional location u as the shortest distance from u to W .
This function computes the distance map of the window X and returns the distance map as
a pixel image. The greyscale value at a pixel u equals the distance from u to the nearest
pixel in X.
Additionally, the return value has an attribute "bdry" which is also a pixel image. The
grey values in "bdry" give the distance from each pixel to the bounding rectangle of the
image.
If X is a binary pixel mask, the distance values computed are not the usual Euclidean
distances. Instead the distance between two pixels is measured by the length of the shortest
path connecting the two pixels. A path is a series of steps between neighbouring pixels
(each pixel has 8 neighbours). This is the standard ‘distance transform’ algorithm of image
processing (Rosenfeld and Kak, 1968; Borgefors, 1986).
If X is a polygonal window, then exact Euclidean distances will be computed if discretise=FALSE.
If discretise=TRUE then the window will first be converted to a binary pixel mask and the
discrete path distances will be computed.
The arguments ... are passed to [Link] to control the pixel resolution.
This function is a method for the generic distmap.

Value
A pixel image (object of class "im") whose greyscale values are the values of the distance
map. The return value has an attribute "bdry" which is a pixel image.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Borgefors, G. Distance transformations in digital images. Computer Vision, Graphics and
Image Processing 34 (1986) 344–371.
Rosenfeld, A. and Pfalz, J.L. Distance functions on digital pictures. Pattern Recognition 1
(1968) 33-61.

See Also
distmap, [Link], [Link]
[Link] 147

Examples
data(letterR)
U <- distmap(letterR)
## Not run:
plot(U)
plot(attr(U, "bdry"))

## End(Not run)

[Link] Distance Map of Point Pattern

Description
Computes the distance from each pixel to the nearest point in the given point pattern.

Usage
## S3 method for class 'ppp':
distmap(X, ...)

Arguments
X A point pattern (object of class "ppp").
... Arguments passed to [Link] to control pixel resolution.

Details
The “distance map” of a point pattern X is the function f whose value f(u) is defined for
any two-dimensional location u as the shortest distance from u to X.
This function computes the distance map of the point pattern X and returns the distance
map as a pixel image. The greyscale value at a pixel u equals the distance from u to the
nearest point of the pattern X.
Additionally, the return value has two attributes, "index" and "bdry", which are also
pixel images. The grey values in "bdry" give the distance from each pixel to the bounding
rectangle of the image. The grey values in "index" are integers identifying which point of
X is closest.
This is a method for the generic function distmap.

Value
A pixel image (object of class "im") whose greyscale values are the values of the distance
map. The return value has attributes "index" and "bdry" which are also pixel images.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
distmap, [Link], [Link]
148 [Link]

Examples
data(cells)
U <- distmap(cells)
## Not run:
plot(U)
plot(attr(U, "bdry"))
plot(attr(U, "index"))

## End(Not run)

[Link] Distance Map of Line Segment Pattern

Description
Computes the distance from each pixel to the nearest line segment in the given line segment
pattern.

Usage
## S3 method for class 'psp':
distmap(X, ...)

Arguments
X A line segment pattern (object of class "psp").
... Arguments passed to [Link] to control pixel resolution.

Details
The “distance map” of a line segment pattern X is the function f whose value f(u) is
defined for any two-dimensional location u as the shortest distance from u to X.
This function computes the distance map of the line segment pattern X and returns the
distance map as a pixel image. The greyscale value at a pixel u equals the distance from
u to the nearest line segment of the pattern X. Distances are computed using analytic
geometry.
Additionally, the return value has two attributes, "index" and "bdry", which are also
pixel images. The grey values in "bdry" give the distance from each pixel to the bounding
rectangle of the image. The grey values in "index" are integers identifying which line
segment of X is closest.
This is a method for the generic function distmap.
Note that this function gives the exact distance from the centre of each pixel to the nearest
line segment. To compute the exact distance from the points in a point pattern to the
nearest line segment, use nncross or project2segment.

Value
A pixel image (object of class "im") whose greyscale values are the values of the distance
map. The return value has attributes "index" and "bdry" which are also pixel images.
[Link] 149

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
distmap, [Link], [Link], nncross, nearestsegment, project2segment.

Examples
a <- psp(runif(20),runif(20),runif(20),runif(20), window=owin())
Z <- distmap(a)
plot(Z)
plot(a, add=TRUE)

[Link] Extract Dummy Points Used to Fit a Point Process Model

Description
Given a fitted point process model, this function extracts the ‘dummy points’ of the quadra-
ture scheme used to fit the model.

Usage
[Link](object, drop=FALSE)

Arguments
object fitted point process model (an object of class "ppm").
drop Logical value determining whether to delete dummy points that were not
used to fit the model.

Details
An object of class "ppm" represents a point process model that has been fitted to data. It
is typically produced by the model-fitting algorithm ppm.
The maximum pseudolikelihood algorithm in ppm approximates the pseudolikelihood inte-
gral by a sum over a finite set of quadrature points, which is constructed by augmenting the
original data point pattern by a set of “dummy” points. The fitted model object returned by
ppm contains complete information about this quadrature scheme. See ppm or [Link]
for further information.
This function [Link] extracts the dummy points of the quadrature scheme. A typical
use of this function would be to count the number of dummy points, to gauge the accuracy
of the approximation to the exact pseudolikelihood.
It may happen that some dummy points are not actually used in fitting the model (typically
because the value of a covariate is NA at these points). The argument drop specifies whether
these unused dummy points shall be deleted (drop=TRUE) or retained (drop=FALSE) in the
return value.
See [Link] for a list of all operations that can be performed on objects of class "ppm".
150 [Link]

Value
A point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], ppm

Examples
data(cells)
fit <- ppm(cells, ~1, Strauss(r=0.1))
X <- [Link](fit)
X$n
# this is the number of dummy points in the quadrature scheme

[Link] Determine Duplicated Points in a Spatial Point Pattern

Description
Determines which points in a spatial point pattern are duplicates of previous points, and
returns a logical vector.

Usage
## S3 method for class 'ppp':
duplicated(x, ...)

Arguments
x A spatial point pattern (object of class "ppp").
... Ignored.

Details
This is a method for the generic function duplicated for point pattern datasets (of class
"ppp", see [Link]).
Two points in a point pattern are deemed to be identical if their x, y coordinates are the
same, and their marks are also the same (if they carry marks). The Examples section
illustrates how it is possible for a point pattern to contain a pair of identical points.
This function determines which points in x duplicate other points that appeared earlier in
the sequence. It returns a logical vector with entries that are TRUE for duplicated points
and FALSE for unique (non-duplicated) points.

Value
A logical vector of length equal to the number of points in x.
eem 151

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
X <- ppp(c(1,1,0.5), c(2,2,1), window=square(3))
duplicated(X)

eem Exponential Energy Marks

Description
Given a point process model fitted to a point pattern, compute the Stoyan-Grabarnik
diagnostic “exponential energy marks” for the data points.

Usage
eem(fit, check=TRUE)

Arguments
fit The fitted point process model. An object of class "ppm".
check Logical value indicating whether to check the internal format of fit. If
there is any possibility that this object has been restored from a dump
file, or has otherwise lost track of the environment where it was originally
computed, set check=TRUE.

Details
Stoyan and Grabarnik (1991) proposed a diagnostic tool for point process models fitted
to spatial point pattern data. Each point x[i] of the data pattern X is given a ‘mark’ or
‘weight’
m[i] = 1/lambda − hat(x[i], X)
where lambda − hat(x[i], X) is the conditional intensity of the fitted model. If the fitted
model is correct, then the sum of these marks for all points in a region B has expected
value equal to the area of B.
The argument fit must be a fitted point process model (object of class "ppm"). Such
objects are produced by the maximum pseudolikelihood fitting algorithm ppm). This fitted
model object contains complete information about the original data pattern and the model
that was fitted to it.
The value returned by eem is the vector of weights m[i] associated with the points x[i] of the
original data pattern. The original data pattern (in corresponding order) can be extracted
from fit using [Link].
The function [Link] produces a set of sensible diagnostic plots based on these
weights.
152 effectfun

Value

A vector containing the values of the exponential energy mark for each point in the pattern.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Stoyan, D. and Grabarnik, P. (1991) Second-order characteristics for stochastic structures


connected with Gibbs point processes. Mathematische Nachrichten, 151:95–100.

See Also

[Link], [Link], [Link], [Link], ppm

Examples

data(cells)
fit <- ppm(cells, ~x, Strauss(r=0.15))
ee <- eem(fit)
sum(ee)/[Link](cells$window) # should be about 1 if model is correct
Y <- setmarks(cells, ee)
plot(Y, main="Cells data\n Exponential energy marks")

effectfun Compute Fitted Effect of a Spatial Covariate in a Point Process


Model

Description

Compute the intensity of a fitted point process model as a function of one of its covariates.

Usage

effectfun(model, covname, ...)

Arguments

model A fitted point process model (object of class "ppm").


covname The name of the covariate. A character string.
... The fixed values of other covariates (in the form name=value) if required.
Emark 153

Details
The object model should be an object of class "ppm" representing a point process model
fitted to point pattern data.
The model’s trend formula should involve a spatial covariate named covname. This could
be "x" or "y" representing one of the Cartesian coordinates. More commonly the covariate
is another, external variable that was supplied when fitting the model.
The command effectfun computes the fitted intensity of the point process model as a
function of the covariate named covname. The return value can be plotted immediately,
giving a plot of the fitted intensity against the value of the covariate.
If the model also involves covariates other than covname, then these covariates will be held
fixed. Values for these other covariates must be provided as arguments to effectfun in the
form name=value.
This command is just a wrapper for the prediction method [Link]. For more com-
plicated computations about the fitted intensity, use [Link].

Value
A data frame containing a column of values of the covariate and a column of values of the
fitted intensity.
If the covariate named covname is numeric (rather than a factor or logical variable), the
return value is also of class "fv" so that it can be plotted immediately.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, [Link], [Link]

Examples
data(copper)
X <- copper$SouthPoints
D <- distmap(copper$SouthLines)
fit <- ppm(X, ~polynom(Z, 7), covariates=list(Z=D))
plot(effectfun(fit, "Z"))
fit <- ppm(X, ~x + polynom(Z, 7), covariates=list(Z=D))
plot(effectfun(fit, "Z", x=20))

Emark Diagnostics for random marking

Description
Estimate the summary functions E(r) and V (r) for a marked point pattern, proposed by
Schlather et al (2004) as diagnostics for dependence between the points and the marks.
154 Emark

Usage
Emark(X, r=NULL,
correction=c("isotropic", "Ripley", "translate"),
method="density", ..., normalise=FALSE)
Vmark(X, r=NULL,
correction=c("isotropic", "Ripley", "translate"),
method="density", ..., normalise=FALSE)

Arguments
X The observed point pattern. An object of class "ppp" or something ac-
ceptable to [Link]. The pattern should have numeric marks.
r Optional. Numeric vector. The values of the argument r at which the
function E(r) or V (r) should be evaluated. There is a sensible default.
correction A character vector containing any selection of the options "isotropic",
"Ripley" or "translate". It specifies the edge correction(s) to be ap-
plied.
method A character vector indicating the user’s choice of density estimation tech-
nique to be used. Options are "density", "loess", "sm" and "smrep".
... Arguments passed to the density estimation routine (density, loess or
[Link]) selected by method.
normalise IfTRUE, normalise the estimate of E(r) or V (r) so that it would have value
equal to 1 if the marks are independent of the points.

Details
For a marked point process, Schlather et al (2004) defined the functions E(r) and V (r) to
be the conditional mean and conditional variance of the mark attached to a typical random
point, given that there exists another random point at a distance r away from it.
More formally,
E(r) = E0u [M (0)]
and
V (r) = E0u [(M (0) − E(u))2 ]
where E0u denotes the conditional expectation given that there are points of the process at
the locations 0 and u separated by a distance r, and where M (0) denotes the mark attached
to the point 0.
These functions may serve as diagnostics for dependence between the points and the marks.
If the points and marks are independent, then E(r) and V (r) should be constant (not
depending on r). See Schlather et al (2004).
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern with numeric marks.
The argument r is the vector of values for the distance r at which kf (r) is estimated.
This algorithm assumes that X can be treated as a realisation of a stationary (spatially
homogeneous) random spatial point process in the plane, observed through a bounded
window. The window (which is specified in X as X$window) may have arbitrary shape.
Biases due to edge effects are treated in the same manner as in Kest. The edge corrections
implemented here are
Emark 155

isotropic/Ripley Ripley’s isotropic correction (see Ripley, 1988; Ohser, 1983). This is
implemented only for rectangular and polygonal windows (not for binary masks).
translate Translation correction (Ohser, 1983). Implemented for all window geometries,
but slow for complex windows.
Note that the estimator assumes the process is stationary (spatially homogeneous).
The numerator and denominator of the mark correlation function (in the expression above)
are estimated using density estimation techniques. The user can choose between
"density" which uses the standard kernel density estimation routine density, and works
only for evenly-spaced r values;
"loess" which uses the function loess in the package modreg;
"sm" which uses the function [Link] in the package sm and is extremely slow;
"smrep" which uses the function [Link] in the package sm and is relatively fast, but
may require manual control of the smoothing parameter hmult.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns
r the values of the argument r at which the function E(r) or V (r) has been
estimated
theo the theoretical, constant value of E(r) or V (r) when the marks attached
to different points are independent
together with a column or columns named "iso" and/or "trans", according to the selected
edge corrections. These columns contain estimates of the function E(r) or V (r) obtained
by the edge corrections named.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Schlather, M. and Ribeiro, P. and Diggle, P. (2004) Detecting dependence between marks
and locations of marked point processes. Journal of the Royal Statistical Society, series B
66 (2004) 79-83.

See Also
Mark correlation markcorr, mark variogram markvario for numeric marks.
Mark connection function markconnect and multitype K-functions Kcross, Kdot for factor-
valued marks.

Examples
data(spruces)

plot(Emark(spruces))
E <- Emark(spruces, method="density", kernel="epanechnikov")
plot(Vmark(spruces))
156 [Link]

[Link] Endpoints of Line Segment Pattern

Description
Extracts the endpoints of each line segment in a line segment pattern.

Usage
[Link](x, which="both")

Arguments
x A line segment pattern (object of class "psp").
which String specifying which endpoint or endpoints should be returned. See
Details.

Details
This function extracts one endpoint, or both endpoints, from each of the line segments in
x, and returns these points as a point pattern object.
The argument which determines which endpoint or endpoints of each line segment should
be returned:

which="both" (the default): both endpoints of each line segment are returned. The result
is a point pattern with twice as many points as there are line segments in x.
which="first" select the first endpoint of each line segment (returns the points with co-
ordinates x$ends$x0, x$ends$y0).
which="second" select the second endpoint of each line segment (returns the points with
coordinates x$ends$x1, x$ends$y1).
which="left" select the left-most endpoint (the endpoint with the smaller x coordinate)
of each line segment.
which="right" select the right-most endpoint (the endpoint with the greater x coordinate)
of each line segment.
which="lower" select the lower endpoint (the endpoint with the smaller y coordinate) of
each line segment.
which="upper" select the upper endpoint (the endpoint with the greater y coordinate) of
each line segment.

The result is a point pattern. It also has an attribute "id" which is an integer vector
identifying the segment which contributed each point.

Value
Point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
envelope 157

See Also
[Link], [Link], [Link]

Examples
a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
plot(a)
b <- [Link](a, "left")
plot(b, add=TRUE)

envelope Simulation envelopes of summary function

Description
Computes simulation envelopes of a summary function.

Usage
envelope(Y, fun=Kest, nsim=99, nrank=1, ...,
simulate=NULL, verbose=TRUE, clipdata=TRUE,
start=NULL,control=list(nrep=1e5,expand=1.5),
transform=NULL,global=FALSE,ginterval=NULL,
savefuns=FALSE, savepatterns=FALSE,
nsim2=nsim, VARIANCE=FALSE, nSD=2, Yname=NULL, internal=NULL)

Arguments
Y Either a point pattern (object of class "ppp") or a fitted point process
model (object of class "ppm" or "kppm").
fun Function that computes the desired summary statistic for a point pattern.
nsim Number of simulated point patterns to be generated when computing the
envelopes.
nrank Integer. Rank of the envelope value amongst the nsim simulated values.
A rank of 1 means that the minimum and maximum simulated values will
be used.
... Extra arguments passed to fun.
simulate Optional. Specifies how to generate the simulated point patterns. If
simulate is an expression in the R language, then this expression will be
evaluated nsim times, to obtain nsim point patterns which are taken as the
simulated patterns from which the envelopes are computed. If simulate
is a list of point patterns, then the entries in this list will be treated as the
simulated patterns from which the envelopes are computed. Alternatively
simulate may be an object produced by the envelope command: see
Details.
verbose Logical flag indicating whether to print progress reports during the sim-
ulations.
158 envelope

clipdata Logical flag indicating whether the data point pattern should be clipped to
the same window as the simulated patterns, before the summary function
for the data is computed. This should usually be TRUE to ensure that the
data and simulations are properly comparable.
start,control Optional. These specify the arguments start and control of rmh, giving
complete control over the simulation algorithm.
transform Optional. A transformation to be applied to the function values, before
the envelopes are computed. An expression object (see Details).
global Logical flag indicating whether envelopes should be pointwise (global=FALSE)
or simultaneous (global=TRUE).
ginterval Optional. A vector of length 2 specifying the interval of r values for the
simultaneous critical envelopes. Only relevant if global=TRUE.
savefuns Logical flag indicating whether to save all the simulated function values.
savepatterns Logical flag indicating whether to save all the simulated point patterns.
nsim2 Number of extra simulated point patterns to be generated if it is neces-
sary to use simulation to estimate the theoretical mean of the summary
function. Only relevant when global=TRUE and the simulations are not
based on CSR.
VARIANCE Logical. If TRUE, critical envelopes will be calculated as sample mean plus
or minus nSD times sample standard deviation.
nSD Number of estimated standard deviations used to determine the critical
envelopes, if VARIANCE=TRUE.
Yname Character string that should be used as the name of the data point pattern
Y when printing or plotting the results.
internal Do not use this argument. It is used by the package’s internal code.

Details
Simulation envelopes can be used to assess the goodness-of-fit of a point process model to
point pattern data. See the References.
This function first generates nsim random point patterns in one of the following ways.

ˆ If Y is a point pattern (an object of class "ppp") and simulate=NULL, then this routine
generates nsim simulations of Complete Spatial Randomness (i.e. nsim simulated point
patterns each being a realisation of the uniform Poisson point process) with the same
intensity as the pattern Y. (If Y is a multitype point pattern, then the simulated
patterns are also given independent random marks; the probability distribution of the
random marks is determined by the relative frequencies of marks in Y.)
ˆ If Y is a fitted point process model (an object of class "ppm" or "kppm") and simulate=NULL,
then this routine generates nsim simulated realisations of that model.
ˆ If simulate is supplied, then it determines how the simulated point patterns are
generated. It may be either
– an expression in the R language, typically containing a call to a random generator.
This expression will be evaluated nsim times to yield nsim point patterns. For ex-
ample if simulate=expression(runifpoint(100)) then each simulated pattern
consists of exactly 100 independent uniform random points.
– a list of point patterns. The entries in this list will be taken as the simulated
patterns.
envelope 159

– an object of class "envelope". This should have been produced by calling envelope
with the argument savepatterns=TRUE. The simulated point patterns that were
saved in this object will be extracted and used as the simulated patterns for the
new envelope computation. This makes it possible to plot envelopes for two differ-
ent summary functions based on exactly the same set of simulated point patterns.

The summary statistic fun is applied to each of these simulated patterns. Typically fun
is one of the functions Kest, Gest, Fest, Jest, pcf, Kcross, Kdot, Gcross, Gdot, Jcross,
Jdot, Kmulti, Gmulti, Jmulti or Kinhom. It may also be a character string containing the
name of one of these functions.
The statistic fun can also be a user-supplied function; if so, then it must have arguments X
and r like those in the functions listed above, and it must return an object of class "fv".
Upper and lower critical envelopes are computed in one of the following ways:

pointwise: by default, envelopes are calculated pointwise (i.e. for each value of the distance
argument r), by sorting the nsim simulated values, and taking the m-th lowest and m-
th highest values, where m = nrank. For example if nrank=1, the upper and lower
envelopes are the pointwise maximum and minimum of the simulated values.
The pointwise envelopes are not “confidence bands” for the true value of the function!
Rather, they specify the critical points for a Monte Carlo test (Ripley, 1981). The
test is constructed by choosing a fixed value of r, and rejecting the null hypothesis if
the observed function value lies outside the envelope at this value of r. This test has
exact significance level alpha = 2 * nrank/(1 + nsim).
simultaneous: if global=TRUE, then the envelopes are determined as follows. First we
calculate the theoretical mean value of the summary statistic (if we are testing CSR,
the theoretical value is supplied by fun; otherwise we perform a separate set of nsim2
simulations, compute the average of all these simulated values, and take this average
as an estimate of the theoretical mean value). Then, for each simulation, we compare
the simulated curve to the theoretical curve, and compute the maximum absolute
difference between them (over the interval of r values specified by ginterval). This
gives a deviation value di for each of the nsim simulations. Finally we take the m-
th largest of the deviation values, where m=nrank, and call this dcrit. Then the
simultaneous envelopes are of the form lo = expected - dcrit and hi = expected
+ dcrit where expected is either the theoretical mean value theo (if we are testing
CSR) or the estimated theoretical value mmean (if we are testing another model). The
simultaneous critical envelopes have constant width 2 * dcrit.
The simultaneous critical envelopes allow us to perform a different Monte Carlo test
(Ripley, 1981). The test rejects the null hypothesis if the graph of the observed function
lies outside the envelope at any value of r. This test has exact significance level alpha
= nrank/(1 + nsim).
based on sample moments: if VARIANCE=TRUE, the algorithm calculates the (pointwise)
sample mean and sample variance of the simulated functions. Then the envelopes are
computed as mean plus or minus nSD standard deviations. These envelopes do not have
an exact significance interpretation. They are a naive approximation to the critical
points of the Neyman-Pearson test assuming the summary statistic is approximately
Normally distributed.

The return value is an object of class "fv" containing the summary function for the data
point pattern, the upper and lower simulation envelopes, and the theoretical expected value
(exact or estimated) of the summary function for the model being tested. It can be plotted
using [Link].
160 envelope

If VARIANCE=TRUE then the return value also includes the sample mean, sample variance
and other quantities.
Arguments can be passed to the function fun through .... This makes it possible to select
the edge correction used to calculate the summary statistic. See the Examples. Selecting
only a single edge correction will make the code run much faster.
If Y is a fitted cluster point process model (object of class "kppm"), and simulate=NULL,
then the model is simulated directly using [Link].
If Y is a fitted Gibbs point process model (object of class "ppm"), and simulate=NULL,
then the model is simulated by running the Metropolis-Hastings algorithm rmh. Complete
control over this algorithm is provided by the arguments start and control which are
passed to rmh.
For simultaneous critical envelopes (global=TRUE) the following options are also useful:
ginterval determines the interval of r values over which the deviation between curves is
calculated. It should be a numeric vector of length 2. There is a sensible default
(namely, the recommended plotting interval for fun(X), or the range of r values if r
is explicitly specified).
transform specifies a transformation of the summary function fun that will be carried out
before the deviations are computed. It must be an expression object using the symbol .
to represent the function value. For example, the conventional way to
p normalise the K
function (Ripley, 1981) is to transform it to the L function L(r) = K(r)/π and this
is implemented by setting transform=expression(sqrt(./pi)). Such transforms are
only useful if global=TRUE.
It is also possible to extract the summary functions for each of the individual simulated
point patterns, by setting savefuns=TRUE. Then the return value also has an attribute
"simfuns" containing all the summary functions for the individual simulated patterns. It
is an "fv" object containing functions named sim1, sim2, ... representing the nsim
summary functions.
It is also possible to save the simulated point patterns themselves, by setting savepatterns=TRUE.
Then the return value also has an attribute "simpatterns" which is a list of length nsim
containing all the simulated point patterns.

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing columns
r the vector of values of the argument r at which the summary function
fun has been estimated
obs values of the summary function for the data point pattern
lo lower envelope of simulations
hi upper envelope of simulations
and either
theo theoretical value of the summary function under CSR (Complete Spatial
Randomness, a uniform Poisson point process) if the simulations were
generated according to CSR
mmean estimated theoretical value of the summary function, computed by aver-
aging simulated values, if the simulations were not generated according
to CSR.
envelope 161

Additionally, if savepatterns=TRUE, the return value has an attribute "simpatterns"


which is a list containing the nsim simulated patterns. If savefuns=TRUE, the return value
has an attribute "simfuns" which is an object of class "fv" containing the summary func-
tions computed for each of the nsim simulated patterns.

Warning
An error may be generated if one of the simulations produces a point pattern that is empty,
or is otherwise unacceptable to the function fun.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Arnold, 2003.
Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.

See Also
[Link], [Link], Kest, Gest, Fest, Jest, pcf, ppp, ppm

Examples
data(simdat)
X <- simdat

# Envelope of K function under CSR


## Not run:
plot(envelope(X))

## End(Not run)

# Translation edge correction (this is also FASTER):


## Not run:
plot(envelope(X, correction="translate"))

## End(Not run)

# Envelope of K function for simulations from Gibbs model


data(cells)
fit <- ppm(cells, ~1, Strauss(0.05))
## Not run:
plot(envelope(fit))
plot(envelope(fit), global=TRUE)

## End(Not run)
162 envelope

# Envelope of K function for simulations from cluster model


data(redwood)
fit <- kppm(redwood, ~1, "Thomas")
## Not run:
plot(envelope(fit, Gest))
plot(envelope(fit, Gest, global=TRUE))

## End(Not run)

# Envelope of G function under CSR


## Not run:
plot(envelope(X, Gest))

## End(Not run)

# Envelope of L function under CSR


# L(r) = sqrt(K(r)/pi)
## Not run:
E <- envelope(X, Kest)
plot(E, sqrt(./pi) ~ r)

## End(Not run)

# Simultaneous critical envelope for L function


# (alternatively, use Lest)
## Not run:
plot(envelope(X, Kest, transform=expression(sqrt(./pi)), global=TRUE))

## End(Not run)

# How to pass arguments needed to compute the summary functions:


# We want envelopes for Jcross(X, "A", "B")
# where "A" and "B" are types of points in the dataset 'demopat'

data(demopat)
## Not run:
plot(envelope(demopat, Jcross, i="A", j="B"))

## End(Not run)

# Use of `simulate'
## Not run:
plot(envelope(cells, Gest, simulate=expression(runifpoint(42))))
plot(envelope(cells, Gest, simulate=expression(rMaternI(100,0.02))))

## End(Not run)

# Envelope under random toroidal shifts


data(amacrine)
[Link] 163

## Not run:
plot(envelope(amacrine, Kcross, i="on", j="off",
simulate=expression(rshift(amacrine, radius=0.25))))

## End(Not run)

# Envelope under random shifts with erosion


## Not run:
plot(envelope(amacrine, Kcross, i="on", j="off",
simulate=expression(rshift(amacrine, radius=0.1, edge="erode"))))

## End(Not run)

# Envelope of INHOMOGENEOUS K-function with fitted trend


## Not run:
trend <- [Link](X, 1.5)
plot(envelope(X, Kinhom, lambda=trend,
simulate=expression(rpoispp(trend))))

## End(Not run)

# Precomputed list of point patterns


X <- rpoispp(50)
PatList <- list()
for(i in 1:20) PatList[[i]] <- runifpoint(X$n)
plot(envelope(X, Kest, nsim=20, simulate=PatList))

# re-using the same point patterns


EK <- envelope(X, Kest, nsim=10, savepatterns=TRUE)
EG <- envelope(X, Kest, nsim=10, simulate=EK)

[Link] Areas of Morphological Erosions

Description
Computes the areas of successive morphological erosions of a window.

Usage
[Link](w, r)

Arguments
w A window.
r Numeric vector of radii at which erosions will be performed.

Details
This function computes the areas of the erosions of the window w by each of the radii r[i].
The morphological erosion of a set W by a distance r > 0 is the subset consisting of all
points x ∈ W such that the distance from x to the boundary of W is greater than or equal
to r. In other words it is the result of trimming a margin of width r off the set W .
164 erosion

The argument r should be a vector of positive numbers. The argument w should be a


window (an object of class "owin", see [Link] for details) or can be given in any
format acceptable to [Link]().
Unless w is a rectangle, the computation is performed using a pixel raster approximation.
To compute the eroded window itself, use erosion.

Value
Numeric vector, of the same length as r, giving the areas of the successive erosions.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link], erosion

Examples
w <- owin(c(0,1),c(0,1))
a <- [Link](w, seq(0.01,0.49,by=0.01))

erosion Morphological Erosion

Description
Perform morphological erosion of a window, a line segment pattern or a point pattern.

Usage
erosion(w, r, ...)
## S3 method for class 'owin':
erosion(w, r, [Link]=TRUE, ...,
strict=FALSE, polygonal=NULL)
## S3 method for class 'ppp':
erosion(w, r,...)
## S3 method for class 'psp':
erosion(w, r,...)

Arguments
w A window (object of class "owin" or a line segment pattern (object of
class "psp") or a point pattern (object of class "ppp").
r positive number: the radius of erosion.
[Link] logical: if TRUE, erode the bounding rectangle as well.
... extra arguments to [Link] controlling the pixel resolution, if pixel ap-
proximation is used.
erosion 165

strict Logical flag determining the fate of boundary pixels, if pixel approxima-
tion is used. See details.
polygonal Logical flag indicating whether to compute a polygonal approximation to
the erosion (polygonal=TRUE) or a pixel grid approximation (polygonal=FALSE).

Details
The morphological erosion of a set W by a distance r > 0 is the subset consisting of all
points x ∈ W such that the distance from x to the boundary of W is greater than or equal
to r. In other words it is the result of trimming a margin of width r off the set W .
If polygonal=TRUE then a polygonal approximation to the erosion is computed. If polygonal=FALSE
then a pixel approximation to the erosion is computed from the distance map of w. The ar-
guments "..." are passed to [Link] to control the pixel resolution. The erosion consists of
all pixels whose distance from the boundary of w is strictly greater than r (if strict=TRUE)
or is greater than or equal to r (if strict=FALSE).
When w is a window, the default (when polygonal=NULL) is to compute a polygonal ap-
proximation if w is a rectangle or polygonal window, and to compute a pixel approximation
if w is a window of type "mask".
If [Link] is false, the resulting window is given the same outer, bounding rectangle
as the original window w. If [Link] is true, the original bounding rectangle is also
eroded by the same distance r.
To simply compute the area of the eroded window, use [Link].

Value
If r > 0, an object of class "owin" representing the eroded region (or NULL if this region is
empty). If r=0, the result is identical to w.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
dilation for the opposite operation.
owin, [Link], [Link]

Examples
w <- owin(c(0,1),c(0,1))
v <- erosion(w, 0.1)
# returns rectangle [0.1, 0.9] x [0.1,0.9]
## Not run:
v <- erosion(w, 0.6)
# erosion is empty

## End(Not run)
166 [Link]

[Link] Evaluate Expression Involving Function Arrays

Description
Evaluates any expression involving one or more function arrays (fasp objects) and returns
another function array.

Usage
[Link](expr, envir)

Arguments
expr An expression.
envir Optional. The environment in which to evaluate the expression.

Details
This is a wrapper to make it easier to perform pointwise calculations with the arrays of
summary functions used in spatial statistics.
A function array (object of class "fasp") can be regarded as a matrix whose entries are
functions. Objects of this kind are returned by the command alltypes.
Suppose X is an object of class "fasp". Then [Link](X+3) effectively adds 3 to the
value of every function in the array X, and returns the resulting object.
Suppose X and Y are two objects of class "fasp" which are compatible (for example the
arrays must have the same dimensions). Then [Link](X + Y) will add the corresponding
functions in each cell of the arrays X and Y, and return the resulting array of functions.
In general, expr can be any expression involving (a) the names of objects of class "fasp",
(b) scalar constants, and (c) functions which are vectorised. See the Examples.
First [Link] determines which of the variable names in the expression expr refer to
objects of class "fasp". The expression is then evaluated for each cell of the array using
[Link].
The expression expr must be vectorised. There must be at least one object of class "fasp"
in the expression. All such objects must be compatible.

Value
Another object of class "fasp".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], Kest
[Link] 167

Examples
# manipulating the K function
data(amacrine)
K <- alltypes(amacrine, "K")

# expressions involving a fasp object


[Link](K + 3)
L <- [Link](sqrt(K/pi))

# expression involving two fasp objects


[Link](K - L)

[Link] Evaluate Expression Involving Functions

Description
Evaluates any expression involving one or more function value (fv) objects, and returns
another object of the same kind.

Usage
[Link](expr, envir)

Arguments
expr An expression.
envir Optional. The environment in which to evaluate the expression.

Details
This is a wrapper to make it easier to perform pointwise calculations with the summary
functions used in spatial statistics.
An object of class "fv" is essentially a data frame containing several different statistical
estimates of the same function. Such objects are returned by Kest and its relatives.
For example, suppose X is an object of class "fv" containing several different estimates of
the Ripley’s K function K(r), evaluated at a sequence of values of r. Then [Link](X+3)
effectively adds 3 to each function estimate in X, and returns the resulting object.
Suppose X and Y are two objects of class "fv" which are compatible (in particular they have
the same vector of r values). Then [Link](X + Y) will add the corresponding function
values in X and Y, and return the resulting function.
In general, expr can be any expression involving (a) the names of objects of class "fv", (b)
scalar constants, and (c) functions which are vectorised. See the Examples.
First [Link] determines which of the variable names in the expression expr refer to objects
of class "fv". Each such name is replaced by a vector containing the function values. The
expression is then evaluated. The result should be a vector; it is taken as the new vector of
function values.
The expression expr must be vectorised. There must be at least one object of class "fv"
in the expression. All such objects must be compatible.
168 [Link]

Value
Another object of class "fv".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], Kest

Examples
# manipulating the K function
X <- rpoispp(42)
Ks <- Kest(X)

[Link](Ks + 3)
Ls <- [Link](sqrt(Ks/pi))

# manipulating two K functions


Y <- rpoispp(20)
Kr <- Kest(Y)

Kdif <- [Link](Ks - Kr)


Z <- [Link](sqrt(Ks/pi) - sqrt(Kr/pi))

[Link] Evaluate Expression Involving Pixel Images

Description
Evaluates any expression involving one or more pixel images, and returns a pixel image.

Usage
[Link](expr, envir)

Arguments
expr An expression.
envir Optional. The environment in which to evaluate the expression.

Details
This function is a wrapper to make it easier to perform pixel-by-pixel calculations in an
image.
Pixel images in spatstat are represented by objects of class "im" (see [Link]). These
are essentially matrices of pixel values, with extra attributes recording the pixel dimensions,
etc.
ewcdf 169

Suppose X is a pixel image. Then [Link](X+3) will add 3 to the value of every pixel in X,
and return the resulting pixel image.
Suppose X and Y are two pixel images with compatible dimensions: they have the same
number of pixels, the same physical size of pixels, and the same bounding box. Then
[Link](X + Y) will add the corresponding pixel values in X and Y, and return the resulting
pixel image.
In general, expr can be any expression in the R language involving (a) the names of pixel
images, (b) scalar constants, and (c) functions which are vectorised. See the Examples.
First [Link] determines which of the variable names in the expression expr refer to pixel
images. Each such name is replaced by a matrix containing the pixel values. The expression
is then evaluated. The result should be a matrix; it is taken as the matrix of pixel values.
The expression expr must be vectorised. There must be at least one pixel image in the
expression. All images must have compatible dimensions.

Value
An image object of class "im".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
# test images
X <- [Link](function(x,y) { x^2 - y^2 }, [Link]())
Y <- [Link](function(x,y) { 3 * x + y }, [Link]())

[Link](X + 3)
[Link](X - Y)
[Link](abs(X - Y))
Z <- [Link](sin(X * pi) + Y)

ewcdf Weighted Empirical Cumulative Distribution Function

Description
Compute a weighted version of the empirical cumulative distribution function.

Usage
ewcdf(x, weights = rep(1/length(x), length(x)))

Arguments
x Numeric vector of observations.
weights Numeric vector of non-negative weights for x.
170 [Link]

Details

This is a modification of the standard function ecdf allowing the observations x to have
weights.
The weighted e.c.d.f. (empirical cumulative distribution function) Fn is defined so that, for
any real number y, the value of Fn(y) is equal to the total weight of all entries of x that
are less than or equal to y. That is Fn(y) = sum(weights[x <= y]).
Thus Fn is a step function which jumps at the values of x. The height of the jump at a
point y is the total weight of all entries in x number of tied observations at that value.
Missing values are ignored.
If weights is omitted, the default is equivalent to ecdf(x).

Value

A function, of class "ecdf", inheriting from "stepfun".

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

ecdf

Examples
x <- rnorm(100)
w <- runif(100)
plot(ewcdf(x,w))

[Link] Expand Window By Factor

Description
Expands the bounding box of a window by a given factor.

Usage

[Link](W, f=1)

Arguments
W A window.
f Scalar factor for expansion of the area of the window.
[Link] 171

Details
The argument w should be a window (an object of class "owin", see [Link] for details)
or can be given in any format acceptable to [Link]().
The bounding box of the window W is expanded by a scale factor equal to the square root of
f in both the x and y directions, so that the area increases by a factor f. The centre of this
expanded rectangle is the same as the centre of the original bounding box. The expanded
rectangle is returned.
This quirky little function exists mainly for reference, as it is the rule for calculating window
expansion in our implementation of the Metropolis-Hastings algorithm [Link].
For general transformations of the scale, location and orientation of a window, see shift,
affine and rotate.

Value
A rectangular window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link], shift, rotate, affine

Examples
w <- square(1)
[Link](w, 9)
# returns the square [-1,2] x [-1,2]

[Link] Extract Subset of Function Array

Description
Extract a subset of a function array (an object of class "fasp").

Usage
## S3 method for class 'fasp':
x[I, J, drop=TRUE,...]

Arguments
x A function array. An object of class "fasp".
I any valid expression for a subset of the row indices of the array.
J any valid expression for a subset of the column indices of the array.
drop Logical. When the selected subset consists of only one cell of the array, if
drop=FALSE the result is still returned as a 1 × 1 array of functions (class
"fasp") while if drop=TRUE it is returned as a function (class "fv").
... Ignored.
172 [Link]

Details

A function array can be regarded as a matrix whose entries are functions. See [Link]
for an explanation of function arrays.
This routine extracts a sub-array according to the usual conventions for matrix indexing.

Value

A function array (of class "fasp"). Exceptionally, if the array has only one cell, and if
drop=TRUE, then the result is a function value table (class "fv").

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link]

Examples
# Lansing woods data - multitype points with 6 types
data(lansing)

# compute 6 x 6 array of all cross-type K functions


a <- alltypes(lansing, "K")

# extract first three marks only


b <- a[1:3,1:3]
## Not run: plot(b)
# subset pertaining to hickories
h <- a[levels(lansing$marks) == "hickory", ]
## Not run: plot(h)

[Link] Extract Subset of Function Values

Description

Extract a subset of an object of class "fv".

Usage

## S3 method for class 'fv':


x[i, j, ..., drop=FALSE]
[Link] 173

Arguments
x a function value object, of class "fv" (see [Link]). Essentially a data
frame.
i any appropriate subset index. Selects a subset of the rows of the data
frame, i.e. a subset of the domain of the function(s) represented by x.
j any appropriate subset index for the columns of the data frame. Selects
some of the functions present in x.
drop, ... Ignored.

Details
This is a method for "[" for the class "fv". It is very similar to [.[Link] except for
a few extra checks on the sanity of the result.

Value
A function value object (of class "fv").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link]

Examples
data(cells)
K <- Kest(cells)

# discard the estimates of K(r) for r > 0.1


Ksub <- K[K$r <= 0.1, ]

# discard the border method estimator


Ksub <- K[ , names(K) != "border"]

[Link] Extract Subset of Image

Description
Extract a subset or subregion of a pixel image.

Usage
## S3 method for class 'im':
x[i, drop=TRUE, ..., raster=NULL]
174 [Link]

Arguments
x A two-dimensional pixel image. An object of class "im".
i Object defining the subregion or subset to be extracted. Either a spatial
window (an object of class "owin"), or a pixel image with logical values,
or a point pattern (an object of class "ppp"), or something that can be
converted to a point pattern by [Link].
... Ignored.
drop Logical value. Locations in w that lie outside the spatial domain of the
image x return a pixel value of NA if drop=FALSE, and are omitted if
drop=TRUE.
raster Optional. An object of class "owin" or "im" determining a pixel grid.

Details
This function extracts a subset of the pixel values in a pixel image. (To reassign the pixel
values, see [<-.im).
The image x must be an object of class "im" representing a pixel image defined inside a
rectangle in two-dimensional space (see [Link]).
The subset to be extracted is determined by the argument i. If i is a spatial window (an
object of class "owin"), the values of the image inside this window are extracted (after
first clipping the window to the spatial domain of the image if necessary). If i is a pixel
image with logical values, it is interpreted as a spatial window (with TRUE values inside the
window and FALSE outside). If i is a point pattern (an object of class "ppp"), then the
values of the pixel image at the points of this pattern are extracted.
At locations outside the spatial domain of the image, the pixel value is undefined, and
is taken to be NA. The logical argument drop determines whether such NA values will be
returned or omitted. It also influences the format of the return value.
If i is a point pattern (or something that can be converted to a point pattern by [Link]
such as a list of x,y coordinates), then X[i, drop=FALSE] is a numeric vector containing
the pixel values at each of the points of the pattern. Its length is equal to the number of
points in the pattern i. It may contain NAs corresponding to points which lie outside the
spatial domain of the image x. By contrast, X[i] or X[i, drop=TRUE] contains only those
pixel values which are not NA. It may be shorter.
If i is a spatial window then X[i, drop=FALSE] is another pixel image of the same dimen-
sions as x obtained by setting all pixels outside the window i to have value NA. When the
result is displayed by [Link] the effect is that the pixel image x is clipped to the window
i.
If i is a spatial window which is not a rectangle (i$type != "rectangle") then X[i,
drop=TRUE] is a numeric vector containing the pixel values for all pixels that lie inside the
window i.
If i is a rectangle (a spatial window with i$type = "rectangle") then X[i, drop=TRUE]
is a pixel image. The spatial domain of this image is the intersection of i with the spatial
domain of x.
If the optional argument raster is given, then it should be a binary image mask or a
pixel image. Then x will first be converted to an image defined on the pixel grid implied
by raster, before the subset operation is carried out. In particular, x[i, raster=i,
drop=FALSE] will return an image defined on the same pixel array as the object i.
[Link] 175

Value

Either a pixel image or a vector of pixel values. See Details.

Warning

If W is a window or a pixel image, then x[W, drop=FALSE] will return an image defined on
the same pixel array as the original image x. If you want to obtain an image whose pixel
dimensions agree with those of W, use the raster argument, x[W, raster=W, drop=FALSE].

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [<-.im, [Link], [Link], [Link], [Link]

Examples
# make up an image
X <- setcov([Link]())
plot(X)

# a rectangular subset
W <- owin(c(0,0.5),c(0.2,0.8))
Y <- X[W]
plot(Y)

# a polygonal subset
data(letterR)
R <- affine(letterR, diag(c(1,1)/2), c(-2,-0.7))
Y <- X[R, drop=FALSE]
plot(Y)

# a point pattern
P <- rpoispp(20)
Y <- X[P]

# look up a specified location


X[list(x=0.1,y=0.2)]

# 10 x 10 pixel array
X <- [Link](function(x,y) { x + y }, owin(c(-1,1),c(-1,1)), dimyx=10)
# 100 x 100
W <- [Link](disc(1, c(0,0)), dimyx=100)
# 10 x 10 raster
X[W,drop=FALSE]
# 100 x 100 raster
X[W, raster=W, drop=FALSE]
176 [Link]

[Link] Extract or Replace Subset of a List of Things

Description
Replace a subset of a list of things.

Usage
## S3 replacement method for class 'listof':
x[i] <- value

Arguments
x An object of class "listof" representing a list of things which all belong
to one class.
i Subset index. Any valid subset index in the usual R sense.
value Replacement value for the subset.

Details
This is a subset replacement method for the class "listof".
The argument x should be an object of class "listof" representing a list of things that all
belong to one class.
The method replaces a designated subset of x, and returns an object of class "listof".

Value
Another object of class "listof".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
x <- list(A=runif(10), B=runif(10), C=runif(10))
class(x) <- c("listof", class(x))
x[1] <- list(A=rnorm(10))
[Link] 177

[Link] Extract or Replace Subset of Point Pattern

Description
Extract or replace a subset of a point pattern. Extraction of a subset has the effect of
thinning the points and/or trimming the window.

Usage
## S3 method for class 'ppp':
x[i, j, drop, ...]
## S3 replacement method for class 'ppp':
x[i, j] <- value

Arguments
x A two-dimensional point pattern. An object of class "ppp".
i Subset index. Either a valid subset index in the usual R sense, indicating
which points should be retained, or a window (an object of class "owin")
delineating a subset of the original observation window.
value Replacement value for the subset. A point pattern.
j Redundant. Included for backward compatibility.
drop, ... Ignored. These arguments are required for compatibility with the generic
function.

Details
These functions extract a designated subset of a point pattern, or replace the designated
subset with another point pattern.
The function [.ppp is a method for [ for the class "ppp". It extracts a designated subset of
a point pattern, either by “thinning” (retaining/deleting some points of a point pattern) or
“trimming” (reducing the window of observation to a smaller subregion and retaining only
those points which lie in the subregion) or both.
The pattern will be “thinned” if i is a subset index in the usual R sense: either a numeric
vector of positive indices (identifying the points to be retained), a numeric vector of negative
indices (identifying the points to be deleted) or a logical vector of length equal to the number
of points in the point pattern x. In the latter case, the points (x$x[i], x$y[i]) for which
subset[i]=TRUE will be retained, and the others will be deleted.
The pattern will be “trimmed” if i is an object of class "owin" specifying a window of
observation. The points of x lying inside the new window will be retained. Alternatively i
may be a pixel image (object of class "im") with logical values; the pixels with the value
TRUE will be interpreted as a window.
The function [<-.ppp is a method for [<- for the class "ppp". It replaces the designated
subset with the point pattern value. The subset of x to be replaced is designated by the
argument i as above.
The replacement point pattern value must lie inside the window of the original pattern x.
The ordering of points in x will be preserved if the replacement pattern value has the same
number of points as the subset to be replaced. Otherwise the ordering is unpredictable.
178 [Link]

If the original pattern x has marks, then the replacement pattern value must also have
marks, of the same type.
Use the function unmark to remove marks from a marked point pattern.
Use the function [Link] to select those points in a marked point pattern which have a
specified mark.

Value
A point pattern (of class "ppp").

Warnings
The function does not check whether window is a subset of x$window. Nor does it check
whether value lies inside x$window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], unmark, [Link], [Link]

Examples
data(longleaf)
# Longleaf pines data
## Not run:
plot(longleaf)

## End(Not run)

# adult trees defined to have diameter at least 30 cm


adult <- (longleaf$marks >= 30)
longadult <- longleaf[adult]
## Not run:
plot(longadult)

## End(Not run)
# note that the marks are still retained.
# Use unmark(longadult) to remove the marks

# New Zealand trees data


data(nztrees)
## Not run:
plot(nztrees) # plot shows a line of trees at the far right
abline(v=148, lty=2) # cut along this line

## End(Not run)
nzw <- owin(c(0,148),c(0,95)) # the subwindow
# trim dataset to this subwindow
nzsub <- nztrees[nzw]
## Not run:
plot(nzsub)
[Link] 179

## End(Not run)

# Redwood data
data(redwood)
## Not run:
plot(redwood)

## End(Not run)
# Random thinning: delete 60% of data
retain <- (runif(redwood$n) < 0.4)
thinred <- redwood[retain]
## Not run:
plot(thinred)

## End(Not run)
# Scramble 60% of data
modif <- (runif(redwood$n) < 0.6)
scramble <- function(x) { runifpoint(x$n, x$window) }
redwood[modif] <- scramble(redwood[modif])

# Lansing woods data - multitype points


data(lansing)

# Hickory trees
hicks <- split(lansing)$hickory

# Trees in subwindow
win <- owin(c(0.3, 0.6),c(0.2, 0.5))
lsub <- lansing[win]

# Scramble the locations of trees in subwindow, retaining their marks


lansing[win] <- scramble(lsub) %mark% (lsub$marks)

[Link] Extract Subset of Line Segment Pattern

Description
Extract a subset of a line segment pattern.

Usage
## S3 method for class 'psp':
x[i, j, drop, ...]

Arguments
x A two-dimensional line segment pattern. An object of class "psp".
i Subset index. Either a valid subset index in the usual R sense, indicat-
ing which segments should be retained, or a window (an object of class
"owin") delineating a subset of the original observation window.
j Redundant - included for backward compatibility.
180 [Link]

drop Ignored. Required for compatibility with generic function.


... Ignored.

Details
These functions extract a designated subset of a line segment pattern.
The function [.psp is a method for [ for the class "psp". It extracts a designated subset of
a line segment pattern, either by “thinning” (retaining/deleting some line segments of a line
segment pattern) or “trimming” (reducing the window of observation to a smaller subregion
and clipping the line segments to this boundary) or both.
The pattern will be “thinned” if subset is specified. The line segments designated by subset
will be retained. Here subset can be a numeric vector of positive indices (identifying the
line segments to be retained), a numeric vector of negative indices (identifying the line
segments to be deleted) or a logical vector of length equal to the number of line segments in
the line segment pattern x. In the latter case, the line segments for which subset[i]=TRUE
will be retained, and the others will be deleted.
The pattern will be “trimmed” if window is specified. This should be an object of class owin
specifying a window of observation to which the line segment pattern x will be trimmed.
Line segments of x lying inside the new window will be retained unchanged. Line segments
lying partially inside the new window and partially outside it will be clipped so that they
lie entirely inside.
Both “thinning” and “trimming” can be performed together.

Value
A line segment pattern (of class "psp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
a <- psp(runif(20),runif(20),runif(20),runif(20), window=owin())
plot(a)
# thinning
id <- sample(c(TRUE, FALSE), 20, replace=TRUE)
b <- a[id]
plot(b, add=TRUE, lwd=3)
# trimming
plot(a)
w <- owin(c(0.1,0.7), c(0.2, 0.8))
b <- a[,w]
plot(b, add=TRUE, col="red")
[Link] 181

[Link] Subset of Quadrature Scheme

Description
Extract a subset of a quadrature scheme.

Usage
## S3 method for class 'quad':
x[...]

Arguments
x A quadrature scheme (object of class "quad").
... Arguments passed to [.ppp to determine the subset.

Details
This function extracts a designated subset of a quadrature scheme.
The function [.quad is a method for [ for the class "quad". It extracts a designated subset
of a quadrature scheme.
The subset to be extracted is determined by the arguments ... which are interpreted by
[.ppp. Thus it is possible to take the subset consisting of all quadrature points that lie
inside a given region, or a subset of quadrature points identified by numeric indices.

Value

A quadrature scheme (object of class "quad").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also

[Link], [.ppp.

Examples
data(nztrees)
Q <- quadscheme(nztrees)
W <- owin(c(0,148),c(0,95)) # a subwindow
Q[W]
182 [Link]

[Link] Extract or Replace Sub-Patterns

Description
Extract or replace some of the sub-patterns in a split point pattern.

Usage
## S3 method for class 'splitppp':
x[...]
## S3 replacement method for class 'splitppp':
x[...] <- value

Arguments
x An object of class "splitppp", representing a point pattern separated
into a list of sub-patterns.
... Subset index. Any valid subset index in the usual R sense.
value Replacement value for the subset. A list of point patterns.

Details
These are subset methods for the class "splitppp".
The argument x should be an object of class "splitppp", representing a point pattern that
has been separated into a list of sub-patterns. It is created by [Link].
The methods extract or replace a designated subset of the list x, and return an object of
class "splitppp".

Value
Another object of class "splitppp".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
data(amacrine) # multitype point pattern
y <- split(amacrine)
y[1]
y["off"]
y[1] <- list(runifpoint(42, amacrine$window))
[Link] 183

[Link] Extract or Replace Subset of Tessellation

Description
Extract, change or delete a subset of the tiles of a tessellation, to make a new tessellation.

Usage
## S3 method for class 'tess':
x[...]
## S3 replacement method for class 'tess':
x[...] <- value

Arguments
x A tessellation (object of class "tess").
... One argument that specifies the subset to be extracted or changed. Any
valid format for the subset index in a list.
value Replacement value for the selected tiles of the tessellation. A list of win-
dows (objects of class "owin") or NULL.

Details
A tessellation (object of class "tess", see tess) is effectively a list of tiles (spatial regions)
that cover a spatial region. The subset operator [.tess extracts some of these tiles and
forms a new tessellation, which of course covers a smaller region than the original.
The replacement operator changes the selected tiles. The replacement value may be either
NULL (which causes the selected tiles to be removed from x) or a list of the same length
as the selected subset. The entries of value may be windows (objects of class "owin") or
NULL to indicate that the corresponding tile should be deleted.
Generally it does not make sense to replace a tile in a tessellation with a completely different
tile, because the tiles are expected to fit together. However this facility is sometimes useful
for making small adjustments to polygonal tiles.

Value
A tessellation (object of class "tess").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
tess,
184 F3est

Examples
A <- tess(xgrid=0:4, ygrid=0:3)
B <- A[c(1, 3, 4, 7, 12)]
E <- A[-1]
A[c(2, 5, 11)] <- NULL

F3est Empty Space Function of a Three-Dimensional Point Pattern

Description
Estimates the empty space function F3 (r) from a three-dimensional point pattern.

Usage
F3est(X, ..., rmax = NULL, nrval = 128, vside = NULL, correction = c("rs", "km", "cs"))

Arguments
X Three-dimensional point pattern (object of class "pp3").
... Ignored.
rmax Optional. Maximum value of argument r for which F3 (r) will be esti-
mated.
nrval Optional. Number of values of r for which F3 (r) will be estimated. A
large value of nrval is required to avoid discretisation effects.
vside Optional. Side length of the voxels in the discrete approximation.
correction Optional. Character vector specifying the edge correction(s) to be applied.
See Details.

Details
For a stationary point process Φ in three-dimensional space, the empty space function is
F3 (r) = P (d(0, Φ) ≤ r)
where d(0, Φ) denotes the distance from a fixed origin 0 to the nearest point of Φ.
The three-dimensional point pattern X is assumed to be a partial realisation of a stationary
point process Φ. The empty space function of Φ can then be estimated using techniques
described in the References.
The box containing the point pattern is discretised into cubic voxels of side length vside.
The distance function d(u, Φ) is computed for every voxel centre point u using a three-
dimensional version of the distance transform algorithm (Borgefors, 1986). The empirical
cumulative distribution function of these values, with appropriate edge corrections, is the
estimate of F3 (r).
The available edge corrections are:
"rs": the reduced sample (aka minus sampling, border correction) estimator (Baddeley et
al, 1993)
"km": the three-dimensional version of the Kaplan-Meier estimator (Baddeley and Gill,
1997)
"cs": the three-dimensional generalisation of the Chiu-Stoyan or Hanisch estimator (Chiu
and Stoyan, 1998).
[Link] 185

Value
A function value table (object of class "fv") that can be plotted, printed or coerced to a
data frame containing the function values.

Warnings
A large value of nrval is required in order to avoid discretisation effects (due to the use of
histograms in the calculation).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rana Moyeed.

References
Baddeley, A.J, Moyeed, R.A., Howard, C.V. and Boyde, A. Analysis of a three-dimensional
point pattern with replication. Applied Statistics 42 (1993) 641–668.
Baddeley, A.J. and Gill, R.D. (1997) Kaplan-Meier estimators of interpoint distance distri-
butions for spatial point processes. Annals of Statistics 25, 263–292.
Borgefors, G. (1986) Distance transformations in digital images. Computer Vision, Graphics
and Image Processing 34, 344–371.
Chiu, S.N. and Stoyan, D. (1998) Estimators of distance distributions for spatial patterns.
Statistica Neerlandica 52, 239–246.

See Also
G3est, K3est.

Examples
X <- rpoispp3(42)
Z <- F3est(X)
if(interactive()) plot(Z)

[Link] Function Arrays for Spatial Patterns

Description
A class "fasp" to represent a “matrix” of functions, amenable to plotting as a matrix of
plot panels.

Details
An object of this class is a convenient way of storing (and later plotting, editing, etc) a
set of functions fi,j (r) of a real argument r, defined for each possible pair (i, j) of indices
1 ≤ i, j ≤ n. We may think of this as a matrix or array of functions fi,j .
Function arrays are particularly useful in the analysis of a multitype point pattern (a point
pattern in which the points are identified as belonging to separate types). We may want
to compute a summary function for the points of type i only, for each of the possible types
186 [Link]

i. This produces a 1 × m array of functions. Alternatively we may compute a summary


function for each possible pair of types (i, j). This produces an m × m array of functions.
For multitype point patterns the command alltypes will compute arrays of summary
functions for each possible type or for each possible pair of types. The function alltypes
returns an object of class "fasp".
An object of class "fasp" is a list containing at least the following components:

fns A list of data frames, each representing one of the functions.


which A matrix representing the spatial arrangement of the functions. If which[i,j] = k
then the function represented by fns[[k]] should be plotted in the panel at position
(i, j). If which[i,j] = NA then nothing is plotted in that position.
titles A list of character strings, providing suitable plotting titles for the functions.
[Link] A list of default formulae for plotting each of the functions.
title A character string, giving a default title for the array when it is plotted.

Functions available
There are methods for plot, print and "[" for this class.
The plot method displays the entire array of functions. The method [.fasp selects a
sub-array using the natural indices i,j.
The command [Link] can be used to apply a transformation to each function in the
array, and to combine two arrays.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
alltypes, [Link], [.fasp, [Link]

Examples
# multitype point pattern
data(amacrine)
GG <- alltypes(amacrine, "G")
plot(GG)

# select the row corresponding to cells of type "on"


Gon <- GG["on", ]
plot(Gon)

# extract the G function for i = "on", j = "off"


Gonoff <- GG["on", "off", drop=TRUE]

# Fisher variance stabilising transformation


GGfish <- [Link](asin(sqrt(GG)))
plot(GGfish)
Fest 187

Fest Estimate the empty space function F

Description
Estimates the empty space function F (r) from a point pattern in a window of arbitrary
shape.

Usage
Fest(X, ..., eps, r=NULL, breaks=NULL, correction=c("rs", "km", "cs"))

Arguments
X The observed point pattern, from which an estimate of F (r) will be
computed. An object of class ppp, or data in any format acceptable
to [Link]().
... Ignored.
eps Optional. A positive number. The resolution of the discrete approxima-
tion to Euclidean distance (see below). There is a sensible default.
r Optional. Numeric vector. The values of the argument r at which F (r)
should be evaluated. There is a sensible default. First-time users are
strongly advised not to specify this argument. See below for important
conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
correction Optional. The edge correction(s) to be used to estimate F (r). A vector
of character strings selected from "none", "rs", "km", "cs" and "best".

Details
The empty space function (also called the “spherical contact distribution” or the “point-to-
nearest-event ” distribution) of a stationary point process X is the cumulative distribution
function F of the distance from a fixed point in space to the nearest point of X.
An estimate of F derived from a spatial point pattern dataset can be used in exploratory
data analysis and formal inference about the pattern (Cressie, 1991; Diggle, 1983; Ripley,
1988). In exploratory analyses, the estimate of F is a useful statistic summarising the sizes
of gaps in the pattern. For inferential purposes, the estimate of F is usually compared to
the true value of F for a completely random (Poisson) point process, which is
2
F (r) = 1 − e−λπr

where λ is the intensity (expected number of points per unit area). Deviations between the
empirical and theoretical F curves may suggest spatial clustering or spatial regularity.
This algorithm estimates the empty space function F from the point pattern X. It assumes
that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial
point process in the plane, observed through a bounded window. The window (which is
specified in X) may have arbitrary shape.
The argument X is interpreted as a point pattern object (of class "ppp", see [Link])
and can be supplied in any of the formats recognised by [Link].
188 Fest

The algorithm uses two discrete approximations which are controlled by the parameter eps
and by the spacing of values of r respectively. (See below for details.) First-time users are
strongly advised not to specify these arguments.
The estimation of F is hampered by edge effects arising from the unobservability of points
of the random pattern outside the window. An edge correction is needed to reduce bias
(Baddeley, 1998; Ripley, 1988). The edge corrections implemented here are the border
method or ”reduced sample” estimator, the spatial Kaplan-Meier estimator (Baddeley and
Gill, 1997) and the Chiu-Stoyan estimator (Chiu and Stoyan, 1998).
Our implementation makes essential use of the distance transform algorithm of image pro-
cessing (Borgefors, 1986). A fine grid of pixels is created in the observation window. The
Euclidean distance between two pixels is approximated by the length of the shortest path
joining them in the grid, where a path is a sequence of steps√between adjacent pixels, and
horizontal, vertical and diagonal steps have length 1, 1 and 2 respectively in pixel units.
If the pixel grid is sufficiently fine then this is an accurate approximation.
The parameter eps is the pixel width of the rectangular raster used to compute the distance
transform (see below). It must not be too large: the absolute error in distance values due
to discretisation is bounded by eps.
If eps is not specified, the function checks whether the window X$window contains pixel
raster information. If so, then eps is set equal to the pixel width of the raster; otherwise,
eps defaults to 1/100 of the width of the observation window.
The argument r is the vector of values for the distance r at which F (r) should be evaluated.
It is also used to determine the breakpoints (in the sense of hist for the computation
of histograms of distances. The estimators are computed from histogram counts. This
introduces a discretisation error which is controlled by the fineness of the breakpoints.
First-time users would be strongly advised not to specify r. However, if it is specified,
r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc
contained in the window. Furthermore, the spacing of successive r values must be very fine
(ideally not greater than eps/4).
The algorithm also returns an estimate of the hazard rate function, λ(r), of F (r). The
hazard rate is defined by
d
λ(r) = − log(1 − F (r))
dr
The hazard rate of F has been proposed as a useful exploratory statistic (Baddeley and Gill,
1994). The estimate of λ(r) given here is a discrete approximation to the hazard rate of
the Kaplan-Meier estimator of F . Note that F is absolutely continuous (for any stationary
point process X), so the hazard function always exists (Baddeley and Gill, 1997).
The naive empirical distribution of distances from each location in the window to the nearest
point of the data pattern, is a biased estimate of F . However this is also returned by the
algorithm (if correction="none"), as it is sometimes useful in other contexts. Care should
be taken not to use the uncorrected empirical F as if it were an unbiased estimator of F .

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing up to seven columns:
r the values of the argument r at which the function F (r) has been esti-
mated
rs the “reduced sample” or “border correction” estimator of F (r)
km the spatial Kaplan-Meier estimator of F (r)
Fest 189

hazard the hazard rate λ(r) of F (r) by the spatial Kaplan-Meier method
cs the Chiu-Stoyan estimator of F (r)
raw the uncorrected estimate of F (r), i.e. the empirical distribution of the
distance from a random point in the window to the nearest point of the
data pattern X
theo the theoretical value of F (r) for a stationary Poisson process of the same
estimated intensity.

Warnings
The reduced sample (border method) estimator of F is pointwise approximately unbiased,
but need not be a valid distribution function; it may not be a nondecreasing function of r.
Its range is always within [0, 1].
The spatial Kaplan-Meier estimator of F is always nondecreasing but its maximum value
may be less than 1.
The estimate of λ(r) returned by the algorithm is an approximately unbiased estimate for
the integral of λ() over the corresponding histogram cell. It may exhibit oscillations due
to discretisation effects. We recommend modest smoothing, such as kernel smoothing with
kernel width equal to the width of a histogram cell.

Note
Sizeable amounts of memory may be needed during the calculation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A.J. Spatial sampling and censoring. In O.E. Barndorff-Nielsen, W.S. Kendall
and M.N.M. van Lieshout (eds) Stochastic Geometry: Likelihood and Computation. Chap-
man and Hall, 1998. Chapter 2, pages 37-78.
Baddeley, A.J. and Gill, R.D. The empty space hazard of a spatial pattern. Research Report
1994/3, Department of Mathematics, University of Western Australia, May 1994.
Baddeley, A.J. and Gill, R.D. Kaplan-Meier estimators of interpoint distance distributions
for spatial point processes. Annals of Statistics 25 (1997) 263-292.
Borgefors, G. Distance transformations in digital images. Computer Vision, Graphics and
Image Processing 34 (1986) 344-371.
Chiu, S.N. and Stoyan, D. (1998) Estimators of distance distributions for spatial patterns.
Statistica Neerlandica 52, 239–246.
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.
190 finpines

See Also
Gest, Jest, Kest, [Link], [Link], [Link]

Examples
data(cells)
Fc <- Fest(cells, 0.01)

# Tip: don't use F for the left hand side!


# That's an abbreviation for FALSE

plot(Fc)

# P-P style plot


plot(Fc, cbind(km, theo) ~ theo)

# The empirical F is above the Poisson F


# indicating an inhibited pattern

## Not run:
plot(Fc, . ~ theo)
plot(Fc, asin(sqrt(.)) ~ asin(sqrt(theo)))

## End(Not run)

finpines Pine saplings in Finland.

Description
The data record the locations of 126 pine saplings in a Finnish forest, their heights and
their diameters.
The main dataset finpines is a marked point pattern containing the locations of the
saplings marked by their heights. Additional data in [Link] record the sapling
diameters.
Sapling locations are given in metres (to six significant digits); heights are in metres
(rounded to the nearest 0.1 metre, except in one case to the nearest 0.05 metres); diameters
are in centimetres (rounded to the nearest centimetre).
The data were recorded by Professor Seppo Kellomaki, Faculty of Forestry, University of
Joensuu, Finland, and subsequently massaged by Professor Antti Penttinen, Department
of Statistics, University of Jyv\”askyl\”a, Finland.
Originally the point locations were observed in polar coordinates with rather poor angular
precision. Hence the coordinates are imprecise for large radius because of rounding errors:
indeed the alignments can be observed by eye.
The data were manipulated by Prof Penttinen by making small angular perturbations at
random. After this transformation, the original data (in a circular plot) were clipped to a
square window, for convenience.
Professor Penttinen emphasises that the data were intended only for initial experimentation.
They have some strange features. For example, if the height is less than 1.3 metres then
the diameter can be uncertain. Also there are some very close pairs of points. Some pairs
[Link] 191

of trees (namely (58,59), (78,79), (96,97) and (102,103)) violate the requirement that the
interpoint distance should be greater than half the sum of their diameters.
These data have subsequently been analysed by Van Lieshout (2004).

Usage
data(finpines)

Format
finpines is an object of class "ppp" representing the point pattern of sapling locations
marked by their heights. See [Link] for details of the format.
[Link] is a list with one component diameter which is a numeric vector containing
the diameters of the points.

Source
Prof Antti Penttinen

References
Van Lieshout, M.N.M. (2004) A J-function for marked point patterns. Research Report
PNA-R0404, June 2004. Centrum voor Wiskunde en Informatica (CWI), Amsterdam,
2004.

Examples
data(finpines)
plot(unmark(finpines), main="Finnish pines: locations")
plot(finpines, main="locations and heights")
plot(finpines %mark% [Link]$diameter, main="diameters")
plot(finpines %mark% [Link]$diameter,
main="diameters to scale", markscale=1/200)

[Link] Extract the Interaction from a Fitted Point Process Model

Description
Given a point process model that has been fitted to point pattern data, this function extracts
the interpoint interaction part of the model as a separate object.

Usage
fitin(object)
## S3 method for class 'ppm':
fitin(object)

Arguments
object A fitted point process model (object of class "ppm").
192 [Link]

Details
An object of class "ppm" describes a fitted point process model. It contains information
about the original data to which the model was fitted, the spatial trend that was fitted, the
interpoint interaction that was fitted, and other data. See [Link]) for details of this
class.
The function fitin extracts from this model the information about the fitted interpoint
interaction only. The information is organised as an object of class "fii" (fitted interpoint
interaction). This object can be printed or plotted.
Users may find this a convenient way to plot the fitted interpoint interaction term, as shown
in the Examples.

Value
An object of class "fii" representing the fitted interpoint interaction. This object can be
printed and plotted.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, [Link],

Examples
data(betacells)

# unmarked
X <- unmark(betacells)
model <- ppm(X, ~1, PairPiece(seq(10,100,by=10)))
f <- fitin(model)
f
plot(f)

# marked
# fit the stationary multitype Strauss process to `betacells'
r <- 30.0 * matrix(c(1,2,2,1), nrow=2,ncol=2)
model <- ppm(betacells, ~1, MultiStrauss(c("off","on"), r))
f <- fitin(model)
f
plot(f)

[Link] Fitted Conditional Intensity for Point Process Model

Description
Given a point process model fitted to a point pattern, compute the fitted conditional in-
tensity of the model at the points of the pattern, or at the points of the quadrature scheme
used to fit the model.
[Link] 193

Usage
## S3 method for class 'ppm':
fitted(object, ..., type="lambda", dataonly=FALSE,
drop=FALSE, check=TRUE, repair=TRUE)

Arguments
object The fitted point process model (an object of class "ppm")
... Ignored.
type String (partially matched) indicating whether the fitted value is the con-
ditional intensity ("lambda") or the trend ("trend").
dataonly Logical. If TRUE, then values will only be computed at the points of
the data point pattern. If FALSE, then values will be computed at all
the points of the quadrature scheme used to fit the model, including the
points of the data point pattern.
drop Logical value determining whether to delete quadrature points that were
not used to fit the model.
check Logical value indicating whether to check the internal format of object.
If there is any possibility that this object has been restored from a dump
file, or has otherwise lost track of the environment where it was originally
computed, set check=TRUE.
repair Logical value indicating whether to repair the internal format of object,
if it is found to be damaged.

Details
The argument object must be a fitted point process model (object of class "ppm"). Such
objects are produced by the model-fitting algorithm ppm).
This function evaluates the conditional intensity λ̂(u, x) or spatial trend b̂(u) of the fitted
point process model for certain locations u, where x is the original point pattern dataset to
which the model was fitted.
The locations u at which the fitted conditional intensity/trend is evaluated, are the points
of the quadrature scheme used to fit the model in ppm. They include the data points (the
points of the original point pattern dataset x) and other “dummy” points in the window of
observation.
The argument drop is explained in [Link].
Use [Link] to compute the fitted conditional intensity at other locations or with
other values of the explanatory variables.

Value
A vector containing the values of the fitted conditional intensity or (if type="trend") the
fitted spatial trend.
Entries in this vector correspond to the quadrature points (data or dummy points) used to fit
the model. The quadrature points can be extracted from object by [Link]([Link](object)).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
194 fryplot

References
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005). Residual analysis for spatial
point processes (with discussion). Journal of the Royal Statistical Society, Series B 67,
617–666.

See Also
[Link], ppm, [Link]

Examples
data(cells)
str <- ppm(cells, ~x, Strauss(r=0.15))
lambda <- fitted(str)

# extract quadrature points in corresponding order


quadpoints <- [Link]([Link](str))

# plot conditional intensity values


# as circles centred on the quadrature points
quadmarked <- setmarks(quadpoints, lambda)
plot(quadmarked)

fryplot Fry Plot of Point Pattern

Description
Displays the Fry plot (Patterson plot) of a spatial point pattern.

Usage
fryplot(X, ..., width=NULL)
frypoints(X)

Arguments
X A point pattern (object of class "ppp") or something acceptable to [Link].
... Optional arguments to control the appearance of the plot.
width Optional parameter indicating the width of a box for a zoomed-in view
of the Fry plot near the origin.

Details
The function fryplot generates a Fry plot (or Patterson plot); frypoints returns the
points of the Fry plot as a point pattern dataset.
Fry (1979) and Hanna and Fry (1979) introduced a manual graphical method for investi-
gating features of a spatial point pattern of mineral deposits. A transparent sheet, marked
with an origin or centre point, is placed over the point pattern. The transparent sheet
is shifted so that the origin lies over one of the data points, and the positions of all the
other data points are copied onto the transparent sheet. This procedure is repeated for
each data point in turn. The resulting plot (the Fry plot) is a pattern of n(n − 1) points,
fryplot 195

where n is the original number of data points. This procedure was previously proposed by
Patterson (1934, 1935) for studying inter-atomic distances in crystals, and is also known as
a Patterson plot.
The function fryplot generates the Fry/Patterson plot. Standard graphical parameters
such as main, pch, lwd, col, bg, cex can be used to control the appearance of the plot. To
zoom in (to view only a subset of the Fry plot at higher magnification), use the argument
width to specify the width of a rectangular field of view centred at the origin, or the
standard graphical arguments xlim and ylim to specify another rectangular field of view.
(The actual field of view may be slightly larger, depending on the graphics device.)
The function frypoints returns the points of the Fry plot as a point pattern object. There
may be a large number of points in this pattern, so this function should be used only if
further analysis of the Fry plot is required.
Fry plots are particularly useful for recognising anisotropy in regular point patterns. A void
around the origin in the Fry plot suggests regularity (inhibition between points) and the
shape of the void gives a clue to anisotropy in the pattern. Fry plots are also useful for
detecting periodicity or rounding of the spatial coordinates.
In mathematical terms, the Fry plot of a point pattern X is simply a plot of the vectors
X[i] - X[j] connecting all pairs of distinct points in X.
The Fry plot is related to the K function (see Kest) and the reduced second moment
measure (see Kmeasure). For example, the number of points in the Fry plot lying within a
circle of given radius is an unnormalised and uncorrected version of the K function. The Fry
plot has a similar appearance to the plot of the reduced second moment measure Kmeasure
when the smoothing parameter sigma is very small.
The Fry plot does not adjust for the effect of the size and shape of the sampling window.
The density of points in the Fry plot tapers off near the edges of the plot. This is an edge
effect, a consequence of the bounded sampling window. In geological applications this is
usually not important, because interest is focused on the behaviour near the origin where
edge effects can be ignored. To correct for the edge effect, use Kmeasure or Kest or its
relatives.

Value
fryplot returns NULL. frypoints returns a point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Fry, N. (1979) Random point distributions and strain measurement in rocks. Tectonophysics
60, 89–105.
Hanna, S.S. and Fry, N. (1979) A comparison of methods of strain determination in rocks
from southwest Dyfed (Pembrokeshire) and adjacent areas. Journal of Structural Geology
1, 155–162.
Patterson, A.L. (1934) A Fourier series method for the determination of the component of
inter-atomic distances in crystals. Physics Reviews 46, 372–376.
Patterson, A.L. (1935) A direct method for the determination of the components of inter-
atomic distances in crystals. Zeitschrift fuer Krystallographie 90, 517–554.
196 [Link]

See Also
Kmeasure, Kest

Examples
data(cells)
fryplot(cells)
Y <- frypoints(cells)
data(amacrine)
X <- split(amacrine)$off
fryplot(X, width=0.25)

[Link] Data Frames of Function Values

Description
A class "fv" to support the convenient plotting of several estimates of the same function.

Details
An object of this class is a convenient way of storing and plotting several different estimates
of the same function.
It is a data frame with extra attributes indicating the recommended way of plotting the
function, and other information.
There are methods for print and plot for this class.
Objects of class "fv" are returned by Fest, Gest,Jest, and Kest.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
Fest, Gest, Jest, Kest

Examples
data(cells)
K <- Kest(cells)

class(K)

K # prints a sensible summary

plot(K)
G3est 197

G3est Nearest Neighbour Distance Distribution Function of a Three-


Dimensional Point Pattern

Description
Estimates the nearest-neighbour distance distribution function G3 (r) from a three-dimensional
point pattern.

Usage
G3est(X, ..., rmax = NULL, nrval = 128, correction = c("rs", "km", "Hanisch"))

Arguments
X Three-dimensional point pattern (object of class "pp3").
... Ignored.
rmax Optional. Maximum value of argument r for which G3 (r) will be esti-
mated.
nrval Optional. Number of values of r for which G3 (r) will be estimated. A
large value of nrval is required to avoid discretisation effects.
correction Optional. Character vector specifying the edge correction(s) to be applied.
See Details.

Details
For a stationary point process Φ in three-dimensional space, the nearest-neighbour function
is
G3 (r) = P (d∗ (x, Φ) ≤ r | x ∈ Φ)
the cumulative distribution function of the distance d∗ (x, Φ) from a typical point x in Φ to
its nearest neighbour, i.e. to the nearest other point of Φ.
The three-dimensional point pattern X is assumed to be a partial realisation of a stationary
point process Φ. The nearest neighbour function of Φ can then be estimated using techniques
described in the References. For each data point, the distance to the nearest neighbour is
computed. The empirical cumulative distribution function of these values, with appropriate
edge corrections, is the estimate of G3 (r).
The available edge corrections are:

"rs": the reduced sample (aka minus sampling, border correction) estimator (Baddeley et
al, 1993)
"km": the three-dimensional version of the Kaplan-Meier estimator (Baddeley and Gill,
1997)
"Hanisch": the three-dimensional generalisation of the Hanisch estimator (Hanisch, 1984).

Value
A function value table (object of class "fv") that can be plotted, printed or coerced to a
data frame containing the function values.
198 ganglia

Warnings
A large value of nrval is required in order to avoid discretisation effects (due to the use of
histograms in the calculation).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rana Moyeed.

References
Baddeley, A.J, Moyeed, R.A., Howard, C.V. and Boyde, A. (1993) Analysis of a three-
dimensional point pattern with replication. Applied Statistics 42, 641–668.
Baddeley, A.J. and Gill, R.D. (1997) Kaplan-Meier estimators of interpoint distance distri-
butions for spatial point processes. Annals of Statistics 25, 263–292.
Hanisch, K.-H. (1984) Some remarks on estimators of the distribution function of near-
est neighbour distance in stationary spatial point patterns. Mathematische Operations-
forschung und Statistik, series Statistics 15, 409–412.

See Also
F3est, K3est

Examples
X <- rpoispp3(42)
Z <- G3est(X)
if(interactive()) plot(Z)

ganglia Beta Ganglion Cells in Cat Retina, Old Version

Description
Point pattern of retinal ganglion cells identified as ‘on’ or ‘off’. A marked point pattern.

Usage
data(ganglia)

Format
An object of class "ppp" representing the point pattern of cell locations. Entries include

x Cartesian x-coordinate of cell


y Cartesian y-coordinate of cell
marks factor with levels off and on
indicating “off” and “on” cells

See [Link] for details of the format.


Gcross 199

Notes
Important: these data are INCORRECT. See below.
The data represent a pattern of beta-type ganglion cells in the retina of a cat recorded in
Figure 6(a) of W\”assle et al. (1981).
The pattern was first analysed by W\”assle et al (1981) using nearest neighbour distances.
The data used in their analysis are not available.
The present dataset ganglia was scanned from Figure 6(a) of W\”assle et al (1981) in
the early 1990’s, but we have no further information. This dataset is the one analysed by
Van Lieshout and Baddeley (1999) using multitype J functions, and by Stoyan (1995) using
second order methods (pair correlation and mark correlation).
It has now been discovered that these data are incorrect. They are not faithful to the
scale in Figure 6 of W\”assle et al (1981), and they contain some scanning errors. Hence
they should not be used to address the original scientific question. They have been retained
only for comparison with other analyses in the statistical literature.
A new, corrected dataset, scanned from the original microscope image, has been provided
under the name betacells. Use that dataset for any further study.

Warnings
These data are incorrect. Use the new corrected dataset betacells.

Source
W\”assle et al (1981), data supplied by Marie-Colette van Lieshout and attributed to Peter
Diggle

References
Stoyan, D. (1995) Personal communication.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.
W\”assle, H., Boycott, B. B. & Illing, R.-B. (1981). Morphology and mosaic of on- and
off-beta cells in the cat retina and some functional considerations. Proc. Roy. Soc. London
Ser. B 212, 177–195.

Gcross Multitype Nearest Neighbour Distance Function (i-to-j)

Description
For a multitype point pattern, estimate the distribution of the distance from a point of type
i to the nearest point of type j.

Usage
Gcross(X, i, j, r=NULL, breaks=NULL, ..., correction=c("rs", "km", "han"))
200 Gcross

Arguments
X The observed point pattern, from which an estimate of the cross type
distance distribution function Gij (r) will be computed. It must be a mul-
titype point pattern (a marked point pattern whose marks are a factor).
See under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
j Number or character string identifying the type (mark value) of the points
in X to which distances are measured. Defaults to the second level of
marks(X).
r Optional. Numeric vector. The values of the argument r at which the
distribution function Gij (r) should be evaluated. There is a sensible de-
fault. First-time users are strongly advised not to specify this argument.
See below for important conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
... Ignored.
correction Optional. Character string specifying the edge correction(s) to be used.
Options are "none", "rs", "km", "hanisch" and "best".

Details
This function Gcross and its companions Gdot and Gmulti are generalisations of the func-
tion Gest to multitype point patterns.
A multitype point pattern is a spatial pattern of points classified into a finite number of
possible “colours” or “types”. In the spatstat package, a multitype pattern is represented as
a single point pattern object in which the points carry marks, and the mark value attached
to each point determines the type of that point.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern, and the mark vector X$marks
must be a factor. The arguments i and j will be interpreted as levels of the factor X$marks.
(Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest level,
not the number 3).
The “cross-type” (type i to type j) nearest neighbour distance distribution function of a
multitype point process is the cumulative distribution function Gij (r) of the distance from
a typical random point of the process with type i the nearest point of type j.
An estimate of Gij (r) is a useful summary statistic in exploratory data analysis of a multi-
type point pattern. If the process of type i points were independent of the process of type
j points, then Gij (r) would equal Fj (r), the empty space function of the type j points. For
a multitype Poisson point process where the type i points have intensity λi , we have
2
Gij (r) = 1 − e−λj πr

Deviations between the empirical and theoretical Gij curves may suggest dependence be-
tween the points of types i and j.
This algorithm estimates the distribution function Gij (r) from the point pattern X. It as-
sumes that X can be treated as a realisation of a stationary (spatially homogeneous) ran-
dom spatial point process in the plane, observed through a bounded window. The window
Gcross 201

(which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects
are treated in the same manner as in Gest.
The argument r is the vector of values for the distance r at which Gij (r) should be evalu-
ated. It is also used to determine the breakpoints (in the sense of hist) for the computation
of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed
from histogram counts. In the case of the Kaplan-Meier estimator this introduces a dis-
cretisation error which is controlled by the fineness of the breakpoints.
First-time users would be strongly advised not to specify r. However, if it is specified,
r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc
contained in the window. Furthermore, the successive entries of r must be finely spaced.
The algorithm also returns an estimate of the hazard rate function, λ(r), of Gij (r). This
estimate should be used with caution as Gij (r) is not necessarily differentiable.
The naive empirical distribution of distances from each point of the pattern X to the nearest
other point of the pattern, is a biased estimate of Gij . However this is also returned by the
algorithm, as it is sometimes useful in other contexts. Care should be taken not to use the
uncorrected empirical Gij as if it were an unbiased estimator of Gij .

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing six numeric columns

r the values of the argument r at which the function Gij (r) has been esti-
mated
rs the “reduced sample” or “border correction” estimator of Gij (r)
han the Hanisch-style estimator of Gij (r)
km the spatial Kaplan-Meier estimator of Gij (r)
hazard the hazard rate λ(r) of Gij (r) by the spatial Kaplan-Meier method
raw the uncorrected estimate of Gij (r), i.e. the empirical distribution of the
distances from each point of type i to the nearest point of type j
theo the theoretical value of Gij (r) for a marked Poisson process with the same
estimated intensity (see below).

Warnings
The arguments i and j are interpreted as levels of the factor X$marks. Beware of the usual
trap with factors: numerical values are not interpreted in the same way as character values.
See the first example.
The function Gij does not necessarily have a density.
The reduced sample estimator of Gij is pointwise approximately unbiased, but need not
be a valid distribution function; it may not be a nondecreasing function of r. Its range is
always within [0, 1].
The spatial Kaplan-Meier estimator of Gij is always nondecreasing but its maximum value
may be less than 1.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
202 Gdot

References
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit : analysis of a
bivariate spatial point pattern. J. Neurosci. Meth. 18, 115–125.
Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants’ nests. Applied
Statistics 32, 293–303
Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of
several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also
Gdot, Gest, Gmulti

Examples
data(betacells)
# cat retina data
G01 <- Gcross(betacells)

# equivalent to:
## Not run:
G01 <- Gcross(betacells, "off", "on")

## End(Not run)

plot(G01)

# empty space function of `on' points


## Not run:
F1 <- Fest(split(betacells)$on, r = G01$r, eps=10.0)
lines(F1$r, F1$km, lty=3)

## End(Not run)

# synthetic example
pp <- runifpoispp(30)
pp <- pp %mark% factor(sample(0:1, pp$n, replace=TRUE))
G <- Gcross(pp, "0", "1") # note: "0" not 0

Gdot Multitype Nearest Neighbour Distance Function (i-to-any)


Gdot 203

Description
For a multitype point pattern, estimate the distribution of the distance from a point of type
i to the nearest other point of any type.

Usage
Gdot(X, i, r=NULL, breaks=NULL, ..., correction=c("km", "rs", "han"))

Arguments
X The observed point pattern, from which an estimate of the distance dis-
tribution function Gi• (r) will be computed. It must be a multitype point
pattern (a marked point pattern whose marks are a factor). See under
Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
r Optional. Numeric vector. The values of the argument r at which the
distribution function Gi• (r) should be evaluated. There is a sensible de-
fault. First-time users are strongly advised not to specify this argument.
See below for important conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
... Ignored.
correction Optional. Character string specifying the edge correction(s) to be used.
Options are "none", "rs", "km", "hanisch" and "best".

Details
This function Gdot and its companions Gcross and Gmulti are generalisations of the func-
tion Gest to multitype point patterns.
A multitype point pattern is a spatial pattern of points classified into a finite number of
possible “colours” or “types”. In the spatstat package, a multitype pattern is represented as
a single point pattern object in which the points carry marks, and the mark value attached
to each point determines the type of that point.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern, and the mark vector X$marks
must be a factor. The argument will be interpreted as a level of the factor X$marks.
(Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest
level, not the number 3).
The “dot-type” (type i to any type) nearest neighbour distance distribution function of a
multitype point process is the cumulative distribution function Gi• (r) of the distance from
a typical random point of the process with type i the nearest other point of the process,
regardless of type.
An estimate of Gi• (r) is a useful summary statistic in exploratory data analysis of a mul-
titype point pattern. If the type i points were independent of all other points, then Gi• (r)
would equal Gii (r), the nearest neighbour distance distribution function of the type i points
alone. For a multitype Poisson point process with total intensity λ, we have
2
Gi• (r) = 1 − e−λπr
204 Gdot

Deviations between the empirical and theoretical Gi• curves may suggest dependence of the
type i points on the other points.
This algorithm estimates the distribution function Gi• (r) from the point pattern X. It
assumes that X can be treated as a realisation of a stationary (spatially homogeneous)
random spatial point process in the plane, observed through a bounded window. The
window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge
effects are treated in the same manner as in Gest.
The argument r is the vector of values for the distance r at which Gi• (r) should be evalu-
ated. It is also used to determine the breakpoints (in the sense of hist) for the computation
of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed
from histogram counts. In the case of the Kaplan-Meier estimator this introduces a dis-
cretisation error which is controlled by the fineness of the breakpoints.
First-time users would be strongly advised not to specify r. However, if it is specified,
r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc
contained in the window. Furthermore, the successive entries of r must be finely spaced.
The algorithm also returns an estimate of the hazard rate function, λ(r), of Gi• (r). This
estimate should be used with caution as Gi• (r) is not necessarily differentiable.
The naive empirical distribution of distances from each point of the pattern X to the nearest
other point of the pattern, is a biased estimate of Gi• . However this is also returned by the
algorithm, as it is sometimes useful in other contexts. Care should be taken not to use the
uncorrected empirical Gi• as if it were an unbiased estimator of Gi• .

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing six numeric columns
r the values of the argument r at which the function Gi• (r) has been esti-
mated
rs the “reduced sample” or “border correction” estimator of Gi• (r)
han the Hanisch-style estimator of Gi• (r)
km the spatial Kaplan-Meier estimator of Gi• (r)
hazard the hazard rate λ(r) of Gi• (r) by the spatial Kaplan-Meier method
raw the uncorrected estimate of Gi• (r), i.e. the empirical distribution of the
distances from each point of type i to the nearest other point of any type.
theo the theoretical value of Gi• (r) for a marked Poisson process with the same
estimated intensity (see below).

Warnings
The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap
with factors: numerical values are not interpreted in the same way as character values. See
the first example.
The function Gi• does not necessarily have a density.
The reduced sample estimator of Gi• is pointwise approximately unbiased, but need not
be a valid distribution function; it may not be a nondecreasing function of r. Its range is
always within [0, 1].
The spatial Kaplan-Meier estimator of Gi• is always nondecreasing but its maximum value
may be less than 1.
Gest 205

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit : analysis of a
bivariate spatial point pattern. J. Neurosci. Meth. 18, 115–125.
Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants’ nests. Applied
Statistics 32, 293–303
Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of
several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also
Gcross, Gest, Gmulti

Examples
data(betacells)
# cat retina data
G0. <- Gdot(betacells, "off")
plot(G0.)

# synthetic example
pp <- runifpoispp(30)
pp <- pp %mark% factor(sample(0:1, pp$n, replace=TRUE))
G <- Gdot(pp, "0") # note: "0" not 0

Gest Nearest Neighbour Distance Function G

Description
Estimates the nearest neighbour distance distribution function G(r) from a point pattern
in a window of arbitrary shape.

Usage
Gest(X, r=NULL, breaks=NULL, ..., correction=c("rs", "km", "han"))
206 Gest

Arguments
X The observed point pattern, from which an estimate of G(r) will be
computed. An object of class ppp, or data in any format acceptable
to [Link]().
r Optional. Numeric vector. The values of the argument r at which G(r)
should be evaluated. There is a sensible default. First-time users are
strongly advised not to specify this argument. See below for important
conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
... Ignored.
correction Optional. The edge correction(s) to be used to estimate G(r). A vector
of character strings selected from "none", "rs", "km", "Hanisch" and
"best".

Details
The nearest neighbour distance distribution function (also called the “event-to-event ” or
“inter-event ” distribution) of a point process X is the cumulative distribution function G
of the distance from a typical random point of X to the nearest other point of X.
An estimate of G derived from a spatial point pattern dataset can be used in exploratory
data analysis and formal inference about the pattern (Cressie, 1991; Diggle, 1983; Ripley,
1988). In exploratory analyses, the estimate of G is a useful statistic summarising one
aspect of the “clustering” of points. For inferential purposes, the estimate of G is usually
compared to the true value of G for a completely random (Poisson) point process, which is
2
G(r) = 1 − e−λπr

where λ is the intensity (expected number of points per unit area). Deviations between the
empirical and theoretical G curves may suggest spatial clustering or spatial regularity.
This algorithm estimates the nearest neighbour distance distribution function G from the
point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially
homogeneous) random spatial point process in the plane, observed through a bounded
window. The window (which is specified in X as X$window) may have arbitrary shape.
The argument X is interpreted as a point pattern object (of class "ppp", see [Link])
and can be supplied in any of the formats recognised by [Link]().
The estimation of G is hampered by edge effects arising from the unobservability of points
of the random pattern outside the window. An edge correction is needed to reduce bias
(Baddeley, 1998; Ripley, 1988). The edge corrections implemented here are the border
method or “reduced sample” estimator, the spatial Kaplan-Meier estimator (Baddeley and
Gill, 1997) and the Hanisch estimator (Hanisch, 1984).
The argument r is the vector of values for the distance r at which G(r) should be evaluated.
It is also used to determine the breakpoints (in the sense of hist) for the computation
of histograms of distances. The estimators are computed from histogram counts. This
introduces a discretisation error which is controlled by the fineness of the breakpoints.
First-time users would be strongly advised not to specify r. However, if it is specified,
r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc
contained in the window. Furthermore, the successive entries of r must be finely spaced.
Gest 207

The algorithm also returns an estimate of the hazard rate function, λ(r), of G(r). The
hazard rate is defined as the derivative

d
λ(r) = − log(1 − G(r))
dr

This estimate should be used with caution as G is not necessarily differentiable.


The naive empirical distribution of distances from each point of the pattern X to the nearest
other point of the pattern, is a biased estimate of G. However it is sometimes useful. It can
be returned by the algorithm, by selecting correction="none". Care should be taken not
to use the uncorrected empirical G as if it were an unbiased estimator of G.
To simply compute the nearest neighbour distance for each point in the pattern, use nndist.
To determine which point is the nearest neighbour of a given point, use nnwhich.

Value

An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing some or all of the following columns:

r the values of the argument r at which the function G(r) has been esti-
mated
rs the “reduced sample” or “border correction” estimator of G(r)
km the spatial Kaplan-Meier estimator of G(r)
hazard the hazard rate λ(r) of G(r) by the spatial Kaplan-Meier method
raw the uncorrected estimate of G(r), i.e. the empirical distribution of the
distances from each point in the pattern X to the nearest other point of
the pattern
han the Hanisch correction estimator of G(r)
theo the theoretical value of G(r) for a stationary Poisson process of the same
estimated intensity.

Warnings

The function G does not necessarily have a density. Any valid c.d.f. may appear as the
nearest neighbour distance distribution function of a stationary point process.
The reduced sample estimator of G is pointwise approximately unbiased, but need not be a
valid distribution function; it may not be a nondecreasing function of r. Its range is always
within [0, 1].
The spatial Kaplan-Meier estimator of G is always nondecreasing but its maximum value
may be less than 1.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>
208 Geyer

References
Baddeley, A.J. Spatial sampling and censoring. In O.E. Barndorff-Nielsen, W.S. Kendall
and M.N.M. van Lieshout (eds) Stochastic Geometry: Likelihood and Computation. Chap-
man and Hall, 1998. Chapter 2, pages 37-78.
Baddeley, A.J. and Gill, R.D. Kaplan-Meier estimators of interpoint distance distributions
for spatial point processes. Annals of Statistics 25 (1997) 263-292.
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Hanisch, K.-H. (1984) Some remarks on estimators of the distribution function of nearest-
neighbour distance in stationary spatial point patterns. Mathematische Operationsforschung
und Statistik, series Statistics 15, 409–412.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.

See Also
nndist, nnwhich, Fest, Jest, Kest, [Link], [Link], [Link]

Examples
data(cells)
G <- Gest(cells)
plot(G)

# P-P style plot


plot(G, cbind(km,theo) ~ theo)

# the empirical G is below the Poisson G,


# indicating an inhibited pattern

## Not run:
plot(G, . ~ r)
plot(G, . ~ theo)
plot(G, asin(sqrt(.)) ~ asin(sqrt(theo)))

## End(Not run)

Geyer Geyer’s Saturation Point Process Model

Description
Creates an instance of Geyer’s saturation point process model which can then be fitted to
point pattern data.

Usage
Geyer(r,sat)
Geyer 209

Arguments
r Interaction radius. A positive real number.
sat Saturation threshold. A positive real number.

Details
Geyer (1999) introduced the “saturation process”, a modification of the Strauss process
(see Strauss) in which the total contribution to the potential from each point (from its
pairwise interaction with all other points) is trimmed to a maximum value s. This model
is implemented in the function Geyer().
The saturation point process with interaction radius r, saturation threshold s, and param-
eters β and γ, is the point process in which each point xi in the pattern X contributes a
factor
βγ min(s,t(xi ,X))
to the probability density of the point pattern, where t(xi , X) denotes the number of ‘close
neighbours’ of xi in the pattern X. A close neighbour of xi is a point xj with j 6= i such
that the distance between xi and xj is less than or equal to r.
If the saturation threshold s is set to infinity, this model reduces to the Strauss process
(see Strauss) with interaction parameter γ 2 . If s = 0, the model reduces to the Poisson
point process. If s is a finite positive number, then the interaction parameter γ may take
any positive value (unlike the case of the Strauss process), with values γ < 1 describing
an ‘ordered’ or ‘inhibitive’ pattern, and values γ > 1 describing a ‘clustered’ or ‘attractive’
pattern.
The nonstationary saturation process is similar except that the value β is replaced by a
function β(xi ) of location.
The function ppm(), which fits point process models to point pattern data, requires an
argument of class "interact" describing the interpoint interaction structure of the model
to be fitted. The appropriate description of the saturation process interaction is yielded
by Geyer(r, sat) where the arguments r and sat specify the Strauss interaction radius r
and the saturation threshold s, respectively. See the examples below.
Note the only arguments are the interaction radius r and the saturation threshold sat.
When r and sat are fixed, the model becomes an exponential family. The canonical pa-
rameters log(β) and log(γ) are estimated by ppm(), not fixed in Geyer().

Value
An object of class "interact" describing the interpoint interaction structure of Geyer’s
saturation point process with interaction radius r and saturation threshold sat.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E.
Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry:
Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and
Applied Probability, number 80. Pages 79–140.
210 Gmulti

See Also
ppm, [Link], [Link], Strauss, SatPiece

Examples
data(cells)
ppm(cells, ~1, Geyer(r=0.07, sat=2))
# fit the stationary saturation process to `cells'

Gmulti Marked Nearest Neighbour Distance Function

Description
For a marked point pattern, estimate the distribution of the distance from a typical point
in subset I to the nearest point of subset J.

Usage
Gmulti(X, I, J, r=NULL, breaks=NULL, ...,
disjoint=NULL, correction=c("rs", "km", "han"))

Arguments
X The observed point pattern, from which an estimate of the multitype
distance distribution function GIJ (r) will be computed. It must be a
marked point pattern. See under Details.
I Subset of points of X from which distances are measured.
J Subset of points in X to which distances are measured.
r Optional. Numeric vector. The values of the argument r at which the
distribution function GIJ (r) should be evaluated. There is a sensible
default. First-time users are strongly advised not to specify this argument.
See below for important conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
... Ignored.
disjoint Optional flag indicating whether the subsets I and J are disjoint. If
missing, this value will be computed by inspecting the vectors I and J.
correction Optional. Character string specifying the edge correction(s) to be used.
Options are "none", "rs", "km", "hanisch" and "best".

Details
The function Gmulti generalises Gest (for unmarked point patterns) and Gdot and Gcross
(for multitype point patterns) to arbitrary marked point patterns.
Suppose XI , XJ are subsets, possibly overlapping, of a marked point process. This function
computes an estimate of the cumulative distribution function GIJ (r) of the distance from
a typical point of XI to the nearest distinct point of XJ .
Gmulti 211

The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link].
The arguments I and J specify two subsets of the point pattern. They may be logical
vectors of length equal to X$n, or integer vectors with entries in the range 1 to X$n, etc.
This algorithm estimates the distribution function GIJ (r) from the point pattern X. It
assumes that X can be treated as a realisation of a stationary (spatially homogeneous)
random spatial point process in the plane, observed through a bounded window. The
window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge
effects are treated in the same manner as in Gest.
The argument r is the vector of values for the distance r at which GIJ (r) should be evalu-
ated. It is also used to determine the breakpoints (in the sense of hist) for the computation
of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed
from histogram counts. In the case of the Kaplan-Meier estimator this introduces a dis-
cretisation error which is controlled by the fineness of the breakpoints.
First-time users would be strongly advised not to specify r. However, if it is specified,
r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc
contained in the window. Furthermore, the successive entries of r must be finely spaced.
The algorithm also returns an estimate of the hazard rate function, λ(r), of GIJ (r). This
estimate should be used with caution as GIJ (r) is not necessarily differentiable.
The naive empirical distribution of distances from each point of the pattern X to the nearest
other point of the pattern, is a biased estimate of GIJ . However this is also returned by
the algorithm, as it is sometimes useful in other contexts. Care should be taken not to use
the uncorrected empirical GIJ as if it were an unbiased estimator of GIJ .

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing six numeric columns

r the values of the argument r at which the function GIJ (r) has been esti-
mated
rs the “reduced sample” or “border correction” estimator of GIJ (r)
han the Hanisch-style estimator of GIJ (r)
km the spatial Kaplan-Meier estimator of GIJ (r)
hazard the hazard rate λ(r) of GIJ (r) by the spatial Kaplan-Meier method
raw the uncorrected estimate of GIJ (r), i.e. the empirical distribution of the
distances from each point of type i to the nearest point of type j
theo the theoretical value of GIJ (r) for a marked Poisson process with the
same estimated intensity

Warnings
The function GIJ does not necessarily have a density.
The reduced sample estimator of GIJ is pointwise approximately unbiased, but need not
be a valid distribution function; it may not be a nondecreasing function of r. Its range is
always within [0, 1].
The spatial Kaplan-Meier estimator of GIJ is always nondecreasing but its maximum value
may be less than 1.
212 gpc2owin

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit : analysis of a
bivariate spatial point pattern. J. Neurosci. Meth. 18, 115–125.
Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants’ nests. Applied
Statistics 32, 293–303
Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of
several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also
Gcross, Gdot, Gest

Examples
data(longleaf)
# Longleaf Pine data: marks represent diameter

Gm <- Gmulti(longleaf, longleaf$marks <= 15, longleaf$marks >= 25)


plot(Gm)

gpc2owin Convert Polygonal Region into Different Format

Description
Conversion between the different representations of a polygonal region in the packages
spatstat and gpclib.

Usage
gpc2owin(x)
owin2gpc(x)

Arguments
x Object representing a polygonal region. An object of class "owin" in the
spatstat package (for owin2gpc) or an object of class "[Link]" in the
gpclib package (for gpc2owin).
gridcentres 213

Details
The packages spatstat and gpclib have slightly different internal formats for representing a
polygonal region in the two-dimensional plane. In gpclib a polygonal region is an object of
class "[Link]", while in spatstat it is an object of class "owin" and of type "polygonal".
These two functions convert the two formats: owin2gpc converts an "owin" to a "[Link]",
while gpc2owin does the reverse.
Conversion of a "[Link]" to an "owin" can also be performed by calling [Link].

Value
An object of class "owin" in the spatstat package (for gpc2owin) or an object of class
"[Link]" in the gpclib package (for owin2gpc).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link]

Examples
data(letterR)
if([Link]("gpclib") && require(gpclib)) {
R <- owin2gpc(letterR)
L <- gpc2owin(R)
} else cat("gpclib is not available\n")

gridcentres Rectangular grid of points

Description
Generates a rectangular grid of points in a window

Usage
gridcentres(window, nx, ny)

Arguments
window A window. An object of class owin, or data in any format acceptable to
[Link]().
nx Number of points in each row of the rectangular grid.
ny Number of points in each column of the rectangular grid.
214 gridweights

Details
This function creates a rectangular grid of points in the window.
The bounding rectangle of the window is divided into a regular nx × ny grid of rectangular
tiles. The function returns the x, y coordinates of the centres of these tiles.
Note that some of these grid points may lie outside the window, if window is not of type
"rectangle". The function [Link] can be used to select those grid points which do
lie inside the window. See the examples.
This function is useful in creating dummy points for quadrature schemes (see quadscheme)
and for other miscellaneous purposes.

Value
A list with two components x and y, which are numeric vectors giving the coordinates of
the points of the rectangular grid.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], quadscheme, [Link], stratrand

Examples
w <- [Link]()
xy <- gridcentres(w, 10,15)
## Not run:
plot(w)
points(xy)

## End(Not run)

bdry <- list(x=c(0.1,0.3,0.7,0.4,0.2),


y=c(0.1,0.1,0.5,0.7,0.3))
w <- owin(c(0,1), c(0,1), poly=bdry)
xy <- gridcentres(w, 30, 30)
ok <- [Link](xy$x, xy$y, w)
## Not run:
plot(w)
points(xy$x[ok], xy$y[ok])

## End(Not run)

gridweights Compute Quadrature Weights Based on Grid Counts

Description
Computes quadrature weights for a given set of points, using the “counting weights” for a
grid of rectangular tiles.
gridweights 215

Usage
gridweights(X, ntile, ..., window=NULL, verbose=FALSE, npix=NULL, areas=NULL)

Arguments
X Data defining a point pattern.
ntile Number of tiles in each row and column of the rectangular grid. An
integer vector of length 1 or 2.
... Ignored.
window Default window for the point pattern
verbose Logical flag. If TRUE, information will be printed about the computation
of the grid weights.
npix Dimensions of pixel grid to use when computing a digital approximation
to the tile areas.
areas Vector of areas of the tiles, if they are already known.

Details
This function computes a set of quadrature weights for a given pattern of points (typically
comprising both “data” and ‘dummy” points). See [Link] for an explanation of
quadrature weights and quadrature schemes.
The weights are computed by the “counting weights” rule based on a regular grid of rect-
angular tiles. First X and (optionally) window are converted into a point pattern object.
Then the bounding rectangle of the window of the point pattern is divided into a regular
ntile[1] * ntile[2] grid of rectangular tiles. The weight attached to a point of X is the
area of the tile in which it lies, divided by the number of points of X lying in that tile.
For non-rectangular windows the tile areas are currently calculated by approximating the
window as a binary mask. The accuracy of this approximation is controlled by npix, which
becomes the argument dimyx of [Link].

Value
Vector of nonnegative weights for each point in X.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
Q <- quadscheme(runifpoispp(10))
X <- [Link](Q) # data and dummy points together
w <- gridweights(X, 10)
w <- gridweights(X, c(10, 10))
216 harmonic

hamster Aherne’s hamster tumour data

Description
Point pattern of cell nuclei in hamster kidney, each nucleus classified as either ‘dividing’ or
‘pyknotic’. A multitype point pattern.

Usage
data(hamster)

Format
An object of class "ppp" representing the point pattern of cell locations. Entries include

x Cartesian x-coordinate of cell


y Cartesian y-coordinate of cell
marks factor with levels "dividing" and "pyknotic".

See [Link] for details of the format.

Notes
These data were presented and analysed by Diggle (1983, section 7.3).
The data give the positions of the centres of the nuclei of certain cells in a histological section
of tissue from a laboratory-induced metastasising lymphoma in the kidney of a hamster.
The nuclei are classified as either ”pyknotic” (corresponding to dying cells) or ”dividing”
(corresponding to cells arrested in metaphase, i.e. in the act of dividing). The background
void is occupied by unrecorded, interphase cells in relatively large numbers.
The sampling window is a square, originally about 0.25 mm square in real units, which has
been rescaled to the unit square.

Source
Dr W. A. Aherne, Department of Pathology, University of Newcastle-upon-Tyne, UK. Data
supplied by Prof. Peter Diggle

References
Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.

harmonic Basis for Harmonic Functions

Description
Evaluates a basis for the harmonic polynomials in x and y of degree less than or equal to
n.
harmonic 217

Usage
harmonic(x, y, n)

Arguments
x Vector of x coordinates
y Vector of y coordinates
n Maximum degree of polynomial

Details
This function computes a basis for the harmonic polynomials in two variables x and y up
to a given degree n and evaluates them at given x, y locations. It can be used in model
formulas (for example in the model-fitting functions lm,glm,gam and ppm) to specify a linear
predictor which is a harmonic function.
A function f (x, y) is harmonic if

∂2 ∂2
f + f = 0.
∂x2 ∂y 2
The harmonic polynomials of degree less than or equal to n have a basis consisting of 2n
functions.
This function was implemented on a suggestion of P. McCullagh for fitting nonstationary
spatial trend to point process models.

Value
A data frame with 2 * n columns giving the values of the basis functions at the coordinates.
Each column is labelled by an algebraic expression for the corresponding basis function.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm

Examples
data(longleaf)
X <- unmark(longleaf)
# inhomogeneous point pattern

# fit Poisson point process with log-cubic intensity


fit.3 <- ppm(X, ~ polynom(x,y,3), Poisson())

# fit Poisson process with log-cubic-harmonic intensity


fit.h <- ppm(X, ~ harmonic(x,y,3), Poisson())

# Likelihood ratio test


lrts <- 2 * (fit.3$maxlogpl - fit.h$maxlogpl)
218 heather

x <- X$x
y <- X$y
df <- ncol(polynom(x,y,3)) - ncol(harmonic(x,y,3))
pval <- 1 - pchisq(lrts, df=df)

heather Diggle’s Heather Data

Description
The spatial mosaic of vegetation of the heather plant (Calluna vulgaris) recorded in a 10
by 20 metre sampling plot in Sweden.

Usage
data(heather)

Format
A list with three entries, representing the same data at different spatial resolutions:

coarse original heather data, 100 by 200 pixels


medium current heather data, 256 by 512 pixels
fine finest resolution data, 778 by 1570 pixels

Each of these entries is an object of class "owin" containing a binary pixel mask.

Notes on data
These data record the spatial mosaic of vegetation of the heather plant (Calluna vulgaris)
in a 10 by 20 metre sampling plot near Jadraas, Sweden. They were recorded and first
analysed by Diggle(1981).
The dataset heather contains three different versions of the data that have been analysed
by different writers over the decades.

coarse: Data as originally digitised by Diggle in 1983 at 100 by 200 pixels resolution (i.e.
10 pixels = 1 metre).
These data were entered by hand in the form of a run-length encoding (original file no
longer available) and translated by a program into a 100 by 200 pixel binary image.
There are known to be some errors in the image which arise from errors in counting
the run-length so that occasionally there will be an unexpected ’spike’ on one single
column.
fine: A fine scale digitisation of the original map, prepared by CWI (Centre for Computer
Science, Amsterdam, Netherlands) in 1994.
The original hand-drawn map was scanned by Adrian Baddeley, and processed by
Chris Jonker, Henk Heijmans and Adrian Baddeley to yield a clean binary image of
778 by 1570 pixels resolution.
medium: The version of the heather data currently supplied on Professor Diggle’s website.
This is a 256 by 512 pixel image. The method used to create this image is not stated.
Hest 219

History of analysis of data


The data were recorded, presented and analysed by Diggle (1983). He proposed a Boolean
model consisting of discs of random size with centres generated by of a Poisson point process.
Renshaw and Ford (1983) reported that spectral analysis of the data suggested the presence
of strong row and column effects. However, this may have been attributable to errors in
the run-length encoding of the original data.
Hall (1985) and Hall (1988, pp 301-318) took a bootstrap approach.
Ripley (1988, pp. 121-122, 131-135] used opening and closing functions to argue that a
Boolean model of discs is inappropriate.
Cressie (1991, pp. 763-770) tried a more general Boolean model.

Source
Peter Diggle

References
Cressie, N.A.C. (1991) Statistics for Spatial Data. John Wiley and Sons, New York.
Diggle, P.J. (1981) Binary mosaics and the spatial pattern of heather. Biometrics 37,
531-539.
Hall, P. (1985) Resampling a coverage pattern. Stochastic Processes and their Applications
20 231-246.
Hall, P. (1988) An introduction to the theory of coverage processes. John Wiley and Sons,
New York.
Renshaw, E. and Ford, E.D. (1983) The interpretation of process from pattern using two-
dimensional spectral analysis: Methods and problems of interpretation. Applied Statistics
32 51-63.
Ripley, B.D. (1988) Statistical Inference for Spatial Processes. Cambridge University Press.

Hest Spherical Contact Distribution Function

Description
Estimates the spherical contact distribution function of a random set.

Usage
Hest(X, ...)

Arguments
X The observed random set. An object of class "ppp", "psp" or "owin".
... Arguments passed to [Link] to control the discretisation.
220 Hest

Details
The spherical contact distribution function of a stationary random set X is the cumulative
distribution function H of the distance from a fixed point in space to the nearest point of
X, given that the point lies outside X. That is, H(r) equals the probability that X lies
closer than r units away from the fixed point x, given that X does not cover x.
For a point process, the spherical contact distribution function is the same as the empty
space function F discussed in Fest.
For Hest, the argument X may be a point pattern (object of class "ppp"), a line segment
pattern (object of class "psp") or a window (object of class "owin"). It is assumed to be a
realisation of a stationary random set.
The algorithm first calls distmap to compute the distance transform of X, then computes
the Kaplan-Meier and reduced-sample estimates of the cumulative distribution following
Hansen et al (1999).

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing five columns:

r the values of the argument r at which the function H(r) has been esti-
mated
rs the “reduced sample” or “border correction” estimator of H(r)
km the spatial Kaplan-Meier estimator of H(r)
hazard the hazard rate λ(r) of H(r) by the spatial Kaplan-Meier method
raw the uncorrected estimate of H(r), i.e. the empirical distribution of the
distance from a fixed point in the window to the nearest point of X

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A.J. Spatial sampling and censoring. In O.E. Barndorff-Nielsen, W.S. Kendall
and M.N.M. van Lieshout (eds) Stochastic Geometry: Likelihood and Computation. Chap-
man and Hall, 1998. Chapter 2, pages 37-78.
Baddeley, A.J. and Gill, R.D. The empty space hazard of a spatial pattern. Research Report
1994/3, Department of Mathematics, University of Western Australia, May 1994.
Hansen, M.B., Baddeley, A.J. and Gill, R.D. First contact distributions for spatial patterns:
regularity and estimation. Advances in Applied Probability 31 (1999) 15-33.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.

See Also
Fest
[Link] 221

Examples
X <- runifpoint(42)
H <- Hest(X)
Y <- rpoisline(10)
H <- Hest(Y)
data(heather)
H <- Hest(heather$coarse)

[Link] Histogram of Pixel Values in an Image

Description
Computes and displays a histogram of the pixel values in a pixel image. The hist method
for class "im".

Usage
## S3 method for class 'im':
hist(x, ..., probability=FALSE)

Arguments
x A pixel image (object of class "im").
... Arguments passed to [Link] or barplot.
probability Logical. If TRUE, the histogram will be normalised to give probabilities or
probability densities.

Details
This function computes and (by default) displays a histogram of the pixel values in the
image x.
An object of class "im" describes a pixel image. See [Link]) for details of this class.
The function [Link] is a method for the generic function hist for the class "im".
Any arguments in ... are passed to [Link] (for numeric valued images) or barplot
(for factor or logical images). For example, such arguments control the axes, and may be
used to suppress the plotting.

Value
For numeric-valued images, an object of class "histogram" as returned by [Link].
This object can be plotted.
For factor-valued or logical images, an object of class "barplotdata", which can be plotted.
This is a list with components called counts (contingency table of counts of the numbers
of pixels taking each possible value), probs (corresponding relative frequencies) and mids
(graphical x-coordinates of the midpoints of the bars in the barplot).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
222 humberside

See Also
hist, [Link], barplot, [Link], [Link].

Examples
X <- [Link](function(x,y) {x^2}, [Link]())
hist(X)
hist(cut(X,3))

humberside Humberside Data on Childhood Leukaemia and Lymphoma

Description
Spatial locations of cases of childhood leukaemia and lymphoma, and randomly-selected
controls, in North Humberside. A marked point pattern.

Usage
data(humberside)

Format
The dataset humberside is an object of class "ppp" representing a marked point pattern.
Entries include

x Cartesian x-coordinate of home address


y Cartesian y-coordinate of home address
marks factor with levels case and control
indicating whether this is a disease case
or a control.

See [Link] for details of the format.


The dataset [Link] is an object of the same format, representing the same
point pattern data, but contained in a larger, 5-sided convex polygon.

Notes
Cuzick and Edwards (1990) first presented and analysed these data.
The data record 62 cases of childhood leukaemia and lymphoma diagnosed in the North
Humberside region of England between 1974 and 1986, together with 141 controls selected
at random from the birth register for the same period.
The data are represented as a marked point pattern, with the points giving the spatial
location of each individual’s home address (actually, the centroid for the postal code) and
the marks identifying cases and controls.
Coordinates are expressed in units of 100 metres, and the resolution is 100 metres. At this
resolution, there are some duplicated points.
Two versions of the dataset are supplied, both containing the same point coordinates, but
using different windows. The dataset humberside has a polygonal window with 102 edges
which closely approximates the Humberside region, while [Link] has a convex
hyperframe 223

5-sided polygonal window originally used by Diggle and Chetwynd (1991) and shown in
Figure 1 of that paper. (This pentagon has been modified slightly from the original data,
by shifting two vertices horizontally by 1 unit, so that the pentagon contains all the data
points.)

Source
Dr Ray Cartwright and Dr Freda Alexander. Published and analysed in Cuzick and Edwards
(1990), see Table 1. Pentagonal boundary from Diggle and Chetwynd (1991), Figure 1.
Point coordinates and pentagonal boundary supplied by Andrew Lawson. Detailed region
boundary was digitised by Adrian Baddeley, 2005, from a reprint of Cuzick and Edwards
(1990).

References
J. Cuzick and R. Edwards (1990) Spatial clustering for inhomogeneous populations. Journal
of the Royal Statistical Society, series B, 52 (1990) 73-104.
P.J. Diggle and A.G. Chetwynd (1991) Second-order analysis of spatial clustering for inho-
mogeneous populations. Biometrics 47 (1991) 1155-1163.

Examples
data(humberside)
plot(humberside)
plot([Link]$window, add=TRUE, lty=2)

hyperframe Hyper Data Frame

Description
Create a two-dimensional array in which each column consists of values of one type (as in
a data frame) or consists of objects of one class.

Usage
hyperframe(...,
[Link]=NULL, [Link]=FALSE, [Link]=TRUE,
stringsAsFactors=[Link]())

Arguments
... Arguments of the form value or tag=value. Each value is either an
atomic vector, or a list of objects of the same class, or a single atomic
value, or a single object. Each value will become a column of the array.
The tag determines the name of the column. See Details.
[Link],[Link],[Link],stringsAsFactors
Arguments passed to [Link] controlling the names of the rows,
whether to check that rows are consistent, whether to check validity of
the column names, and whether to convert character columns to factors.
224 hyperframe

Details
A hyperframe is like a data frame, except that its entries can be objects of any kind.
A hyperframe is a two-dimensional array in which each column consists of values of one
type (as in a data frame) or consists of objects of one class.
The arguments ... are any number of arguments of the form value or tag=value. Each
value will become a column of the array. The tag determines the name of the column.
Each value can be either
ˆ an atomic vector or factor (i.e. numeric vector, integer vector, character vector, logical
vector, complex vector or factor)
ˆ a list of objects which are all of the same class
ˆ one atomic value, which will be replicated to make an atomic vector or factor
ˆ one object, which will be replicated to make a list of objects.
All columns (vectors, factors and lists) must be of the same length, if their length is greater
than 1.

Value
An object of class "hyperframe".

Methods for Hyperframes


There are methods for print, plot, summary, with, [, $, $<-, names, [Link] and
[Link] for the class of hyperframes. There is also [Link], [Link]
and [Link].

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
# equivalent to a data frame
hyperframe(X=1:10, Y=3)

# list of functions
hyperframe(f=list(sin, cos, tan))

# table of functions and matching expressions


hyperframe(f=list(sin, cos, tan),
e=list(expression(sin(x)), expression(cos(x)), expression(tan(x))))

hyperframe(X=1:10, Y=letters[1:10], Z=factor(letters[1:10]),


stringsAsFactors=FALSE)

lambda <- runif(10, min=50, max=100)


X <- lapply([Link](lambda), function(x) { rpoispp(x) })
hyperframe(lambda=lambda, X=X)
[Link] 225

[Link] Identify Points in a Point Pattern

Description

If a point pattern is plotted in the graphics window, this function will find the point of
the pattern which is nearest to the mouse position, and print its mark value (or its serial
number if there is no mark).

Usage

## S3 method for class 'ppp':


identify(x, ...)

Arguments

x A point pattern (object of class "ppp").


... Arguments passed to [Link].

Details

This is a method for the generic function identify for point pattern objects.
The point pattern x should first be plotted using [Link]. Then identify(x) reads the
position of the graphics pointer each time the left mouse button is pressed. It then finds
the point of the pattern x closest to the mouse position. If this closest point is sufficiently
close to the mouse pointer, its index (and its mark if any) will be returned as part of the
value of the call.
Each time a point of the pattern is identified, text will be displayed next to the point,
showing its serial number (if x is unmarked) or its mark value (if x is marked).

Value

If x is unmarked, the result is a vector containing the serial numbers of the points in the
pattern x that were identified. If x is marked, the result is a 2-column matrix, the first
column containing the serial numbers and the second containing the marks for these points.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

identify, clickppp
226 Iest

Iest Estimate the I-function

Description
Estimates the summary function I(r) for a multitype point pattern.

Usage
Iest(X, ..., eps=NULL, r=NULL, breaks=NULL, correction=NULL)

Arguments
X The observed point pattern, from which an estimate of I(r) will be com-
puted. An object of class "ppp", or data in any format acceptable to
[Link]().
... Ignored.
eps the resolution of the discrete approximation to Euclidean distance (see
below). There is a sensible default.
r Optional. Numeric vector of values for the argument r at which I(r)
should be evaluated. There is a sensible default. First-time users are
strongly advised not to specify this argument. See below for important
conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
Details section.
correction Optional. Vector of character strings specifying the edge correction(s) to
be used by Jest.

Details
The I function summarises the dependence between types in a multitype point process (Van
Lieshout and Baddeley, 1999) It is based on the concept of the J function for an unmarked
point process (Van Lieshout and Baddeley, 1996). See Jest for information about the J
function.
The I function is defined as
m
X
I(r) = pi Jii (r) − J•• (r)
i=1

where J•• is the J function for the entire point process ignoring the marks, while Jii is the
J function for the process consisting of points of type i only, and pi is the proportion of
points which are of type i.
The I function is designed to measure dependence between points of different types, even
if the points are not Poisson. Let X be a stationary multitype point process, and write
Xi for the process of points of type i. If the processes Xi are independent of each other,
then the I-function is identically equal to 0. Deviations I(r) < 1 or I(r) > 1 typically
indicate negative and positive association, respectively, between types. See Van Lieshout
and Baddeley (1999) for further information.
An estimate of I derived from a multitype spatial point pattern dataset can be used in
exploratory data analysis and formal inference about the pattern. The estimate of I(r) is
Iest 227

compared against the constant function 0. Deviations I(r) < 1 or I(r) > 1 may suggest
negative and positive association, respectively.
This algorithm estimates the I-function from the multitype point pattern X. It assumes that
X can be treated as a realisation of a stationary (spatially homogeneous) random spatial
marked point process in the plane, observed through a bounded window.
The argument X is interpreted as a point pattern object (of class "ppp", see [Link])
and can be supplied in any of the formats recognised by [Link](). It must be a multitype
point pattern (it must have a marks vector which is a factor).
The function Jest is called to compute estimates of the J functions in the formula above.
In fact three different estimates are computed using different edge corrections. See Jest for
information.

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing

r the vector of values of the argument r at which the function I has been
estimated
rs the “reduced sample” or “border correction” estimator of I(r) computed
from the border-corrected estimates of J functions
km the spatial Kaplan-Meier estimator of I(r) computed from the Kaplan-
Meier estimates of J functions
han the Hanisch-style estimator of I(r) computed from the Hanisch-style es-
timates of J functions
un the uncorrected estimate of I(r) computed from the uncorrected estimates
of J
theo the theoretical value of I(r) for a stationary Poisson process: identically
equal to 0

Note
Sizeable amounts of memory may be needed during the calculation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Van Lieshout, M.N.M. and Baddeley, A.J. (1996) A nonparametric measure of spatial in-
teraction in point patterns. Statistica Neerlandica 50, 344–361.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also
Jest
228 im

Examples
data(amacrine)
Ic <- Iest(amacrine)
plot(Ic, main="Amacrine Cells data")
# values are below I= 0, suggesting negative association
# between 'on' and 'off' cells.

im Create a Pixel Image Object

Description
Creates an object of class "im" representing a two-dimensional pixel image.

Usage
im(mat, xcol=seq(ncol(mat)), yrow=seq(nrow(mat)), lev=levels(mat),
unitname=NULL)

Arguments
mat matrix or vector containing the pixel values of the image.
xcol vector of x coordinates for the pixel gid
yrow vector of y coordinates for the pixel grid
lev possible factor levels, if mat should be interpreted as a factor.
unitname Optional. Name of unit of length. Either a single character string, or
a vector of two character strings giving the singular and plural forms,
respectively.

Details
This function creates an object of class "im" representing a two-dimensional pixel image.
See [Link] for details of this class.
The matrix mat contains the ‘greyscale’ values for a rectangular grid of pixels. Note carefully
that the entry mat[i,j] gives the pixel value at the location (xcol[j],yrow[i]). That is,
the row index of the matrix mat corresponds to increasing y coordinate, while the column
index of mat corresponds to increasing x coordinate. Thus yrow has one entry for each
row of mat and xcol has one entry for each column of mat. Under the usual convention
in R, a correct display of the image would be obtained by transposing the matrix, e.g.
[Link](xcol, yrow, t(mat)), if you wanted to do it by hand.
The entries of mat may be numeric (real or integer), complex, logical, character, or fac-
tor values. If mat is not a matrix, it will be converted into a matrix with nrow(mat) =
length(yrow) and ncol(mat) = length(xcol).
R does not allow a matrix to have factor-valued entries. So to make a factor-valued image
from raw data, you must supply mat as a factor vector and specify the arguments xcol and
yrow to determine the dimensions of the image. See the examples. (Alternatively you can
use the functions [Link] or [Link] to make factor-valued images from other images).
For a description of the methods available for pixel image objects, see [Link].
To convert other kinds of data to a pixel image (for example, functions or windows), use
[Link].
[Link] 229

Warnings
The internal representation of images is likely to change in future releases of spatstat. The
safe way to extract pixel values from an image object is to use [Link] or [.im.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link], [.im, [Link]

Examples
vec <- rnorm(1200)
mat <- matrix(vec, nrow=30, ncol=40)
whitenoise <- im(mat)
whitenoise <- im(mat, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))
whitenoise <- im(vec, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))
plot(whitenoise)

# FACTOR-VALUED IMAGES:
cutvec <- cut(mat, 3)
# although mat was a matrix, cutvec is a vector, with factor values
cutwhite <- im(cutvec, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))
# cutwhite is a factor-valued image
plot(cutwhite)

[Link] Class of Images

Description
A class "im" to represent a two-dimensional pixel image.

Details
An object of this class represents a two-dimensional pixel image. It specifies
ˆ the dimensions of the rectangular array of pixels
ˆ x and y coordinates for the pixels
ˆ a numeric value (“grey value”) at each pixel

If X is an object of type im, it contains the following elements:

v matrix of values
dim dimensions of matrix v
xrange range of x coordinates of image window
yrange range of y coordinates of image window
xstep width of one pixel
ystep height of one pixel
xcol vector of x coordinates of centres of pixels
yrow vector of y coordinates of centres of pixels
230 incircle

Users are strongly advised not to manipulate these entries directly.


Objects of class "im" may be created by the functions im and [Link]. Image objects are also
returned by various functions including distmap, Kmeasure, setcov, [Link] and [Link].
Image objects may be displayed using the methods [Link], [Link], [Link] and
[Link]. There are also methods [Link] for printing information about an image,
[Link] for summarising an image, [Link] for calculating the average pixel value,
[Link] for plotting a histogram of pixel values, [Link] for calculating quantiles of
pixel values, and [Link] for dividing the range of pixel values into categories.
Pixel values in an image may be extracted using the subset operator [.im. To extract all
pixel values from an image object, use [Link]. The levels of a factor-valued image
can be extracted and changed with levels and levels<-.
Calculations involving one or more images (for example, squaring all the pixel values in
an image, converting numbers to factor levels, or subtracting one image from another) can
often be done easily using [Link]. To find all pixels satisfying a certain constraint, use
solutionset.
Note carefully that the entry v[i,j] gives the pixel value at the location (xcol[j],yrow[i].
That is, the row index of the matrix v corresponds to increasing y coordinate, while the
column index of mat corresponds to increasing x coordinate. Thus yrow has one entry for
each row of v and xcol has one entry for each column of v. Under the usual convention
in R, a correct display of the image would be obtained by transposing the matrix, e.g.
[Link](xcol, yrow, t(v)), if you wanted to do it by hand.

Warnings
The internal representation of images is likely to change in future releases of spatstat. Do
not address the entries in an image directly. To extract all pixel values from an image
object, use [Link].

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
im, [Link], [Link], [Link], [Link], [.im

incircle Find Largest Circle Inside Window

Description
Find the largest circle contained in a given window.

Usage
incircle(W)

Arguments
W A window (object of class "owin").
infline 231

Details
Given a window W of any type and shape, this function determines the largest circle that is
contained inside W.
For non-rectangular windows, the incircle is computed approximately by finding the maxi-
mum of the distance map (see distmap) of the complement of the window.

Value
A list with entries x,y,r giving the location (x,y) and radius r of the incircle.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link]

Examples
W <- square(1)
Wc <- incircle(W)
plot(W)
plot(disc(Wc$r, c(Wc$x, Wc$y)), add=TRUE)

data(letterR)
plot(letterR)
Rc <- incircle(letterR)
plot(disc(Rc$r, c(Rc$x, Rc$y)), add=TRUE)

W <- [Link](letterR)
plot(W)
Rc <- incircle(W)
plot(disc(Rc$r, c(Rc$x, Rc$y)), add=TRUE)

infline Infinite Straight Lines

Description
Define the coordinates of one or more straight lines in the plane

Usage
infline(a = NULL, b = NULL, h = NULL, v = NULL, p = NULL, theta = NULL)
## S3 method for class 'infline':
print(x, ...)
## S3 method for class 'infline':
plot(x, ...)
232 infline

Arguments
a,b Numeric vectors of equal length giving the intercepts a and slopes b of
the lines. Incompatible with h,v,p,theta
h Numeric vector giving the positions of horizontal lines when they cross
the y axis. Incompatible with a,b,v,p,theta
v Numeric vector giving the positions of vertical lines when they cross the
x axis. Incompatible with a,b,h,p,theta
p,theta Numeric vectors of equal length giving the polar coordinates of the line.
Incompatible with a,b,h,v
x An object of class "infline"
... Extra arguments passed to print for printing or abline for plotting

Details
The class infline is a convenient way to handle infinite straight lines in the plane.
The position of a line can be specified in several ways:

ˆ its intercept a and slope b in the equation y = a + bx can be used unless the line is
vertical.
ˆ for vertical lines we can use the position v where the line crosses the y axis
ˆ for horizontal lines we can use the position h where the line crosses the x axis
ˆ the polar coordinates p and θ can be used for any line. The line equation is

y cos θ + x sin θ = p

The command infline will accept line coordinates in any of these formats. The arguments
a,b,h,v have the same interpretation as they do in the line-plotting function abline.
The command infline converts between different coordinate systems (e.g. from a,b to
p,theta) and returns an object of class "infline" that contains a representation of the
lines in each appropriate coordinate system. This object can be printed and plotted.

Value
The value of infline is an object of class "infline" which is basically a data frame with
columns a,b,h,v,p,theta. Each row of the data frame represents one line. Entries may
be NA if a coordinate is not applicable to a particular line.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
infline(a=10:13,b=1)
infline(p=1:3, theta=pi/4)
plot(c(-1,1),c(-1,1),type="n",xlab="",ylab="", asp=1)
plot(infline(p=0.4, theta=seq(0,pi,length=20)))
[Link] 233

[Link] Infinite Order Interaction Family

Description
An object describing the family of all Gibbs point processes with infinite interaction order.

Details
Advanced Use Only!
This structure would not normally be touched by the user. It describes the interaction
structure of Gibbs point processes which have infinite order of interaction, such as the
area-interaction process AreaInter.
Anyway, [Link] is an object of class "isf" containing a function [Link]$eval
for evaluating the sufficient statistics of a Gibbs point process model taking an exponential
family form.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283–322.

See Also
AreaInter to create the area interaction process structure.
Other families: [Link], [Link], [Link].

[Link] Test Whether Points Are Inside A Window

Description
Test whether points lie inside or outside a given window.

Usage
[Link](x, y, w)

Arguments
x Vector of x coordinates of points to be tested.
y Vector of y coordinates of points to be tested.
w A window. This should be an object of class owin, or can be given in any
format acceptable to [Link]().
234 [Link]

Details
This function tests whether each of the points (x[i],y[i]) lies inside or outside the window
w and returns TRUE if it is inside.
The boundary of the window is treated as being inside.
If w is of type "rectangle" or "polygonal", the algorithm uses analytic geometry (the
discrete Stokes theorem). Computation time is linear in the number of points and (for
polygonal windows) in the number of vertices of the boundary polygon. Boundary cases
are correct to single precision accuracy.
If w is of type "mask" then the pixel closest to (x[i],y[i]) is tested. The results may be
incorrect for points lying within one pixel diameter of the window boundary.
Normally x and y must be numeric vectors of equal length (length zero is allowed) containing
the coordinates of points. Alternatively x can be a point pattern (object of class "ppp")
while y is missing; then the coordinates of the point pattern are extracted.

Value
Logical vector whose ith entry is TRUE if the corresponding point (x[i],y[i]) is inside w.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
# hexagonal window
k <- 6
theta <- 2 * pi * (0:(k-1))/k
co <- cos(theta)
si <- sin(theta)
mas <- owin(c(-1,1), c(-1,1), poly=list(x=co, y=si))
## Not run:
plot(mas)

## End(Not run)

# random points in rectangle


x <- runif(30,min=-1, max=1)
y <- runif(30,min=-1, max=1)

ok <- [Link](x, y, mas)

## Not run:
points(x[ok], y[ok])
points(x[!ok], y[!ok], pch="x")

## End(Not run)
[Link] 235

[Link] Interpolate a Pixel Image

Description
Interpolates the values of a pixel image at any desired location in the frame.

Usage
[Link](Z, x, y)

Arguments
Z Pixel image (object of class "im") with numeric or integer values.
x,y Vectors of Cartesian coordinates.

Details
A value at each location (x[i],y[i]) will be interpolated using the pixel values of Z at
the four surrounding pixel centres, by simple bilinear interpolation.
At the boundary (where (x[i],y[i]) is not surrounded by four pixel centres) the value at
the nearest pixel is taken.

Value
Vector of interpolated values, with NA for points that lie outside the domain of the image.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
opa <- par(mfrow=c(1,2))
# coarse image
V <- [Link](function(x,y) { x^2 + y }, owin(), dimyx=10)
plot(V, main="coarse image", col=[Link](256))

# lookup value at location (0.5,0.5)


V[list(x=0.5,y=0.5)]
# interpolated value at location (0.5,0.5)
[Link](V, 0.5, 0.5)
# true value is 0.75

# how to obtain an interpolated image at a desired resolution


U <- [Link]([Link], W=owin(), Z=V, dimyx=256)
plot(U, main="interpolated image", col=[Link](256))
par(opa)
236 [Link]

[Link] Intersection, Union or Set Subtraction of Two Windows

Description

Yields the intersection, union or set subtraction of two windows.

Usage

[Link](A, B, ..., fatal=TRUE)


[Link](A,B, ...)
[Link](A,B, ...)

Arguments

A A window object (see Details).


B A window object.
... Optional arguments passed to [Link] to control the discretisation, if
required.
fatal Logical. Determines what happens if the intersection is empty.

Details

The function [Link] computes the intersection between the two windows A and
B, while [Link] computes their union. The function [Link] computes the
intersection of A with the complement of B.
The arguments A and B must be window objects (either objects of class "owin", or data
that can be coerced to this class by [Link]).
If the intersection is empty, then if fatal=FALSE the result is NULL, while if fatal=TRUE
an error occurs.

Value

A window (object of class "owin").

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [Link], [Link], [Link]


[Link] 237

Examples
# rectangles
u <- [Link]()
v <- owin(c(0.5,3.5), c(0.4,2.5))
# polygon
data(letterR)
# mask
m <- [Link](letterR)

# two rectangles
[Link](u, v)
[Link](u,v)
[Link](u,v)

# polygon and rectangle


[Link](letterR, v)
[Link](letterR,v)
[Link](letterR,v)

# mask and rectangle


[Link](m, v)
[Link](m,v)
[Link](m,v)

# mask and polygon


p <- rotate(v, 0.2)
[Link](m, p)
[Link](m,p)
[Link](m,p)

# two polygons
A <- letterR
B <- rotate(letterR, 0.2)
plot([Link](A,B), main="intersection")
w <- [Link](A, B)
plot(w, add=TRUE, col="lightblue")
plot(A, add=TRUE)
plot(B, add=TRUE)

plot([Link](A,B), main="union")
w <- [Link](A,B)
plot(w, add=TRUE, col="lightblue")
plot(A, add=TRUE)
plot(B, add=TRUE)

plot([Link](A,B), main="set minus")


w <- [Link](A,B)
plot(w, add=TRUE, col="lightblue")
plot(A, add=TRUE)
plot(B, add=TRUE)

[Link] Intersection of Two Tessellations


238 [Link]

Description
Yields the intersection of two tessellations, or the intersection of a tessellation with a win-
dow.

Usage
[Link](X, Y, ...)

Arguments
X,Y Two tessellations (objects of class "tess"), or windows (objects of class
"tess"), or other data that can be converted to tessellations by [Link].
... Optional arguments passed to [Link] to control the discretisation, if
required.

Details
A tessellation is a collection of disjoint spatial regions (called tiles) that fit together to form
a larger spatial region. See tess.
If X and Y are not tessellations, they are first converted into tessellations by [Link].
The function [Link] then computes the intersection between the two tessellations.
This is another tessellation, each of whose tiles is the intersection of a tile from X and a tile
from Y.
One possible use of this function is to slice a window W into subwindows determined by a
tessellation. See the Examples.

Value
A tessellation (object of class "tess").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
tess, [Link], [Link]

Examples
opa <- par(mfrow=c(1,3))
# polygon
data(letterR)
plot(letterR)
# tessellation of rectangles
X <- tess(xgrid=seq(2, 4, length=10), ygrid=seq(0, 3.5, length=8))
plot(X)
plot([Link](X, letterR))

A <- runifpoint(10)
B <- runifpoint(10)
plot(DA <- dirichlet(A))
plot(DB <- dirichlet(B))
iplot 239

plot([Link](DA, DB))

par(opa)

iplot Point and Click Interface for Displaying a Point Pattern

Description
Plot a two-dimensional spatial point pattern with interactive (point-and-click) control over
the plot.

Usage
iplot(x, xname)

Arguments
x The spatial point pattern to be plotted. An object of class "ppp".
xname Optional. Character string to use as the title of the dataset.

Details
This function generates a plot of a spatial point pattern dataset (object of class "ppp") and
allows interactive control over the appearance of the plot using a point-and-click interface.
A new popup window is launched. The point pattern x is displayed in the left half of the
window using [Link] with the default values of all the plot parameters. The right side
of the window contains buttons and sliders allowing the user to change the header text,
the plot symbols, the scale used to represent numeric marks, and so on. For a multitype
point pattern, the user can also switch between viewing all points in a single display, and
splitting the points into separate patterns according to type.

Value
NULL.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
istat, [Link], [Link]

Examples
if(interactive()) {
data(cells)
iplot(cells)
}
240 [Link]

[Link] Test Whether a Window is Convex

Description

Determines whether a window is convex.

Usage

[Link](x)

Arguments

x Window (object of class "owin").

Details

If x is a rectangle, the result is TRUE.


If x is polygonal, the result is TRUE if x consists of a single polygon and this polygon is
equal to the minimal convex hull of its vertices computed by chull.
If x is a mask, the algorithm first extracts all boundary pixels of x using vertices. Then
it computes the (polygonal) convex hull K of the boundary pixels. The result is TRUE if
every boundary pixel lies within one pixel diameter of an edge of K.

Value

Logical value, equal to TRUE if x is convex.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

owin, [Link], vertices

[Link] Test Whether An Object Is Empty

Description

Checks whether the argument is an empty window, an empty point pattern, etc.
[Link] 241

Usage
[Link](x)
## S3 method for class 'owin':
[Link](x)
## S3 method for class 'ppp':
[Link](x)
## S3 method for class 'psp':
[Link](x)
## Default S3 method:
[Link](x)

Arguments
x A window (object of class "owin"), a point pattern (object of class "ppp"),
or a line segment pattern (object of class "psp").

Details
This function tests whether the object x represents an empty spatial object, such as an
empty window, a point pattern with zero points, or a line segment pattern with zero line
segments.
An empty window can be obtained as the output of [Link], erosion, opening,
[Link] and some other operations.
An empty point pattern or line segment pattern can be obtained as the result of simulation.

Value
Logical value.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

[Link] Test Whether An Object Is A Pixel Image

Description
Tests whether its argument is a pixel image (object of class "im").

Usage
[Link](x)

Arguments
x Any object.
242 [Link]

Details
This function tests whether the argument x is a pixel image object of class "im". For details
of this class, see [Link].
The object is determined to be an image if it inherits from class "im".

Value
TRUE if x is a pixel image, otherwise FALSE.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

[Link] Test Whether Marks Are Present

Description
Generic function to test whether a given object (usually a point pattern or something related
to a point pattern) has “marks” attached to the points.

Usage
[Link](X, ...)

Arguments
X Object to be inspected
... Other arguments.

Details
“Marks” are observations attached to each point of a point pattern. For example the
longleaf dataset contains the locations of trees, each tree being marked by its diame-
ter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of
cell may be regarded as a mark attached to the location of the cell.
Other objects related to point patterns, such as point process models, may involve marked
points.
This function tests whether the object X contains or involves marked points. It is generic;
methods are provided for point patterns (objects of class "ppp") and point process models
(objects of class "ppm").

Value
Logical value, equal to TRUE if X is marked.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
[Link] 243

See Also
[Link], [Link]

[Link] Test Whether A Point Process Model is Marked

Description
Tests whether a fitted point process model involves “marks” attached to the points.

Usage
## S3 method for class 'ppm':
[Link](X, ...)

Arguments
X Fitted point process model (object of class "ppm") usually obtained from
ppm.
... Ignored.

Details
“Marks” are observations attached to each point of a point pattern. For example the
longleaf dataset contains the locations of trees, each tree being marked by its diame-
ter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of
cell may be regarded as a mark attached to the location of the cell.
The argument X is a fitted point process model (an object of class "ppm") typically obtained
by fitting a model to point pattern data using ppm.
This function returns TRUE if the original data (to which the model X was fitted) were a
marked point pattern.
Note that this is not the same as testing whether the model involves terms that depend on
the marks (i.e. whether the fitted model ignores the marks in the data). Currently we have
not implemented a test for this.
If this function returns TRUE, the implications are (for example) that any simulation of this
model will require simulation of random marks as well as random point locations.

Value
Logical value, equal to TRUE if X is a model that was fitted to a marked point pattern
dataset.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]
244 [Link]

Examples
data(lansing)
# Multitype point pattern --- trees marked by species

fit1 <- ppm(lansing, ~ marks, Poisson())


[Link](fit1)
# TRUE

fit2 <- ppm(lansing, ~ 1, Poisson())


[Link](fit2)
# TRUE

data(cells)
# Unmarked point pattern

fit3 <- ppm(cells, ~ 1, Poisson())


[Link](fit3)
# FALSE

[Link] Test Whether A Point Pattern is Marked

Description
Tests whether a point pattern has “marks” attached to the points.

Usage
## S3 method for class 'ppp':
[Link](X, [Link]="warn", ...)

Arguments
X Point pattern (object of class "ppp")
[Link] String indicating what to do if NA values are encountered amongst the
marks. Options are "warn", "fatal" and "ignore".
... Ignored.

Details
“Marks” are observations attached to each point of a point pattern. For example the
longleaf dataset contains the locations of trees, each tree being marked by its diame-
ter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of
cell may be regarded as a mark attached to the location of the cell.
This function tests whether the point pattern X contains or involves marked points. It is a
method for the generic function [Link].
The argument [Link] determines what action will be taken if the point pattern has a
vector of marks but some or all of the marks are NA. Options are "fatal" to cause a fatal
error; "warn" to issue a warning and then return TRUE; and "ignore" to take no action
except returning TRUE.
[Link] 245

Value
Logical value, equal to TRUE if X is a marked point pattern.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
data(cells)
[Link](cells) #FALSE
data(longleaf)
[Link](longleaf) #TRUE

[Link] Test whether Object is Multitype

Description
Generic function to test whether a given object (usually a point pattern or something related
to a point pattern) has “marks” attached to the points which classify the points into several
types.

Usage
[Link](X, ...)

Arguments
X Object to be inspected
... Other arguments.

Details
“Marks” are observations attached to each point of a point pattern. For example the
longleaf dataset contains the locations of trees, each tree being marked by its diame-
ter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of
cell may be regarded as a mark attached to the location of the cell. Other objects related
to point patterns, such as point process models, may involve marked points.
This function tests whether the object X contains or involves marked points, and that the
marks are a factor.
For example, the amacrine dataset is multitype (there are two types of cells, on and off),
but the longleaf dataset is not multitype (the marks are real numbers).
This function is generic; methods are provided for point patterns (objects of class "ppp")
and point process models (objects of class "ppm").
246 [Link]

Value
Logical value, equal to TRUE if X is multitype.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

[Link] Test Whether A Point Process Model is Multitype

Description
Tests whether a fitted point process model involves “marks” attached to the points that
classify the points into several types.

Usage
## S3 method for class 'ppm':
[Link](X, ...)

Arguments
X Fitted point process model (object of class "ppm") usually obtained from
ppm.
... Ignored.

Details
“Marks” are observations attached to each point of a point pattern. For example the
longleaf dataset contains the locations of trees, each tree being marked by its diame-
ter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of
cell may be regarded as a mark attached to the location of the cell.
The argument X is a fitted point process model (an object of class "ppm") typically obtained
by fitting a model to point pattern data using ppm.
This function returns TRUE if the original data (to which the model X was fitted) were a
multitype point pattern.
Note that this is not the same as testing whether the model involves terms that depend on
the marks (i.e. whether the fitted model ignores the marks in the data). Currently we have
not implemented a test for this.
If this function returns TRUE, the implications are (for example) that any simulation of this
model will require simulation of random marks as well as random point locations.

Value
Logical value, equal to TRUE if X is a model that was fitted to a multitype point pattern
dataset.
[Link] 247

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
data(lansing)
# Multitype point pattern --- trees marked by species

fit1 <- ppm(lansing, ~ marks, Poisson())


[Link](fit1)
# TRUE

fit2 <- ppm(lansing, ~ 1, Poisson())


[Link](fit2)
# TRUE

data(cells)
# Unmarked point pattern

fit3 <- ppm(cells, ~ 1, Poisson())


[Link](fit3)
# FALSE

[Link] Test Whether A Point Pattern is Multitype

Description
Tests whether a point pattern has “marks” attached to the points which classify the points
into several types.

Usage
## S3 method for class 'ppp':
[Link](X, [Link]="warn", ...)

Arguments
X Point pattern (object of class "ppp")
[Link] String indicating what to do if NA values are encountered amongst the
marks. Options are "warn", "fatal" and "ignore".
... Ignored.
248 [Link]

Details
“Marks” are observations attached to each point of a point pattern. For example the
longleaf dataset contains the locations of trees, each tree being marked by its diame-
ter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of
cell may be regarded as a mark attached to the location of the cell.
This function tests whether the point pattern X contains or involves marked points, and
that the marks are a factor. It is a method for the generic function [Link].
For example, the amacrine dataset is multitype (there are two types of cells, on and off),
but the longleaf dataset is not multitype (the marks are real numbers).
The argument [Link] determines what action will be taken if the point pattern has a
vector of marks but some or all of the marks are NA. Options are "fatal" to cause a fatal
error; "warn" to issue a warning and then return TRUE; and "ignore" to take no action
except returning TRUE.

Value
Logical value, equal to TRUE if X is a multitype point pattern.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
data(cells)
[Link](cells) #FALSE - no marks
data(longleaf)
[Link](longleaf) #FALSE - real valued marks
data(amacrine)
[Link](amacrine) #TRUE

[Link] Test Whether An Object Is A Window

Description
Checks whether its argument is a window (object of class "owin").

Usage
[Link](x)

Arguments
x Any object.
[Link] 249

Details

This function tests whether the object x is a window object of class "owin". See [Link]
for details of this class.
The result is determined to be TRUE if x inherits from "owin", i.e. if x has "owin" amongst
its classes.

Value

TRUE if x is a point pattern, otherwise FALSE.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

[Link] Test Whether An Object Is A Fitted Point Process Model

Description

Checks whether its argument is a fitted point process model (object of class "ppm").

Usage

[Link](x)

Arguments

x Any object.

Details

This function tests whether the object x is a fitted point process model object of class
"ppm". See [Link] for details of this class.

Value

TRUE if x has "ppm" amongst its classes, otherwise FALSE.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>
250 [Link]

[Link] Test Whether An Object Is A Point Pattern

Description
Checks whether its argument is a point pattern (object of class "ppp").

Usage
[Link](x)

Arguments
x Any object.

Details
This function tests whether the object x is a point pattern object of class "ppp". See
[Link] for details of this class.
The result is determined to be TRUE if x inherits from "ppp", i.e. if x has "ppp" amongst
its classes.

Value
TRUE if x is a point pattern, otherwise FALSE.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

[Link] Determine Whether One Window is Contained In Another

Description
Tests whether window A is a subset of window B.

Usage
[Link](A, B)

Arguments
A A window object (see Details).
B A window object (see Details).
istat 251

Details
This function tests whether the window A is a subset of the window B.
The arguments A and B must be window objects (either objects of class "owin", or data
that can be coerced to this class by [Link]).
Various algorithms are used, depending on the geometrical type of the two windows.
Note that if B is not rectangular, the algorithm proceeds by discretising A, converting it
to a pixel mask using [Link]. In this case the resulting answer is only “approximately
correct”. The accuracy of the approximation can be controlled: see [Link].

Value
Logical scalar; TRUE if A is a sub-window of B, otherwise FALSE.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
w1 <- [Link](c(0,1,0,1))
w2 <- [Link](c(-1,2,-1,2))
[Link](w1,w2) # Returns TRUE.
[Link](w2,w1) # Returns FALSE.

istat Point and Click Interface for Exploratory Analysis of Point Pat-
tern

Description
Compute various summary functions for a point pattern using a point-and-click interface.

Usage
istat(x, xname)

Arguments
x The spatial point pattern to be analysed. An object of class "ppp".
xname Optional. Character string to use as the title of the dataset.

Details
This command launches an interactive (point-and-click) interface which offers a choice of
spatial summary functions that can be applied to the point pattern x.
The selected summary function is computed for the point pattern x and plotted in a popup
window.
The selection of functions includes Kest, Lest, pcf, Fest ,Gest and Jest. For the function
pcf it is possible to control the bandwidth parameter bw.
There is also an option to show simulation envelopes of the summary function.
252 japanesepines

Value
NULL.

Note
Before adjusting the bandwidth parameter bw, it is advisable to select No simulation en-
velopes to save a lot of computation time.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
iplot

Examples
if(interactive()) {
data(swedishpines)
istat(swedishpines)
}

japanesepines Japanese Pines Point Pattern

Description
The data give the locations of Japanese black pine saplings in a square sampling region in
a natural forest. The observations were originally collected by Numata (1961).
These data are used as a standard example in the textbook of Diggle (2003); see pages 1,
14, 19, 22, 24, 56–57 and 61.

Usage
data(japanesepines)

Format
An object of class "ppp" representing the point pattern of tree locations in a 5.7 x 5.7 metre
square, rescaled to the unit square and rounded to two decimal places.
See [Link] for details of the format of a point pattern object.

Source
Diggle (2003), obtained from Numata (1961)
Jcross 253

References
Diggle, P.J. (2003) Statistical Analysis of Spatial Point Patterns. Arnold Publishers.
Numata, M. (1961) Forest vegetation in the vicinity of Choshi. Coastal flora and vegetation
at Choshi, Chiba Prefecture. IV. Bulletin of Choshi Marine Laboratory, Chiba University
3, 28–48 (in Japanese).

Jcross Multitype J Function (i-to-j)

Description
For a multitype point pattern, estimate the multitype J function summarising the interpoint
dependence between points of type i and of type j.

Usage
Jcross(X, i, j, eps=NULL, r=NULL, breaks=NULL, ..., correction=NULL)

Arguments
X The observed point pattern, from which an estimate of the multitype J
function Jij (r) will be computed. It must be a multitype point pattern
(a marked point pattern whose marks are a factor). See under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
j Number or character string identifying the type (mark value) of the points
in X to which distances are measured. Defaults to the second level of
marks(X).
eps A positive number. The resolution of the discrete approximation to Eu-
clidean distance (see below). There is a sensible default.
r Optional. Numeric vector. The values of the argument r at which the
function Jij (r) should be evaluated. There is a sensible default. First-
time users are strongly advised not to specify this argument. See below
for important conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
... Ignored.
correction Optional. Character string specifying the edge correction(s) to be used.
Options are "none", "rs", "km", "Hanisch" and "best".

Details
This function Jcross and its companions Jdot and Jmulti are generalisations of the func-
tion Jest to multitype point patterns.
A multitype point pattern is a spatial pattern of points classified into a finite number of
possible “colours” or “types”. In the spatstat package, a multitype pattern is represented as
254 Jcross

a single point pattern object in which the points carry marks, and the mark value attached
to each point determines the type of that point.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern, and the mark vector X$marks
must be a factor. The argument i will be interpreted as a level of the factor X$marks.
(Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest
level, not the number 3).
The “type i to type j” multitype J function of a stationary multitype point process X was
introduced by Van lieshout and Baddeley (1999). It is defined by

1 − Gij (r)
Jij (r) =
1 − Fj (r)

where Gij (r) is the distribution function of the distance from a type i point to the nearest
point of type j, and Fj (r) is the distribution function of the distance from a fixed point in
space to the nearest point of type j in the pattern.
An estimate of Jij (r) is a useful summary statistic in exploratory data analysis of a multi-
type point pattern. If the subprocess of type i points is independent of the subprocess of
points of type j, then Jij (r) ≡ 1. Hence deviations of the empirical estimate of Jij from
the value 1 may suggest dependence between types.
This algorithm estimates Jij (r) from the point pattern X. It assumes that X can be treated
as a realisation of a stationary (spatially homogeneous) random spatial point process in
the plane, observed through a bounded window. The window (which is specified in X as
X$window) may have arbitrary shape. Biases due to edge effects are treated in the same
manner as in Jest, using the Kaplan-Meier and border corrections. The main work is done
by Gmulti and Fest.
The argument r is the vector of values for the distance r at which Jij (r) should be evaluated.
The values of r must be increasing nonnegative numbers and the maximum r value must
exceed the radius of the largest disc contained in the window.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing six numeric columns

J the recommended estimator of Jij (r), currently the Kaplan-Meier estima-


tor.
r the values of the argument r at which the function Jij (r) has been esti-
mated
km the Kaplan-Meier estimator of Jij (r)
rs the “reduced sample” or “border correction” estimator of Jij (r)
han the Hanisch-style estimator of Jij (r)
un the “uncorrected” estimator of Jij (r) formed by taking the ratio of un-
corrected empirical estimators of 1 − Gij (r) and 1 − Fj (r), see Gdot and
Fest.
theo the theoretical value of Jij (r) for a marked Poisson process, namely 1.

The result also has two attributes "G" and "F" which are respectively the outputs of Gcross
and Fest for the point pattern.
Jdot 255

Warnings

The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap
with factors: numerical values are not interpreted in the same way as character values. See
the first example.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Van Lieshout, M.N.M. and Baddeley, A.J. (1996) A nonparametric measure of spatial in-
teraction in point patterns. Statistica Neerlandica 50, 344–361.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Jdot, Jest, Jmulti

Examples
# Lansing woods data: 6 types of trees
data(lansing)

Jhm <- Jcross(lansing, "hickory", "maple")


# diagnostic plot for independence between hickories and maples
plot(Jhm)

# synthetic example with two types "a" and "b"


pp <- runifpoint(30) %mark% factor(sample(c("a","b"), 30, replace=TRUE))
J <- Jcross(pp)

Jdot Multitype J Function (i-to-any)

Description

For a multitype point pattern, estimate the multitype J function summarising the interpoint
dependence between the type i points and the points of any type.

Usage

Jdot(X, i, eps=NULL, r=NULL, breaks=NULL, ..., correction=NULL)


256 Jdot

Arguments
X The observed point pattern, from which an estimate of the multitype J
function Ji• (r) will be computed. It must be a multitype point pattern
(a marked point pattern whose marks are a factor). See under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
eps A positive number. The resolution of the discrete approximation to Eu-
clidean distance (see below). There is a sensible default.
r numeric vector. The values of the argument r at which the function
Ji• (r) should be evaluated. There is a sensible default. First-time users
are strongly advised not to specify this argument. See below for important
conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
... Ignored.
correction Optional. Character string specifying the edge correction(s) to be used.
Options are "none", "rs", "km", "Hanisch" and "best".

Details
This function Jdot and its companions Jcross and Jmulti are generalisations of the func-
tion Jest to multitype point patterns.
A multitype point pattern is a spatial pattern of points classified into a finite number of
possible “colours” or “types”. In the spatstat package, a multitype pattern is represented as
a single point pattern object in which the points carry marks, and the mark value attached
to each point determines the type of that point.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern, and the mark vector X$marks
must be a factor. The argument i will be interpreted as a level of the factor X$marks.
(Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest
level, not the number 3).
The “type i to any type” multitype J function of a stationary multitype point process X
was introduced by Van lieshout and Baddeley (1999). It is defined by

1 − Gi• (r)
Ji• (r) =
1 − F• (r)

where Gi• (r) is the distribution function of the distance from a type i point to the nearest
other point of the pattern, and F• (r) is the distribution function of the distance from a
fixed point in space to the nearest point of the pattern.
An estimate of Ji• (r) is a useful summary statistic in exploratory data analysis of a mul-
titype point pattern. If the pattern is a marked Poisson point process, then Ji• (r) ≡ 1. If
the subprocess of type i points is independent of the subprocess of points of all types not
equal to i, then Ji• (r) equals Jii (r), the ordinary J function (see Jest and Van Lieshout
and Baddeley (1996)) of the points of type i. Hence deviations from zero of the empirical
estimate of Ji• − Jii may suggest dependence between types.
This algorithm estimates Ji• (r) from the point pattern X. It assumes that X can be treated
as a realisation of a stationary (spatially homogeneous) random spatial point process in
Jdot 257

the plane, observed through a bounded window. The window (which is specified in X as
X$window) may have arbitrary shape. Biases due to edge effects are treated in the same
manner as in Jest, using the Kaplan-Meier and border corrections. The main work is done
by Gmulti and Fest.
The argument r is the vector of values for the distance r at which Ji• (r) should be evaluated.
The values of r must be increasing nonnegative numbers and the maximum r value must
exceed the radius of the largest disc contained in the window.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing six numeric columns

J the recommended estimator of Ji• (r), currently the Kaplan-Meier estima-


tor.
r the values of the argument r at which the function Ji• (r) has been esti-
mated
km the Kaplan-Meier estimator of Ji• (r)
rs the “reduced sample” or “border correction” estimator of Ji• (r)
han the Hanisch-style estimator of Ji• (r)
un the “uncorrected” estimator of Ji• (r) formed by taking the ratio of un-
corrected empirical estimators of 1 − Gi• (r) and 1 − F• (r), see Gdot and
Fest.
theo the theoretical value of Ji• (r) for a marked Poisson process, namely 1.

The result also has two attributes "G" and "F" which are respectively the outputs of Gdot
and Fest for the point pattern.

Warnings
The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap
with factors: numerical values are not interpreted in the same way as character values. See
the first example.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Van Lieshout, M.N.M. and Baddeley, A.J. (1996) A nonparametric measure of spatial in-
teraction in point patterns. Statistica Neerlandica 50, 344–361.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also
Jcross, Jest, Jmulti
258 Jest

Examples
# Lansing woods data: 6 types of trees
data(lansing)

Jh. <- Jdot(lansing, "hickory")


plot(Jh.)
# diagnostic plot for independence between hickories and other trees
Jhh <- Jest(lansing[lansing$marks == "hickory", ])
plot(Jhh, add=TRUE)

## Not run:
# synthetic example with two marks "a" and "b"
pp <- runifpoint(30) %mark% factor(sample(c("a","b"), 30, replace=TRUE))
J <- Jdot(pp, "a")

## End(Not run)

Jest Estimate the J-function

Description
Estimates the summary function J(r) for a point pattern in a window of arbitrary shape.

Usage
Jest(X, ..., eps=NULL, r=NULL, breaks=NULL, correction=NULL)

Arguments
X The observed point pattern, from which an estimate of J(r) will be com-
puted. An object of class "ppp", or data in any format acceptable to
[Link]().
... Ignored.
eps the resolution of the discrete approximation to Euclidean distance (see
below). There is a sensible default.
r vector of values for the argument r at which J(r) should be evaluated.
There is a sensible default. First-time users are strongly advised not to
specify this argument. See below for important conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
Details section.
correction Optional. Character string specifying the choice of edge correction(s) in
Fest and Gest.

Details
The J function (Van Lieshout and Baddeley, 1996) of a stationary point process is defined
as
1 − G(r)
J(r) =
1 − F (r)
Jest 259

where G(r) is the nearest neighbour distance distribution function of the point process (see
Gest) and F (r) is its empty space function (see Fest).
For a completely random (uniform Poisson) point process, the J-function is identically
equal to 1. Deviations J(r) < 1 or J(r) > 1 typically indicate spatial clustering or spatial
regularity, respectively. The J-function is one of the few characteristics that can be com-
puted explicitly for a wide range of point processes. See Van Lieshout and Baddeley (1996),
Baddeley et al (2000), Thonnes and Van Lieshout (1999) for further information.
An estimate of J derived from a spatial point pattern dataset can be used in exploratory
data analysis and formal inference about the pattern. The estimate of J(r) is compared
against the constant function 1. Deviations J(r) < 1 or J(r) > 1 may suggest spatial
clustering or spatial regularity, respectively.
This algorithm estimates the J-function from the point pattern X. It assumes that X can
be treated as a realisation of a stationary (spatially homogeneous) random spatial point
process in the plane, observed through a bounded window. The window (which is specified
in X as X$window) may have arbitrary shape.
The argument X is interpreted as a point pattern object (of class "ppp", see [Link])
and can be supplied in any of the formats recognised by [Link]().
The functions Fest and Gest are called to compute estimates of F (r) and G(r) respectively.
These estimates are then combined by simply taking the ratio J(r) = (1 − G(r))/(1 − F (r)).
In fact three different estimates are computed using different edge corrections (Baddeley,
1998). The Kaplan-Meier estimate (returned as km) is the ratio J = (1-G)/(1-F) of the
Kaplan-Meier estimates of 1 − F and 1 − G computed by Fest and Gest respectively. The
reduced-sample or border corrected estimate (returned as rs) is the same ratio J = (1-
G)/(1-F) of the border corrected estimates. These estimators are slightly biased for J, since
they are ratios of approximately unbiased estimators. The logarithm of the Kaplan-Meier
estimate is unbiased for log J.
The uncorrected estimate (returned as un) is the ratio J = (1-G)/(1-F) of the uncorrected
(“raw”) estimates of the survival functions of F and G, which are the empirical distribution
functions of the empty space distances Fest(X,...)$raw and of the nearest neighbour
distances Gest(X,...)$raw. The uncorrected estimates of F and G are severely biased.
However the uncorrected estimate of J is approximately unbiased (if the process is close to
Poisson); it is insensitive to edge effects, and should be used when edge effects are severe
(see Baddeley et al, 2000).
The algorithm for Fest uses two discrete approximations which are controlled by the pa-
rameter eps and by the spacing of values of r respectively. See Fest for details. First-time
users are strongly advised not to specify these arguments.
Note that the value returned by Jest includes the output of Fest and Gest as attributes
(see the last example below). If the user is intending to compute the F,G and J functions
for the point pattern, it is only necessary to call Jest.

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing

r the vector of values of the argument r at which the function J has been
estimated
J the recommended estimate of J(r), which is the Kaplan-Meier estimate
km
260 Jest

rs the “reduced sample” or “border correction” estimator of J(r) computed


from the border-corrected estimates of F and G
km the spatial Kaplan-Meier estimator of J(r) computed from the Kaplan-
Meier estimates of F and G
han the Hanisch-style estimator of J(r) computed from the Hanisch estimate
of G and the Chiu-Stoyan estimate of F
un the uncorrected estimate of J(r) computed from the uncorrected estimates
of F and G
theo the theoretical value of J(r) for a stationary Poisson process: identically
equal to 1
The data frame also has attributes
F the output of Fest for this point pattern, containing three estimates of
the empty space function F (r) and an estimate of its hazard function
G the output of Gest for this point pattern, containing three estimates of
the nearest neighbour distance distribution function G(r) and an estimate
of its hazard function

Note
Sizeable amounts of memory may be needed during the calculation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A.J. Spatial sampling and censoring. In O.E. Barndorff-Nielsen, W.S. Kendall
and M.N.M. van Lieshout (eds) Stochastic Geometry: Likelihood and Computation. Chap-
man and Hall, 1998. Chapter 2, pages 37–78.
Baddeley, A.J. and Gill, R.D. The empty space hazard of a spatial pattern. Research Report
1994/3, Department of Mathematics, University of Western Australia, May 1994.
Baddeley, A.J. and Gill, R.D. Kaplan-Meier estimators of interpoint distance distributions
for spatial point processes. Annals of Statistics 25 (1997) 263–292.
Baddeley, A., Kerscher, M., Schladitz, K. and Scott, B.T. Estimating the J function without
edge correction. Statistica Neerlandica 54 (2000) 315–328.
Borgefors, G. Distance transformations in digital images. Computer Vision, Graphics and
Image Processing 34 (1986) 344–371.
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.
Thonnes, E. and Van Lieshout, M.N.M, A comparative study on the power of Van Lieshout
and Baddeley’s J-function. Biometrical Journal 41 (1999) 721–734.
Van Lieshout, M.N.M. and Baddeley, A.J. A nonparametric measure of spatial interaction
in point patterns. Statistica Neerlandica 50 (1996) 344–361.
Jmulti 261

See Also
Fest, Gest, Kest, [Link], [Link], [Link]

Examples
data(cells)
J <- Jest(cells, 0.01)
plot(J, main="cells data")
# values are far above J= 1, indicating regular pattern

data(redwood)
J <- Jest(redwood, 0.01)
plot(J, main="redwood data")
# values are below J= 1, indicating clustered pattern

Jmulti Marked J Function

Description
For a marked point pattern, estimate the multitype J function summarising dependence
between the points in subset I and those in subset J.

Usage
Jmulti(X, I, J, eps=NULL, r=NULL, breaks=NULL, ..., disjoint=NULL,
correction=NULL)

Arguments
X The observed point pattern, from which an estimate of the multitype
distance distribution function JIJ (r) will be computed. It must be a
marked point pattern. See under Details.
I Subset of points of X from which distances are measured.
J Subset of points in X to which distances are measured.
eps A positive number. The pixel resolution of the discrete approximation to
Euclidean distance (see Jest). There is a sensible default.
r numeric vector. The values of the argument r at which the distribution
function JIJ (r) should be evaluated. There is a sensible default. First-
time users are strongly advised not to specify this argument. See below
for important conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
... Ignored.
disjoint Optional flag indicating whether the subsets I and J are disjoint. If
missing, this value will be computed by inspecting the vectors I and J.
correction Optional. Character string specifying the edge correction(s) to be used.
Options are "none", "rs", "km", "Hanisch" and "best".
262 Jmulti

Details
The function Jmulti generalises Jest (for unmarked point patterns) and Jdot and Jcross
(for multitype point patterns) to arbitrary marked point patterns.
Suppose XI , XJ are subsets, possibly overlapping, of a marked point process. Define

1 − GIJ (r)
JIJ (r) =
1 − FJ (r)

where FJ (r) is the cumulative distribution function of the distance from a fixed location
to the nearest point of XJ , and GIJ (r) is the distribution function of the distance from a
typical point of XI to the nearest distinct point of XJ .
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link].
The arguments I and J specify two subsets of the point pattern. They may be logical
vectors of length equal to X$n, or integer vectors with entries in the range 1 to X$n, etc.
It is assumed that X can be treated as a realisation of a stationary (spatially homogeneous)
random spatial point process in the plane, observed through a bounded window. The
window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge
effects are treated in the same manner as in Jest.
The argument r is the vector of values for the distance r at which JIJ (r) should be evalu-
ated. It is also used to determine the breakpoints (in the sense of hist) for the computation
of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed
from histogram counts. In the case of the Kaplan-Meier estimator this introduces a dis-
cretisation error which is controlled by the fineness of the breakpoints.
First-time users would be strongly advised not to specify r. However, if it is specified,
r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc
contained in the window. Furthermore, the successive entries of r must be finely spaced.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing six numeric columns

r the values of the argument r at which the function JIJ (r) has been esti-
mated
rs the “reduced sample” or “border correction” estimator of JIJ (r)
km the spatial Kaplan-Meier estimator of JIJ (r)
han the Hanisch-style estimator of JIJ (r)
un the uncorrected estimate of JIJ (r), formed by taking the ratio of uncor-
rected empirical estimators of 1 − GIJ (r) and 1 − FJ (r), see Gdot and
Fest.
theo the theoretical value of JIJ (r) for a marked Poisson process with the same
estimated intensity, namely 1.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
K3est 263

References
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also
Jcross, Jdot, Jest

Examples
data(longleaf)
# Longleaf Pine data: marks represent diameter

Jm <- Jmulti(longleaf, longleaf$marks <= 15, longleaf$marks >= 25)


plot(Jm)

K3est K-function of a Three-Dimensional Point Pattern

Description
Estimates the K-function from a three-dimensional point pattern.

Usage
K3est(X, ..., rmax = NULL, nrval = 128, correction = c("translation", "isotropic"))

Arguments
X Three-dimensional point pattern (object of class "pp3").
... Ignored.
rmax Optional. Maximum value of argument r for which K3 (r) will be esti-
mated.
nrval Optional. Number of values of r for which K3 (r) will be estimated. A
large value of nrval is required to avoid discretisation effects.
correction Optional. Character vector specifying the edge correction(s) to be applied.
See Details.

Details
For a stationary point process Φ in three-dimensional space, the three-dimensional K func-
tion is
1
K3 (r) = E(N (Φ, x, r) | x ∈ Φ)
λ
where λ is the intensity of the process (the expected number of points per unit volume) and
N (Φ, x, r) is the number of points of Φ, other than x itself, which fall within a distance r of
x. This is the three-dimensional generalisation of Ripley’s K function for two-dimensional
point processes (Ripley, 1977).
264 [Link]

The three-dimensional point pattern X is assumed to be a partial realisation of a stationary


point process Φ. The distance between each pair of distinct points is computed. The em-
pirical cumulative distribution function of these values, with appropriate edge corrections,
is renormalised to give the estimate of K3 (r).
The available edge corrections are:

"translation": the Ohser translation correction estimator (Ohser, 1983; Baddeley et al,
1993)
"isotropic": the three-dimensional counterpart of Ripley’s isotropic edge correction (Rip-
ley, 1977; Baddeley et al, 1993).

Value
A function value table (object of class "fv") that can be plotted, printed or coerced to a
data frame containing the function values.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rana Moyeed.

References
Baddeley, A.J, Moyeed, R.A., Howard, C.V. and Boyde, A. (1993) Analysis of a three-
dimensional point pattern with replication. Applied Statistics 42, 641–668.
Ohser, J. (1983) On estimators for the reduced second moment measure of point processes.
Mathematische Operationsforschung und Statistik, series Statistics, 14, 63 – 71.
Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal
Statistical Society, Series B, 39, 172 – 212.

See Also
F3est, G3est

Examples
X <- rpoispp3(42)
Z <- K3est(X)
if(interactive()) plot(Z)

[Link] Kaplan-Meier Estimator using Histogram Data

Description
Compute the Kaplan-Meier estimator of a survival time distribution function, from his-
togram data

Usage
[Link](obs, nco, breaks, upperobs=0)
[Link] 265

Arguments
obs vector of n integers giving the histogram of all observations (censored or
uncensored survival times)
nco vector of n integers giving the histogram of uncensored observations (those
survival times that are less than or equal to the censoring time)
breaks Vector of n + 1 breakpoints which were used to form both histograms.
upperobs Number of observations beyond the rightmost breakpoint, if any.

Details
This function is needed mainly for internal use in spatstat, but may be useful in other
applications where you want to form the Kaplan-Meier estimator from a huge dataset.
Suppose Ti are the survival times of individuals i = 1, . . . , M with unknown distribution
function F (t) which we wish to estimate. Suppose these times are right-censored by random
censoring times Ci . Thus the observations consist of right-censored survival times T̃i =
min(Ti , Ci ) and non-censoring indicators Di = 1{Ti ≤ Ci } for each i.
If the number of observations M is large, it is efficient to use histograms. Form the histogram
obs of all observed times T̃i . That is, obs[k] counts the number of values T̃i in the interval
(breaks[k],breaks[k+1]] for k > 1 and [breaks[1],breaks[2]] for k = 1. Also form
the histogram nco of all uncensored times, i.e. those T̃i such that Di = 1. These two
histograms are the arguments passed to [Link].
The vectors km and lambda returned by [Link] are (histogram approximations to)
the Kaplan-Meier estimator of F (t) and its hazard rate λ(t). Specifically, km[k] is an
estimate of F(breaks[k+1]), and lambda[k] is an estimate of the average of λ(t) over the
interval (breaks[k],breaks[k+1]).
The histogram breaks must include 0. If the histogram breaks do not span the range of
the observations, it is important to count how many survival times T̃i exceed the rightmost
breakpoint, and give this as the value upperobs.

Value
A list with two elements:

km Kaplan-Meier estimate of the survival time c.d.f. F (t)


lambda corresponding Nelson-Aalen estimate of the hazard rate λ(t)

These are numeric vectors of length n.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]
266 Kcross

Kcross Multitype K Function (Cross-type)

Description
For a multitype point pattern, estimate the multitype K function which counts the expected
number of points of type j within a given distance of a point of type i.

Usage
Kcross(X, i, j, r=NULL, breaks=NULL, correction, ...)

Arguments
X The observed point pattern, from which an estimate of the cross type K
function Kij (r) will be computed. It must be a multitype point pattern
(a marked point pattern whose marks are a factor). See under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
j Number or character string identifying the type (mark value) of the points
in X to which distances are measured. Defaults to the second level of
marks(X).
r numeric vector. The values of the argument r at which the distribution
function Kij (r) should be evaluated. There is a sensible default. First-
time users are strongly advised not to specify this argument. See below
for important conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
correction A character vector containing any selection of the options "border",
"[Link]", "isotropic", "Ripley", "translate", "none" or "best".
It specifies the edge correction(s) to be applied.
... Ignored.

Details
This function Kcross and its companions Kdot and Kmulti are generalisations of the func-
tion Kest to multitype point patterns.
A multitype point pattern is a spatial pattern of points classified into a finite number of
possible “colours” or “types”. In the spatstat package, a multitype pattern is represented as
a single point pattern object in which the points carry marks, and the mark value attached
to each point determines the type of that point.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern, and the mark vector X$marks
must be a factor.
The arguments i and j will be interpreted as levels of the factor X$marks. If i and j are
missing, they default to the first and second level of the marks factor, respectively.
The “cross-type” (type i to type j) K function of a stationary multitype point process X is
defined so that λj Kij (r) equals the expected number of additional random points of type j
Kcross 267

within a distance r of a typical point of type i in the process X. Here λj is the intensity of
the type j points, i.e. the expected number of points of type j per unit area. The function
Kij is determined by the second order moment properties of X.
An estimate of Kij (r) is a useful summary statistic in exploratory data analysis of a multi-
type point pattern. If the process of type i points were independent of the process of type
j points, then Kij (r) would equal πr2 . Deviations between the empirical Kij curve and the
theoretical curve πr2 may suggest dependence between the points of types i and j.
This algorithm estimates the distribution function Kij (r) from the point pattern X. It
assumes that X can be treated as a realisation of a stationary (spatially homogeneous)
random spatial point process in the plane, observed through a bounded window. The
window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge
effects are treated in the same manner as in Kest, using the border correction.
The argument r is the vector of values for the distance r at which Kij (r) should be evaluated.
The values of r must be increasing nonnegative numbers and the maximum r value must
exceed the radius of the largest disc contained in the window.
The pair correlation function can also be applied to the result of Kcross; see pcf.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns

r the values of the argument r at which the function Kij (r) has been esti-
mated
theo the theoretical value of Kij (r) for a marked Poisson process, namely πr2

together with a column or columns named "border", "[Link]", "iso" and/or "trans",
according to the selected edge corrections. These columns contain estimates of the function
Kij (r) obtained by the edge corrections named.

Warnings
The arguments i and j are interpreted as levels of the factor X$marks. Beware of the usual
trap with factors: numerical values are not interpreted in the same way as character values.
See the first example.
The reduced sample estimator of Kij is pointwise approximately unbiased, but need not
be a valid distribution function; it may not be a nondecreasing function of r. Its range is
always within [0, 1].

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants’ nests. Applied
Statistics 32, 293–303
268 [Link]

Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of


several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.

See Also
Kdot, Kest, Kmulti, pcf

Examples
data(betacells)
# cat retina data
K01 <- Kcross(betacells, "off", "on")
plot(K01)

## Not run:
K10 <- Kcross(betacells, "on", "off")

# synthetic example
pp <- runifpoispp(50)
pp <- pp %mark% factor(sample(0:1, pp$n, replace=TRUE))
K <- Kcross(pp, "0", "1") # note: "0" not 0

## End(Not run)

[Link] Inhomogeneous Cross K Function

Description
For a multitype point pattern, estimate the inhomogeneous version of the cross K function,
which counts the expected number of points of type j within a given distance of a point of
type i, adjusted for spatially varying intensity.

Usage
[Link](X, i, j, lambdaI=NULL, lambdaJ=NULL, ..., r=NULL, breaks=NULL,
correction = c("border", "isotropic", "Ripley", "translate"),
sigma=NULL, varcov=NULL,
lambdaIJ=NULL)

Arguments
X The observed point pattern, from which an estimate of the inhomogeneous
cross type K function Kij (r) will be computed. It must be a multitype
point pattern (a marked point pattern whose marks are a factor). See
under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
[Link] 269

j Number or character string identifying the type (mark value) of the points
in X to which distances are measured. Defaults to the second level of
marks(X).
lambdaI Optional. Values of the the estimated intensity of the sub-process of
points of type i. Either a pixel image (object of class "im"), a numeric
vector containing the intensity values at each of the type i points in X,
or a function(x,y) which can be evaluated to give the intensity value at
any location.
lambdaJ Optional. Values of the the estimated intensity of the sub-process of
points of type j. Either a pixel image (object of class "im"), a numeric
vector containing the intensity values at each of the type j points in X,
or a function(x,y) which can be evaluated to give the intensity value at
any location.
r Optional. Numeric vector giving the values of the argument r at which the
cross K function Kij (r) should be evaluated. There is a sensible default.
First-time users are strongly advised not to specify this argument. See
below for important conditions on r.
breaks Optional. An alternative to the argument r. Not normally invoked by
the user. See the Details section.
correction A character vector containing any selection of the options "border",
"[Link]", "isotropic", "Ripley", "translate", "none" or "best".
It specifies the edge correction(s) to be applied.
... Ignored.
sigma Standard deviation of isotropic Gaussian smoothing kernel, used in com-
puting leave-one-out kernel estimates of lambdaI, lambdadot if they are
omitted.
varcov Variance-covariance matrix of anisotropic Gaussian kernel, used in com-
puting leave-one-out kernel estimates of lambdaI, lambdadot if they are
omitted. Incompatible with sigma.
lambdaIJ Optional. A matrix containing estimates of the product of the intensities
lambdaI and lambdaJ for each pair of points of types i and j respectively.

Details
This is a generalisation of the function Kcross to include an adjustment for spatially inho-
mogeneous intensity, in a manner similar to the function Kinhom.
The inhomogeneous cross-type K function is described by Moller and Waagepetersen (2003,
pages 48-49 and 51-53).
Briefly, given a multitype point process, suppose the sub-process of points of type j has
intensity function λj (u) at spatial locations u. Suppose we place a mass of 1/λj (ζ) at each
point ζ of type j. Then the expected total mass per unit area is 1. The inhomogeneous
“cross-type” K function Kij inhom (r) equals the expected total mass within a radius r of a
point of the process of type i.
If the process of type i points were independent of the process of type j points, then
Kijinhom (r) would equal πr2 . Deviations between the empirical K curve and the theoretical
ij
curve πr2 suggest dependence between the points of types i and j.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern, and the mark vector X$marks
must be a factor.
270 [Link]

The arguments i and j will be interpreted as levels of the factor X$marks. (Warning: this
means that an integer value i=3 will be interpreted as the 3rd smallest level, not the number
3). If i and j are missing, they default to the first and second level of the marks factor,
respectively.
The argument lambdaI supplies the values of the intensity of the sub-process of points of
type i. It may be either
a pixel image (object of class "im") which gives the values of the type i intensity at all
locations in the window containing X;
a numeric vector containing the values of the type i intensity evaluated only at the data
points of type i. The length of this vector must equal the number of type i points in
X.
a function which can be evaluated to give values of the intensity at any locations.
omitted: if lambdaI is omitted then it will be estimated using a leave-one-out kernel
smoother.
If lambdaI is omitted, then it will be estimated using a ‘leave-one-out’ kernel smoother,
as described in Baddeley, Moller and Waagepetersen (2000). The estimate of lambdaI
for a given point is computed by removing the point from the point pattern, applying
kernel smoothing to the remaining points using [Link], and evaluating the smoothed
intensity at the point in question. The smoothing kernel bandwidth is controlled by the
arguments sigma and varcov, which are passed to [Link] along with any extra
arguments.
Similarly lambdaJ should contain estimated values of the intensity of the sub-process of
points of type j. It may be either a pixel image, a function, a numeric vector, or omitted.
The optional argument lambdaIJ is for advanced use only. It is a matrix containing esti-
mated values of the products of these two intensities for each pair of data points of types i
and j respectively.
The argument r is the vector of values for the distance r at which Kij (r) should be evaluated.
The values of r must be increasing nonnegative numbers and the maximum r value must
exceed the radius of the largest disc contained in the window.
The argument correction chooses the edge correction as explained e.g. in Kest.
The pair correlation function can also be applied to the result of [Link]; see pcf.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns
r the values of the argument r at which the function Kij (r) has been esti-
mated
theo the theoretical value of Kij (r) for a marked Poisson process, namely πr2
together with a column or columns named "border", "[Link]", "iso" and/or "trans",
according to the selected edge corrections. These columns contain estimates of the function
Kij (r) obtained by the edge corrections named.

Warnings
The arguments i and j are interpreted as levels of the factor X$marks. Beware of the usual
trap with factors: numerical values are not interpreted in the same way as character values.
Kdot 271

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Moller, J. and Waagepetersen, R. Statistical Inference and Simulation for Spatial Point
Processes Chapman and Hall/CRC Boca Raton, 2003.

See Also
Kcross, Kinhom, pcf

Examples
# Lansing Woods data
data(lansing)
lansing <- lansing[seq(1,lansing$n, by=10)]
ma <- split(lansing)$maple
wh <- split(lansing)$whiteoak

# method (1): estimate intensities by nonparametric smoothing


lambdaM <- [Link](ma, sigma=0.15, at="points")
lambdaW <- [Link](wh, sigma=0.15, at="points")
K <- [Link](lansing, "whiteoak", "maple", lambdaW, lambdaM)

# method (2): leave-one-out


K <- [Link](lansing, "whiteoak", "maple", sigma=0.15)

# method (3): fit parametric intensity model


fit <- ppm(lansing, ~marks * polynom(x,y,2))
# evaluate fitted intensities at data points
# (these are the intensities of the sub-processes of each type)
inten <- fitted(fit, dataonly=TRUE)
# split according to types of points
lambda <- split(inten, lansing$marks)
K <- [Link](lansing, "whiteoak", "maple",
lambda$whiteoak, lambda$maple)

# synthetic example: type A points have intensity 50,


# type B points have intensity 100 * x
lamB <- [Link](function(x,y){50 + 100 * x}, owin())
X <- superimpose(A=runifpoispp(50), B=rpoispp(lamB))
K <- [Link](X, "A", "B",
lambdaI=[Link](50, X$window), lambdaJ=lamB)

Kdot Multitype K Function (i-to-any)

Description
For a multitype point pattern, estimate the multitype K function which counts the expected
number of other points of the process within a given distance of a point of type i.
272 Kdot

Usage
Kdot(X, i, r=NULL, breaks=NULL, correction, ...)

Arguments
X The observed point pattern, from which an estimate of the multitype K
function Ki• (r) will be computed. It must be a multitype point pattern
(a marked point pattern whose marks are a factor). See under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
r numeric vector. The values of the argument r at which the distribution
function Ki• (r) should be evaluated. There is a sensible default. First-
time users are strongly advised not to specify this argument. See below
for important conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
correction A character vector containing any selection of the options "border",
"[Link]", "isotropic", "Ripley", "translate", "none" or "best".
It specifies the edge correction(s) to be applied.
... Ignored.

Details
This function Kdot and its companions Kcross and Kmulti are generalisations of the func-
tion Kest to multitype point patterns.
A multitype point pattern is a spatial pattern of points classified into a finite number of
possible “colours” or “types”. In the spatstat package, a multitype pattern is represented as
a single point pattern object in which the points carry marks, and the mark value attached
to each point determines the type of that point.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern, and the mark vector X$marks
must be a factor.
The argument i will be interpreted as a level of the factor X$marks. If i is missing, it
defaults to the first level of the marks factor, i = levels(X$marks)[1].
The “type i to any type” multitype K function of a stationary multitype point process X is
defined so that λKi• (r) equals the expected number of additional random points within a
distance r of a typical point of type i in the process X. Here λ is the intensity of the process,
i.e. the expected number of points of X per unit area. The function Ki• is determined by
the second order moment properties of X.
An estimate of Ki• (r) is a useful summary statistic in exploratory data analysis of a mul-
titype point pattern. If the subprocess of type i points were independent of the subprocess
of points of all types not equal to i, then Ki• (r) would equal πr2 . Deviations between the
empirical Ki• curve and the theoretical curve πr2 may suggest dependence between types.
This algorithm estimates the distribution function Ki• (r) from the point pattern X. It
assumes that X can be treated as a realisation of a stationary (spatially homogeneous)
random spatial point process in the plane, observed through a bounded window. The
window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge
effects are treated in the same manner as in Kest, using the border correction.
Kdot 273

The argument r is the vector of values for the distance r at which Ki• (r) should be evaluated.
The values of r must be increasing nonnegative numbers and the maximum r value must
exceed the radius of the largest disc contained in the window.
The pair correlation function can also be applied to the result of Kdot; see pcf.

Value

An object of class "fv" (see [Link]).


Essentially a data frame containing numeric columns

r the values of the argument r at which the function Ki• (r) has been esti-
mated
theo the theoretical value of Ki• (r) for a marked Poisson process, namely πr2

together with a column or columns named "border", "[Link]", "iso" and/or "trans",
according to the selected edge corrections. These columns contain estimates of the function
Ki• (r) obtained by the edge corrections named.

Warnings

The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap
with factors: numerical values are not interpreted in the same way as character values. See
the first example.
The reduced sample estimator of Ki• is pointwise approximately unbiased, but need not
be a valid distribution function; it may not be a nondecreasing function of r. Its range is
always within [0, 1].

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants’ nests. Applied
Statistics 32, 293–303
Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of
several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.

See Also

Kdot, Kest, Kmulti, pcf


274 [Link]

Examples
# Lansing woods data: 6 types of trees
data(lansing)

## Not run:
Kh. <- Kdot(lansing, "hickory")

## End(Not run)

# diagnostic plot for independence between hickories and other trees


plot(Kh.)

## Not run:
# synthetic example with two marks "a" and "b"
pp <- runifpoispp(50)
pp <- pp %mark% factor(sample(c("a","b"), pp$n, replace=TRUE))
K <- Kdot(pp, "a")

## End(Not run)

[Link] Inhomogeneous Multitype K Dot Function

Description
For a multitype point pattern, estimate the inhomogeneous version of the dot K function,
which counts the expected number of points of any type within a given distance of a point
of type i, adjusted for spatially varying intensity.

Usage
[Link](X, i, lambdaI=NULL, lambdadot=NULL, ..., r=NULL, breaks=NULL,
correction = c("border", "isotropic", "Ripley", "translate"),
sigma=NULL, varcov=NULL, lambdaIdot=NULL)

Arguments
X The observed point pattern, from which an estimate of the inhomogeneous
cross type K function Ki• (r) will be computed. It must be a multitype
point pattern (a marked point pattern whose marks are a factor). See
under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
lambdaI Optional. Values of the estimated intensity of the sub-process of points
of type i. Either a pixel image (object of class "im"), a numeric vector
containing the intensity values at each of the type i points in X, or a
function(x,y) which can be evaluated to give the intensity value at any
location.
lambdadot Optional. Values of the estimated intensity of the entire point process,
Either a pixel image (object of class "im"), a numeric vector containing
the intensity values at each of the points in X, or a function(x,y) which
can be evaluated to give the intensity value at any location.
[Link] 275

... Ignored.
r Optional. Numeric vector giving the values of the argument r at which the
cross K function Kij (r) should be evaluated. There is a sensible default.
First-time users are strongly advised not to specify this argument. See
below for important conditions on r.
breaks Optional. An alternative to the argument r. Not normally invoked by
the user. See the Details section.
correction A character vector containing any selection of the options "border",
"[Link]", "isotropic", "Ripley", "translate", "none" or "best".
It specifies the edge correction(s) to be applied.
sigma Standard deviation of isotropic Gaussian smoothing kernel, used in com-
puting leave-one-out kernel estimates of lambdaI, lambdadot if they are
omitted.
varcov Variance-covariance matrix of anisotropic Gaussian kernel, used in com-
puting leave-one-out kernel estimates of lambdaI, lambdadot if they are
omitted. Incompatible with sigma.
lambdaIdot Optional. A matrix containing estimates of the product of the intensities
lambdaI and lambdadot for each pair of points, the first point of type i
and the second of any type.

Details
This is a generalisation of the function Kdot to include an adjustment for spatially inhomo-
geneous intensity, in a manner similar to the function Kinhom.
Briefly, given a multitype point process, consider the points without their types, and suppose
this unmarked point process has intensity function λ(u) at spatial locations u. Suppose we
place a mass of 1/λ(ζ) at each point ζ of the process. Then the expected total mass per
unit area is 1. The inhomogeneous “dot-type” K function Ki• inhom (r) equals the expected
total mass within a radius r of a point of the process of type i, discounting this point itself.
If the process of type i points were independent of the points of other types, then K inhom (r)
i•
would equal πr2 . Deviations between the empirical Ki• curve and the theoretical curve πr2
suggest dependence between the points of types i and j for j 6= i.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern, and the mark vector X$marks
must be a factor.
The argument i will be interpreted as a level of the factor X$marks. (Warning: this means
that an integer value i=3 will be interpreted as the 3rd smallest level, not the number 3).
If i is missing, it defaults to the first level of the marks factor, i = levels(X$marks)[1].
The argument lambdaI supplies the values of the intensity of the sub-process of points of
type i. It may be either

a pixel image (object of class "im") which gives the values of the type i intensity at all
locations in the window containing X;
a numeric vector containing the values of the type i intensity evaluated only at the data
points of type i. The length of this vector must equal the number of type i points in
X.
a function of the form function(x,y) which can be evaluated to give values of the in-
tensity at any locations.
276 [Link]

omitted: if lambdaI is omitted then it will be estimated using a leave-one-out kernel


smoother.
If lambdaI is omitted, then it will be estimated using a ‘leave-one-out’ kernel smoother,
as described in Baddeley, Moller and Waagepetersen (2000). The estimate of lambdaI
for a given point is computed by removing the point from the point pattern, applying
kernel smoothing to the remaining points using [Link], and evaluating the smoothed
intensity at the point in question. The smoothing kernel bandwidth is controlled by the
arguments sigma and varcov, which are passed to [Link] along with any extra
arguments.
Similarly the argument lambdadot should contain estimated values of the intensity of the
entire point process. It may be either a pixel image, a numeric vector of length equal to
the number of points in X, a function, or omitted.
For advanced use only, the optional argument lambdaIdot is a matrix containing estimated
values of the products of these two intensities for each pair of points, the first point of type
i and the second of any type.
The argument r is the vector of values for the distance r at which Ki• (r) should be evaluated.
The values of r must be increasing nonnegative numbers and the maximum r value must
exceed the radius of the largest disc contained in the window.
The argument correction chooses the edge correction as explained e.g. in Kest.
The pair correlation function can also be applied to the result of [Link]; see pcf.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns
r the values of the argument r at which the function Ki• (r) has been esti-
mated
theo the theoretical value of Ki• (r) for a marked Poisson process, namely πr2
together with a column or columns named "border", "[Link]", "iso" and/or "trans",
according to the selected edge corrections. These columns contain estimates of the function
Ki• (r) obtained by the edge corrections named.

Warnings
The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap
with factors: numerical values are not interpreted in the same way as character values.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Moller, J. and Waagepetersen, R. Statistical Inference and Simulation for Spatial Point
Processes Chapman and Hall/CRC Boca Raton, 2003.

See Also
Kdot, Kinhom, [Link], pcf
Kest 277

Examples
# Lansing Woods data
data(lansing)
lansing <- lansing[seq(1,lansing$n, by=10)]
ma <- split(lansing)$maple
lg <- unmark(lansing)

# Estimate intensities by nonparametric smoothing


lambdaM <- [Link](ma, sigma=0.15, at="points")
lambdadot <- [Link](lg, sigma=0.15, at="points")
K <- [Link](lansing, "maple", lambdaI=lambdaM,
lambdadot=lambdadot)

# Equivalent
K <- [Link](lansing, "maple", sigma=0.15)

# synthetic example: type A points have intensity 50,


# type B points have intensity 50 + 100 * x
lamB <- [Link](function(x,y){50 + 100 * x}, owin())
lamdot <- [Link](function(x,y) { 100 + 100 * x}, owin())
X <- superimpose(A=runifpoispp(50), B=rpoispp(lamB))
K <- [Link](X, "B", lambdaI=lamB, lambdadot=lamdot)

Kest K-function

Description
Estimates Ripley’s reduced second moment function K(r) from a point pattern in a window
of arbitrary shape.

Usage
Kest(X, ..., r=NULL, breaks=NULL,
correction=c("border", "isotropic", "Ripley", "translate"),
nlarge=3000, domain=NULL, [Link]=FALSE)

Arguments
X The observed point pattern, from which an estimate of K(r) will be com-
puted. An object of class "ppp", or data in any format acceptable to
[Link]().
... Ignored.
r Optional. Vector of values for the argument r at which K(r) should be
evaluated. Users are advised not to specify this argument; there is a
sensible default.
breaks Optional. An alternative to the argument r. Not normally invoked by
the user. See the Details section.
correction Optional. A character vector containing any selection of the options
"none", "border", "[Link]", "isotropic", "Ripley", "translate",
"none" or "best". It specifies the edge correction(s) to be applied.
278 Kest

nlarge Optional. Efficiency threshold. If the number of points exceeds nlarge,


then only the border correction will be computed, using a fast algorithm.
domain Optional. Calculations will be restricted to this subset of the window.
See Details.
[Link] Logical. If TRUE, the approximate variance of K̂(r) under CSR will also
be computed.

Details
The K function (variously called “Ripley’s K-function” and the “reduced second moment
function”) of a stationary point process X is defined so that λK(r) equals the expected
number of additional random points within a distance r of a typical random point of X.
Here λ is the intensity of the process, i.e. the expected number of points of X per unit area.
The K function is determined by the second order moment properties of X.
An estimate of K derived from a spatial point pattern dataset can be used in exploratory
data analysis and formal inference about the pattern (Cressie, 1991; Diggle, 1983; Ripley,
1977, 1988). In exploratory analyses, the estimate of K is a useful statistic summarising
aspects of inter-point “dependence” and “clustering”. For inferential purposes, the estimate
of K is usually compared to the true value of K for a completely random (Poisson) point
process, which is K(r) = πr2 . Deviations between the empirical and theoretical K curves
may suggest spatial clustering or spatial regularity.
This routine Kest estimates the K function of a stationary point process, given observation
of the process inside a known, bounded window. The argument X is interpreted as a point
pattern object (of class "ppp", see [Link]) and can be supplied in any of the formats
recognised by [Link]().
The estimation of K is hampered by edge effects arising from the unobservability of points
of the random pattern outside the window. An edge correction is needed to reduce bias
(Baddeley, 1998; Ripley, 1988). The corrections implemented here are

border the border method or “reduced sample” estimator (see Ripley, 1988). This is the
least efficient (statistically) and the fastest to compute. It can be computed for a
window of arbitrary shape.
isotropic/Ripley Ripley’s isotropic correction (see Ripley, 1988; Ohser, 1983). This is
implemented for rectangular and polygonal windows (not for binary masks).
translate Translation correction (Ohser, 1983). Implemented for all window geometries,
but slow for complex windows.

For instructional purposes, you can set correction="none" to compute an estimate of the
K function without edge correction. This estimate is biased and should not be used for
data analysis.
You can also set correction="best" to select the best correction that is available for the
geometry of the window. Currently this is Ripley’s isotropic correction for a rectangular or
polygonal windows, and the translation correction for masks.
The estimates of K(r) are of the form
a XX
K̂(r) = I(dij ≤ r)eij
(n − 1)π i j

where a is the area of the window, n is the number of data points, and the sum is taken
over all ordered pairs of points i and j in X. Here dij is the distance between the two points,
and I(dij ≤ r) is the indicator that equals 1 if the distance is less than or equal to r. The
Kest 279

term eij is the edge correction weight (which depends on the choice of edge correction listed
above).
Note that this estimator assumes the process is stationary (spatially homogeneous). For
inhomogeneous point patterns, see Kinhom.
If the point pattern X contains more than about 3000 points, the isotropic and translation
edge corrections can be computationally prohibitive. The computations for the border
method are much faster, and are statistically efficient when there are large numbers of
points. Accordingly, if the number of points in X exceeds the threshold nlarge, then
only the border correction will be computed. Setting nlarge=Inf will prevent this from
happening. Setting nlarge=0 is equivalent to selecting only the border correction with
correction="border".
Approximations to the variance of K̂(r) are available, for the case of the isotropic edge
correction estimator, assuming complete spatial randomness (Ripley, 1988; Lotwick and
Silverman, 1982; Diggle, 2003, pp 51-53). If [Link]=TRUE, then the result of Kest also
has a column named rip values of Ripley’s (1988) approximation to var(K̂(r)), and (if the
window is a rectangle) a column named ls giving values of Lotwick and Silverman’s (1982)
approximation.
If the argument domain is given, the calculations will be restricted to a subset of the data.
In the formula for K(r) above, the first point i will be restricted to lie inside domain. The
result is an approximately unbiased estimate of K(r) based on pairs of points in which
the first point lies inside domain and the second point is unrestricted. This is useful in
bootstrap techniques. The argument domain should be a window (object of class "owin")
or something acceptable to [Link]. It must be a subset of the window of the point pattern
X.
The estimator Kest ignores marks. Its counterparts for multitype point patterns are Kcross,
Kdot, and for general marked point patterns see Kmulti.
Some writers, particularly Stoyan (1994, 1995) advocate the use of the “pair correlation
function”
K ′ (r)
g(r) =
2πr
where K ′ (r) is the derivative of K(r). See pcf on how to estimate this function.

Value

An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing columns

r the vector of values of the argument r at which the function K has been
estimated
theo the theoretical value K(r) = πr2 for a stationary Poisson process

together with columns named "border", "[Link]", "iso" and/or "trans", according
to the selected edge corrections. These columns contain estimates of the function K(r)
obtained by the edge corrections named.
If [Link]=TRUE then the return value also has columns rip and ls containing approx-
imations to the variance of K̂(r).
280 Kest

Warnings
The estimator of K(r) is approximately unbiased for each fixed r. Bias increases with r and
depends on the window geometry. For a rectangular window it is prudent to restrict the r
values to a maximum of 1/4 of the smaller side length of the rectangle. Bias may become
appreciable for point patterns consisting of fewer than 15 points.
While K(r) is always a non-decreasing function, the estimator of K is not guaranteed to
be non-decreasing. This is rarely a problem in practice.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A.J. Spatial sampling and censoring. In O.E. Barndorff-Nielsen, W.S. Kendall
and M.N.M. van Lieshout (eds) Stochastic Geometry: Likelihood and Computation. Chap-
man and Hall, 1998. Chapter 2, pages 37–78.
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Ohser, J. (1983) On estimators for the reduced second moment measure of point processes.
Mathematische Operationsforschung und Statistik, series Statistics, 14, 63 – 71.
Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal
Statistical Society, Series B, 39, 172 – 212.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications.
2nd edition. Springer Verlag.
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.

See Also
localK to extract individual summands in the K function.
pcf for the pair correlation.
Fest, Gest, Jest for alternative summary functions.
Kcross, Kdot, Kinhom, Kmulti for counterparts of the K function for multitype point
patterns.
[Link] for the calculation of reduced sample estimators.

Examples
pp <- runifpoint(50)
K <- Kest(pp)
data(cells)
K <- Kest(cells, correction="isotropic")
plot(K)
plot(K, main="K function for cells")
# plot the L function
plot(K, sqrt(iso/pi) ~ r)
plot(K, sqrt(./pi) ~ r, ylab="L(r)", main="L function for cells")
[Link] 281

[Link] K-function using FFT

Description
Estimates the reduced second moment function K(r) from a point pattern in a window of
arbitrary shape, using the Fast Fourier Transform.

Usage
[Link](X, sigma, r=NULL, breaks=NULL)

Arguments
X The observed point pattern, from which an estimate of K(r) will be com-
puted. An object of class "ppp", or data in any format acceptable to
[Link]().
sigma standard deviation of the isotropic Gaussian smoothing kernel.
r vector of values for the argument r at which K(r) should be evaluated.
There is a sensible default.
breaks An alternative to the argument r. Not normally invoked by the user. See
Details.

Details
This is an alternative to the function Kest for estimating the K function. It may be useful
for very large patterns of points.
Whereas Kest computes the distance between each pair of points analytically, this func-
tion discretises the point pattern onto a rectangular pixel raster and applies Fast Fourier
Transform techniques to estimate K(t). The hard work is done by the function Kmeasure.
The result is an approximation whose accuracy depends on the resolution of the pixel raster.
The resolution is controlled by setting the parameter npixel in [Link].

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing columns

r the vector of values of the argument r at which the function K has been
estimated
border the estimates of K(r) for these values of r
theo the theoretical value K(r) = πr2 for a stationary Poisson process

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
282 Kinhom

References
Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Ohser, J. (1983) On estimators for the reduced second moment measure of point processes.
Mathematische Operationsforschung und Statistik, series Statistics, 14, 63 – 71.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications.
2nd edition. Springer Verlag.
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.

See Also
Kest, Kmeasure, [Link]

Examples
pp <- runifpoint(10000)
## Not run:
[Link](npixel=512)

## End(Not run)

Kpp <- [Link](pp, 0.01)


plot(Kpp)

Kinhom Inhomogeneous K-function

Description
Estimates the inhomogeneous K function of a non-stationary point pattern.

Usage
Kinhom(X, lambda=NULL, ..., r = NULL, breaks = NULL,
correction=c("border", "[Link]", "isotropic", "translate"),
nlarge = 1000,
lambda2=NULL, reciplambda=NULL, reciplambda2=NULL,
sigma=NULL, varcov=NULL)

Arguments
X The observed data point pattern, from which an estimate of the inhomo-
geneous K function will be computed. An object of class "ppp" or in a
format recognised by [Link]()
lambda Optional. Values of the estimated intensity function. Either a vector
giving the intensity values at the points of the pattern X, a pixel image
(object of class "im") giving the intensity values at all locations, or a
function(x,y) which can be evaluated to give the intensity value at any
location.
Kinhom 283

... Extra arguments. Ignored if lambda is present. Passed to [Link]


if lambda is omitted.
r vector of values for the argument r at which the inhomogeneous K func-
tion should be evaluated. Not normally given by the user; there is a
sensible default.
breaks An alternative to the argument r. Not normally invoked by the user. See
Details.
correction A character vector containing any selection of the options "border",
"[Link]", "isotropic", "Ripley", "translate", "none" or "best".
It specifies the edge correction(s) to be applied.
nlarge Optional. Efficiency threshold. If the number of points exceeds nlarge,
then only the border correction will be computed, using a fast algorithm.
lambda2 Advanced use only. Matrix containing estimates of the products λ(xi )λ(xj )
of the intensities at each pair of data points xi and xj .
reciplambda Alternative to lambda. Values of the estimated reciprocal 1/λ of the
intensity function. Either a vector giving the reciprocal intensity values
at the points of the pattern X, a pixel image (object of class "im") giving
the reciprocal intensity values at all locations, or a function(x,y) which
can be evaluated to give the reciprocal intensity value at any location.
reciplambda2 Advanced use only. Alternative to lambda2. A matrix giving values of
the estimated reciprocal products 1/λ(xi )λ(xj ) of the intensities at each
pair of data points xi and xj .
sigma,varcov Optional arguments passed to [Link] to control the smoothing
bandwidth, when lambda is estimated by kernel smoothing.

Details
This computes a generalisation of the K function for inhomogeneous point patterns, pro-
posed by Baddeley, Moller and Waagepetersen (2000).
The “ordinary” K function (variously known as the reduced second order moment function
and Ripley’s K function), is described under Kest. It is defined only for stationary point
processes.
The inhomogeneous K function Kinhom (r) is a direct generalisation to nonstationary point
processes. Suppose x is a point process with non-constant intensity λ(u) at each location
u. Define Kinhom (r) to be the expected value, given that u is a point of x, of the sum of all
terms 1/λ(u)λ(xj ) over all points xj in the process separated from u by a distance less than
r. This reduces to the ordinary K function if λ() is constant. If x is an inhomogeneous
Poisson process with intensity function λ(u), then Kinhom (r) = πr2 .
This allows us to inspect a point pattern for evidence of interpoint interactions after al-
lowing for spatial inhomogeneity of the pattern. Values Kinhom (r) > πr2 are suggestive of
clustering.
The argument lambda should supply the (estimated) values of the intensity function λ. It
may be either
a numeric vector containing the values of the intensity function at the points of the
pattern X.
a pixel image (object of class "im") assumed to contain the values of the intensity function
at all locations in the window.
a function which can be evaluated to give values of the intensity at any locations.
284 Kinhom

omitted: if lambda is omitted, then it will be estimated using a ‘leave-one-out’ kernel


smoother.
If lambda is a numeric vector, then its length should be equal to the number of points in the
pattern X. The value lambda[i] is assumed to be the the (estimated) value of the intensity
λ(xi ) for the point xi of the pattern X. Each value must be a positive number; NA’s are
not allowed.
If lambda is a pixel image, the domain of the image should cover the entire window of the
point pattern. If it does not (which may occur near the boundary because of discretisation
error), then the missing pixel values will be obtained by applying a Gaussian blur to lambda
using blur, then looking up the values of this blurred image for the missing locations. (A
warning will be issued in this case.)
If lambda is a function, then it will be evaluated in the form lambda(x,y) where x and y
are vectors of coordinates of the points of X. It should return a numeric vector with length
equal to the number of points in X.
If lambda is omitted, then it will be estimated using a ‘leave-one-out’ kernel smoother, as
described in Baddeley, Moller and Waagepetersen (2000). The estimate lambda[i] for the
point X[i] is computed by removing X[i] from the point pattern, applying kernel smoothing
to the remaining points using [Link], and evaluating the smoothed intensity at the
point X[i]. The smoothing kernel bandwidth is controlled by the arguments sigma and
varcov, which are passed to [Link] along with any extra arguments.
Edge corrections are used to correct bias in the estimation of Kinhom . Each edge-corrected
estimate of Kinhom (r) is of the form
X X 1{dij ≤ r}e(xi , xj , r)
b inhom (r) =
K
i j
λ(xi )λ(xj )

where dij is the distance between points xi and xj , and e(xi , xj , r) is an edge correction
factor. For the ‘border’ correction,
1(bi > r)
e(xi , xj , r) = P
j 1(b j > r)/λ(xj )

where bi is the distance from xi to the boundary of the window. For the ‘modified border’
correction,
1(bi > r)
e(xi , xj , r) =
area(W ⊖ r)
where W ⊖ r is the eroded window obtained by trimming a margin of width r from the
border of the original window. For the ‘translation’ correction,
1
e(xi , xj , r) =
area(W ∩ (W + (xj − xi )))
and for the ‘isotropic’ correction,
1
e(xi , xj , r) =
area(W )g(xi , xj )

where g(xi , xj ) is the fraction of the circumference of the circle with centre xi and radius
||xi − xj || which lies inside the window.
If the point pattern X contains more than about 1000 points, the isotropic and translation
edge corrections can be computationally prohibitive. The computations for the border
method are much faster, and are statistically efficient when there are large numbers of
Kinhom 285

points. Accordingly, if the number of points in X exceeds the threshold nlarge, then
only the border correction will be computed. Setting nlarge=Inf will prevent this from
happening. Setting nlarge=0 is equivalent to selecting only the border correction with
correction="border".
The pair correlation function can also be applied to the result of Kinhom; see pcf.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing at least the following columns,

r the vector of values of the argument r at which the pair correlation func-
tion g(r) has been estimated
theo vector of values of πr2 , the theoretical value of Kinhom (r) for an inhomo-
geneous Poisson process

and containing additional columns according to the choice specified in the correction ar-
gument. The additional columns are named border, trans and iso and give the estimated
values of Kinhom (r) using the border correction, translation correction, and Ripley isotropic
correction, respectively.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A., Moller, J. and Waagepetersen, R. (2000) Non- and semiparametric estimation
of interaction in inhomogeneous point patterns. Statistica Neerlandica 54, 329–350.

See Also
Kest, pcf

Examples
data(lansing)
# inhomogeneous pattern of maples
X <- unmark(split(lansing)$maple)

# (1) intensity function estimated by model-fitting


# Fit spatial trend: polynomial in x and y coordinates
fit <- ppm(X, ~ polynom(x,y,2), Poisson())
# (a) predict intensity values at points themselves,
# obtaining a vector of lambda values
lambda <- predict(fit, locations=X, type="trend")
# inhomogeneous K function
Ki <- Kinhom(X, lambda)
plot(Ki)
# (b) predict intensity at all locations,
# obtaining a pixel image
lambda <- predict(fit, type="trend")
Ki <- Kinhom(X, lambda)
286 [Link]

plot(Ki)

# (2) intensity function estimated by heavy smoothing


Ki <- Kinhom(X, sigma=0.1)
plot(Ki)

# (3) simulated data: known intensity function


lamfun <- function(x,y) { 50 + 100 * x }
# inhomogeneous Poisson process
Y <- rpoispp(lamfun, 150, owin())
# evaluate intensity at points of pattern
lambda <- lamfun(Y$x, Y$y)
# inhomogeneous K function
Ki <- Kinhom(Y, lambda)
plot(Ki)

# How to make simulation envelopes:


# Example shows method (2)
## Not run:
smo <- [Link](X, sigma=0.1)
Ken <- envelope(X, Kinhom, nsim=99,
simulate=expression(rpoispp(smo)),
sigma=0.1, correction="trans")
plot(Ken)

## End(Not run)

[Link] Kaplan-Meier and Reduced Sample Estimator using Histograms

Description
Compute the Kaplan-Meier and Reduced Sample estimators of a survival time distribution
function, using histogram techniques

Usage
[Link](o, cc, d, breaks)

Arguments
o vector of observed survival times
cc vector of censoring times
d vector of non-censoring indicators
breaks Vector of breakpoints to be used to form histograms.

Details
This function is needed mainly for internal use in spatstat, but may be useful in other
applications where you want to form the Kaplan-Meier estimator from a huge dataset.
Suppose Ti are the survival times of individuals i = 1, . . . , M with unknown distribution
function F (t) which we wish to estimate. Suppose these times are right-censored by random
Kmeasure 287

censoring times Ci . Thus the observations consist of right-censored survival times T̃i =
min(Ti , Ci ) and non-censoring indicators Di = 1{Ti ≤ Ci } for each i.
The arguments to this function are vectors o, cc, d of observed values of T̃i , Ci and Di
respectively. The function computes histograms and forms the reduced-sample and Kaplan-
Meier estimates of F (t) by invoking the functions [Link] and [Link]. This
is efficient if the lengths of o, cc, d (i.e. the number of observations) is large.
The vectors km and hazard returned by [Link] are (histogram approximations to)
the Kaplan-Meier estimator of F (t) and its hazard rate λ(t). Specifically, km[k] is an
estimate of F(breaks[k+1]), and lambda[k] is an estimate of the average of λ(t) over
the interval (breaks[k],breaks[k+1]). This approximation is exact only if the survival
times are discrete and the histogram breaks are fine enough to ensure that each interval
(breaks[k],breaks[k+1]) contains only one possible value of the survival time.
The vector rs is the reduced-sample estimator, rs[k] being the reduced sample estimate
of F(breaks[k+1]). This value is exact, i.e. the use of histograms does not introduce any
approximation error in the reduced-sample estimator.

Value
A list with five elements

rs Reduced-sample estimate of the survival time c.d.f. F (t)


km Kaplan-Meier estimate of the survival time c.d.f. F (t)
hazard corresponding Nelson-Aalen estimate of the hazard rate λ(t)
r values of t for which F (t) is estimated
breaks the breakpoints vector

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Kmeasure Reduced Second Moment Measure

Description
Estimates the reduced second moment measure κ from a point pattern in a window of
arbitrary shape.

Usage
Kmeasure(X, sigma, edge=TRUE, ..., varcov=NULL)
288 Kmeasure

Arguments
X The observed point pattern, from which an estimate of κ will be computed.
An object of class "ppp", or data in any format acceptable to [Link]().
sigma Standard deviation σ of the Gaussian smoothing kernel. Incompatible
with varcov.
edge logical value indicating whether an edge correction should be applied.
... Ignored.
varcov Variance-covariance matrix of the Gaussian smoothing kernel. Incompat-
ible with sigma.

Details
The reduced second moment measure κ of a stationary point process X is defined so that,
for a ‘typical’ point x of the process, the expected number of other points y of the process
such that the vector y − x lies in a region A, equals λκ(A). Here λ is the intensity of the
process, i.e. the expected number of points of X per unit area.
The more familiar K-function K(t) is just the value of the reduced second moment measure
for each disc centred at the origin; that is, K(t) = κ(b(0, t)).
An estimate of κ derived from a spatial point pattern dataset can be useful in exploratory
data analysis. Its advantage over the K-function is that it is also sensitive to anisotropy
and directional effects.
This function computes an estimate of κ from a point pattern dataset X, which is assumed
to be a realisation of a stationary point process, observed inside a known, bounded window.
Marks are ignored.
The algorithm approximates the point pattern and its window by binary pixel images,
introduces a Gaussian smoothing kernel and uses the Fast Fourier Transform fft to form
a density estimate of κ. The calculation corresponds to the edge correction known as the
“translation correction”.
The Gaussian smoothing kernel may be specified by either of the arguments sigma or
varcov. If sigma is a single number, this specifies an isotropic Gaussian kernel with stan-
dard deviation sigma on each coordinate axis. If sigma is a vector of two numbers, this
specifies a Gaussian kernel with standard deviation sigma[1] on the x axis, standard de-
viation sigma[2] on the y axis, and zero correlation between the x and y axes. If varcov
is given, this specifies the variance-covariance matrix of the Gaussian kernel. There do not
seem to be any well-established rules for selecting the smoothing kernel in this context.
The density estimate of κ is returned in the form of a real-valued pixel image. Pixel values
are estimates of the integral of the second moment density over the pixel. (The uniform
Poisson process would have values identically equal to a where a is the area of a pixel.)
Sums of pixel values over a desired region A are estimates of the value of κ(A). The image
x and y coordinates are on the same scale as vector displacements in the original point
pattern window. The point x=0, y=0 corresponds to the ‘typical point’. A peak in the
image near (0,0) suggests clustering; a dip in the image near (0,0) suggests inhibition;
peaks or dips at other positions suggest possible periodicity.

Value
A real-valued pixel image (an object of class "im", see [Link]) whose pixel values are
estimates of the value of the reduced second moment measure for each pixel (i.e. estimates
of the integral of the second moment density over each pixel).
Kmulti 289

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications.
2nd edition. Springer Verlag.
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.

See Also
Kest, fryplot, [Link], [Link]

Examples
data(cells)
image(Kmeasure(cells, 0.05))
# shows pronounced dip around origin consistent with strong inhibition
data(redwood)
image(Kmeasure(redwood, 0.03), col=grey(seq(1,0,length=32)))
# shows peaks at several places, reflecting clustering and ?periodicity

Kmulti Marked K-Function

Description
For a marked point pattern, estimate the multitype K function which counts the expected
number of points of subset J within a given distance from a typical point in subset I.

Usage
Kmulti(X, I, J, r=NULL, breaks=NULL, correction, ...)

Arguments
X The observed point pattern, from which an estimate of the multitype K
function KIJ (r) will be computed. It must be a marked point pattern.
See under Details.
I Subset index specifying the points of X from which distances are measured.
J Subset index specifying the points in X to which distances are measured.
r numeric vector. The values of the argument r at which the multitype K
function KIJ (r) should be evaluated. There is a sensible default. First-
time users are strongly advised not to specify this argument. See below
for important conditions on r.
breaks An alternative to the argument r. Not normally invoked by the user. See
the Details section.
correction A character vector containing any selection of the options "border",
"[Link]", "isotropic", "Ripley", "translate", "none" or "best".
It specifies the edge correction(s) to be applied.
... Ignored.
290 Kmulti

Details
The function Kmulti generalises Kest (for unmarked point patterns) and Kdot and Kcross
(for multitype point patterns) to arbitrary marked point patterns.
Suppose XI , XJ are subsets, possibly overlapping, of a marked point process. The multitype
K function is defined so that λJ KIJ (r) equals the expected number of additional random
points of XJ within a distance r of a typical point of XI . Here λJ is the intensity of XJ
i.e. the expected number of points of XJ per unit area. The function KIJ is determined
by the second order moment properties of X.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link].
The arguments I and J specify two subsets of the point pattern. They may be logical
vectors of length equal to X$n, or integer vectors with entries in the range 1 to X$n, etc.
The argument r is the vector of values for the distance r at which KIJ (r) should be evalu-
ated. It is also used to determine the breakpoints (in the sense of hist) for the computation
of histograms of distances.
First-time users would be strongly advised not to specify r. However, if it is specified,
r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc
contained in the window.
This algorithm assumes that X can be treated as a realisation of a stationary (spatially
homogeneous) random spatial point process in the plane, observed through a bounded
window. The window (which is specified in X as X$window) may have arbitrary shape.
Biases due to edge effects are treated in the same manner as in Kest. The edge corrections
implemented here are
border the border method or “reduced sample” estimator (see Ripley, 1988). This is the
least efficient (statistically) and the fastest to compute. It can be computed for a
window of arbitrary shape.
isotropic/Ripley Ripley’s isotropic correction (see Ripley, 1988; Ohser, 1983). This is
currently implemented only for rectangular windows.
translate Translation correction (Ohser, 1983). Implemented for all window geometries.
The pair correlation function pcf can also be applied to the result of Kmulti.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns
r the values of the argument r at which the function KIJ (r) has been esti-
mated
theo the theoretical value of KIJ (r) for a marked Poisson process, namely πr2
together with a column or columns named "border", "[Link]", "iso" and/or "trans",
according to the selected edge corrections. These columns contain estimates of the function
KIJ (r) obtained by the edge corrections named.

Warnings
The function KIJ is not necessarily differentiable.
The border correction (reduced sample) estimator of KIJ used here is pointwise approxi-
mately unbiased, but need not be a nondecreasing function of r, while the true KIJ must
be nondecreasing.
kppm 291

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.
Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit : analysis of a
bivariate spatial point pattern. J. Neurosci. Meth. 18, 115–125.
Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants’ nests. Applied
Statistics 32, 293–303
Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of
several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.
Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.
Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd
edition. Springer Verlag, 1995.
Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in
multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Kcross, Kdot, Kest, pcf

Examples
data(longleaf)
# Longleaf Pine data: marks represent diameter

K <- Kmulti(longleaf, longleaf$marks <= 15, longleaf$marks >= 25)


plot(K)

kppm Fit cluster point process model

Description

Fit a homogeneous or inhomogeneous cluster point process model to a point pattern.

Usage

kppm(X, trend = ~1, clusters = "Thomas", covariates = NULL, ...)


292 kppm

Arguments
X Point pattern (object of class "ppp") to which the model should be fitted.
trend An R formula, with no left hand side, specifying the form of the log
intensity.
clusters Character string determining the cluster model. Partially matched. Op-
tions are "Thomas" and "MatClust".
covariates The values of any spatial covariates (other than the Cartesian coordinates)
required by the model. A named list of pixel images.
... Arguments passed to [Link] or [Link] controlling the min-
imum contrast fitting algorithm.

Details
This function fits a cluster point process model to the point pattern dataset X.
The algorithm first estimates the intensity function of the point process, by fitting a Poisson
process with log intensity of the form specified by the formula trend. Then the inhomo-
geneous K function is estimated using the fitted intensity. Finally the parameters of the
cluster model are estimated by the method of minimum contrast using the inhomogeneous
K function.
Currently the only options for the cluster mechanism are clusters="Thomas" for the
Thomas process and clusters="MatClust" for the Matern cluster process.

Value
An object of class "kppm" representing the fitted model. There are methods for printing,
plotting, predicting, simulating and updating objects of this class.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Waagepetersen, R. (2006). An estimation function approach to inference for inhomogeneous
Neyman-Scott processes. Submitted.

See Also
[Link], [Link], [Link], [Link], [Link], [Link],
mincontrast, Kinhom, ppm

Examples
data(redwood)
kppm(redwood, ~1, "Thomas")
kppm(redwood, ~x, "MatClust")
[Link] 293

[Link] Kolmogorov-Smirnov Test for Point Process Model

Description
Performs a Kolmogorov-Smirnov test of goodness-of-fit of a Poisson point process model.
The test compares the observed and predicted distributions of the values of a spatial co-
variate.

Usage
kstest(...)
## S3 method for class 'ppp':
kstest(X, covariate, ..., jitter=TRUE)
## S3 method for class 'ppm':
kstest(model, covariate, ..., jitter=TRUE)

Arguments
X A point pattern (object of class "ppp").
model A fitted point process model (object of class "ppm").
covariate The spatial covariate on which the test will be based. An image (object
of class "im") or a function.
... Arguments passed to [Link] to control the test.
jitter Logical flag. If jitter=TRUE, values of the covariate will be slightly per-
turbed at random, to avoid tied values in the test.

Details
These functions perform a goodness-of-fit test of a Poisson point process model fitted to
point pattern data. The observed distribution of the values of a spatial covariate at the data
points, and the predicted distribution of the same values under the model, are compared
using the Kolmogorov-Smirnov test.
The function kstest is generic, with methods for point patterns ("ppp") and point process
models ("ppm").
ˆ If X is a point pattern dataset (object of class "ppp"), then kstest(X, ...) per-
forms a goodness-of-fit test of the uniform Poisson point process (Complete Spatial
Randomness, CSR) for this dataset.
ˆ If model is a fitted point process model (object of class "ppm") then kstest(model,
...) performs a test of goodness-of-fit for this fitted model. In this case, model should
be a Poisson point process.
The test is performed by comparing the observed distribution of the values of a spatial
covariate at the data points, and the predicted distribution of the same covariate under the
model, using the classical Kolmogorov-Smirnov test. Thus, you must nominate a spatial
covariate for this test.
The argument covariate should be either a function(x,y) or a pixel image (object of
class "im" containing the values of a spatial function. If covariate is an image, it should
have numeric values, and its domain should cover the observation window of the model.
294 [Link]

If covariate is a function, it should expect two arguments x and y which are vectors of
coordinates, and it should return a numeric vector of the same length as x and y.
First the original data point pattern is extracted from model. The values of the covariate
at these data points are collected.
The predicted distribution of the values of the covariate under the fitted model is com-
puted as follows. The values of the covariate at all locations in the observation window
are evaluated, weighted according to the point process intensity of the fitted model, and
compiled into a cumulative distribution function F using ewcdf.
The probability integral transformation is then applied: the values of the covariate at the
original data points are transformed by the predicted cumulative distribution function F
into numbers between 0 and 1. If the model is correct, these numbers are i.i.d. uniform
random numbers. The Kolmogorov-Smirnov test of uniformity is applied using [Link].
This test was apparently first described (in the context of spatial data) by Berman (1986).
See also Baddeley et al (2005).
The return value is an object of class "htest" containing the results of the hypothesis test.
The print method for this class gives an informative summary of the test outcome.
The return value also belongs to the class "kstest" for which there is a plot method
[Link]. The plot method displays the empirical cumulative distribution function of
the covariate at the data points, and the predicted cumulative distribution function of the
covariate under the model, plotted against the value of the covariate.
The argument jitter controls whether covariate values are randomly perturbed, in order to
avoid ties. If the original data contains any ties in the covariate (i.e. points with equal values
of the covariate), and if jitter=FALSE, then the Kolmogorov-Smirnov test implemented in
[Link] will issue a warning that it cannot calculate the exact p-value. To avoid this, if
jitter=TRUE each value of the covariate will be perturbed by adding a small random value.
The perturbations are normally distributed with standard deviation equal to one hundredth
of the range of values of the covariate. This prevents ties, and the p-value is still correct.
There is a very slight loss of power.

Value
An object of class "htest" containing the results of the test. See [Link] for details. The
return value can be printed to give an informative summary of the test.
The value also belongs to the class "kstest" for which there is a plot method.

Warning
The outcome of the test involves a small amount of random variability, because (by default)
the coordinates are randomly perturbed to avoid tied values. Hence, if kstest is executed
twice, the p-values will not be exactly the same. To avoid this behaviour, set jitter=FALSE.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial
point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.
lansing 295

Berman, M. (1986) Testing for spatial association between a point process and another
stochastic process. Applied Statistics 35, 54–62.

See Also
[Link], [Link], bermantest, [Link], ppm

Examples
# real data: Swedish Pines
data(swedishpines)

# test covariate = x coordinate


xcoord <- function(x,y) { x }

# test of CSR
kstest(swedishpines, xcoord)

# fit inhomogeneous Poisson model and test


model <- ppm(swedishpines, ~x + y)
kstest(model, xcoord)

# synthetic data: nonuniform Poisson process


X <- rpoispp(function(x,y) { 100 * exp(x) }, win=square(1))

# fit uniform Poisson process


fit0 <- ppm(X, ~1)
# fit correct nonuniform Poisson process
fit1 <- ppm(X, ~x)

# test wrong model


kstest(fit0, xcoord)
# test right model
kstest(fit1, xcoord)

lansing Lansing Woods Point Pattern

Description
Locations and botanical classification of trees in Lansing Woods.
The data come from an investigation of a 924 ft x 924 ft (19.6 acre) plot in Lansing Woods,
Clinton County, Michigan USA by D.J. Gerrard. The data give the locations of 2251 trees
and their botanical classification (into hickories, maples, red oaks, white oaks, black oaks
and miscellaneous trees). The original plot size (924 x 924 feet) has been rescaled to the
unit square.

Usage
data(lansing)

Format
An object of class "ppp" representing the point pattern of tree locations. Entries include
296 Lcross

x Cartesian x-coordinate of tree


y Cartesian y-coordinate of tree
marks factor with levels indicating species of each tree

The levels of marks are blackoak, hickory, maple, misc, redoak and whiteoak. See
[Link] for details of the format of a point pattern object.

References
Besag, J. (1978) Some methods of statistical analysis for spatial data. Bull. Internat.
Statist. Inst. 44, 77–92.
Cox, T.F. (1976) The robust estimation of the density of a forest stand using a new condi-
tioned distance method. Biometrika 63, 493–500.
Cox, T.F. (1979) A method for mapping the dense and sparse regions of a forest stand.
Applied Statistics 28, 14–19.
Cox, T.F. and Lewis, T. (1976) A conditioned distance ratio method for analysing spatial
patterns. Biometrika 63, 483–492.
Diggle, P.J. (1979a) The detection of random heterogeneity in plant populations. Biometrics
33, 390–394.
Diggle, P.J. (1979b) Statistical methods for spatial point patterns in ecology. Spatial and
temporal analysis in ecology. R.M. Cormack and J.K. Ord (eds.) Fairland: International
Co-operative Publishing House. pages 95–150.
Diggle, P.J. (1981) Some graphical methods in the analysis of spatial point patterns. In
Interpreting Multivariate Data. V. Barnett (eds.) John Wiley and Sons. Pages 55–73.
Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.
Gerrard, D.J. (1969) Competition quotient: a new measure of the competition affecting
individual forest trees. Research Bulletin 20, Agricultural Experiment Station, Michigan
State University.
Lotwick, H.W. (1981) Spatial stochastic point processes. PhD thesis, University of Bath,
UK.
Ord, J.K. (1978) How many trees in a forest? Mathematical Scientist 3, 23–33.

Examples
data(lansing)
plot(lansing)
plot(split(lansing))
plot(split(lansing)$maple)

Lcross Multitype L-function (cross-type)

Description
Calculates an estimate of the cross-type L-function for a multitype point pattern.

Usage
Lcross(X, i, j, ...)
Lcross 297

Arguments
X The observed point pattern, from which an estimate of the cross-type L
function Lij (r) will be computed. It must be a multitype point pattern
(a marked point pattern whose marks are a factor). See under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured.
j Number or character string identifying the type (mark value) of the points
in X to which distances are measured.
... Arguments passed to Kcross.

Details
The cross-type L-function is a transformation of the cross-type K-function,
r
Kij (r)
Lij (r) =
π
where Kij (r) is the cross-type K-function from type i to type j. See Kcross for information
about the cross-type K-function.
The command Lcross first calls Kcross to compute the estimate of the cross-type K-
function, and then applies the square root transformation.
For a marked point pattern in which the points of type i are independent of the points of
type j, the theoretical value of the L-function is Lij (r) = r. The square root also has the
effect of stabilising the variance of the estimator, so that Lij is more appropriate for use in
simulation envelopes and hypothesis tests.

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing columns
r the vector of values of the argument r at which the function Lij has been
estimated
theo the theoretical value Lij (r) = r for a stationary Poisson process
together with columns named "border", "[Link]", "iso" and/or "trans", according
to the selected edge corrections. These columns contain estimates of the function Lij
obtained by the edge corrections named.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
Kcross, Ldot, Lest

Examples
data(amacrine)
L <- Lcross(amacrine, "off", "on")
plot(L)
298 [Link]

[Link] Inhomogeneous Cross Type L Function

Description
For a multitype point pattern, estimate the inhomogeneous version of the cross-type L
function.

Usage
[Link](X, i, j, ...)

Arguments
X The observed point pattern, from which an estimate of the inhomogeneous
cross type L function Lij (r) will be computed. It must be a multitype
point pattern (a marked point pattern whose marks are a factor). See
under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
j Number or character string identifying the type (mark value) of the points
in X to which distances are measured. Defaults to the second level of
marks(X).
... Other arguments passed to [Link].

Details
This is a generalisation of the function Lcross to include an adjustment for spatially inho-
mogeneous intensity, in a manner similar to the function Linhom.
All the arguments are passed to [Link], which estimates the inhomogeneous mul-
titype K function p
Kij (r) for the point pattern. The resulting values are then transformed
by taking L(r) = K(r)/π.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns
r the values of the argument r at which the function Lij (r) has been esti-
mated
theo the theoretical value of Lij (r) for a marked Poisson process, identically
equal to r
together with a column or columns named "border", "[Link]", "iso" and/or "trans",
according to the selected edge corrections. These columns contain estimates of the function
Lij (r) obtained by the edge corrections named.

Warnings
The arguments i and j are interpreted as levels of the factor X$marks. Beware of the usual
trap with factors: numerical values are not interpreted in the same way as character values.
Ldot 299

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Moller, J. and Waagepetersen, R. Statistical Inference and Simulation for Spatial Point
Processes Chapman and Hall/CRC Boca Raton, 2003.

See Also
Lcross, Linhom, [Link]

Examples
# Lansing Woods data
data(lansing)
lansing <- lansing[seq(1,lansing$n, by=10)]
ma <- split(lansing)$maple
wh <- split(lansing)$whiteoak

# method (1): estimate intensities by nonparametric smoothing


lambdaM <- [Link](ma, sigma=0.15, at="points")
lambdaW <- [Link](wh, sigma=0.15, at="points")
L <- [Link](lansing, "whiteoak", "maple", lambdaW, lambdaM)

# method (2): fit parametric intensity model


fit <- ppm(lansing, ~marks * polynom(x,y,2))
# evaluate fitted intensities at data points
# (these are the intensities of the sub-processes of each type)
inten <- fitted(fit, dataonly=TRUE)
# split according to types of points
lambda <- split(inten, lansing$marks)
L <- [Link](lansing, "whiteoak", "maple",
lambda$whiteoak, lambda$maple)

# synthetic example: type A points have intensity 50,


# type B points have intensity 100 * x
lamB <- [Link](function(x,y){50 + 100 * x}, owin())
X <- superimpose(A=runifpoispp(50), B=rpoispp(lamB))
L <- [Link](X, "A", "B",
lambdaI=[Link](50, X$window), lambdaJ=lamB)

Ldot Multitype L-function (i-to-any)

Description
Calculates an estimate of the multitype L-function (from type i to any type) for a multitype
point pattern.

Usage
Ldot(X, i, ...)
300 Ldot

Arguments
X The observed point pattern, from which an estimate of the dot-type L
function Lij (r) will be computed. It must be a multitype point pattern
(a marked point pattern whose marks are a factor). See under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured.
... Arguments passed to Kdot.

Details
This command computes
r
Ki• (r)
Li• (r) =
π
where Ki• (r) is the multitype K-function from points of type i to points of any type. See
Kdot for information about Ki• (r).
The command Ldot first calls Kdot to compute the estimate of the i-to-any K-function,
and then applies the square root transformation.
For a marked Poisson point process, the theoretical value of the L-function is Li• (r) = r.
The square root also has the effect of stabilising the variance of the estimator, so that Li•
is more appropriate for use in simulation envelopes and hypothesis tests.

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing columns

r the vector of values of the argument r at which the function Li• has been
estimated
theo the theoretical value Li• (r) = r for a stationary Poisson process

together with columns named "border", "[Link]", "iso" and/or "trans", according
to the selected edge corrections. These columns contain estimates of the function Li•
obtained by the edge corrections named.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
Kdot, Lcross, Lest

Examples
data(amacrine)
L <- Ldot(amacrine, "off")
plot(L)
[Link] 301

[Link] Inhomogeneous Multitype L Dot Function

Description
For a multitype point pattern, estimate the inhomogeneous version of the dot L function.

Usage
[Link](X, i, ...)

Arguments
X The observed point pattern, from which an estimate of the inhomogeneous
cross type L function Li• (r) will be computed. It must be a multitype
point pattern (a marked point pattern whose marks are a factor). See
under Details.
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured. Defaults to the first level of
marks(X).
... Other arguments passed to [Link].

Details
This a generalisation of the function Ldot to include an adjustment for spatially inhomo-
geneous intensity, in a manner similar to the function Linhom.
All the arguments are passed to [Link], which estimates the inhomogeneous multitype
K function
p Ki• (r) for the point pattern. The resulting values are then transformed by taking
L(r) = K(r)/π.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns

r the values of the argument r at which the function Li• (r) has been esti-
mated
theo the theoretical value of Li• (r) for a marked Poisson process, identical to
r.

together with a column or columns named "border", "[Link]", "iso" and/or "trans",
according to the selected edge corrections. These columns contain estimates of the function
Li• (r) obtained by the edge corrections named.

Warnings
The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap
with factors: numerical values are not interpreted in the same way as character values.
302 [Link]

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Moller, J. and Waagepetersen, R. Statistical Inference and Simulation for Spatial Point
Processes Chapman and Hall/CRC Boca Raton, 2003.

See Also
Ldot, Linhom, [Link], [Link].

Examples
# Lansing Woods data
data(lansing)
lansing <- lansing[seq(1,lansing$n, by=10)]
ma <- split(lansing)$maple
lg <- unmark(lansing)

# Estimate intensities by nonparametric smoothing


lambdaM <- [Link](ma, sigma=0.15, at="points")
lambdadot <- [Link](lg, sigma=0.15, at="points")
L <- [Link](lansing, "maple", lambdaI=lambdaM,
lambdadot=lambdadot)

# synthetic example: type A points have intensity 50,


# type B points have intensity 50 + 100 * x
lamB <- [Link](function(x,y){50 + 100 * x}, owin())
lamdot <- [Link](function(x,y) { 100 + 100 * x}, owin())
X <- superimpose(A=runifpoispp(50), B=rpoispp(lamB))
L <- [Link](X, "B", lambdaI=lamB, lambdadot=lamdot)

[Link] Lengths of Line Segments

Description
Computes the length of each line segment in a line segment pattern.

Usage
[Link](x)

Arguments
x A line segment pattern (object of class "psp").

Details
The length of each line segment is computed and the lengths are returned as a numeric
vector.
LennardJones 303

Value
Numeric vector.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
b <- [Link](a)

LennardJones The Lennard-Jones Potential

Description
Creates the Lennard-Jones pairwise interaction structure which can then be fitted to point
pattern data.

Usage
LennardJones()

Details
In a pairwise interaction point process with the Lennard-Jones pair potential, each pair of
points in the point pattern, a distance d apart, contributes a factor
    σ 6 
σ 12
exp − +τ
d d
to the probability density, where σ and τ are positive parameters to be estimated.
See Examples for a plot of this expression.
This potential causes very strong inhibition between points at short range, and attrac-
tion between points at medium range. Roughly speaking, σ controls the scale of both
types of interaction, and τ determines the strength of attraction. The potential switches
from inhibition to attraction at d = σ/τ 1/6 . Maximum attraction occurs at distance
d = ( τ2 )1/6 σ and the maximum achieved is exp(τ 2 /4). Interaction is negligible for dis-
tances d > 2σ max{1, τ 1/6 }.
This potential is used (in a slightly different parameterisation) to model interactions between
uncharged molecules in statistical physics.
The function ppm(), which fits point process models to point pattern data, requires an
argument of class "interact" describing the interpoint interaction structure of the model
to be fitted. The appropriate description of the Lennard-Jones pairwise interaction is yielded
by the function LennardJones(). See the examples below.
The “canonical regular parameters” estimated by ppm are θ1 = σ 12 and θ2 = τ σ 6 .
304 Lest

Value
An object of class "interact" describing the Lennard-Jones interpoint interaction struc-
ture.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, [Link], [Link]

Examples
X <- rpoispp(100)
ppm(X, ~1, LennardJones(), correction="translate")
# Typically yields very small values for theta_1, theta_2
# so the values of sigma, tau may not be sensible

Lest L-function

Description
Calculates an estimate of Ripley’s L-function for a spatial point pattern.

Usage
Lest(...)

Arguments
... Arguments passed to Kest to estimate the K-function.

Details
This command computes an estimate of the L-function for a spatial point pattern. The
L-function is a transformation of Ripley’s K-function,
r
K(r)
L(r) =
π
where K(r) is the K-function.
See Kest for information about Ripley’s K-function.
The command Lest first calls Kest to compute the estimate of the K-function, and then
applies the square root transformation.
For a completely random (uniform Poisson) point pattern, the theoretical value of the L-
function is L(r) = r. The square root also has the effect of stabilising the variance of the
estimator, so that L is more appropriate for use in simulation envelopes and hypothesis
tests.
letterR 305

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing columns

r the vector of values of the argument r at which the function L has been
estimated
theo the theoretical value L(r) = r for a stationary Poisson process

together with columns named "border", "[Link]", "iso" and/or "trans", according
to the selected edge corrections. These columns contain estimates of the function L(r)
obtained by the edge corrections named.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
Kest, pcf

Examples
data(cells)
L <- Lest(cells)
plot(L, main="L function for cells")

letterR Window in Shape of Letter R

Description
A window in the shape of the capital letter R, for use in demonstrations.

Usage
data(letterR)

Format
An object of class "owin" representing the capital letter R, in the same font as the R
package logo. See [Link] for details of the format.

Source
Adrian Baddeley
306 levelset

levelset Level Set of a Pixel Image

Description
Given a pixel image, find all pixels which have values less than a specified threshold value
(or greater than a threshold, etc), and assemble these pixels into a window.

Usage
levelset(X, thresh, compare="<=")

Arguments

X A pixel image (object of class ”im”).


thresh Threshold value. A single number or value compatible with the pixel
values in X.
compare Character string specifying one of the comparison operators "<", ">",
"==", "<=", ">=", "!=".

Details
If X is a pixel image with numeric values, then levelset(X, thresh) finds the region of
space where the pixel values are less than or equal to the threshold value thresh. This
region is returned as a spatial window.
The argument compare specifies how the pixel values should be compared with the threshold
value. Instead of requiring pixel values to be less than or equal to thresh, you can specify
that they must be less than (<), greater than (>), equal to (==), greater than or equal to
(>=), or not equal to (!=) the threshold value thresh.
If X has non-numeric pixel values (for example, logical or factor values) it is advisable to
use only the comparisons == and !=, unless you really know what you are doing.
For more complicated logical comparisons, see solutionset.

Value
A spatial window (object of class "owin", see [Link]) containing the pixels satisfying
the constraint.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [Link], solutionset.


[Link] 307

Examples
# test image
X <- [Link](function(x,y) { x^2 - y^2 }, [Link]())

W <- levelset(X, 0.2)


W <- levelset(X, -0.3, ">")

# compute area of level set


[Link](levelset(X, 0.1))

[Link] Fit a Log-Gaussian Cox Point Process by Minimum Contrast

Description
Fits a log-Gaussian Cox point process model (with exponential covariance function) to a
point pattern dataset by the Method of Minimum Contrast.

Usage
[Link](X, startpar=list(sigma2=1,alpha=1), lambda=NULL,
q = 1/4, p = 2, rmin = NULL, rmax = NULL, ...)

Arguments
X Data to which the model will be fitted. Either a point pattern or a
summary statistic. See Details.
startpar Vector of starting values for the parameters of the log-Gaussian Cox pro-
cess model.
lambda Optional. An estimate of the intensity of the point process.
q,p Optional. Exponents for the contrast criterion.
rmin, rmax Optional. The interval of r values for the contrast criterion.
... Optional arguments passed to optim to control the optimisation algo-
rithm. See Details.

Details
This algorithm fits a log-Gaussian Cox point process model to a point pattern dataset by
the Method of Minimum Contrast, using the K function.
The argument X can be either

a point pattern: An object of class "ppp" representing a point pattern dataset. The K
function of the point pattern will be computed using Kest, and the method of minimum
contrast will be applied to this.
a summary statistic: An object of class "fv" containing the values of a summary statis-
tic, computed for a point pattern dataset. The summary statistic should be the K
function, and this object should have been obtained by a call to Kest or one of its
relatives.
308 [Link]

The algorithm fits a log-Gaussian Cox point process (LGCP) model to X, by finding the
parameters of the LGCP model which give the closest match between the theoretical K
function of the LGCP model and the observed K function. For a more detailed explanation
of the Method of Minimum Contrast, see mincontrast.
The model fitted is a stationary, isotropic log-Gaussian Cox process with exponential co-
variance (Moller and Waagepetersen, 2003, pp. 72-76). To define this process we start with
a stationary Gaussian random field Z in the two-dimensional plane, with constant mean µ
and covariance function
c(r) = σ 2 e−r/α
where σ 2 and α are parameters. Given Z, we generate a Poisson point process Y with
intensity function λ(u) = exp(Z(u)) at location u. Then Y is a log-Gaussian Cox process.
The theoretical K-function of the LGCP is
Z r
K(r) = 2πs exp(σ 2 exp(−s/α)) ds.
0

The theoretical intensity of the LGCP is

σ2
λ = exp(µ + ).
2
In this algorithm, the Method of Minimum Contrast is first used to find optimal values of
the parameters σ 2 and α. Then the remaining parameter µ is inferred from the estimated
intensity λ.
If the argument lambda is provided, then this is used as the value of λ. Otherwise, if X is
a point pattern, then λ will be estimated from X. If X is a summary statistic and lambda is
missing, then the intensity λ cannot be estimated, and the parameter µ will be returned as
NA.
The remaining arguments rmin,rmax,q,p control the method of minimum contrast; see
mincontrast.
The optimisation algorithm can be controlled through the additional arguments "..."
which are passed to the optimisation function optim. For example, to constrain the param-
eter values to a certain range, use the argument method="L-BFGS-B" to select an optimi-
sation algorithm that respects box constraints, and use the arguments lower and upper to
specify (vectors of) minimum and maximum values for each parameter.

Value
An object of class "minconfit". There are methods for printing and plotting this object.
It contains the following main components:

par Vector of fitted parameter values.


fit Function value table (object of class "fv") containing the observed values
of the summary statistic (observed) and the theoretical values of the
summary statistic computed from the fitted model parameters.

Author(s)
Rasmus Waagepetersen <rw@[Link]>. Adapted for spatstat by Adrian Baddeley
<adrian@[Link]> [Link]
Linhom 309

References
Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial
Point Processes. Chapman and Hall/CRC, Boca Raton.
Waagepetersen, R. (2006). An estimation function approach to inference for inhomogeneous
Neyman-Scott processes. Submitted.

See Also
[Link], [Link], mincontrast, Kest

Examples
data(redwood)
u <- [Link](redwood, c(sigma2=0.1, alpha=1))
u
plot(u)

Linhom L-function

Description
Calculates an estimate of the inhomogeneous version of Ripley’s L-function for a spatial
point pattern.

Usage
Linhom(...)

Arguments
... Arguments passed to Kinhom to estimate the inhomogeneous K-function.

Details
This command computes an estimate of the inhomogeneous version of the L-function for a
spatial point pattern
The original L-function is a transformation of Ripley’s K-function,
r
K(r)
L(r) =
π
where K(r) is the Ripley K-function of a spatially homogeneous point pattern, estimated
by Kest.
The inhomogeneous L-function is the corresponding transformation of the inhomogeneous
K-function, estimated by Kinhom. It is appropriate when the point pattern clearly does not
have a homogeneous intensity of points.
The command Linhom first calls Kinhom to compute the estimate of the inhomogeneous
K-function, and then applies the square root transformation.
For a Poisson point pattern (homogeneous or inhomogeneous), the theoretical value of the
inhomogeneous L-function is L(r) = r. The square root also has the effect of stabilising the
variance of the estimator, so that L is more appropriate for use in simulation envelopes and
hypothesis tests.
310 localK

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing columns
r the vector of values of the argument r at which the function L has been
estimated
theo the theoretical value L(r) = r for a stationary Poisson process
together with columns named "border", "[Link]", "iso" and/or "trans", according
to the selected edge corrections. These columns contain estimates of the function L(r)
obtained by the edge corrections named.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
Kest, Lest, Kinhom, pcf

Examples
data(japanesepines)
X <- japanesepines
L <- Linhom(X, sigma=0.1)
plot(L, main="Inhomogeneous L function for Japanese Pines")

localK Neighbourhood density function

Description
Computes the neighbourhood density function, a local version of the K-function defined by
Getis and Franklin (1987).

Usage
localK(X, ..., correction = "Ripley", verbose = TRUE, rvalue=NULL)
localL(X, ..., correction = "Ripley", verbose = TRUE, rvalue=NULL)

Arguments
X A point pattern (object of class "ppp").
... Ignored.
correction String specifying the edge correction to be applied. Options are "none",
"translate", "Ripley", "isotropic" or "best". Only one correction
may be specified.
verbose Logical flag indicating whether to print progress reports during the cal-
culation.
rvalue Optional. A single value of the distance argument r at which the function
L or K should be computed.
localK 311

Details
The command localL computes the neighbourhood density function, a local version of Rip-
ley’s L-function, proposed by Getis and Franklin (1987). The command localK computes
the local analogue of the K-function.
Given a spatial point pattern X, the neighbourhood density function Li (r) associated with
the ith point in X is computed by
s X
a
Li (r) = eij
(n − 1)π j

where the sum is over all points j 6= i that lie within a distance r of the ith point, a is
the area of the observation window, n is the number of points in X, and eij is an edge
correction term (as described in Kest). The value of Li (r) can also be interpreted as one
of the summands that contributes to the global estimate of the L function.
By default, the function Li (r) or Ki (r) is computed for a range of r values for each point
i. The results are stored as a function value table (object of class "fv") with a column of
the table containing the function estimates for each point of the pattern X.
Alternatively, if the argument rvalue is given, and it is a single number, then the function
will only be computed for this value of r, and the results will be returned as a numeric
vector, with one entry of the vector for each point of the pattern X.

Value
If rvalue is given, the result is a numeric vector of length equal to the number of points in
the point pattern.
If rvalue is absent, the result is an object of class "fv", see [Link], which can be
plotted directly using [Link]. Essentially a data frame containing columns

r the vector of values of the argument r at which the function K has been
estimated
theo the theoretical value K(r) = πr2 or L(r) = r for a stationary Poisson
process

together with columns containing the values of the neighbourhood density function for each
point in the pattern. Column i corresponds to the ith point. The last two columns contain
the r and theo values.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Getis, A. and Franklin, J. (1987) Second-order neighbourhood analysis of mapped point
patterns. Ecology 68, 473–477.

See Also
Kest, Lest
312 [Link]

Examples
data(ponderosa)
X <- ponderosa

# compute all the local L functions


L <- localL(X)

# plot all the local L functions against r


plot(L, main="local L functions for ponderosa")

# plot only the local L function for point number 7


plot(L, iso007 ~ r)

# compute the values of L(r) for r = 12 metres


L12 <- localL(X, rvalue=12)

# Spatially interpolate the values of L12


# Compare Figure 5(b) of Getis and Franklin (1987)
X12 <- X %mark% L12
Z <- [Link](X12, sigma=5, dimyx=128)

plot(Z, col=[Link](128), main="smoothed neighbourhood density")


contour(Z, add=TRUE)
points(X, pch=16, cex=0.5)

[Link] Log Likelihood for Poisson Point Process Model

Description
Extracts the log likelihood of a fitted Poisson point process model.

Usage
## S3 method for class 'ppm':
logLik(object, ...)

Arguments
object Fitted point process model. An object of class "ppm".
... Ignored.

Details
The maximised value of the log likelihood for the fitted model (as approximated by quadra-
ture using the Berman-Turner approximation) is extracted.
If object is not a Poisson process, the maximised log pseudolikelihood is returned, with a
warning.

Value
A numerical value.
longleaf 313

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm

Examples
data(cells)
fit <- ppm(cells, ~x)
logLik(fit)
AIC(fit)

longleaf Longleaf Pines Point Pattern

Description
Locations and sizes of Longleaf pine trees. A marked point pattern.
The data record the locations and diameters of 584 Longleaf pine (Pinus palustris) trees in
a 200 x 200 metre region in southern Georgia (USA). They were collected and analysed by
Platt, Evans and Rathbun (1988).
This is a marked point pattern; the mark associated with a tree is its diameter at breast
height (dbh), a convenient measure of its size. Several analyses have considered only the
“adult” trees which are conventionally defined as those trees with dbh greater than or equal
to 30 cm.
The pattern is regarded as spatially inhomogeneous.

Usage
data(longleaf)

Format
An object of class "ppp" representing the point pattern of tree locations. Entries include

x Cartesian x-coordinate of tree


y Cartesian y-coordinate of tree
marks diameter at breast height, in centimetres.

See [Link] for details of the format of a point pattern object.

Source

Platt, Evans and Rathbun (1988)


314 lurking

References
Platt, W. J., Evans, G. W. and Rathbun, S. L. (1988) The population dynamics of a
long-lived Conifer (Pinus palustris). The American Naturalist 131, 491–525.
Rathbun, S. L. and Cressie, N. (1994) A space-time survival point process for a longleaf pine
forest in southern Georgia. Journal of the American Statistical Association 89, 1164–1173.

Examples
data(longleaf)
plot(longleaf)
plot(cut(longleaf, breaks=c(0,30,Inf), labels=c("Sapling","Adult")))

lurking Lurking variable plot

Description
Plot spatial point process residuals against a covariate

Usage
lurking(object, covariate, type="eem",
cumulative=TRUE,
clipwindow=[Link](object),
rv,
[Link], [Link]=TRUE,
typename,
covname,
oldstyle=FALSE, check=TRUE,
...,
splineargs=list(spar=0.5))

Arguments
object The fitted point process model (an object of class "ppm") for which di-
agnostics should be produced. This object is usually obtained from ppm.
Alternatively, object may be a point pattern (object of class "ppp").
covariate The covariate against which residuals should be plotted. Either a numeric
vector, a pixel image, or an expression. See Details below.
type String indicating the type of residuals or weights to be computed. Choices
include "eem", "raw", "inverse" and "pearson". See [Link] for
all possible choices.
cumulative Logical flag indicating whether to plot a cumulative sum of marks (cumulative=TRUE)
or the derivative of this sum, a marginal density of the smoothed residual
field (cumulative=FALSE).
clipwindow If not NULL this argument indicates that residuals shall only be computed
inside a subregion of the window containing the original point pattern
data. Then clipwindow should be a window object of class "owin".
lurking 315

rv Usually absent. If this argument is present, the values of the residuals


will not be calculated from the fitted model object but will instead be
taken directly from this vector.
[Link] Logical value indicating whether error bounds should be added to plot.
The default is TRUE for Poisson models and FALSE for non-Poisson models.
See Details.
[Link] Logical value indicating whether plots should be shown. If [Link]=FALSE,
only the computed coordinates for the plots are returned. See Value.
typename Usually absent. If this argument is present, it should be a string, and will
be used (in the axis labels of plots) to describe the type of residuals.
covname A string name for the covariate, to be used in axis labels of plots.
oldstyle Logical flag indicating whether error bounds should be plotted using the
approximation given in the original paper (oldstyle=TRUE), or using the
correct asymptotic formula (oldstyle=FALSE).
check Logical flag indicating whether the integrity of the data structure in
object should be checked.
... Arguments passed to [Link] and lines to control the plot be-
haviour.
splineargs A list of arguments passed to [Link] for the estimation of the
derivatives in the case cumulative=FALSE.

Details
This function generates a ‘lurking variable’ plot for a fitted point process model. Resid-
uals from the model represented by object are plotted against the covariate specified by
covariate. This plot can be used to reveal departures from the fitted model, in particular,
to reveal that the point pattern depends on the covariate.
First the residuals from the fitted model (Baddeley et al, 2004) are computed at each
quadrature point, or alternatively the ‘exponential energy marks’ (Stoyan and Grabarnik,
1991) are computed at each data point. The argument type selects the type of residual or
weight. See [Link] for options and explanation.
A lurking variable plot for point processes (Baddeley et al, 2004) displays either the cu-
mulative sum of residuals/weights (if cumulative = TRUE) or a kernel-weighted average
of the residuals/weights (if cumulative = FALSE) plotted against the covariate. The em-
pirical plot (solid lines) is shown together with its expected value assuming the model is
true (dashed lines) and optionally also the pointwise two-standard-deviation limits (dotted
lines).
To be more precise, let Z(u) denote the value of the covariate at a spatial location u.
ˆ If cumulative=TRUE then we plot H(z) against z, where H(z) is the sum of the
residuals over all quadrature points where the covariate takes a value less than or
equal to z, or the sum of the exponential energy weights over all data points where
the covariate takes a value less than or equal to z.
ˆ If cumulative=FALSE then we plot h(z) against z, where h(z) is the derivative of H(z),
computed approximately by spline smoothing.
For the point process residuals E(H(z)) = 0, while for the exponential energy weights
E(H(z)) = area of the subset of the window satisfying Z(u) <= z.
If the empirical and theoretical curves deviate substantially from one another, the interpre-
tation is that the fitted model does not correctly account for dependence on the covariate.
316 lurking

The correct form (of the spatial trend part of the model) may be suggested by the shape
of the plot.
If [Link] = TRUE, then superimposed on the lurking variable plot are the pointwise two-
standard-deviation error limits for H(x) calculated for the inhomogeneous Poisson process.
The default is [Link] = TRUE for Poisson models and [Link] = FALSE for non-Poisson
models.
By default, the two-standard-deviation limits are calculated from the exact formula for the
asymptotic variance of the residuals under the asymptotic normal approximation, equation
(37) of Baddeley et al (2006). However, for compatibility with the original paper of Baddeley
et al (2005), if oldstyle=TRUE, the two-standard-deviation limits are calculated using the
innovation variance, an over-estimate of the true variance of the residuals.
The argument object must be a fitted point process model (object of class "ppm") typically
produced by the maximum pseudolikelihood fitting algorithm ppm).
The argument covariate is either a numeric vector, a pixel image, or an R language
expression. If it is a numeric vector, it is assumed to contain the values of the covariate for
each of the quadrature points in the fitted model. The quadrature points can be extracted
by [Link](object).
If covariate is a pixel image, it is assumed to contain the values of the covariate at each
location in the window. The values of this image at the quadrature points will be extracted.
Alternatively, if covariate is an expression, it will be evaluated in the same environment
as the model formula used in fitting the model object. It must yield a vector of the same
length as the number of quadrature points. The expression may contain the terms x and
y representing the cartesian coordinates, and may also contain other variables that were
available when the model was fitted. Certain variable names are reserved words; see ppm.
Note that lurking variable plots for the x and y coordinates are also generated by [Link],
amongst other types of diagnostic plots. This function is more general in that it enables
the user to plot the residuals against any chosen covariate that may have been present.
For advanced use, even the values of the residuals/weights can be altered. If the argument
rv is present, the residuals will not be calculated from the fitted model object but will
instead be taken directly from rv. The vector rv should be numeric, and its length should
equal the number of data points in the original point pattern (if type="eem") or the number
of quadrature points used to fit the model (otherwise).

Value
A list containing two dataframes empirical and theoretical. The first dataframe empirical
contains columns covariate and value giving the coordinates of the lurking variable plot.
The second dataframe theoretical contains columns covariate, mean and sd giving the
coordinates of the plot of the theoretical mean and standard deviation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial
point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.
Baddeley, A., Moller, J. and Pakes, A.G. (2006) Properties of residuals for spatial point
processes. To appear.
lut 317

Stoyan, D. and Grabarnik, P. (1991) Second-order characteristics for stochastic structures


connected with Gibbs point processes. Mathematische Nachrichten, 151:95–100.

See Also
[Link], [Link], [Link], [Link], eem, ppm

Examples
data(nztrees)
fit <- ppm(nztrees, ~x, Poisson())
lurking(fit, expression(x))
lurking(fit, expression(x), cumulative=FALSE)

lut Lookup Tables

Description
Create a lookup table.

Usage
lut(outputs, ..., breaks=NULL, inputs=NULL)

Arguments
outputs Vector of output values
... Ignored.
inputs Input values to which the output values are associated. A factor or vector
of the same length as outputs. Incompatible with breaks.
breaks Breakpoints for the lookup table. A numeric vector of length equal to
length(outputs)+1.

Details
A lookup table is a function, mapping input values to output values.
The command lut creates an object representing a lookup table, which can then be used
to control various behaviour in the spatstat package. It can also be used to compute the
output value assigned to any input value.
The argument outputs specifies the output values to which input data values will be
mapped. It should be a vector of any atomic type (e.g. numeric, logical, character, complex)
or factor values.
Exactly one of the arguments inputs and breaks must be specified by name.
If inputs is given, then it should be a vector or factor, of the same length as outputs.
The entries of inputs can be any atomic type (e.g. numeric, logical, character, complex)
or factor values. The resulting lookup table associates the value inputs[i] with the value
outputs[i].
If breaks is given, then it determines intervals of the real number line which are mapped
to each output value. It should be a numeric vector, of length at least 2, with entries that
318 markconnect

are in increasing order. Infinite values are allowed. Any number in the range between
breaks[i] and breaks[i+1] will be mapped to the value outputs[i].
The result is an object of class "lut". There is a print method for this class. Some plot
commands in the spatstat package accept an object of this class as a specification of a
lookup table.
The result is also a function f which can be used to compute the output value assigned to
any input data value. That is, f(x) returns the output value assigned to x. This also works
for vectors of input data values.

Value

A function, which is also an object of class "lut".

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

colourmap.

Examples
# lookup table for real numbers, using breakpoints
cr <- lut(factor(c("low", "medium", "high")), breaks=c(0,5,10,15))
cr
cr(3.2)
cr(c(3,5,7))
# lookup table for discrete set of values
ct <- lut(c(0,1), inputs=c(FALSE, TRUE))
ct(TRUE)

markconnect Mark Connection Function

Description

Estimate the marked connection function of a multitype point pattern.

Usage

markconnect(X, i, j, r=NULL,
correction=c("isotropic", "Ripley", "translate"),
method="density", ..., normalise=FALSE)
markconnect 319

Arguments
X The observed point pattern. An object of class "ppp" or something ac-
ceptable to [Link].
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured.
j Number or character string identifying the type (mark value) of the points
in X to which distances are measured.
r numeric vector. The values of the argument r at which the mark connec-
tion function pij (r) should be evaluated. There is a sensible default.
correction A character vector containing any selection of the options "isotropic",
"Ripley" or "translate". It specifies the edge correction(s) to be ap-
plied.
method A character vector indicating the user’s choice of density estimation tech-
nique to be used. Options are "density", "loess", "sm" and "smrep".
... Arguments passed to the density estimation routine (density, loess or
[Link]) selected by method.
normalise If TRUE, normalise the pair connection function by dividing it by pi pj ,
the estimated probability that randomly-selected points will have marks
i and j.

Details
The mark connection function pij (r) of a multitype point process X is a measure of the
dependence between the types of two points of the process a distance r apart.
Informally pij (r) is defined as the conditional probability, given that there is a point of the
process at a location u and another point of the process at a location v separated by a
distance ||u − v|| = r, that the first point is of type i and the second point is of type j. See
Stoyan and Stoyan (1994).
If the marks attached to the points of X are independent and identically distributed, then
pij (r) ≡ pi pj where pi denotes the probability that a point is of type i. Values larger than
this, pij (r) > pi pj , indicate positive association between the two types, while smaller values
indicate negative association.
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a multitype point pattern (a marked point pattern with
factor-valued marks).
The argument r is the vector of values for the distance r at which pij (r) is estimated. There
is a sensible default.
This algorithm assumes that X can be treated as a realisation of a stationary (spatially
homogeneous) random spatial point process in the plane, observed through a bounded
window. The window (which is specified in X as X$window) may have arbitrary shape.
Biases due to edge effects are treated in the same manner as in Kest. The edge corrections
implemented here are

isotropic/Ripley Ripley’s isotropic correction (see Ripley, 1988; Ohser, 1983). This is
implemented only for rectangular and polygonal windows (not for binary masks).
translate Translation correction (Ohser, 1983). Implemented for all window geometries,
but slow for complex windows.
320 markconnect

Note that the estimator assumes the process is stationary (spatially homogeneous).
The mark connection function is estimated using density estimation techniques. The user
can choose between

"density" which uses the standard kernel density estimation routine density, and works
only for evenly-spaced r values;
"loess" which uses the function loess in the package modreg;
"sm" which uses the function [Link] in the package sm and is extremely slow;
"smrep" which uses the function [Link] in the package sm and is relatively fast, but
may require manual control of the smoothing parameter hmult.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns

r the values of the argument r at which the mark connection function pij (r)
has been estimated
theo the theoretical value of pij (r) when the marks attached to different points
are independent

together with a column or columns named "iso" and/or "trans", according to the selected
edge corrections. These columns contain estimates of the function pij (r) obtained by the
edge corrections named.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.

See Also
Multitype pair correlation pcfcross and multitype K-functions Kcross, Kdot.
Use alltypes to compute the mark connection functions between all pairs of types.
Mark correlation markcorr and mark variogram markvario for numeric-valued marks.

Examples
# Hughes' amacrine data
# Cells marked as 'on'/'off'
data(amacrine)
M <- markconnect(amacrine, "on", "off")
plot(M)

# Compute for all pairs of types at once


plot(alltypes(amacrine, markconnect))
markcorr 321

markcorr Mark Correlation Function

Description
Estimate the marked correlation function of a marked point pattern.

Usage
markcorr(X, f = function(m1, m2) { m1 * m2}, r=NULL,
correction=c("isotropic", "Ripley", "translate"),
method="density", ...,
f1=NULL, normalise=TRUE, fargs=NULL)

Arguments
X The observed point pattern. An object of class "ppp" or something ac-
ceptable to [Link].
f Optional. Test function f used in the definition of the mark correlation
function. An R function with at least two arguments. There is a sensible
default.
r Optional. Numeric vector. The values of the argument r at which the
mark correlation function kf (r) should be evaluated. There is a sensible
default.
correction A character vector containing any selection of the options "isotropic",
"Ripley", "translate", "none" or "best". It specifies the edge correc-
tion(s) to be applied.
method A character vector indicating the user’s choice of density estimation tech-
nique to be used. Options are "density", "loess", "sm" and "smrep".
... Arguments passed to the density estimation routine (density, loess or
[Link]) selected by method.
f1 An alternative to f. If this argument is given, then f is assumed to take
the form f (u, v) = f1 (u)f1 (v).
normalise If normalise=FALSE, compute only the numerator of the expression for
the mark correlation.
fargs Optional. A list of extra arguments to be passed to the function f or f1.

Details
By default, this command calculates an estimate of Stoyan’s mark correlation kmm (r) for
the point pattern.
Alternatively if the argument f or f1 is given, then it calculates Stoyan’s generalised mark
correlation kf (r) with test function f .
Theoretical definitions are as follows (see Stoyan and Stoyan (1994, p. 262)):

ˆ For a point process X with numeric marks, Stoyan’s mark correlation function kmm (r),
is
E0u [M (0)M (u)]
kmm (r) =
E[M, M ′ ]
322 markcorr

where E0u denotes the conditional expectation given that there are points of the process
at the locations 0 and u separated by a distance r, and where M (0), M (u) denote the
marks attached to these two points. On the denominator, M, M ′ are random marks
drawn independently from the marginal distribution of marks, and E is the usual
expectation.
ˆ For a multitype point process X, the mark correlation is

P0u [M (0)M (u)]


kmm (r) =
P [M = M ′ ]

where P and P0u denote the probability and conditional probability.


ˆ The generalised mark correlation function kf (r) of a marked point process X, with
test function f , is
E0u [f (M (0), M (u))]
kf (r) =
E[f (M, M ′ )]
The test function f is any function f (m1 , m2 ) with two arguments which are possible marks
of the pattern, and which returns a nonnegative real value. Common choices of f are: for
continuous real-valued marks,
f (m1 , m2 ) = m1 m2
for discrete marks (multitype point patterns),

f (m1 , m2 ) = 1(m1 = m2 )

and for marks taking values in [0, 2π),

f (m1 , m2 ) = sin(m1 − m2 )

.
Note that kf (r) is not a “correlation” in the usual statistical sense. It can take any non-
negative real value. The value 1 suggests “lack of correlation”: if the marks attached to the
points of X are independent and identically distributed, then kf (r) ≡ 1. The interpretation
of values larger or smaller than 1 depends on the choice of function f .
The argument X must be a point pattern (object of class "ppp") or any data that are
acceptable to [Link]. It must be a marked point pattern.
The argument f determines the function to be applied to pairs of marks. It has a sensible
default, which depends on the kind of marks in X. If the marks are numeric values, then
f <- function(m1, m2) { m1 * m2} computes the product of two marks. If the marks
are a factor (i.e. if X is a multitype point pattern) then f <- function(m1, m2) { m1 ==
m2} yields the value 1 when the two marks are equal, and 0 when they are unequal. These
are the conventional definitions for numerical marks and multitype points respectively.
The argument f may be specified by the user. It must be an R function, accepting two
arguments m1 and m2 which are vectors of equal length containing mark values (of the same
type as the marks of X). (It may also take additional arguments, passed through fargs). It
must return a vector of numeric values of the same length as m1 and m2. The values must
be non-negative, and NA values are not permitted.
Alternatively the user may specify the argument f1 instead of f. This indicates that the test
function f should take the form f (u, v) = f1 (u)f1 (v) where f1 (u) is given by the argument
f1. The argument f1 should be an R function with at least one argument. (It may also
take additional arguments, passed through fargs).
The argument r is the vector of values for the distance r at which kf (r) is estimated.
markcorr 323

This algorithm assumes that X can be treated as a realisation of a stationary (spatially


homogeneous) random spatial point process in the plane, observed through a bounded
window. The window (which is specified in X as X$window) may have arbitrary shape.
Biases due to edge effects are treated in the same manner as in Kest. The edge corrections
implemented here are

isotropic/Ripley Ripley’s isotropic correction (see Ripley, 1988; Ohser, 1983). This is
implemented only for rectangular and polygonal windows (not for binary masks).
translate Translation correction (Ohser, 1983). Implemented for all window geometries,
but slow for complex windows.

Note that the estimator assumes the process is stationary (spatially homogeneous).
The numerator and denominator of the mark correlation function (in the expression above)
are estimated using density estimation techniques. The user can choose between

"density" which uses the standard kernel density estimation routine density, and works
only for evenly-spaced r values;
"loess" which uses the function loess in the package modreg;
"sm" which uses the function [Link] in the package sm and is extremely slow;
"smrep" which uses the function [Link] in the package sm and is relatively fast, but
may require manual control of the smoothing parameter hmult.

If normalise=FALSE then the algorithm will compute only the numerator

cf (r) = E0u f (M (0), M (u))

of the expression for the mark correlation function.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns

r the values of the argument r at which the mark correlation function kf (r)
has been estimated
theo the theoretical value of kf (r) when the marks attached to different points
are independent, namely 1

together with a column or columns named "iso" and/or "trans", according to the selected
edge corrections. These columns contain estimates of the mark correlation function kf (r)
obtained by the edge corrections named.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.
324 markcorrint

See Also
Mark variogram markvario for numeric marks.
Mark connection function markconnect and multitype K-functions Kcross, Kdot for factor-
valued marks.
markcorrint to estimate the indefinite integral of the mark correlation function.

Examples
# CONTINUOUS-VALUED MARKS:
# (1) Spruces
# marks represent tree diameter
data(spruces)
# mark correlation function
ms <- markcorr(spruces)
plot(ms)

# (2) simulated data with independent marks


X <- rpoispp(100)
X <- X %mark% runif(X$n)
## Not run:
Xc <- markcorr(X)
plot(Xc)

## End(Not run)

# MULTITYPE DATA:
# Hughes' amacrine data
# Cells marked as 'on'/'off'
data(amacrine)
# (3) Kernel density estimate with Epanecnikov kernel
# (as proposed by Stoyan & Stoyan)
M <- markcorr(amacrine, function(m1,m2) {m1==m2},
correction="translate", method="density",
kernel="epanechnikov")
plot(M)
# Note: kernel="epanechnikov" comes from help(density)

# (4) Same again with explicit control over bandwidth


## Not run:
M <- markcorr(amacrine,
correction="translate", method="density",
kernel="epanechnikov", bw=0.02)
# see help(density) for correct interpretation of 'bw'

## End(Not run)

markcorrint Mark Correlation Integral

Description
Estimates the mark correlation integral of a marked point pattern.
markcorrint 325

Usage
markcorrint(X, f = NULL, r = NULL,
correction = c("isotropic", "Ripley", "translate"), ...,
f1 = NULL, normalise = TRUE, returnL = FALSE, fargs = NULL)

Arguments
X The observed point pattern. An object of class "ppp" or something ac-
ceptable to [Link].
f Optional. Test function f used in the definition of the mark correlation
function. An R function with at least two arguments. There is a sensible
default.
r Optional. Numeric vector. The values of the argument r at which the
mark correlation function kf (r) should be evaluated. There is a sensible
default.
correction A character vector containing any selection of the options "isotropic",
"Ripley" or "translate". It specifies the edge correction(s) to be ap-
plied.
... Ignored.
f1 An alternative to f. If this argument is given, then f is assumed to take
the form f (u, v) = f1 (u)f1 (v).
normalise If normalise=FALSE, compute only the numerator of the expression for
the mark correlation.
returnL Compute the analogue of the K-function if returnL=FALSE or the ana-
logue of the L-function if returnL=TRUE.
fargs Optional. A list of extra arguments to be passed to the function f or f1.

Details
Given a marked point pattern X, this command estimates the weighted indefinite integral
Z r
Kf (r) = 2π skf (s)ds
0

of the mark correlation function kf (r). See markcorr for a definition of the mark correlation
function.
The use of the weighted indefinite integral was advocated by Penttinen et al (1992). The
relationship between Kf and kf is analogous to the relationship between the classical K-
function K(r) and the pair correlation function g(r).
If returnL=FALSE then the function Kf (r) is returned; otherwise the function
q
Lf (r) = Kf (r)/pi

is returned.

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns
326 markcorrint

r the values of the argument r at which the mark correlation integral Kf (r)
has been estimated
theo the theoretical value of Kf (r) when the marks attached to different points
are independent, namely πr2

together with a column or columns named "iso" and/or "trans", according to the selected
edge corrections. These columns contain estimates of the mark correlation integral Kf (r)
obtained by the edge corrections named (if returnL=FALSE).

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Penttinen, A., Stoyan, D. and Henttonen, H. M. (1992) Marked point processes in forest
statistics. Forest Science 38 (1992) 806-824.
Illian, J., Penttinen, A., Stoyan, H. and Stoyan, D. (2008) Statistical analysis and modelling
of spatial point patterns. Chichester: John Wiley.

See Also

markcorr to estimate the mark correlation function.

Examples

# CONTINUOUS-VALUED MARKS:
# (1) Spruces
# marks represent tree diameter
data(spruces)
# mark correlation function
ms <- markcorrint(spruces)
plot(ms)

# (2) simulated data with independent marks


X <- rpoispp(100)
X <- X %mark% runif(X$n)
Xc <- markcorrint(X)
plot(Xc)

# MULTITYPE DATA:
# Hughes' amacrine data
# Cells marked as 'on'/'off'
data(amacrine)
M <- markcorrint(amacrine, function(m1,m2) {m1==m2},
correction="translate")
plot(M)
markstat 327

markstat Summarise Marks in Every Neighbourhood in a Point Pattern

Description
Visit each point in a point pattern, find the neighbouring points, and summarise their marks

Usage
markstat(X, fun, N, R, ...)

Arguments
X A marked point pattern. An object of class "ppp".
fun Function to be applied to the vector of marks.
N Integer. If this argument is present, the neighbourhood of a point of X
is defined to consist of the N points of X which are closest to it. This
argument is incompatible with R.
R Nonnegative numeric value. If this argument is present, the neighbour-
hood of a point of X is defined to consist of all points of X which lie within
a distance R of it. This argument is incompatible with N.
... extra arguments passed to the function fun. They must be given in the
form name=value.

Details
This algorithm visits each point in the point pattern X, determines which points of X are
“neighbours” of the current point, extracts the marks of these neighbouring points, applies
the function fun to the marks, and collects the value or values returned by fun.
The definition of “neighbours” depends on the arguments N and R, exactly one of which
must be given.
If N is given, then the neighbours of the current point are the N points of X which are
closest to the current point (including the current point itself). If R is given, then the
neighbourhood of the current point consists of all points of X which lie closer than a distance
R from the current point.
Each point of X is visited; the neighbourhood of the current point is determined; the marks
of these points are extracted as a vector v; then the function fun is called as:
fun(v, ...)
where ... are the arguments passed from the call to markstat.
The results of each call to fun are collected and returned according to the usual rules for
apply and its relatives. See Value above.
This function is just a convenient wrapper for a common use of the function applynbd. For
more complex tasks, use applynbd. To simply tabulate the marks in every R-neighbourhood,
use marktable.
328 marktable

Value

Similar to the result of apply. if each call to fun returns a single numeric value, the result is
a vector of dimension X$n, the number of points in X. If each call to fun returns a vector of
the same length m, then the result is a matrix of dimensions c(m,n); note the transposition
of the indices, as usual for the family of apply functions. If the calls to fun return vectors
of different lengths, the result is a list of length X$n.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

applynbd, marktable, [Link], apply

Examples
data(longleaf)

# average diameter of 5 closest neighbours of each tree


md <- markstat(longleaf, mean, N=5)

# range of diameters of trees within 10 metre radius


rd <- markstat(longleaf, range, R=10)

marktable Tabulate Marks in Neighbourhood of Every Point in a Point Pat-


tern

Description

Visit each point in a point pattern, find the neighbouring points, and compile a frequency
table of the marks of these neighbour points.

Usage

marktable(X, R, exclude=TRUE)

Arguments

X A marked point pattern. An object of class "ppp".


R Neighbourhood radius.
exclude Logical. If exclude=TRUE, the neighbours of a point do not include the
point itself. If exclude=FALSE, a point belongs to its own neighbourhood.
markvario 329

Details
This algorithm visits each point in the point pattern X, inspects all the neighbouring points
within a radius R of the current point, and compiles a frequency table of the marks attached
to the neighbours.
The dataset X must be a multitype point pattern, that is, marks(X) must be a factor.
The result is a two-dimensional contingency table with one row for each point in the pattern,
and one column for each possible mark value. The [i,j] entry in the table gives the number
of neighbours of point i that have mark j.
To perform more complicated calculations on the neighbours of every point, use markstat
or applynbd.

Value
A contingency table (object of class "table") with one row for each point in X, and one
column for each possible mark value.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
markstat, applynbd, Kcross, [Link], table

Examples
data(amacrine)
head(marktable(amacrine, 0.1))
head(marktable(amacrine, 0.1, exclude=FALSE))

markvario Mark Variogram

Description
Estimate the mark variogram of a marked point pattern.

Usage
markvario(X, correction = c("isotropic", "Ripley", "translate"),
r = NULL, method = "density", ..., normalise=FALSE)

Arguments
X The observed point pattern. An object of class "ppp" or something ac-
ceptable to [Link]. It must have marks which are numeric.
correction A character vector containing any selection of the options "isotropic",
"Ripley" or "translate". It specifies the edge correction(s) to be ap-
plied.
330 markvario

r numeric vector. The values of the argument r at which the mark vari-
ogram γ(r) should be evaluated. There is a sensible default.
method A character vector indicating the user’s choice of density estimation tech-
nique to be used. Options are "density", "loess", "sm" and "smrep".
... Arguments passed to the density estimation routine (density, loess or
[Link]) selected by method.
normalise If TRUE, normalise the variogram by dividing it by the estimated mark
variance.

Details
The mark variogram γ(r) of a marked point process X is a measure of the dependence
between the marks of two points of the process a distance r apart. It is informally defined
as
1
γ(r) = E[ (M1 − M2 )2 ]
2
where E[] denotes expectation and M1 , M2 are the marks attached to two points of the
process a distance r apart.
The mark variogram of a marked point process is analogous, but not equivalent, to the
variogram of a random field in geostatistics. See Waelder and Stoyan (1996).

Value
An object of class "fv" (see [Link]).
Essentially a data frame containing numeric columns
r the values of the argument r at which the mark variogram γ(r) has been
estimated
theo the theoretical value of γ(r) when the marks attached to different points
are independent; equal to the sample variance of the marks
together with a column or columns named "iso" and/or "trans", according to the selected
edge corrections. These columns contain estimates of the function γ(r) obtained by the edge
corrections named.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Cressie, N.A.C. (1991) Statistics for spatial data. John Wiley and Sons, 1991.
Mase, S. (1996) The threshold method for estimating annual rainfall. Annals of the Institute
of Statistical Mathematics 48 (1996) 201-213.
Waelder, O. and Stoyan, D. (1996) On variograms in point process statistics. Biometrical
Journal 38 (1996) 895-905.

See Also
Mark correlation function markcorr for numeric marks.
Mark connection function markconnect and multitype K-functions Kcross, Kdot for factor-
valued marks.
matchingdist 331

Examples
# Longleaf Pine data
# marks represent tree diameter
data(longleaf)
# Subset of this large pattern
swcorner <- owin(c(0,100),c(0,100))
sub <- longleaf[ , swcorner]
# mark correlation function
mv <- markvario(sub)
plot(mv)

matchingdist Distance for a Point Pattern Matching

Description
Computes the distance associated with a matching between two point patterns.

Usage
matchingdist(matching, type = NULL, cutoff = NULL, q = NULL)

Arguments
matching A point pattern matching (an object of class "pppmatching").
type A character string giving the type of distance to be computed. One of
"spa", "ace" or "mat". See details below.
cutoff The value > 0 at which interpoint distances are cut off.
q The order of the average that is applied to the interpoint distances. May
be Inf, in which case the maximum of the interpoint distances is taken.

Details
Computes the distance specified by type, cutoff, and order for a point matching. If
any of these arguments are not provided, the function uses the corresponding elements of
matching (if available).
For the type "spa" (subpattern assignment) it is assumed that the points of the point
pattern with the smaller cardinality m are matched to a m-point subpattern of the point
pattern with the larger cardinality n in a 1-1 way. The distance is then given as the q-th
order average of the m distances between matched points (minimum of Euclidean distance
and cutoff) and n − m ”penalty distances” of value cutoff.
For the type "ace" (assignment only if cardinalities equal) the matching is assumed to be
1-1 if the cardinalities of the point patterns are the same, in which case the q-th order
average of the matching distances (minimum of Euclidean distance and cutoff) is taken.
If the cardinalities are different, the matching may be arbitrary and the distance returned
is always equal to cutoff.
For the type mat (mass transfer) it is assumed that each point of the point pattern with the
smaller cardinality m has mass 1, each point of the point pattern with the larger cardinality
n has mass m/n, and fractions of these masses are matched in such a way that each point
contributes exactly its mass. The distance is then given as the q-th order weighted average
332 matchingdist

of all distances (minimum of Euclidean distance and cutoff) of (partially) matched points
with weights equal to the fractional masses divided by m.
If the cardinalities of the two point patterns are equal, matchingdist(m, type, cutoff,
q) yields the same result no matter if type is "spa", "ace" or "mat".

Value

Numeric value of the distance associated with the matching.

Author(s)

Dominic Schuhmacher <dominic@[Link]> [Link]

See Also

pppdist [Link]

Examples
# an optimal matching
X <- runifpoint(20)
Y <- runifpoint(20)
[Link] <- pppdist(X, Y)
summary([Link])
matchingdist([Link])
# is the same as the distance given by summary([Link])

# sequential nearest neighbour matching


# (go through all points of point pattern X in sequence
# and match each point with the closest point of Y that is
# still unmatched)
am <- matrix(0, 20, 20)
h <- matrix(c(1:20, rep(0,20)), 20, 2)
h[1,2] = nncross(X[1],Y)[1,2]
for (i in 2:20) {
nn <- nncross(X[i],Y[-h[1:(i-1),2]])[1,2]
h[i,2] <- ((1:20)[-h[1:(i-1),2]])[nn]
}
am[h] <- 1
[Link] <- pppmatching(X, Y, am)
matchingdist([Link], type="spa", cutoff=1, q=1)
# is >= the distance obtained for [Link]
# in most cases strictly >

## Not run:
par(mfrow=c(1,2))
plot([Link])
plot([Link])
text(X$x, X$y, 1:20, pos=1, offset=0.3, cex=0.8)

## End(Not run)
[Link] 333

[Link] Fit the Matern Cluster Point Process by Minimum Contrast

Description
Fits the Matern Cluster point process to a point pattern dataset by the Method of Minimum
Contrast.

Usage
[Link](X, startpar=c(kappa=1,R=1), lambda=NULL,
q = 1/4, p = 2, rmin = NULL, rmax = NULL, ...)

Arguments
X Data to which the Matern Cluster model will be fitted. Either a point
pattern or a summary statistic. See Details.
startpar Vector of starting values for the parameters of the Matern Cluster process.
lambda Optional. An estimate of the intensity of the point process.
q,p Optional. Exponents for the contrast criterion.
rmin, rmax Optional. The interval of r values for the contrast criterion.
... Optional arguments passed to optim to control the optimisation algo-
rithm. See Details.

Details
This algorithm fits the Matern Cluster point process model to a point pattern dataset by
the Method of Minimum Contrast, using the K function.
The argument X can be either

a point pattern: An object of class "ppp" representing a point pattern dataset. The K
function of the point pattern will be computed using Kest, and the method of minimum
contrast will be applied to this.
a summary statistic: An object of class "fv" containing the values of a summary statis-
tic, computed for a point pattern dataset. The summary statistic should be the K
function, and this object should have been obtained by a call to Kest or one of its
relatives.

The algorithm fits the Matern Cluster point process to X, by finding the parameters of the
Matern Cluster model which give the closest match between the theoretical K function of
the Matern Cluster process and the observed K function. For a more detailed explanation
of the Method of Minimum Contrast, see mincontrast.
The Matern Cluster point process is described in Moller and Waagepetersen (2003, p. 62).
It is a cluster process formed by taking a pattern of parent points, generated according
to a Poisson process with intensity κ, and around each parent point, generating a random
number of offspring points, such that the number of offspring of each parent is a Poisson
random variable with mean µ, and the locations of the offspring points of one parent are
independent and uniformly distributed inside a circle of radius R centred on the parent
point.
334 [Link]

The theoretical K-function of the Matern Cluster process is

1 r
K(r) = πr2 + h( )
κ 2R
where
1 p p
h(z) = 2 + [(8z 2 − 4)arccos(z) − 2arcsin(z) + 4z (1 − z 2 )3 − 6z 1 − z 2 ]
π
for z <= 1, and h(z) = 1 for z > 1. The theoretical intensity of the Matern Cluster process
is λ = κµ.
In this algorithm, the Method of Minimum Contrast is first used to find optimal values of
the parameters κ and R. Then the remaining parameter µ is inferred from the estimated
intensity λ.
If the argument lambda is provided, then this is used as the value of λ. Otherwise, if X is
a point pattern, then λ will be estimated from X. If X is a summary statistic and lambda is
missing, then the intensity λ cannot be estimated, and the parameter µ will be returned as
NA.
The remaining arguments rmin,rmax,q,p control the method of minimum contrast; see
mincontrast.
The Matern Cluster process can be simulated, using rMatClust.
Homogeneous or inhomogeneous Matern Cluster models can also be fitted using the function
kppm.
The optimisation algorithm can be controlled through the additional arguments "..."
which are passed to the optimisation function optim. For example, to constrain the param-
eter values to a certain range, use the argument method="L-BFGS-B" to select an optimi-
sation algorithm that respects box constraints, and use the arguments lower and upper to
specify (vectors of) minimum and maximum values for each parameter.

Value
An object of class "minconfit". There are methods for printing and plotting this object.
It contains the following main components:

par Vector of fitted parameter values.


fit Function value table (object of class "fv") containing the observed values
of the summary statistic (observed) and the theoretical values of the
summary statistic computed from the fitted model parameters.

Author(s)
Rasmus Waagepetersen <rw@[Link]> Adapted for spatstat by Adrian Baddeley <adrian@[Link]
[Link]

References
Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial
Point Processes. Chapman and Hall/CRC, Boca Raton.
Waagepetersen, R. (2006). An estimation function approach to inference for inhomogeneous
Neyman-Scott processes. Submitted.
[Link] 335

See Also
kppm, [Link], [Link], mincontrast, Kest, rMatClust to simulate the fitted
model.

Examples
data(redwood)
u <- [Link](redwood, c(kappa=10, R=0.1))
u
plot(u)

[Link] Mean, Median and Range of Pixel Values in an Image

Description
Calculates the mean, median or range of the pixel values in a pixel image.

Usage
## S3 method for class 'im':
mean(x, ...)
## S3 method for class 'im':
median(x, ...)
## S3 method for class 'im':
range(x, ...)

Arguments
x A pixel image (object of class "im").
... Arguments passed to [Link].

Details
These functions calculate the mean, median and range of the pixel values in the image x.
An object of class "im" describes a pixel image. See [Link]) for details of this class.
The function [Link] is a method for the generic function mean for the class "im". Similarly
[Link] is a method for the generic median and [Link] is a method for range.
If the image x is logical-valued, the mean value of x is the fraction of pixels that have the
value TRUE. The median is not defined.
If the image x is factor-valued, then the mean of x is the mean of the integer codes of the
pixel values. The median and range are not defined.
Any arguments in ... are passed to the default method, for example [Link]. In
particular, using the argument trim will compute the trimmed mean, as explained in the
help for [Link].
Other information about an image can be obtained using [Link] or [Link].

Value
A single number.
336 methods.box3

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
mean, median, range, [Link], [Link], [Link], [Link],
[Link], [Link].

Examples
X <- [Link](function(x,y) {x^2}, [Link]())
mean(X)
median(X)
range(X)

mean(X, trim=0.05)

methods.box3 Methods for Three-Dimensional Box

Description
Methods for class "box3".

Usage
## S3 method for class 'box3':
print(x, ...)
## S3 method for class 'box3':
unitname(x)
## S3 replacement method for class 'box3':
unitname(x) <- value

Arguments
x Object of class "box3" representing a three-dimensional box.
... Other arguments passed to [Link].
value Name of the unit of length. See unitname.

Details
These are methods for the generic functions print and unitname for the class "box3" of
three-dimensional boxes.
The print method prints a description of the box, while the unitname method extracts the
name of the unit of length in which the box coordinates are expressed.

Value
For print.box3 the value is NULL. For unitname.box3 an object of class "units".
methods.pp3 337

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
box3, print, unitname

Examples
X <- box3(c(0,10),c(0,10),c(0,5), unitname=c("metre", "metres"))
X
unitname(X)
# Northern European usage
unitname(X) <- "meter"

methods.pp3 Methods for three-dimensional point patterns

Description
Methods for class "pp3".

Usage
## S3 method for class 'pp3':
print(x, ...)
## S3 method for class 'pp3':
summary(object, ...)
## S3 method for class 'pp3':
unitname(x)
## S3 replacement method for class 'pp3':
unitname(x) <- value

Arguments
x,object Object of class "pp3".
... Ignored.
value Name of the unit of length. See unitname.

Details
These are methods for the generic functions print, summary, unitname and unitname<-
for the class "pp3" of three-dimensional point patterns.
The print and summary methods print a description of the point pattern.
The unitname method extracts the name of the unit of length in which the point coordinates
are expressed. The unitname<- method assigns the name of the unit of length.

Value
For print.pp3 the value is NULL. For unitname.pp3 an object of class "units".
338 [Link]

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
pp3, print, unitname unitname<-

Examples
X <- pp3(runif(42),runif(42),runif(42), box3(c(0,1), unitname="mm"))
X
unitname(X)
unitname(X) <- c("foot", "feet")
summary(X)

[Link] Methods for Multidimensional Space-Time Point Patterns

Description
Methods for printing and plotting a general multidimensional space-time point pattern.

Usage
## S3 method for class 'ppx':
print(x, ...)
## S3 method for class 'ppx':
plot(x, ...)

Arguments
x Multidimensional point pattern (object of class "ppx").
... Additional arguments passed to plot methods.

Details
These are the print and plot methods for the class "ppx" of multidimensional point
patterns.

Value
NULL.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppx
[Link] 339

[Link] Midpoints of Line Segment Pattern

Description
Computes the midpoints of each line segment in a line segment pattern.

Usage
[Link](x)

Arguments
x A line segment pattern (object of class "psp").

Details
The midpoint of each line segment is computed.

Value
Point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
b <- [Link](a)

mincontrast Method of Minimum Contrast

Description
A general low-level algorithm for fitting theoretical point process models to point pattern
data by the Method of Minimum Contrast.

Usage
mincontrast(observed, theoretical, startpar, ...,
ctrl=list(q = 1/4, p = 2, rmin=NULL, rmax=NULL),
fvlab=list(label=NULL, desc="minimum contrast fit"),
explain=list(dataname=NULL, modelname=NULL, fname=NULL))
340 mincontrast

Arguments
observed Summary statistic, computed for the data. An object of class "fv".
theoretical An R language function that calculates the theoretical expected value of
the summary statistic, given the model parameters. See Details.
startpar Vector of initial values of the parameters of the point process model
(passed to theoretical).
... Additional arguments passed to the function theoretical and to the
optimisation algorithm optim.
ctrl Optional. List of arguments controlling the optimisation. See Details.
fvlab Optional. List containing some labels for the return value. See Details.
explain Optional. List containing strings that give a human-readable description
of the model, the data and the summary statistic.

Details
This function is a general algorithm for fitting point process models by the Method of
Minimum Contrast. If you want to fit the Thomas process, see [Link]. If you want
to fit a log-Gaussian Cox process, see [Link]. If you want to fit the Matern cluster
process, see [Link].
The Method of Minimum Contrast (Diggle and Gratton, 1984) is a general technique for
fitting a point process model to point pattern data. First a summary function (typically
the K function) is computed from the data point pattern. Second, the theoretical expected
value of this summary statistic under the point process model is derived (if possible, as an
algebraic expression involving the parameters of the model) or estimated from simulations
of the model. Then the model is fitted by finding the optimal parameter values for the
model to give the closest match between the theoretical and empirical curves.
The argument observed should be an object of class "fv" (see [Link]) containing the
values of a summary statistic computed from the data point pattern. Usually this is the
function K(r) computed by Kest or one of its relatives.
The argument theoretical should be a user-supplied function that computes the theoret-
ical expected value of the summary statistic. It must have an argument named par that
will be the vector of parameter values for the model (the length and format of this vector
are determined by the starting values in startpar). The function theoretical should also
expect a second argument (the first argument other than par) containing values of the dis-
tance r for which the theoretical value of the summary statistic K(r) should be computed.
The value returned by theoretical should be a vector of the same length as the given
vector of r values.
The argument ctrl determines the contrast criterion (the objective function that will be
minimised). The algorithm minimises the criterion
Z rmax
D(θ) = |F̂ (r)q − Fθ (r)q |p dr
rmin

where θ is the vector of parameters of the model, F̂ (r) is the observed value of the summary
statistic computed from the data, Fθ (r) is the theoretical expected value of the summary
statistic, and p, q are two exponents. The default is q = 1/4, p=2 so that the contrast
criterion is the integrated squared difference between the fourth roots of the two functions
(Waagepetersen, 2006).
miplot 341

The other arguments just make things print nicely. The argument fvlab contains labels for
the component fit of the return value. The argument explain contains human-readable
strings describing the data, the model and the summary statistic.
The "..." argument of mincontrast can be used to pass extra arguments to the func-
tion theoretical and/or to the optimisation function optim. In this case, the function
theoretical should also have a "..." argument and should ignore it (so that it ignores
arguments intended for optim).

Value
An object of class "minconfit". There are methods for printing and plotting this object.
It contains the following components:

par Vector of fitted parameter values.


fit Function value table (object of class "fv") containing the observed values
of the summary statistic (observed) and the theoretical values of the
summary statistic computed from the fitted model parameters.
opt The return value from the optimizer optim.
crtl The control parameters of the algorithm.
info List of explanatory strings.

Author(s)
Rasmus Waagepetersen <rw@[Link]>, adapted for spatstat by Adrian Baddeley <adrian@[Link]
[Link]

References
Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statis-
tical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.
Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial
Point Processes. Chapman and Hall/CRC, Boca Raton.
Waagepetersen, R. (2006). An estimation function approach to inference for inhomogeneous
Neyman-Scott processes. Submitted.

See Also
kppm, [Link], [Link], [Link],

miplot Morishita Index Plot

Description
Displays the Morishita Index Plot of a spatial point pattern.

Usage
miplot(X, ...)
342 miplot

Arguments
X A point pattern (object of class "ppp") or something acceptable to [Link].
... Optional arguments to control the appearance of the plot.

Details
Morishita (1959) defined an index of spatial aggregation for a spatial point pattern based
on quadrat counts. The spatial domain of the point pattern is first divided into Q subsets
(quadrats) of equal size and shape. The numbers of points falling in each quadrat are
counted. Then the Morishita Index is computed as
PQ
i=1ni (ni − 1)
MI = Q
N (N − 1)

where ni is the number of points falling in the i-th quadrat, and N is the total number of
points. If the pattern is completely random, MI should be approximately equal to 1. Values
of MI greater than 1 suggest clustering.
The Morishita Index plot is a plot of the Morishita Index MI against the linear dimension of
the quadrats. The point pattern dataset is divided into 2 × 2 quadrats, then 3 × 3 quadrats,
etc, and the Morishita Index is computed each time. This plot is an attempt to discern
different scales of dependence in the point pattern data.

Value
None.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
M. Morishita (1959) Measuring of the dispersion of individuals and analysis of the distri-
butional patterns. Memoir of the Faculty of Science, Series E2, Kyushu University. Pages
215–235.

See Also
quadratcount

Examples
data(longleaf)
miplot(longleaf)
opa <- par(mfrow=c(2,3))
data(cells)
data(japanesepines)
data(redwood)
plot(cells)
plot(japanesepines)
plot(redwood)
miplot(cells)
miplot(japanesepines)
[Link] 343

miplot(redwood)
par(opa)

[Link] Compute Images of Constructed Covariates

Description
For a point process model fitted to spatial point pattern data, this function computes pixel
images of the covariates in the design matrix.

Usage
[Link](object, W = [Link](object), ...)

Arguments
object The fitted point process model (an object of class "ppm".)
W A window (object of class "owin") in which the images should be com-
puted. Defaults to the window in which the model was fitted.
... Other arguments (such as [Link]) passed to [Link].

Details
This command is similar to [Link] except that it computes pixel images of the
covariates, instead of computing the covariate values at certain points only.
The object must be a fitted spatial point process model (object of class "ppm") produced
by the model-fitting function ppm.
The spatial covariates required by the model-fitting procedure are computed at every pixel
location in the window W.
Note that the spatial covariates computed here are not the original covariates that were
supplied when fitting the model. Rather, they are the covariates that actually appear in
the loglinear representation of the (conditional) intensity and in the columns of the design
matrix. For example, they might include dummy or indicator variables for different levels
of a factor, depending on the contrasts that are in force.
The pixel resolution is determined by W if W is a mask (that is W$type = "mask"). Otherwise,
the pixel resolution is determined by [Link].
The result is a named list of pixel images (objects of class "im") containing the values
of the spatial covariates. The names of the list elements are the names of the covariates
determined by [Link].
The result is also of class "listof" so that it can be plotted immediately.

Value
An object of class "listof" consisting of a named list of pixel images (objects of class
"im").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
344 [Link]

See Also
[Link], ppm, [Link], im, [Link], [Link], [Link]

Examples
data(cells)
fit <- ppm(cells, ~x)
[Link](fit)
fit2 <- ppm(cells, ~cut(x,3))
[Link](fit2)

[Link] Extract Design Matrix from Point Process Model

Description
Given a point process model that has been fitted to spatial point pattern data, this function
extracts the design matrix of the model.

Usage
## S3 method for class 'ppm':
[Link](object, ..., keepNA=TRUE)

Arguments
object The fitted point process model (an object of class "ppm".)
keepNA Logical. Determines whether rows containing NA values will be deleted
or retained.
... Other arguments (such as [Link]) passed to [Link].

Details
This command is a method for the generic function [Link]. It extracts the design
matrix of a spatial point process model (class "ppm").
More precisely, this command extracts the design matrix of the generalised linear model
associated with a spatial point process model.
The object must be a fitted point process model (object of class "ppm") fitted to spatial
point pattern data. Such objects are produced by the model-fitting function ppm.
This function [Link] extracts the model matrix for the GLM.
The result is a matrix, with one row for every quadrature point in the fitting procedure,
and one column for every constructed covariate in the design matrix.
If there are NA values in the covariates, the argument keepNA determines whether to retain
or delete the corresponding rows of the model matrix. The default keepNA=TRUE is to
retain them. Note that this differs from the default behaviour of many other methods for
[Link], which typically delete rows containing NA.
The quadrature points themselves can be extracted using [Link].
[Link] 345

Value
A matrix. Rows of the matrix correspond to quadrature points in the fitting procedure
(provided keepNA=TRUE). Columns are covariates in the model.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], ppm, [Link], [Link], [Link], [Link]

Examples
data(cells)
fit <- ppm(cells, ~x)
[Link](fit)
# matrix with two columns: '(Intercept)' and 'x'

[Link] Count Multiplicity of Duplicate Points

Description
Counts the number of duplicates for each point in a spatial point pattern.

Usage
[Link](x)

Arguments
x A spatial point pattern (object of class "ppp").

Details
Two points in a point pattern are deemed to be identical if their x, y coordinates are the
same, and their marks are also the same (if they carry marks). The Examples section
illustrates how it is possible for a point pattern to contain a pair of identical points.
For each point in x, this function counts how many points are identical to it, and returns
the vector of counts.

Value
A vector of integers (multiplicities) of length equal to the number of points in x.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
346 MultiStrauss

See Also
[Link], [Link], [Link]

Examples
X <- ppp(c(1,1,0.5), c(2,2,1), window=square(3))
m <- [Link](X)

# unique points in X, marked by multiplicity


first <- !duplicated(X)
Y <- X[first] %mark% m[first]

MultiStrauss The Multitype Strauss Point Process Model

Description
Creates an instance of the multitype Strauss point process model which can then be fitted
to point pattern data.

Usage
MultiStrauss(types, radii)

Arguments
types Vector of all possible types (i.e. the possible levels of the marks variable
in the data)
radii Matrix of interaction radii

Details
The (stationary) multitype Strauss process with m types, with interaction radii rij and
parameters βj and γij is the pairwise interaction point process in which each point of type
j contributes a factor βj to the probability density of the point pattern, and a pair of points
of types i and j closer than rij units apart contributes a factor γij to the density.
The nonstationary multitype Strauss process is similar except that the contribution of each
individual point xi is a function β(xi ) of location and type, rather than a constant beta.
The function ppm(), which fits point process models to point pattern data, requires an
argument of class "interact" describing the interpoint interaction structure of the model to
be fitted. The appropriate description of the multitype Strauss process pairwise interaction
is yielded by the function MultiStrauss(). See the examples below.
The matrix radii must be symmetric, with entries which are either positive numbers or NA.
A value of NA indicates that no interaction term should be included for this combination of
types.
Note that only the interaction radii are specified in MultiStrauss. The canonical parame-
ters log(βj ) and log(γij ) are estimated by ppm(), not fixed in Strauss().
MultiStraussHard 347

Value
An object of class "interact" describing the interpoint interaction structure of the multi-
type Strauss process with interaction radii radii[i, j].

Warnings
The argument types is interpreted as a set of factor levels. That is, in order that ppm can
fit the multitype Strauss model correctly to a point pattern X, this must be a marked point
pattern; the mark vector X$marks must be a factor; and the argument types must equal
levels(X$marks).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, [Link], [Link], Strauss

Examples
r <- matrix(c(1,2,2,1), nrow=2,ncol=2)
MultiStrauss(1:2, r)
# prints a sensible description of itself
data(betacells)
r <- 30.0 * matrix(c(1,2,2,1), nrow=2,ncol=2)
ppm(betacells, ~1, MultiStrauss(c("off","on"), r))
# fit the stationary multitype Strauss process to `betacells'

## Not run:
ppm(betacells, ~polynom(x,y,3), MultiStrauss(c("off","on"), r))
# fit a nonstationary Strauss process with log-cubic polynomial trend

## End(Not run)

MultiStraussHard The Multitype/Hard Core Strauss Point Process Model

Description
Creates an instance of the multitype/hard core Strauss point process model which can then
be fitted to point pattern data.

Usage
MultiStraussHard(types, iradii, hradii)

Arguments
types Vector of all possible types (i.e. the possible levels of the marks variable
in the data)
iradii Matrix of interaction radii
hradii Matrix of hard core radii
348 MultiStraussHard

Details

This is a hybrid of the multitype Strauss process (see MultiStrauss) and the hard core
process (case γ = 0 of the Strauss process). A pair of points of types i and j must not lie
closer than hij units apart; if the pair lies more than hij and less than rij units apart, it
contributes a factor γij to the probability density.
The matrices iradii and hradii must be symmetric, with entries which are either positive
numbers or NA. A value of NA indicates that no interaction term should be included for this
combination of types.
Note that only the interaction radii and hardcore radii are specified in MultiStraussHard.
The canonical parameters log(βj ) and log(γij ) are estimated by ppm(), not fixed in MultiStraussHard().

Value

An object of class "interact" describing the interpoint interaction structure of the mul-
titype/hard core Strauss process with interaction radii iradii[i, j] and hard core radii
hradii[i, j].

Warnings

The argument types is interpreted as a set of factor levels. That is, in order that ppm can
fit the multitype Strauss model correctly to a point pattern X, this must be a marked point
pattern; the mark vector X$marks must be a factor; and the argument types must equal
levels(X$marks).

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

ppm, [Link], [Link], MultiStrauss, Strauss

Examples

r <- matrix(3, nrow=2,ncol=2)


h <- matrix(c(1,2,2,1), nrow=2,ncol=2)
MultiStraussHard(1:2, r, h)
# prints a sensible description of itself
data(betacells)
r <- 30.0 * matrix(c(1,2,2,1), nrow=2,ncol=2)
h <- 15.0 * matrix(c(NA,1,1,NA), nrow=2,ncol=2)
ppm(betacells, ~1, MultiStraussHard(c("off","on"), r, h))
# fit the stationary multitype hardcore Strauss process to `betacells'
murchison 349

murchison Murchison gold deposits

Description
Data recording the spatial locations of gold deposits and associated geological features in
the Murchison area of Western Australia. Extracted from a large scale (1:500,000) study of
the Murchison area by the Geological Survey of Western Australia (Watkins and Hickman,
1990). The features recorded are

ˆ the locations of gold deposits;


ˆ the locations of geological faults;
ˆ the region that contains greenstone bedrock.

The study region is contained in a 330×400 kilometre rectangle. At this scale, gold deposits
are points, i.e. their spatial extent is negligible. Gold deposits in this region occur only in
greenstone bedrock. Geological faults can be observed reliably only within the same region.
However, some faults have been extrapolated (by geological “interpretation”) outside the
greenstone boundary from information observed in the greenstone region.
These data were analysed by Foxall and Baddeley (2002) and Brown et al (2002); see also
Groves et al (2000), Knox-Robinson and Groves (1997). The main aim is to predict the
intensity of the point pattern of gold deposits from the more easily observable fault pattern.

Usage
data(murchison)

Format
murchison is a list with the following entries:

gold a point pattern (object of class "ppp") representing the point pattern of gold deposits.
See [Link] for details of the format.
faults a line segment pattern (object of class "psp") representing the geological faults. See
[Link] for details of the format.
greenstone the greenstone bedrock region. An object of class "owin". Consists of multiple
irregular polygons with holes.

All coordinates are given in metres.

Source
Data were kindly provided by Dr Carl Knox-Robinson of the Department of Geology and
Geophysics, University of Western Australia. Permission to use the data is granted by Dr
Tim Griffin, Geological Survey of Western Australia and by Dr Knox-Robinson. Please
make appropriate acknowledgement to Watkins and Hickman (1990) and the Geological
Survey of Western Australia.
350 nbfires

References

Brown, W.M., Gedeon, T.D., Baddeley, A.J. and Groves, D.I. (2002) Bivariate J-function
and other graphical statistical methods help select the best predictor variables as inputs for
a neural network method of mineral prospectivity mapping. In U. Bayer, H. Burger and
W. Skala (eds.) IAMG 2002: 8th Annual Conference of the International Association for
Mathematical Geology, Volume 1, 2002. International Association of Mathematical Geology.
Pages 257–268.
Foxall, R. and Baddeley, A. (2002) Nonparametric measures of association between a spatial
point process and a random set, with geological applications. Applied Statistics 51, 165–
182.
Groves, D.I., Goldfarb, R.J., Knox-Robinson, C.M., Ojala, J., Gardoll, S, Yun, G.Y. and
Holyland, P. (2000) Late-kinematic timing of orogenic gold deposits and significance for
computer-based exploration techniques with emphasis on the Yilgarn Block, Western Aus-
tralia. Ore Geology Reviews, 17, 1–38.
Knox-Robinson, C.M. and Groves, D.I. (1997) Gold prospectivity mapping using a geo-
graphic information system (GIS), with examples from the Yilgarn Block of Western Aus-
tralia. Chronique de la Recherche Miniere 529, 127–138.
Watkins, K.P. and Hickman, A.H. (1990) Geological evolution and mineralization of the
Murchison Province, Western Australia. Bulletin 137, Geological Survey of Western Aus-
tralia. 267 pages. Published by Department of Mines, Western Australia, 1990. Available
online from Department of Industry and Resources, State Government of Western Australia,
[Link]

Examples

if(interactive()) {
data(murchison)
plot(murchison$greenstone, main="Murchison data", col="lightgreen")
plot(murchison$gold, add=TRUE, pch="+",col="blue")
plot(murchison$faults, add=TRUE, col="red")
}

nbfires Point Patterns of New Brunswick Forest Fires

Description

Point patterns created from yearly records, provided by the New Brunswick Department
of Natural Resources, of all fires falling under their jurisdiction for the years 1987 to 2003
inclusive (with the year 1988 omitted until further notice).

Usage

data(nbfires)
nbfires 351

Format
Executing data(nbfires) creates three objects: nbfires, nbextras, and [Link].
The object nbfires is a marked point pattern (an object of class "ppp") consisting of all
of the fires in the years 1987 to 2003 inclusive, with the omission of 1988. The marks
consist of the last two digits of the years, with the string nbfires. prepended. Patterns
for individual years can be extracted using the function [Link](). (See “Examples”.)
The object nbextras is a list of data frames, with names extras.87, . . . , extras.03. The
columns of these data frames provide “extra” information about the fires. (See “Details”.)
The object [Link] is a rectangular window which covers central New Brunswick. It is
provided for use in illustrative and “practice” calculations inasmuch as the use of a rectan-
gular window simplifies some computations considerably.

Details
The coordinates of the fire locations were provided in terms of latitude and longitude, to the
nearest minute of arc. These were converted to New Brunswick stereographic projection
coordinates (Thomson, Mephan and Steeves, 1977) which was the coordinate system in
which the map of New Brunswick — which constitutes the observation window for the
pattern — was obtained. The conversion was done using a C program kindly provided
by Jonathan Beaudoin of the Department of Geodesy and Geomatics, University of New
Brunswick.
Finally the data and window were rescaled since the use of the New Brunswick stereographic
projection coordinate system resulted in having to deal with coordinates which are expressed
as very large integers with a bewildering number of digits. Amongst other things, these huge
numbers tended to create very untidy axis labels on graphs. The width of the bounding box
of the window was made equal to 1000 (nameless) units. In addition the lower left hand
corner of this bounding box was shifted to the origin. The height of the bounding box was
changed proportionately, resulting in a value of approximately 959.
The window for the fire patterns comprises 6 polygonal components, consisting of mainland
New Brunswick and the 5 largest islands. Some lakes which should form holes in the main-
land component are currently missing; this problem will be remedied in future releases. The
window was formed by “simplifying” the map that was originally obtained. The simplifi-
cation consisted in reducing (using an interactive visual technique) the number of polygon
edges in each component. For instance the number of edges in the mainland component
was reduced from over 138,000 to 500.
For some purposes it is probably better to use a discretized (mask type) window. See
“Examples”.
Because of the coarseness of the coordinates of the original data (1 minute of longitude is
approximately 1 kilometer at the latitude of New Brunswick), data entry errors, and the
simplification of the observation window, many of the original fire locations appeared to be
outside of the window. This problem was addressed by shifting the location of the “outsider”
points slightly, or deleting them, as seemed appropriate.
The columns of the data frames comprising nbextras are

[Link] A code for the type of fire with 1 = forest, 2 = grass, 3 = dump, and 4 = other.
[Link] The discovery date of the fire, which is the nearest possible surrogate for the start
date of the fire. These columns are of class Date and have the format yyyy-mm-dd
[Link] The discovery time (time of day) of the fire, on a 24 hour clock. These columns
are of mode character and have the format HH:MM.
352 nbfires

[Link] The discovery date and time of the fire, expressed in “Julian days”, i.e. as
a decimal fraction representing the number of days since the beginning of the year
(midnight 31 December).
[Link] The date on which the fire was judged to be “out”.
[Link] The time of day on a 24 hour clock, at which the fire was judged to be “out”.
[Link] The date and time at which the fire was judged to be “out”, expressed in Julian
days.
cause General cause of the fire, coded as 1 = railroads, 2 = unknown, 3 = miscellaneous, 4
= lightning, 5 = forest industry, 6 = incendiary, 7 = recreation, 8 = resident, 9 = other
industry. Causes 2, 4, and 6 are designated as “final” by the New Brunswick Depart-
ment of Natural Resources, meaning (it seems) “that’s all there is to it”. Other causes
are apparently intended to be refined by being combined with “source of ignition”.
[Link] Source of ignition, coded as 1 = cigarette/match/pipe/ashes, 2 = burning without
a permit, 3 = burning with a permit, 4 = prescribed burn, 5 = wood spark, 6 =
machine spark, 7 = campfire, 8 = chainsaw, 9 = machinery, 10 = vehicle accident, 11
= railroad accident, 12 = wheelbox on railcars, 13 = hot flakes off railcar wheels, 14 =
dump (i.e. fire escaping from a dump), 15 = ashes (briquettes, burning garbage, etc.)
[Link] The final size of the fire (area burned) in hectares, to the nearest 10th hectare.
Note that due to data entry errors some of the“out dates”and“out times”in the original data
sets were actually earlier than the corresponding “discovery dates” and “discover times”. In
such cases all corresponding entries of the extras data frame (i.e. [Link], [Link],
[Link], [Link], [Link], and [Link]) were set equal to NA. Also, some of
the dates and times were missing (equal to NA) in the original data sets.

Source
The data were kindly provided by the New Brunswick Department of Natural Resources.
Special thanks are due to Jefferey Betts for a great deal of assistance.

References
Turner, Rolf (2007) Point patterns of forest fire locations. To appear in Environmental and
Ecological Statistics.
Thomson, D. B., Mephan, M. P., and Steeves, R. R. (1977) The stereographic double
projection. Technical Report 46, University of New Brunswick, Fredericton, N. B., Canada
URL: [Link]/Pubs/[Link].

Examples
## Not run:
data(nbfires)
X <- split(nbfires) # Create a list of yearly point patterns.
attach(X) # Make the individual point patterns accessible.
attach(nbextras) # Make the individual `extras' accessible.
ftyp <- extras.00$[Link]
Y.00 <- nbfires.00[ftyp==1 | ftyp==2] # Pick out forest and grass fires.
stt <- extras.00$[Link][ftyp==1 | ftyp==2]
fin <- extras.00$[Link][ftyp==1 | ftyp==2]
Y.00 <- setmarks(Y.00,fin-stt) # Mark the pattern with fire duration.
plot(Y.00)
#
[Link] <- [Link](nbfires$window, dimyx=500)
[Link] 353

plot([Link], col=c("green", "white"))


plot(nbfires$window, border="red", add=TRUE)
#
plot(unmark(Y.00)[[Link]], add=TRUE)
plot([Link],add=TRUE,border="blue")
#
K.00 <- Kest(Y.00)
plot(K.00)

## End(Not run)

[Link] Find Pixel Nearest to a Given Point

Description
Given cartesian coordinates, find the nearest pixel.

Usage
[Link](x,y,w, indices=TRUE)

Arguments
x Numeric vector of x coordinates of any points
y Numeric vector of y coordinates of any points
w A window (an object of class "owin") of type "mask" representing a binary
pixel image.
indices Logical flag indicating whether to return the row and column indices, or
the actual x, y coordinates.

Details
The argument w should be a window (an object of class "owin", see [Link] for details)
of type "mask". This represents a binary pixel image.
The arguments x and y should be numeric vectors of equal length. They are interpreted
as the coordinates of points in space. For each point (x[i], y[i]), the function finds the
nearest pixel in the grid of pixels for w.
If indices=TRUE, this function returns a list containing two vectors rr and cc giving row
and column positions (in the image matrix). For the location (x[i],y[i]) the nearest
pixel is at row rr[i] and column cc[i] of the image.
If indices=FALSE, the function returns a list containing two vectors x and y giving the
actual coordinates of the pixels.

Value
If indices=TRUE, a list containing two vectors rr and cc giving row and column positions
(in the image matrix). If indices=FALSE, a list containing vectors x and y giving actual
coordinates of the pixels.
354 nearestsegment

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
w <- owin(c(0,1), c(0,1), mask=matrix(TRUE, 100,100)) # 100 x 100 grid
[Link](0.5, 0.3, w)
[Link](0.5, 0.3, w, indices=FALSE)

nearestsegment Find Line Segment Nearest to Each Point

Description
Given a point pattern and a line segment pattern, this function finds the nearest line segment
for each point.

Usage
nearestsegment(X, Y)

Arguments
X A point pattern (object of class "ppp").
Y A line segment pattern (object of class "psp").

Details
The distance between a point x and a straight line segment y is defined to be the shortest
Euclidean distance between x and any location on y. This algorithm first calculates the
distance from each point of X to each segment of Y. Then it determines, for each point x in
X, which segment of Y is closest. The index of this segment is returned.

Value
Integer vector v (of length equal to the number of points in X) identifying the nearest
segment to each point. If v[i] = j, then Y[j] is the line segment lying closest to X[i].

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
project2segment to project each point of X to a point lying on one of the line segments.
Use [Link] to identify the nearest line segment for each pixel in a grid.
nncorr 355

Examples
X <- runifpoint(3)
Y <- [Link](matrix(runif(20), 5, 4), window=owin())
v <- nearestsegment(X,Y)
plot(Y)
plot(X, add=TRUE)
plot(X[1], add=TRUE, col="red")
plot(Y[v[1]], add=TRUE, lwd=2, col="red")

nncorr Nearest-Neighbour Correlation Indices of Marked Point Pattern

Description
Computes nearest-neighbour correlation indices of a marked point pattern, including the
nearest-neighbour mark product index (default case of nncorr), the nearest-neighbour mark
index (nnmean), and the nearest-neighbour variogram index (nnvario).

Usage
nncorr(X,
f = function(m1, m2) { m1 * m2 },
...,
use = "[Link]", method = c("pearson", "kendall", "spearman"))
nnmean(X)
nnvario(X)

Arguments
X The observed point pattern. An object of class "ppp".
f Function f used in the definition of the nearest neighbour correlation.
... Extra arguments passed to f.
use,method Arguments passed to the standard correlation function cor.

Details
The nearest neighbour correlation index n̄f of a marked point process X is a number
measuring the dependence between the mark of a typical point and the mark of its nearest
neighbour.
The command nncorr computes the nearest neighbour correlation index based on any
test function f provided by the user. The default behaviour of nncorr is to compute the
nearest neighbour mark product index. The commands nnmean and nnvario are convenient
abbreviations for other special choices of f.
In the default case, nncorr(X) computes three different versions of the nearest-neighbour
correlation index: the unnormalised, normalised, and classical correlations.

unnormalised: The unnormalised nearest neighbour correlation (Stoyan and Stoyan,


1994, section 14.7) is defined as

n̄f = E[f (M, M ∗ )]


356 nncorr

where E[] denotes mean value, M is the mark attached to a typical point of the point
process, and M ∗ is the mark attached to its nearest neighbour (i.e. the nearest other
point of the point process).
Here f is any function f (m1 , m2 ) with two arguments which are possible marks of the
pattern, and which returns a nonnegative real value. Common choices of f are: for
continuous real-valued marks,

f (m1 , m2 ) = m1 m2

for discrete marks (multitype point patterns),

f (m1 , m2 ) = 1(m1 = m2 )

and for marks taking values in [0, 2π),

f (m1 , m2 ) = sin(m1 − m2 )

For example, in the second case, the unnormalised nearest neighbour correlation n̄f
equals the proportion of points in the pattern which have the same mark as their
nearest neighbour.
Note that n̄f is not a “correlation” in the usual statistical sense. It can take values
greater than 1.
normalised: We can define a normalised nearest neighbour correlation by
E[f (M, M ∗ )]
m̄f =
E[f (M, M ′ )]
where again M is the mark attached to a typical point, M ∗ is the mark attached to its
nearest neighbour, and M ′ is an independent copy of M with the same distribution.
This normalisation is also not a “correlation” in the usual statistical sense, but is
normalised so that the value 1 suggests “lack of correlation”: if the marks attached
to the points of X are independent and identically distributed, then m̄f = 1. The
interpretation of values larger or smaller than 1 depends on the choice of function f .
classical: Finally if the marks of X are real numbers, we can also compute the classical
correlation, that is, the correlation coefficient of the two random variables M and M ∗ .
The classical correlation has a value between −1 and 1. Values close to −1 or 1 indicate
strong dependence between the marks.
In the default case where f is not given, nncorr(X) computes the unnormalised and nor-
malised versions of the nearest-neighbour product index E[M M ∗ ], and (if the marks are
real numbers) the classical correlation between M and M ∗ .
The wrapper functions nnmean and nnvario computes the correlation indices for two special
choices of the function f (m1 , m2 ).
ˆ nnmean computes the correlation indices for f (m1 , m2 ) = m1 . The unnormalised index
is simply the mean value of the mark of the neighbour of a typical point, E[M ∗ ], while
the normalised index is E[M ∗ ]/E[M ], the ratio of the mean mark of the neighbour of
a typical point to the mean mark of a typical point.
ˆ nnvario computes the correlation indices for f (m1 , m2 ) = (1/2)(m1 − m2 )2 .
The argument X must be a point pattern (object of class "ppp") and must be a marked
point pattern.
The argument f must be a function, accepting two arguments m1 and m2 which are vectors
of equal length containing mark values (of the same type as the marks of X). It must return a
vector of numeric values of the same length as m1 and m2. The values must be non-negative.
nncross 357

The arguments use and method control the calculation of the classical correlation using
cor, as explained in the help file for cor.
Other arguments may be passed to f through the ... argument.
This algorithm assumes that X can be treated as a realisation of a stationary (spatially
homogeneous) random spatial point process in the plane, observed through a bounded
window. The window (which is specified in X as X$window) may have arbitrary shape.
Biases due to edge effects are treated using the ‘border method’ edge correction.

Value
Labelled vector of length 2 or 3 containing the unnormalised and normalised nearest neigh-
bour correlations, and the classical correlation if appropriate.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.

Examples
data(finpines)
nncorr(finpines)
# heights of neighbouring trees are slightly negatively correlated

data(amacrine)
nncorr(amacrine, function(m1, m2) { m1 == m2})
# neighbouring cells are usually of different type

nncross Nearest Neighbours Between Two Patterns

Description
Given two point patterns X and Y, finds the nearest neighbour in Y of each point of X.
Alternatively Y may be a line segment pattern.

Usage
nncross(X, Y, iX=NULL, iY=NULL)

Arguments
X Point pattern (object of class "ppp").
Y Either a point pattern (object of class "ppp") or a line segment pattern
(object of class "psp").
iX, iY Optional identifiers, applicable only in the case where Y is a point pattern,
used to determine whether a point in X is identical to a point in Y. See
Details
358 nncross

Details
Given two point patterns X and Y this function finds, for each point of X, the nearest point
of Y. The distance between these points is also computed.
Alternatively if X is a point pattern and Y is a line segment pattern, the function finds the
nearest line segment to each point of X, and computes the distance.
The return value is a data frame, with rows corresponding to the points of X. The first
column gives the nearest neighbour distances (i.e. the ith entry is the distance from the
ith point of X to the nearest element of Y). The second column gives the indices of the
nearest neighbours (i.e.\ the ith entry is the index of the nearest element in Y.)
Note that this function is not symmetric in X and Y. To find the nearest neighbour in X of
each point in Y, where Y is a point pattern, use nncross(Y,X).
The arguments iX and iY are used when the two point patterns X and Y have some points
in common. In this situation nncross(X, Y) would return some zero distances. To avoid
this, attach a unique integer identifier to each point, such that two points are identical if
their identifying numbers are equal. Let iX be the vector of identifier values for the points
in X, and iY the vector of identifiers for points in Y. Then the code will only compare two
points if they have different values of the identifier. See the Examples.

Value
A data frame with two columns:

dist Nearest neighbour distance


which Nearest neighbour index in Y

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
link{nndist} for nearest neighbour distances in a single point pattern.

Examples
# two different point patterns
X <- runifpoint(15)
Y <- runifpoint(20)
N <- nncross(X,Y)$which
# note that length(N) = 15
plot(superimpose(X=X,Y=Y), main="nncross", cols=c("red","blue"))
arrows(X$x, X$y, Y[N]$x, Y[N]$y, length=0.15)

# two patterns with some points in common


Z <- runifpoint(50)
X <- Z[1:30]
Y <- Z[20:50]
iX <- 1:30
iY <- 20:50
N <- nncross(X,Y, iX, iY)$which
plot(superimpose(X=X, Y=Y), main="nncross", cols=c("red","blue"))
arrows(X$x, X$y, Y[N]$x, Y[N]$y, length=0.15)
nndist 359

# point pattern and line segment pattern


X <- runifpoint(15)
Y <- rpoisline(10)
N <- nncross(X,Y)

nndist Nearest neighbour distances

Description
Computes the distance from each point to its nearest neighbour in a point pattern. Alter-
natively computes the distance to the second nearest neighbour, or third nearest, etc.

Usage
nndist(X, ..., method="C")
## S3 method for class 'ppp':
nndist(X, ..., k=1, method="C")
## Default S3 method:
nndist(X, Y=NULL, ..., k=1, method="C")

Arguments
X,Y Arguments specifying the locations of a set of points. For [Link],
the argument X should be a point pattern (object of class "ppp"). For
[Link], typically X and Y would be numeric vectors of equal
length. Alternatively Y may be omitted and X may be a list with two
components x and y, or a matrix with two columns.
... Ignored by [Link] and [Link].
k Integer. The algorithm will compute the distance to the kth nearest neigh-
bour.
method String specifying which method of calculation to use. Values are "C" and
"interpreted".

Details
This function computes the Euclidean distance from each point in a point pattern to its
nearest neighbour (the nearest other point of the pattern). If k is specified, it computes the
distance to the kth nearest neighbour.
The function nndist is generic, with a method for point patterns (objects of class "ppp"),
and a default method for coordinate vectors. There is also a method for line segment
patterns, [Link].
The method for point patterns expects a single point pattern argument X and returns the
vector of its nearest neighbour distances.
The default method expects that X and Y will determine the coordinates of a set of points.
Typically X and Y would be numeric vectors of equal length. Alternatively Y may be omitted
and X may be a list with two components named x and y, or a matrix or data frame with
two columns.
360 [Link]

The argument method is not normally used. It is retained only for checking the validity of the
software. If method = "interpreted" then the distances are computed using interpreted
R code only. If method="C" (the default) then C code is used. The C code is faster by two
to three orders of magnitude and uses much less memory.
If there is only one point (if x has length 1), then a nearest neighbour distance of Inf is
returned. If there are no points (if x has length zero) a numeric vector of length zero is
returned.
To identify which point is the nearest neighbour of a given point, use nnwhich.
To use the nearest neighbour distances for statistical inference, it is often advisable to use
the edge-corrected empirical distribution, computed by Gest.
To find the nearest neighbour distances from one point pattern to another point pattern,
use nncross.

Value
Numeric vector of the (kth) nearest neighbour distances for each point.

Warnings
An infinite value is returned if there is only one point in the point pattern (or in general if
there are fewer than k+1 points).

Author(s)
Pavel Grabarnik <[Link]@[Link]> and Adrian Baddeley <adrian@[Link]>
[Link]

See Also
[Link], pairdist, Gest, nnwhich, nncross.

Examples
data(cells)
d <- nndist(cells)
d2 <- nndist(cells, k=2)

x <- runif(100)
y <- runif(100)
d <- nndist(x, y)

# Stienen diagram
plot(cells %mark% (nndist(cells)/2), markscale=1)

[Link] Nearest neighbour distances between line segments

Description
Computes the distance from each line segment to its nearest neighbour in a line segment
pattern. Alternatively finds the distance to the second nearest, third nearest etc.
[Link] 361

Usage
## S3 method for class 'psp':
nndist(X, ..., k=1, method="Fortran")

Arguments
X A line segment pattern (object of class "psp").
... Ignored.
k Integer. The algorithm will find the distance to the kth nearest neighbour.
method String specifying which method of calculation to use. Values are "Fortran"
and "interpreted". Usually not specified.

Details
If k=1, this function computes the distance from each line segment to the nearest other line
segment in X. In general it computes the distance from each line segment to the kth nearest
other line segment.
This is a method for the generic function nndist for the class "psp".
Distances are calculated using the Hausdorff metric. The Hausdorff distance between two
line segments is the maximum distance from any point on one of the segments to the nearest
point on the other segment.
If there are fewer than k line segments in the pattern, the kth nearest neighbour distances
will be infinite (Inf).
The argument method is not normally used. It is retained only for checking the validity of the
software. If method = "interpreted" then the distances are computed using interpreted
R code only. If method="Fortran" (the default) then Fortran code is used. The Fortran
code is somewhat faster.

Value
A numeric vector whose [i] entry is the distance from the line segment numbered i to the
nearest other line segment (or in general the distance to the kth nearest line segment).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
nndist, [Link]

Examples
L <- psp(runif(10), runif(10), runif(10), runif(10), owin())
D <- nndist(L)
362 nnwhich

nnwhich Nearest neighbour

Description
Finds the nearest neighbour of each point in a point pattern.

Usage
nnwhich(X, ..., method="C")
## S3 method for class 'ppp':
nnwhich(X, ..., k=1, method="C")
## Default S3 method:
nnwhich(X, Y=NULL, ..., k=1, method="C")

Arguments
X,Y Arguments specifying the locations of a set of points. For [Link],
the argument X should be a point pattern (object of class "ppp"). For
[Link], typically X and Y would be numeric vectors of equal
length. Alternatively Y may be omitted and X may be a list with two
components x and y, or a matrix with two columns.
... Ignored by [Link] and [Link].
k Integer. The algorithm finds the kth nearest neighbour.
method String specifying which method of calculation to use. Values are "C" and
"interpreted".

Details
For each point in the given point pattern, this function finds its nearest neighbour (the
nearest other point of the pattern). It returns a vector giving, for each point, the index of
the point’s nearest neghbour. If k is specified, the algorithm finds each point’s kth nearest
neighbour.
The function nnwhich is generic, with a method for point patterns (objects of class "ppp")
and a default method.
The method for point patterns expects a single point pattern argument X. The default
method expects that X and Y will determine the coordinates of a set of points. Typically
X and Y would be numeric vectors of equal length. Alternatively Y may be omitted and X
may be a list with two components named x and y, or a matrix or data frame with two
columns.
The argument method is not normally used. It is retained only for checking the validity of the
software. If method = "interpreted" then the distances are computed using interpreted
R code only. If method="C" (the default) then C code is used. The C code is faster by two
to three orders of magnitude and uses much less memory.
If there are no points (if x has length zero) a numeric vector of length zero is returned. If
there is only one point (if x has length 1), then the nearest neighbour is undefined, and a
value of NA is returned. In general if the number of points is less than or equal to k, then
a vector of NA’s is returned.
To evaluate the distance between a point and its nearest neighbour, use nndist.
To find the nearest neighbours from one point pattern to another point pattern, use nncross.
nztrees 363

Value
Integer vector giving, for each point, the index of its nearest neighour (or kth nearest
neighbour).

Warnings
A value of NA is returned if there is only one point in the point pattern.

Author(s)
Pavel Grabarnik <[Link]@[Link]> and Adrian Baddeley <adrian@[Link]>
[Link]

See Also
nndist, nncross

Examples
oldpar <- par(mfrow=c(2,1))
data(cells)
plot(cells)
m <- nnwhich(cells)
m2 <- nnwhich(cells, k=2)

# plot nearest neighbour links


b <- cells[m]
arrows(cells$x, cells$y, b$x, b$y, angle=15, length=0.15, col="red")

# find points which are the neighbour of their neighbour


self <- (m[m] == seq(m))
# plot them
A <- cells[self]
B <- cells[m[self]]
plot(cells)
segments(A$x, A$y, B$x, B$y)
par(oldpar)

nztrees New Zealand Trees Point Pattern

Description
The data give the locations of trees in a forest plot.
They were collected by Mark and Esler (1970) and were extracted and analysed by Ripley
(1981, pp. 169-175). They represent the positions of 86 trees in a forest plot approximately
140 by 85 feet.
Ripley discarded from his analysis the eight trees at the right-hand edge of the plot (which
appear to be part of a planted border) and trimmed the window by a 5-foot margin accord-
ingly.
364 opening

Usage
data(nztrees)

Format
An object of class "ppp" representing the point pattern of tree locations. The Cartesian
coordinates are in feet.
See [Link] for details of the format of a point pattern object.

Note
To trim a 5-foot margin off the window, type nzsub <- nztrees[ , owin(c(0,148),c(0,95))
]

Source
Mark and Esler (1970), Ripley (1981).

References
Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.
Mark, A.F. and Esler, A.E. (1970) An assessment of the point-centred quarter method of
plotless sampling in some New Zealand forests. Proceedings of the New Zealand Ecological
Society 17, 106–110.

opening Morphological Opening

Description
Perform morphological opening of a window, a line segment pattern or a point pattern.

Usage
opening(w, r, ...)
## S3 method for class 'owin':
opening(w, r, ..., polygonal=NULL)
## S3 method for class 'ppp':
opening(w, r, ...)
## S3 method for class 'psp':
opening(w, r, ...)

Arguments
w A window (object of class "owin" or a line segment pattern (object of
class "psp") or a point pattern (object of class "ppp").
r positive number: the radius of the opening.
... extra arguments passed to [Link] controlling the pixel resolution, if a
pixel approximation is used
polygonal Logical flag indicating whether to compute a polygonal approximation to
the erosion (polygonal=TRUE) or a pixel grid approximation (polygonal=FALSE).
Ord 365

Details
The morphological opening (Serra, 1982) of a set W by a distance r > 0 is the subset of
points in W that can be separated from the boundary of W by a circle of radius r. That is,
a point x belongs to the opening if it is possible to draw a circle of radius r (not necessarily
centred on x) that has x on the inside and the boundary of W on the outside. The opened
set is a subset of W.
For a small radius r, the opening operation has the effect of smoothing out irregularities in
the boundary of W . For larger radii, the opening operation removes promontories in the
boundary. For very large radii, the opened set is empty.
The algorithm applies erosion followed by dilation.

Value
If r > 0, an object of class "owin" representing the opened region. If r=0, the result is
identical to w.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Serra, J. (1982) Image analysis and mathematical morphology. Academic Press.

See Also
closing for the opposite operation.
dilation, erosion for the basic operations.
owin, [Link] for information about windows.

Examples
data(letterR)
v <- opening(letterR, 0.3, dimyx=256)
plot(v, main="opening")
plot(letterR, add=TRUE)

Ord Generic Ord Interaction model

Description
Creates an instance of an Ord-type interaction point process model which can then be fitted
to point pattern data.

Usage
Ord(pot, name)
366 [Link]

Arguments

pot An S language function giving the user-supplied interaction potential.


name Character string.

Details

Ord’s point process model (Ord, 1977) is a Gibbs point process of infinite order. Each point
xi in the point pattern x contributes a factor g(ai ) where ai = a(xi , x) is the area of the
tile associated with xi in the Dirichlet tessellation of x.
Ord (1977) proposed fitting this model to forestry data when g(a) has a simple “threshold”
form. That model is implemented in our function OrdThresh. The present function Ord
implements the case of a completely general Ord potential g(a) specified as an S language
function pot.
This is experimental.

Value

An object of class "interact" describing the interpoint interaction structure of a point


process.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283–322.
Ord, J.K. (1977) Contribution to the discussion of Ripley (1977).
Ord, J.K. (1978) How many trees in a forest? Mathematical Scientist 3, 23–33.
Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal
Statistical Society, Series B, 39, 172 – 212.

See Also

ppm, [Link], OrdThresh

[Link] Ord Interaction Process Family

Description

An object describing the family of all Ord interaction point processes


OrdThresh 367

Details

Advanced Use Only!


This structure would not normally be touched by the user. It describes the family of point
process models introduced by Ord (1977).
If you need to create a specific Ord-type model for use in analysis, use the function
OrdThresh or Ord.
Anyway, [Link] is an object of class "isf" containing a function [Link]$eval for
evaluating the sufficient statistics of any Ord type point process model taking an exponential
family form.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283–322.
Ord, J.K. (1977) Contribution to the discussion of Ripley (1977).
Ord, J.K. (1978) How many trees in a forest? Mathematical Scientist 3, 23–33.
Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal
Statistical Society, Series B, 39, 172 – 212.

See Also

[Link], [Link], Poisson, Pairwise, PairPiece, Strauss, StraussHard,


Softcore, Geyer, SatPiece, Saturated, Ord, OrdThresh

OrdThresh Ord’s Interaction model

Description

Creates an instance of Ord’s point process model which can then be fitted to point pattern
data.

Usage

OrdThresh(r)

Arguments

r Positive number giving the threshold value for Ord’s model.


368 owin

Details

Ord’s point process model (Ord, 1977) is a Gibbs point process of infinite order. Each point
xi in the point pattern x contributes a factor g(ai ) where ai = a(xi , x) is the area of the
tile associated with xi in the Dirichlet tessellation of x. The function g is simply g(a) = 1
if a ≥ r and g(a) = γ < 1 if a < r, where r is called the threshold value.
This function creates an instance of Ord’s model with a given value of r. It can then be
fitted to point process data using ppm.

Value

An object of class "interact" describing the interpoint interaction structure of a point


process.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283–322.
Ord, J.K. (1977) Contribution to the discussion of Ripley (1977).
Ord, J.K. (1978) How many trees in a forest? Mathematical Scientist 3, 23–33.
Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal
Statistical Society, Series B, 39, 172 – 212.

See Also

ppm, [Link]

owin Create a Window

Description

Creates an object of class "owin" representing an observation window in the two-dimensional


plane

Usage

owin(xrange=c(0,1), yrange=c(0,1), ..., poly=NULL, mask=NULL,


unitname=NULL, xy=NULL)
owin 369

Arguments
xrange x coordinate limits of enclosing box
yrange y coordinate limits of enclosing box
... Ignored.
poly Optional. Polygonal boundary of window. Incompatible with mask.
mask Optional. Logical matrix giving binary image of window. Incompatible
with poly.
unitname Optional. Name of unit of length. Either a single character string, or
a vector of two character strings giving the singular and plural forms,
respectively.
xy Optional. List with components x and y specifying the pixel coordinates
for mask.

Details
In the spatstat library, a point pattern dataset must include information about the window
of observation. This is represented by an object of class "owin". See [Link] for an
overview.
To create a window in its own right, users would normally invoke owin, although sometimes
[Link] may be convenient.
A window may be rectangular, polygonal, or a mask (a binary image).
ˆ rectangular windows: If only xrange and yrange are given, then the window will
be rectangular, with its x and y coordinate dimensions given by these two arguments
(which must be vectors of length 2). If no arguments are given at all, the default is
the unit square with dimensions xrange=c(0,1) and yrange=c(0,1).
ˆ polygonal windows: If poly is given, then the window will be polygonal.
– single polygon: If poly is a structure with two component vectors x and y of
equal length, then these vectors are interpreted as the cartesian coordinates of
the vertices of a polygon circumscribing the window. The vertices must be listed
anticlockwise. No vertex should be repeated (i.e. do not repeat the first vertex).
– multiple polygons or holes: If poly is a list, each entry poly[[i]] of which is a
structure with two component vectors x and y of equal length, then the successive
list members poly[[i]] are interpreted as separate polygons which together make
up the boundary of the window. The vertices of each polygon must be listed
anticlockwise if the polygon is part of the external boundary, but clockwise if the
polygon is the boundary of a hole in the window. Again, do not repeat any vertex.
ˆ binary masks: If mask is given, then the window will be a binary image. The
argument mask should be a logical matrix such that mask[i,j] is TRUE if the point
(x[j],y[i]) belongs to the window, and FALSE if it does not. Note carefully that
rows of mask correspond to the y coordinate, and columns to the x coordinate. Here
x and y are vectors of x and y coordinates equally spaced over xrange and yrange
respectively. The pixel coordinate vectors x and y may be specified explicitly using
the argument xy, which should be a list containing components x and y. Alternatively
there is a sensible default.
To create a window which is mathematically defined by inequalities in the Cartesian coor-
dinates, use raster.x() and raster.y() as in the examples below.
Functions square and disc will create square and circular windows, respectively.
370 owin

Value
An object of class "owin" describing a window in the two-dimensional plane.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
square, disc, [Link], [Link], [Link], [Link], ppp

Examples
w <- owin()
w <- owin(c(0,1), c(0,1))
# the unit square

w <- owin(c(10,20), c(10,30), unitname=c("foot","feet"))


# a rectangle of dimensions 10 x 20 feet
# with lower left corner at (10,10)

# polygon (diamond shape)


w <- owin(poly=list(x=c(0.5,1,0.5,0),y=c(0,1,2,1)))
w <- owin(c(0,1), c(0,2), poly=list(x=c(0.5,1,0.5,0),y=c(0,1,2,1)))

# polygon with hole


ho <- owin(poly=list(list(x=c(0,1,1,0), y=c(0,0,1,1)),
list(x=c(0.6,0.4,0.4,0.6), y=c(0.2,0.2,0.4,0.4))))

w <- owin(c(-1,1), c(-1,1), mask=matrix(TRUE, 100,100))


# 100 x 100 image, all TRUE
X <- raster.x(w)
Y <- raster.y(w)
wm <- owin(w$xrange, w$yrange, mask=(X^2 + Y^2 <= 1))
# discrete approximation to the unit disc

## Not run:
plot(c(0,1),c(0,1),type="n")
bdry <- locator()
# click the vertices of a polygon (anticlockwise)

## End(Not run)

w <- owin(poly=bdry)
## Not run: plot(w)

## Not run:
im <- [Link](matrix(scan("myfile"), nrow=128, ncol=128))
# read in an arbitrary 128 x 128 digital image from text file
rim <- im[, 128:1]
# Assuming it was given in row-major order in the file
# i.e. scanning left-to-right in rows from top-to-bottom,
# the use of matrix() has effectively transposed rows & columns,
# so to convert it to our format just reverse the column order.
w <- owin(mask=rim)
[Link] 371

plot(w)
# display it to check!

## End(Not run)

[Link] Class owin

Description
A class owin to define the “observation window” of a point pattern

Details
In the spatstat library, a point pattern dataset must include information about the window
or region in which the pattern was observed. A window is described by an object of class
"owin". Windows of arbitrary shape are supported.
An object of class "owin" has one of three types:

"rectangle": a rectangle in the two-dimensional plane with edges parallel to the axes
"polygonal": a region whose boundary is a polygon or several polygons. The region may have holes and may
"mask": a binary image (a logical matrix) set to TRUE for pixels inside the window and FALSE outside th

Objects of class "owin" may be created by the function owin and converted from other
types of data by the function [Link].
They may be manipulated by the functions [Link], [Link], [Link],
rotate, shift, affine, erosion, dilation, opening and closing.
Geometrical calculations available for windows include [Link], perimeter, diameter,
[Link], [Link], [Link], [Link], and [Link]. The
mapping between continuous coordinates and pixel raster indices is facilitated by the func-
tions raster.x, raster.y and [Link].
There is a plot method for window objects, [Link]. This may be useful if you wish to
plot a point pattern’s window without the points for graphical purposes.
There are also methods for summary and print.

Warnings
In a window of type "mask", the row index corresponds to increasing y coordinate, and the
column index corresponds to increasing x coordinate.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link], [Link], [Link], [Link], [Link], [Link],
erosion, dilation, opening, closing, [Link], [Link], [Link], raster.x,
raster.y, [Link], [Link], [Link], [Link], diameter, [Link],
[Link], [Link]
372 pairdist

Examples
w <- owin()
w <- owin(c(0,1), c(0,1))
# the unit square

w <- owin(c(0,1), c(0,2))


## Not run:
plot(w)
# plots edges of a box 1 unit x 2 units
v <- locator()
# click on points in the plot window
# to be the vertices of a polygon
# traversed in anticlockwise order
u <- owin(c(0,1), c(0,2), poly=v)
plot(u)
# plots polygonal boundary using polygon()
plot([Link](u, eps=0.02))
# plots discrete pixel approximation to polygon

## End(Not run)

pairdist Pairwise distances

Description
Computes the matrix of distances between all pairs of ‘things’ in a dataset

Usage
pairdist(X, ...)

Arguments
X Object specifying the locations of a set of ‘things’ (such as a set of points
or a set of line segments).
... Further arguments depending on the method.

Details
Given a dataset X and Y (representing either a point pattern or a line segment pattern)
pairdist computes the distance between each pair of ‘things’ in the dataset, and returns
a matrix containing these distances.
The function pairdist is generic, with methods for point patterns (objects of class "ppp"),
line segment patterns (objects of class "psp") and a default method. See the documentation
for [Link], [Link] or [Link] for details.

Value
A square matrix whose [i,j] entry is the distance between the ‘things’ numbered i and j.
[Link] 373

Author(s)
Pavel Grabarnik <[Link]@[Link]> and Adrian Baddeley <adrian@[Link]>
[Link]

See Also
[Link], [Link], [Link], crossdist, nndist, Kest

[Link] Pairwise distances

Description
Computes the matrix of distances between all pairs of points in a set of points

Usage
## Default S3 method:
pairdist(X, Y=NULL, ..., period=NULL, method="C", squared=FALSE)

Arguments
X,Y Arguments specifying the coordinates of a set of points. Typically X and Y
would be numeric vectors of equal length. Alternatively Y may be omitted
and X may be a list with two components x and y, or a matrix with two
columns.
... Ignored.
period Optional. Dimensions for periodic edge correction.
method String specifying which method of calculation to use. Values are "C" and
"interpreted". Usually not specified.
squared Logical. If squared=TRUE, the squared distances are returned instead
(this computation is faster).

Details
Given the coordinates of a set of points, this function computes the Euclidean distances
between all pairs of points, and returns the matrix of distances. It is a method for the
generic function pairdist.
The arguments X and Y must determine the coordinates of a set of points. Typically X and
Y would be numeric vectors of equal length. Alternatively Y may be omitted and X may be
a list with two components named x and y, or a matrix or data frame with two columns.
Alternatively if period is given, then the distances will be computed in the ‘periodic’ sense
(also known as ‘torus’ distance). The points will be treated as if they are in a rectangle of
width period[1] and height period[2]. Opposite edges of the rectangle are regarded as
equivalent.
If squared=TRUE then the squared Euclidean distances d2 are returned, instead of the
Euclidean distances d. The squared distances are faster to calculate, and are sufficient for
many purposes (such as finding the nearest neighbour of a point).
374 [Link]

The argument method is not normally used. It is retained only for checking the validity of the
software. If method = "interpreted" then the distances are computed using interpreted
R code only. If method="C" (the default) then C code is used. The C code is somewhat
faster.

Value
A square matrix whose [i,j] entry is the distance between the points numbered i and j.

Author(s)
Pavel Grabarnik <[Link]@[Link]> and Adrian Baddeley <adrian@[Link]>
[Link]

See Also
crossdist, nndist, Kest

Examples
x <- runif(100)
y <- runif(100)
d <- pairdist(x, y)
d <- pairdist(cbind(x,y))
d <- pairdist(x, y, period=c(1,1))
d <- pairdist(x, y, squared=TRUE)

[Link] Pairwise distances

Description
Computes the matrix of distances between all pairs of points in a point pattern.

Usage
## S3 method for class 'ppp':
pairdist(X, ..., periodic=FALSE, method="C", squared=FALSE)

Arguments
X A point pattern (object of class "ppp").
... Ignored.
periodic Logical. Specifies whether to apply a periodic edge correction.
method String specifying which method of calculation to use. Values are "C" and
"interpreted". Usually not specified.
squared Logical. If squared=TRUE, the squared distances are returned instead
(this computation is faster).
[Link] 375

Details
This is a method for the generic function pairdist.
Given a point pattern X (an object of class "ppp"), this function computes the Euclidean
distances between all pairs of points in X, and returns the matrix of distances.
Alternatively if periodic=TRUE and the window containing X is a rectangle, then the dis-
tances will be computed in the ‘periodic’ sense (also known as ‘torus’ distance): opposite
edges of the rectangle are regarded as equivalent. This is meaningless if the window is not
a rectangle.
If squared=TRUE then the squared Euclidean distances d2 are returned, instead of the
Euclidean distances d. The squared distances are faster to calculate, and are sufficient for
many purposes (such as finding the nearest neighbour of a point).
The argument method is not normally used. It is retained only for checking the validity of the
software. If method = "interpreted" then the distances are computed using interpreted
R code only. If method="C" (the default) then C code is used. The C code is somewhat
faster.

Value
A square matrix whose [i,j] entry is the distance between the points numbered i and j.

Author(s)
Pavel Grabarnik <[Link]@[Link]> and Adrian Baddeley <adrian@[Link]>
[Link]

See Also
pairdist, [Link], [Link], crossdist, nndist, Kest

Examples
data(cells)
d <- pairdist(cells)
d <- pairdist(cells, periodic=TRUE)
d <- pairdist(cells, squared=TRUE)

[Link] Pairwise distances between line segments

Description
Computes the matrix of distances between all pairs of line segments in a line segment
pattern.

Usage
## S3 method for class 'psp':
pairdist(X, ..., method="Fortran", type="Hausdorff")
376 [Link]

Arguments

X A line segment pattern (object of class "psp").


... Ignored.
method String specifying which method of calculation to use. Values are "Fortran"
and "interpreted". Usually not specified.
type Type of distance to be computed. Options are "Hausdorff" and "separation".
Partial matching is used.

Details

This function computes the distance between each pair of line segments in X, and returns
the matrix of distances.
This is a method for the generic function pairdist for the class "psp".
The distances between line segments are measured in one of two ways:

ˆ if type="Hausdorff", distances are computed in the Hausdorff metric. The Hausdorff


distance between two line segments is the maximum distance from any point on one
of the segments to the nearest point on the other segment.
ˆ if type="separation", distances are computed as the minimum distance from a point
on one line segment to a point on the other line segment. For example, line segments
which cross over each other have separation zero.

The argument method is not normally used. It is retained only for checking the validity of the
software. If method = "interpreted" then the distances are computed using interpreted
R code only. If method="Fortran" (the default) then Fortran code is used. The Fortran
code is somewhat faster.

Value

A square matrix whose [i,j] entry is the distance between the line segments numbered i
and j.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

crossdist, nndist, [Link]

Examples
L <- psp(runif(10), runif(10), runif(10), runif(10), owin())
D <- pairdist(L)
S <- pairdist(L, type="sep")
PairPiece 377

PairPiece The Piecewise Constant Pairwise Interaction Point Process


Model

Description
Creates an instance of a pairwise interaction point process model with piecewise constant
potential function. The model can then be fitted to point pattern data.

Usage
PairPiece(r)

Arguments
r vector of jump points for the potential function

Details
A pairwise interaction point process in a bounded region is a stochastic point process with
probability density of the form
Y Y
f (x1 , . . . , xn ) = α b(xi ) h(xi , xj )
i i<j

where x1 , . . . , xn represent the points of the pattern. The first product on the right hand
side is over all points of the pattern; the second product is over all unordered pairs of points
of the pattern.
Thus each point xi of the pattern contributes a factor b(xi ) to the probability density, and
each pair of points xi , xj contributes a factor h(xi , xj ) to the density.
The pairwise interaction term h(u, v) is called piecewise constant if it depends only on the
distance between u and v, say h(u, v) = H(||u − v||), and H is a piecewise constant function
(a function which is constant except for jumps at a finite number of places). The use of
piecewise constant interaction terms was first suggested by Takacs (1986).
The function ppm(), which fits point process models to point pattern data, requires an
argument of class "interact" describing the interpoint interaction structure of the model
to be fitted. The appropriate description of the piecewise constant pairwise interaction is
yielded by the function PairPiece(). See the examples below.
The entries of r must be strictly increasing, positive numbers. They are interpreted as the
points of discontinuity of H. It is assumed that H(s) = 1 for all s > rmax where rmax is
the maximum value in r. Thus the model has as many regular parameters (see ppm) as
there are entries in r. The i-th regular parameter θi is the logarithm of the value of the
interaction function H on the interval [ri−1 , ri ).
If r is a single number, this model is similar to the Strauss process, see Strauss. The
difference is that in PairPiece the interaction function is continuous on the right, while in
Strauss it is continuous on the left.
The analogue of this model for multitype point processes has not yet been implemented.
378 [Link]

Value
An object of class "interact" describing the interpoint interaction structure of a point pro-
cess. The process is a pairwise interaction process, whose interaction potential is piecewise
constant, with jumps at the distances given in the vector r.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Takacs, R. (1986) Estimator for the pair potential of a Gibbsian point process. Statistics
17, 429–433.

See Also
ppm, [Link], [Link], Strauss [Link]

Examples
PairPiece(c(0.1,0.2))
# prints a sensible description of itself
data(cells)

## Not run:
ppm(cells, ~1, PairPiece(r = c(0.05, 0.1, 0.2)))
# fit a stationary piecewise constant pairwise interaction process

## End(Not run)

ppm(cells, ~polynom(x,y,3), PairPiece(c(0.05, 0.1)))


# nonstationary process with log-cubic polynomial trend

[Link] Saturated Pairwise Interaction Point Process Family

Description
An object describing the Saturated Pairwise Interaction family of point process models

Details
Advanced Use Only!
This structure would not normally be touched by the user. It describes the “saturated
pairwise interaction” family of point process models.
If you need to create a specific interaction model for use in spatial pattern analysis, use
the function Saturated() or the two existing implementations of models in this family,
Geyer() and SatPiece().
Geyer (1999) introduced the “saturation process”, a modification of the Strauss process in
which the total contribution to the potential from each point (from its pairwise interaction
Pairwise 379

with all other points) is trimmed to a maximum value c. This model is implemented in the
function Geyer().
The present class [Link] is the extension of this saturation idea to all pairwise
interactions. Note that the resulting models are no longer pairwise interaction processes -
they have interactions of infinite order.
[Link] is an object of class "isf" containing a function pairwise$eval for eval-
uating the sufficient statistics of any saturated pairwise interaction point process model in
which the original pair potentials take an exponential family form.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E.
Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry:
Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and
Applied Probability, number 80. Pages 79–140.

See Also
Geyer to create the Geyer saturation process.
SatPiece to create a saturated process with piecewise constant pair potential.
Saturated to create a more general saturation model.
Other families: [Link], [Link], [Link].

Pairwise Generic Pairwise Interaction model

Description
Creates an instance of a pairwise interaction point process model which can then be fitted
to point pattern data.

Usage
Pairwise(pot, name, par, parnames, printfun)

Arguments
pot An R language function giving the user-supplied pairwise interaction po-
tential.
name Character string.
par List of numerical values for irregular parameters
parnames Vector of names of irregular parameters
printfun Do not specify this argument: for internal use only.
380 Pairwise

Details
This code constructs a member of the pairwise interaction family [Link] with
arbitrary pairwise interaction potential given by the user.
Each pair of points in the point pattern contributes a factor h(d) to the probability density,
where d is the distance between the two points. The factor term h(d) is

h(d) = exp(−θpot(d))

provided pot(d) is finite, where θ is the coefficient vector in the model.


The function pot must take as its first argument a matrix of interpoint distances, and
evaluate the potential for each of these distances. The result must be either a matrix with
the same dimensions as its input, or an array with its first two dimensions the same as its
input (the latter case corresponds to a vector-valued potential).
If irregular parameters are present, then the second argument to pot should be a vector of
the same type as par giving those parameter values.
The values returned by pot may be finite numeric values, or -Inf indicating a hard core
(that is, the corresponding interpoint distance is forbidden). We define h(d) = 0 if pot(d) =
−∞. Thus, a potential value of minus infinity is always interpreted as corresponding to
h(d) = 0, regardless of the sign and magnitude of θ.

Value
An object of class "interact" describing the interpoint interaction structure of a point
process.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, [Link], [Link]

Examples
#This is the same as StraussHard(r=0.7,h=0.05)
strpot <- function(d,par) {
r <- par$r
h <- par$h
value <- (d <= r)
value[d < h] <- -Inf
value
}
mySH <- Pairwise(strpot, "StraussHard process", list(r=0.7,h=0.05),
c("interaction distance r", "hard core distance h"))
data(cells)
ppm(cells, ~ 1, mySH, correction="isotropic")

# Fiksel (1984) double exponential interaction


# see Stoyan, Kendall, Mecke 1987 p 161

fikspot <- function(d, par) {


r <- par$r
[Link] 381

h <- par$h
zeta <- par$zeta
value <- exp(-zeta * d)
value[d < h] <- -Inf
value[d > r] <- 0
value
}
Fiksel <- Pairwise(fikspot, "Fiksel double exponential process",
list(r=3.5, h=1, zeta=1),
c("interaction distance r",
"hard core distance h",
"exponential coefficient zeta"))
data(spruces)
fit <- ppm(unmark(spruces), ~1, Fiksel, rbord=3.5)
fit
plot(fitin(fit), xlim=c(0,4))
coef(fit)
# corresponding values obtained by Fiksel (1984) were -1.9 and -6.0

[Link] Pairwise Interaction Process Family

Description
An object describing the family of all pairwise interaction Gibbs point processes.

Details
Advanced Use Only!
This structure would not normally be touched by the user. It describes the pairwise inter-
action family of point process models.
If you need to create a specific pairwise interaction model for use in modelling, use the
function Pairwise or one of the existing functions listed below.
Anyway, [Link] is an object of class "isf" containing a function pairwise$eval
for evaluating the sufficient statistics of any pairwise interaction point process model taking
an exponential family form.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
Other families: [Link], [Link], [Link].
Pairwise interactions: Poisson, Pairwise, PairPiece, Strauss, StraussHard, Softcore.
Other interactions: AreaInter, Geyer, Saturated, Ord, OrdThresh.
382 pcf

pcf Pair Correlation Function

Description
Estimate the pair correlation function.

Usage
pcf(X, ...)

Arguments
X Either the observed data point pattern, or an estimate of its K function,
or an array of multitype K functions (see Details).
... Other arguments passed to the appropriate method.

Details
The pair correlation function of a stationary point process is
K ′ (r)
g(r) =
2πr
where K ′ (r) is the derivative of K(r), the reduced second moment function (aka “Ripley’s
K function”) of the point process. See Kest for information about K(r). For a stationary
Poisson process, the pair correlation function is identically equal to 1. Values g(r) < 1
suggest inhibition between points; values greater than 1 suggest clustering.
We also apply the same definition to other variants of the classical K function, such as the
multitype K functions (see Kcross, Kdot) and the inhomogeneous K function (see Kinhom).
For all these variants, the benchmark value of K(r) = πr2 corresponds to g(r) = 1.
This routine computes an estimate of g(r) either directly from a point pattern, or indirectly
from an estimate of K(r) or one of its variants.
This function is generic, with methods for the classes "ppp", "fv" and "fasp".
If X is a point pattern (object of class "ppp") then the pair correlation function is estimated
using a traditional kernel smoothing method (Stoyan and Stoyan, 1994). See [Link] for
details.
If X is a function value table (object of class "fv"), then it is assumed to contain estimates
of the K function or one of its variants (typically obtained from Kest or Kinhom). This
routine computes an estimate of g(r) using smoothing splines to approximate the derivative.
See [Link] for details.
If X is a function value array (object of class "fasp"), then it is assumed to contain estimates
of several K functions (typically obtained from Kmulti or alltypes). This routine computes
an estimate of g(r) for each cell in the array, using smoothing splines to approximate the
derivatives. See [Link] for details.

Value
Either a function value table (object of class "fv", see [Link]) representing a pair corre-
lation function, or a function array (object of class "fasp", see [Link]) representing
an array of pair correlation functions.
[Link] 383

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.

See Also
[Link], [Link], [Link], Kest, Kinhom, Kcross, Kdot, Kmulti, alltypes

Examples
# ppp object
data(simdat)

p <- pcf(simdat)
plot(p)

# fv object
K <- Kest(simdat)
p2 <- pcf(K)
plot(p2)

# multitype pattern; fasp object


data(betacells)

p <- pcf(alltypes(betacells, "K"))


plot(p)

[Link] Pair Correlation Function obtained from array of K functions

Description
Estimates the (bivariate) pair correlation functions of a point pattern, given an array of
(bivariate) K functions.

Usage
## S3 method for class 'fasp':
pcf(X, ..., method="c")

Arguments
X An array of multitype K functions (object of class "fasp").
... Arguments controlling the smoothing spline function [Link].
method Letter "a", "b", "c" or "d" indicating the method for deriving the pair
correlation function from the K function.
384 [Link]

Details

The pair correlation function of a stationary point process is

K ′ (r)
g(r) =
2πr

where K ′ (r) is the derivative of K(r), the reduced second moment function (aka “Ripley’s
K function”) of the point process. See Kest for information about K(r). For a stationary
Poisson process, the pair correlation function is identically equal to 1. Values g(r) < 1
suggest inhibition between points; values greater than 1 suggest clustering.
We also apply the same definition to other variants of the classical K function, such as the
multitype K functions (see Kcross, Kdot) and the inhomogeneous K function (see Kinhom).
For all these variants, the benchmark value of K(r) = πr2 corresponds to g(r) = 1.
This routine computes an estimate of g(r) from an array of estimates of K(r) or its variants,
using smoothing splines to approximate the derivatives. It is a method for the generic
function pcf.
The argument X should be a function array (object of class "fasp", see [Link])
containing several estimates of K functions. This should have been obtained from alltypes
with the argument fun="K".
The smoothing spline operations are performed by [Link] and [Link]
from the modreg library. Four numerical methods are available:

ˆ ”a” apply smoothing to K(r), estimate its derivative, and plug in to the formula above;
K(r)
ˆ ”b” apply smoothing to Y (r) = 2πr constraining Y (0) = 0, estimate the derivative
of Y , and solve;
K(r)
ˆ ”c” apply smoothing to Z(r) = πr 2 constraining Z(0) = 1, estimate its derivative,
and solve.
p
ˆ ”d” apply smoothing to V (r) = K(r), estimate its derivative, and solve.

Method "c" seems to be the best at suppressing variability for small values of r. However
it effectively constrains g(0) = 1. If the point pattern seems to have inhibition at small
distances, you may wish to experiment with method "b" which effectively constrains g(0) =
0. Method "a" seems comparatively unreliable.
Useful arguments to control the splines include the smoothing tradeoff parameter spar and
the degrees of freedom df. See [Link] for details.

Value

A function array (object of class "fasp", see [Link]) representing an array of pair
correlation functions. This can be thought of as a matrix Y each of whose entries Y[i,j] is
a function value table (class "fv") representing the pair correlation function between points
of type i and points of type j.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>
[Link] 385

References
Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications.
2nd edition. Springer Verlag.
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.

See Also
Kest, Kinhom, Kcross, Kdot, Kmulti, alltypes, [Link], [Link]

Examples
# multitype point pattern
data(betacells)

KK <- alltypes(betacells, "K")


p <- [Link](KK, spar=0.5, method="b")
plot(p)
# short range inhibition between all types
# strong inhibition between "on" and "off"

[Link] Pair Correlation Function obtained from K Function

Description
Estimates the pair correlation function of a point pattern, given an estimate of the K
function.

Usage
## S3 method for class 'fv':
pcf(X, ..., method="c")

Arguments
X An estimate of the K function or one of its variants. An object of class
"fv".
... Arguments controlling the smoothing spline function [Link].
method Letter "a", "b", "c" or "d" indicating the method for deriving the pair
correlation function from the K function.

Details
The pair correlation function of a stationary point process is

K ′ (r)
g(r) =
2πr
where K ′ (r) is the derivative of K(r), the reduced second moment function (aka “Ripley’s
K function”) of the point process. See Kest for information about K(r). For a stationary
386 [Link]

Poisson process, the pair correlation function is identically equal to 1. Values g(r) < 1
suggest inhibition between points; values greater than 1 suggest clustering.
We also apply the same definition to other variants of the classical K function, such as the
multitype K functions (see Kcross, Kdot) and the inhomogeneous K function (see Kinhom).
For all these variants, the benchmark value of K(r) = πr2 corresponds to g(r) = 1.
This routine computes an estimate of g(r) from an estimate of K(r) or its variants, using
smoothing splines to approximate the derivative. It is a method for the generic function
pcf for the class "fv".
The argument X should be an estimated K function, given as a function value table (object
of class "fv", see [Link]). This object should be the value returned by Kest, Kcross,
Kmulti or Kinhom.
The smoothing spline operations are performed by [Link] and [Link]
from the modreg library. Four numerical methods are available:

ˆ ”a” apply smoothing to K(r), estimate its derivative, and plug in to the formula above;
K(r)
ˆ ”b” apply smoothing to Y (r) = 2πr constraining Y (0) = 0, estimate the derivative
of Y , and solve;
K(r)
ˆ ”c” apply smoothing to Z(r) = πr 2 constraining Z(0) = 1, estimate its derivative,
and solve.
p
ˆ ”d” apply smoothing to V (r) = K(r), estimate its derivative, and solve.

Method "c" seems to be the best at suppressing variability for small values of r. However
it effectively constrains g(0) = 1. If the point pattern seems to have inhibition at small
distances, you may wish to experiment with method "b" which effectively constrains g(0) =
0. Method "a" seems comparatively unreliable.
Useful arguments to control the splines include the smoothing tradeoff parameter spar and
the degrees of freedom df. See [Link] for details.

Value
A function value table (object of class "fv", see [Link]) representing a pair correlation
function.
Essentially a data frame containing (at least) the variables

r the vector of values of the argument r at which the pair correlation func-
tion g(r) has been estimated
pcf vector of values of g(r)

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications.
2nd edition. Springer Verlag.
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.
[Link] 387

See Also
pcf, [Link], Kest, Kinhom, Kcross, Kdot, Kmulti, alltypes, [Link], [Link]

Examples
# univariate point pattern
data(simdat)

K <- Kest(simdat)
p <- [Link](K, spar=0.5, method="b")
plot(p, main="pair correlation function for simdat")
# indicates inhibition at distances r < 0.3

[Link] Pair Correlation Function of Point Pattern

Description
Estimates the pair correlation function of a point pattern using kernel methods.

Usage
## S3 method for class 'ppp':
pcf(X, ..., r = NULL, kernel="epanechnikov", bw=NULL, stoyan=0.15,
correction=c("translate", "Ripley"))

Arguments
X A point pattern (object of class "ppp").
r Vector of values for the argument r at which g(r) should be evaluated.
There is a sensible default.
kernel Choice of smoothing kernel, passed to density.
bw Bandwidth for smoothing kernel, passed to density.
... Other arguments passed to the kernel density estimation function density.
stoyan Bandwidth coefficient; see Details.
correction Choice of edge correction.

Details
The pair correlation function g(r) is a summary of the dependence between points in a
spatial point process. The best intuitive interpretation is the following: the probability
p(r) of finding two points at locations x and y separated by a distance r is equal to

p(r) = λ2 g(r) dx dy

where λ is the intensity of the point process. For a completely random (uniform Poisson)
process, p(r) = λ2 so g(r) = 1.
Formally, the pair correlation function of a stationary point process is defined by

K ′ (r)
g(r) =
2πr
388 [Link]

where K ′ (r) is the derivative of K(r), the reduced second moment function (aka “Ripley’s
K function”) of the point process. See Kest for information about K(r).
For a stationary Poisson process, the pair correlation function is identically equal to 1.
Values g(r) < 1 suggest inhibition between points; values greater than 1 suggest clustering.
This routine computes an estimate of g(r) by the kernel smoothing method (Stoyan and
Stoyan (1994), pages 284–285). By default, their recommendations are followed exactly.
If correction="translate" then the translation correction is used. The estimate is given
in equation (15.15), page 284 of Stoyan and Stoyan (1994).
If correction="Ripley" then Ripley’s isotropic edge correction is used; the estimate is
given in equation (15.18), page 285 of Stoyan and Stoyan (1994).
If correction=c("translate", "Ripley") then both estimates will be computed.
The choice of smoothing kernel is controlled by the argument kernel which is passed to
density. The default is the Epanechnikov kernel, recommended by Stoyan and Stoyan
(1994, page 285).
The bandwidth of the smoothing kernel can be controlled by the argument bw. Its precise
interpretation is explained in the documentation
√ for density. For the Epanechnikov kernel,
the argument bw is equivalent to h/ 5.
Stoyan and Stoyan (1994, page 285) recommend√ using the Epanechnikov kernel with support
[−h, h] chosen by the rule of thumn h = c/ λ, where λ is the (estimated) intensity of the
point process, and c is a constant in the range from 0.1 to 0.2. See equation (15.16). If bw
is missing, then this rule of thumb will be applied. The argument stoyan determines the
value of c.
The argument r is the vector of values for the distance r at which g(r) should be evaluated.
There is a sensible default. If it is specified, r must be a vector of increasing numbers
starting from r[1] = 0, and max(r) must not exceed half the diameter of the window.

Value
A function value table (object of class "fv"). Essentially a data frame containing the
variables

r the vector of values of the argument r at which the pair correlation func-
tion g(r) has been estimated
theo vector of values equal to 1, the theoretical value of g(r) for the Poisson
process
trans vector of values of g(r) estimated by translation correction
iso vector of values of g(r) estimated by Ripley isotropic correction

as required.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.
pcfcross 389

See Also
Kest, pcf, density

Examples
data(simdat)

p <- pcf(simdat)
plot(p, main="pair correlation function for simdat")
# indicates inhibition at distances r < 0.3

pcfcross Multitype pair correlation function

Description
Calculates an estimate of the cross-type pair correlation function for a multitype point
pattern.

Usage
pcfcross(X, i, j, ...)

Arguments
X The observed point pattern, from which an estimate of the cross-type pair
correlation function gij (r) will be computed. It must be a multitype point
pattern (a marked point pattern whose marks are a factor).
i Number or character string identifying the type (mark value) of the points
in X from which distances are measured.
j Number or character string identifying the type (mark value) of the points
in X to which distances are measured.
... Arguments passed to [Link].

Details
The cross-type pair correlation function is a generalisation of the pair correlation function
pcf to multitype point patterns.
For two locations x and y separated by a distance r, the probability p(r) of finding a point
of type i at location x and a point of type j at location y is

p(r) = λi λj gi,j (r) dx dy

where λi is the intensity of the points of type i. For a completely random Poisson marked
point process, p(r) = λi λj so gi,j (r) = 1. Indeed for any marked point pattern in which
the points of type i are independent of the points of type j, the theoretical value of the
cross-type pair correlation is gi,j (r) = 1.
For a stationary multitype point process, the cross-type pair correlation function between
marks i and j is formally defined as

Ki,j (r)
gi,j (r) =
2πr
390 perimeter


where Ki,j is the derivative of the cross-type K function Ki,j (r). of the point process. See
Kest for information about K(r).
The command pcfcross computes a kernel estimate of the cross-type pair correlation func-
tion between marks i and j. It uses [Link] to compute kernel estimates of the pair
correlation functions for several unmarked point patterns, and uses the bilinear properties
of second moments to obtain the cross-type pair correlation.
See [Link] for a list of arguments that control the kernel estimation.

Value
An object of class "fv", see [Link], which can be plotted directly using [Link].
Essentially a data frame containing columns

r the vector of values of the argument r at which the function gi,j has been
estimated
theo the theoretical value gi,j (r) = 1 for independent marks.

together with columns named "border", "[Link]", "iso" and/or "trans", according
to the selected edge corrections. These columns contain estimates of the function gi,j
obtained by the edge corrections named.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
Mark connection function markconnect.
Pair correlation pcf,[Link].
Kcross

Examples
data(amacrine)
p <- pcfcross(amacrine, "off", "on")
plot(p)

perimeter Perimeter Length of Window

Description
Computes the perimeter length of a window

Usage
perimeter(w)
[Link] 391

Arguments
w A window (object of class "owin") or data that can be converted to a
window by [Link].

Details
This function computes the perimeter (length of the boundary) of the window w. If w is
a rectangle or a polygonal window, the perimeter is the sum of the lengths of the edges
of w. If w is a mask, it is first converted to a polygonal window using [Link],
then staircase edges are removed using [Link], and the perimeter of the resulting
polygon is computed.

Value
A numeric value giving the perimeter length of the window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link] diameter, [Link], [Link]

Examples
perimeter(square(3))
data(letterR)
perimeter(letterR)
if([Link]("gpclib")) {
if(interactive()) {
print(perimeter([Link](letterR)))
} else print(perimeter([Link](letterR, dimyx=32)))
}

[Link] Perspective Plot of Pixel Image

Description
Displays a perspective plot of a pixel image.

Usage
## S3 method for class 'im':
persp(x, ..., colmap=NULL)

Arguments
x The pixel image to be plotted. An object of class "im" (see [Link]).
... Extra arguments passed to [Link] to control the display.
colmap Optional data controlling the colour map. See Details.
392 pixellate

Details
This is the persp method for the class "im".
The pixel image x must have real or integer values. These values are treated as heights of a
surface, and the surface is displayed as a perspective plot on the current plot device, using
equal scales on the x and y axes.
The optional argument colmap gives an easy way to display different altitudes in differ-
ent colours (if this is what you want). If colmap is a character vector, then the range of
altitudes in the perspective plot will be divided into length(colmap) intervals, and those
parts of the surface which lie in a particular altitude range will be assigned the correspond-
ing colour from colmap. Alternatively if colmap is a list with entries breaks and col,
then colmap$breaks determines the breakpoints of the altitude intervals, and colmap$col
provides the corresponding colours.
Graphical parameters controlling the perspective plot are passed through the ... argu-
ments directly to the function [Link]. See the examples in [Link] or in
demo(persp).

Value
Returns the 3D transformation matrix returned by [Link].

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
# an image
Z <- setcov(owin())
persp(Z, colmap=[Link](128), axes=FALSE, shade=0.3)

pixellate Convert Spatial Object to Pixel Image

Description
Convert a spatial object to a pixel image by measuring the amount of stuff in each pixel.

Usage
pixellate(x, ...)

Arguments
x Spatial object to be converted. A point pattern (object of class "ppp"),
a window (object of class "owin") or some other suitable data.
... Arguments passed to methods.
[Link] 393

Details

The function pixellate converts a geometrical object x into a pixel image, by measuring
the amount of x that is inside each pixel.
If x is a point pattern, pixellate(x) counts the number of points of x falling in each pixel.
If x is a window, pixellate(x) measures the area of intersection of each pixel with the
window.
The function pixellate is generic, with methods for point patterns ([Link]) and
windows ([Link]). See the separate documentation for these methods.
The related function [Link] also converts x into a pixel image, but typically measures only
the presence or absence of x inside each pixel.

Value

A pixel image (object of class "im").

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [Link], [Link]

[Link] Convert Window to Pixel Image

Description

Convert a window to a pixel image by measuring the area of intersection between the
window and each pixel in a raster.

Usage

## S3 method for class 'owin':


pixellate(x, W = NULL, ...)

Arguments

x Window (object of class "owin") to be converted.


W Optional. Window determining the pixel raster on which the conversion
should occur.
... Optional. Extra arguments passed to [Link] to determine the pixel
raster.
394 [Link]

Details
This is a method for the generic function pixellate.
It converts a window x into a pixel image, by measuring the amount of x that is inside each
pixel.
(The related function [Link] also converts x into a pixel image, but records only the presence
or absence of x in each pixel.)
The pixel raster for the conversion is determined by the argument W and the extra arguments
....

ˆ If W is given, and it is a binary mask (a window of type "mask") then it determines


the pixel raster.
ˆ If W is given, but it is not a binary mask (it is a window of another type) then it will
be converted to a binary mask using [Link](W, ...).
ˆ If W is not given, it defaults to [Link]([Link](x), ...)

In the second and third cases it would be common to use the argument dimyx to control
the number of pixels. See the Examples.
The algorithm then computes the area of intersection of each pixel with the window.
The result is a pixel image with pixel entries equal to these intersection areas.

Value
A pixel image (object of class "im").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], pixellate, [Link]

Examples
data(letterR)
plot(pixellate(letterR, dimyx=15))
W <- [Link]([Link](letterR), 0.2)
plot(pixellate(letterR, W, dimyx=15))

[Link] Convert Point Pattern to Pixel Image

Description
Converts a point pattern to a pixel image. The value in each pixel is the number of points
falling in that pixel, and is typically either 0 or 1.
[Link] 395

Usage
## S3 method for class 'ppp':
pixellate(x, W=NULL, ..., weights = NULL, padzero=FALSE)

## S3 method for class 'ppp':


[Link](X, ...)

Arguments
x,X Point pattern (object of class "ppp").
... Arguments passed to [Link] to determine the pixel resolution
W Optional window mask (object of class "owin") determining the pixel
raster.
weights Optional vector of weights associated with the points.
padzero Logical flag indicating whether to set pixel values to zero outside the
window.

Details
The functions [Link] and [Link] convert a spatial point pattern x into a pixel
image, by counting the number of points (or the total weight of points) falling in each pixel.
Calling [Link] is equivalent to calling [Link] with its default arguments.
Note that [Link] is more general than [Link] (it has additional arguments
for greater flexibility).
The functions [Link] and [Link] are methods for the generic functions [Link]
and pixellate respectively, for the class of point patterns.
The pixel raster (in which points are counted) is determined by the argument W if it is
present (for [Link] only). In this case W should be a binary mask (a window object
of class "owin" with type "mask"). Otherwise the pixel raster is determined by extracting
the window containing x and converting it to a binary pixel mask using [Link]. The
arguments ... are passed to [Link] to control the pixel resolution.
If weights is NULL, then for each pixel in the mask, the algorithm counts how many points
in x fall in the pixel. This count is usually either 0 (for a pixel with no data points in it) or
1 (for a pixel containing one data point) but may be greater than 1. The result is an image
with these counts as its pixel values.
If weights is given, it should be a numeric vector of the same length as the number of
points in x. For each pixel, the algorithm finds the total weight associated with points in
x that fall in the given pixel. The result is an image with these total weights as its pixel
values.
By default (if zeropad=FALSE) the resulting pixel image has the same spatial domain as
the window of the point pattern x. If zeropad=TRUE then the resulting pixel image has a
rectangular domain; pixels outside the original window are assigned the value zero.

Value
A pixel image (object of class "im").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
396 pixelquad

See Also
pixellate, im, [Link], [Link], [Link].

Examples
data(humberside)
plot(pixellate(humberside))

pixelquad Quadrature Scheme Based on Pixel Grid

Description
Makes a quadrature scheme with a dummy point at every pixel of a pixel image.

Usage
pixelquad(X, W = [Link](X))

Arguments
X Point pattern (object of class "ppp") containing the data points for the
quadrature scheme.
W Specifies the pixel grid. A pixel image (object of class "im"), a window
(object of class "owin"), or anything that can be converted to a window
by [Link].

Details
This is a method for producing a quadrature scheme for use by ppm. It is an alternative to
quadscheme.
The function ppm fits a point process model to an observed point pattern using the Berman-
Turner quadrature approximation (Berman and Turner, 1992; Baddeley and Turner, 2000)
to the pseudolikelihood of the model. It requires a quadrature scheme consisting of the orig-
inal data point pattern, an additional pattern of dummy points, and a vector of quadrature
weights for all these points. Such quadrature schemes are represented by objects of class
"quad". See [Link] for a description of this class.
Given a grid of pixels, this function creates a quadrature scheme in which there is one
dummy point at the centre of each pixel. The counting weights are used (the weight
attached to each quadrature point is 1 divided by the number of quadrature points falling
in the same pixel).
The argument X specifies the locations of the data points for the quadrature scheme. Typ-
ically this would be a point pattern dataset.
The argument W specifies the grid of pixels for the dummy points of the quadrature scheme.
It should be a pixel image (object of class "im"), a window (object of class "owin"), or
anything that can be converted to a window by [Link]. If W is a pixel image or a binary
mask (a window of type "mask") then the pixel grid of W will be used. If W is a rectangular
or polygonal window, then it will first be converted to a binary mask using [Link] at the
default pixel resolution.
[Link] 397

Value

An object of class "quad" describing the quadrature scheme (data points, dummy points,
and quadrature weights) suitable as the argument Q of the function ppm() for fitting a point
process model.
The quadrature scheme can be inspected using the print and plot methods for objects of
class "quad".

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

quadscheme, [Link], ppm

Examples
W <- owin(c(0,1),c(0,1))
X <- runifpoint(42, W)
W <- [Link](W,dimyx=128)
pixelquad(X,W)

[Link] Plot Result of Berman Test

Description

Plot the result of Berman’s test of goodness-of-fit

Usage

## S3 method for class 'bermantest':


plot(x, ...,
lwd=par("lwd"), col=par("col"), lty=par("lty"),
lwd0=lwd, col0=col, lty0=lty)

Arguments

x Object to be plotted. An object of class "bermantest" produced by


bermantest.
... extra arguments that will be passed to the plotting function [Link].
col,lwd,lty The width, colour and type of lines used to plot the empirical distribution.
col0,lwd0,lty0
The width, colour and type of lines used to plot the predicted distribution.
398 [Link]

Details

This is the plot method for the class "bermantest". An object of this class represents
the outcome of Berman’s test of goodness-of-fit of a spatial Poisson point process model,
computed by bermantest.
For the Z1 test (i.e. if x was computed using bermantest( ,which="Z1")), the plot
displays the two cumulative distribution functions that are compared by the test: namely
the empirical cumulative distribution function of the covariate at the data points, F̂ , and
the predicted cumulative distribution function of the covariate under the model, F0 , both
plotted against the value of the covariate. Two vertical lines show the mean values of these
two distributions. If the model is correct, the two curves should be close; the test is based
on comparing the two vertical lines.
For the Z2 test (i.e. if x was computed using bermantest( ,which="Z2")), the plot
displays the empirical cumulative distribution function of the values Ui = F0 (Yi ) where Yi
is the value of the covariate at the i-th data point. The diagonal line with equation y = x
is also shown. Two vertical lines show the mean of the values Ui and the value 1/2. If the
model is correct, the two curves should be close. The test is based on comparing the two
vertical lines.

Value

NULL.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

bermantest

Examples

# synthetic data: nonuniform Poisson process


X <- rpoispp(function(x,y) { 100 * exp(-x) }, win=square(1))

# fit uniform Poisson process


fit0 <- ppm(X, ~1)

# test covariate = x coordinate


xcoord <- function(x,y) { x }

# test wrong model


k <- bermantest(fit0, xcoord, "Z1")

# plot result of test


plot(k, col="red", col0="green")
[Link] 399

[Link] Plot a Colour Map

Description
Displays a colour map as a colour ribbon

Usage
## S3 method for class 'colourmap':
plot(x, ...,
main, xlim = NULL, ylim = NULL, vertical = FALSE, axis = TRUE)

Arguments
x Colour map to be plotted. An object of class "colourmap".
... Graphical arguments passed to [Link].
main Main title for plot. A character string.
xlim Optional range of x values for the location of the colour ribbon.
ylim Optional range of y values for the location of the colour ribbon.
vertical Logical flag determining whether the colour ribbon is plotted as a hori-
zontal strip (FALSE) or a vertical strip (TRUE).
axis Logical flag determining whether an axis should be plotted showing the
numerical values that are mapped to the colours.

Details
This is the plot method for the class "colourmap". An object of this class (created by
the function colourmap) represents a colour map or colour lookup table associating colours
with each data value.
The command [Link] displays the colour map as a colour ribbon. This plot can
be useful on its own to inspect the colour map.
To annotate an existing plot with an explanatory colour ribbon, specify add=TRUE and use
the arguments xlim and/or ylim to control the physical position of the ribbon on the plot.

Value
None.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
colourmap
400 [Link]

Examples
co <- colourmap(rainbow(100), breaks=seq(-1,1,length=101))
plot(co)
plot(co, vertical=TRUE)
ca <- colourmap(rainbow(8), inputs=letters[1:8])
plot(ca)

[Link] Plot a Function Array

Description
Plots an array of summary functions, usually associated with a point pattern, stored in an
object of class "fasp". A method for plot.

Usage
## S3 method for class 'fasp':
plot(x,formule=NULL, ...,
subset=NULL, title=NULL, samex=TRUE,
banner=TRUE, [Link]=NULL,
outerlabels=TRUE, [Link]=1.25,
legend=FALSE)

Arguments
x An object of class "fasp" representing a function array.
formule A formula or list of formulae indicating what variables are to be plotted
against what variable. Each formula is either an R language formula
object, or a string that can be parsed as a formula. If formule is a
list, its k th component should be applicable to the (i, j)th plot where
x$which[i,j]=k. If the formula is left as NULL, then [Link] attempts
to use the component [Link] of x. If that component is NULL
as well, it gives up.
... Arguments passed to [Link] to control the individual plot panels.
subset A logical vector, or a vector of indices, or an expression or a character
string, or a list of such, indicating a subset of the data to be included in
each plot. If subset is a list, its k th component should be applicable to
the (i, j)th plot where x$which[i,j]=k.
title Overall title for the plot.
samex Logical flag indicating whether all individual plots should have the same
x axis limits. This makes it easier to compare the plots. It can only be set
to FALSE if you are using the default plot style (i.e. only when formule
is missing).
banner Logical. If TRUE, the overall title is plotted.
[Link] Vector of length 4 giving the value of the graphics parameter mar control-
ling the size of plot margins for each individual plot panel. See par.
outerlabels Logical. If TRUE, the row and column names of the array of functions
are plotted in the margins of the array of plot panels. If FALSE, each
individual plot panel is labelled by its row and column name.
[Link] 401

[Link]
Character expansion factor for row and column labels of array.
legend Logical flag determining whether to plot a legend in each panel.

Details
An object of class "fasp" represents an array of summary functions, usually associated
with a point pattern. See [Link] for details. Such an object is created, for example,
by alltypes.
The function [Link] is a method for plot. It calls [Link] to plot the individual
panels.
For information about the interpretation of the arguments formule and subset, see [Link].
Arguments that are often passed through ... include col to control the colours of the
different lines in a panel, and lty and lwd to control the line type and line width of the
different lines in a panel. See [Link].
The argument title, if present, will determine the overall title of the plot. If it is absent,
it defaults to x$title. Titles for the individual plot panels will be taken from x$titles.

Value
None.

Warnings
(Each component of) the subset argument may be a logical vector (of the same length as
the vectors of data which are extracted from x), or a vector of indices, or an expression
such as expression(r<=0.2), or a text string, such as "r<=0.2".
Attempting a syntax such as subset = r<=0.2 (without wrapping r<=0.2 either in quote
marks or in expression()) will cause this function to fall over.
Variables referred to in any formula must exist in the data frames stored in x. What the
names of these variables are will of course depend upon the nature of x.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
alltypes, [Link], [Link]

Examples
## Not run:
# Bramble Canes data.
data(bramblecanes)

X.G <- alltypes(bramblecanes,type="G",dataname="Bramblecanes",verb=TRUE)


plot(X.G)
plot(X.G,subset="r<=0.2")
plot(X.G,formule=cbind(asin(sqrt(km)),
asin(sqrt(theo))) ~ asin(sqrt(theo)))
plot(X.G,fo=cbind(km-theo,0)~r,"r<=0.2")
402 [Link]

# Simulated data.
pp <- runifpoint(350, owin(c(0,1),c(0,1)))
pp <- pp %mark% factor(c(rep(1,50),rep(2,100),rep(3,200)))
X.K <- alltypes(pp,type="K",verb=TRUE,dataname="Fake Data")
plot(X.K,fo=cbind(border,theo)~theo,"theo<=0.75")

## End(Not run)

[Link] Plot Function Values

Description
Plot method for the class "fv".

Usage
## S3 method for class 'fv':
plot(x, fmla, ..., subset=NULL, lty=NULL, col=NULL, lwd=NULL,
xlim=NULL, ylim=NULL, xlab=NULL, ylab=NULL,
[Link]=NULL, legend=TRUE, legendpos="topleft")

Arguments
x An object of class "fv", containing the variables to be plotted or variables
from which the plotting coordinates can be computed.
fmla an R language formula determining which variables or expressions are
plotted. Either a formula object, or a string that can be parsed as a
formula.
subset (optional) subset of rows of the data frame that will be plotted.
lty (optional) numeric vector of values of the graphical parameter lty con-
trolling the line style of each plot.
col (optional) numeric vector of values of the graphical parameter col con-
trolling the colour of each plot.
lwd (optional) numeric vector of values of the graphical parameter lwd con-
trolling the line width of each plot.
xlim (optional) range of x axis
ylim (optional) range of y axis
xlab (optional) label for x axis
ylab (optional) label for y axis
... Extra arguments passed to [Link].
[Link] Optional vector of y values that must be included in the y axis. For
example [Link]=0 will ensure that the y axis includes the origin.
legend Logical flag or NULL. If legend=TRUE, the algorithm plots a legend in the
top left corner of the plot, explaining the meaning of the different line
types and colours.
legendpos The position of the legend. Either a character string keyword (see legend
for keyword options) or a pair of coordinates in the format list(x,y).
[Link] 403

Details
This is the plot method for the class "fv".
The use of the argument fmla is like [Link], but offers some extra functionality.
The left and right hand sides of fmla are evaluated in the data frame x, and the results
are plotted against each other (the left side on the y axis against the right side on the x
axis). Both left and right sides may be variables in the data frame or expressions in these
variables.
Multiple curves may be specified by a single formula of the form cbind(y1,y2,...,yn) ~
x, where x,y1,y2,...,yn are expressions involving the variables in the data frame. Each
of the variables y1,y2,...,yn in turn will be plotted against x. See the examples.
A convenient abbreviation is the symbol . which can be used in the formula to represent all
the variables in the data frame (other than the function argument itself). See the examples.
The value returned by this plot function indicates the meaning of the line types and colours
in the plot. It can be used to make a suitable legend for the plot if you want to do this by
hand. See the examples.

Value
Either NULL, or a data frame giving the meaning of the different line types and colours.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], Kest

Examples
data(cells)
K <- Kest(cells)
# K is an object of class "fv"

plot(K, iso ~ r) # plots iso against r

plot(K, sqrt(iso/pi) ~ r) # plots sqrt(iso/r) against r

plot(K, cbind(iso,theo) ~ r) # plots iso against r AND theo against r

plot(K, . ~ r) # plots all available estimates of K against r

plot(K, sqrt(./pi) ~ r) # plots all estimates of L-function


# L(r) = sqrt(K(r)/pi)

plot(K, cbind(iso,theo) ~ r, col=c(2,3))


# plots iso against r in colour 2
# and theo against r in colour 3

plot(K, iso ~ r, subset=quote(r < 0.2))


# plots iso against r for r < 10
404 [Link]

# making a legend by hand


v <- plot(K, . ~ r, ylab="K(r)", legend=FALSE)
legend(0.05, 0.15, legend=v$meaning, lty=v$lty, col=v$col)

[Link] Plot Entries in a Hyperframe

Description
Plots the entries in a hyperframe, in a series of panels, one panel for each row of the
hyperframe.

Usage
## S3 method for class 'hyperframe':
plot(x, e, ..., main, arrange=TRUE,
nrows=NULL, ncols=NULL,
parargs=list(mar=c(1,1,3,1) * marsize),
marsize=0.1)

Arguments
x Data to be plotted. A hyperframe (object of class "hyperframe", see
hyperframe).
e How to plot each row. Optional. R language expression that will be
evaluated in each row of the hyperframe to generate the plots.
... Extra arguments controlling the plot (when e is missing).
main Overall title for the array of plots.
arrange Logical flag indicating whether to plot the objects side-by-side on a single
page (arrange=TRUE) or plot them individually in a succession of frames
(arrange=FALSE).
nrows,ncols Optional. The number of rows/columns in the plot layout (assuming
arrange=TRUE). You can specify either or both of these numbers.
parargs Optional list of arguments passed to par before plotting each panel. Can
be used to control margin sizes, etc.
marsize Optional scale parameter controlling the sizes of margins between the
panels.

Details
This is the plot method for the class "hyperframe".
The argument x must be a hyperframe (like a data frame, except that the entries can be
objects of any class; see hyperframe).
This function generates a series of plots, one plot for each row of the hyperframe. If
arrange=TRUE (the default), then these plots are arranged in a neat array of panels within
a single plot frame. If arrange=FALSE, the plots are simply executed one after another.
Exactly what is plotted, and how it is plotted, depends on the argument e. The default (if
e is missing) is to plot only the first column of x. Each entry in the first column is plotted
using the generic plot command, together with any extra arguments given in ....
[Link] 405

If e is present, it should be an R language expression involving the column names of x. The


expression will be evaluated once for each row of x. It will be evaluated in an environment
where each column name of x is interpreted as meaning the object in that column in the
current row. See the Examples.

Value
NULL.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
hyperframe, [Link]

Examples
H <- hyperframe(id=1:10)
H$X <- with(H, rpoispp(100))
H$D <- with(H, distmap(X))
# points only
plot(H[,"X"])
plot(H, plot(X, main=id))
# points superimposed on images
plot(H, {plot(D, main=id); plot(X, add=TRUE)})

[Link] Plot a Pixel Image

Description
Plot a pixel image.

Usage
## S3 method for class 'im':
plot(x, ..., col=NULL,
ribbon=TRUE, ribsep=0.15, ribwid=0.05, ribn=1024)

Arguments
x The pixel image to be plotted. An object of class "im" (see [Link]).
... Extra arguments passed to image to control the plot.
col Colours representing the pixel values. A character vector representing
colours.
ribbon Logical flag indicating whether to display a ribbon showing the colour
map.
ribsep Factor controlling the space between the ribbon and the image.
ribwid Factor controlling the width of the ribbon.
ribn Number of different values to display in the ribbon.
406 [Link]

Details
This is the plot method for the class "im". [It is also the image method for "im".]
The pixel image x is displayed on the current plot device, using equal scales on the x and
y axes.
If ribbon=TRUE, a legend will be plotted at the right of the image. The legend consists of a
colour ribbon and an axis with tick-marks, showing the correspondence between the pixel
values and the colour map.
Arguments ribsep, ribwid, ribn control the appearance of the ribbon. The width of
the ribbon is ribwid times the size of the pixel image, where ‘size’ means the larger of the
width and the height. The distance separating the ribbon and the image is ribsep times
the size of the pixel image. The ribbon contains ribn different numerical values, evenly
spaced between the minimum and maximum pixel values in the image x, rendered according
to the chosen colour map.
The pixel values are displayed using the colours given in the argument col. The mapping
of pixel values to colours is determined as follows.

logical-valued images: the values FALSE and TRUE are mapped to the colours col[1] and
col[2] respectively. The vector col should have length 2.
factor-valued images: the factor levels levels(x) are mapped to the entries of col in
order. The vector col should have the same length as levels(x).
numeric-valued images: By default, the range of pixel values in x is divided into n =
length(col) equal subintervals, which are mapped to the colours in col. (If col was
not specified, it defaults to a vector of 255 colours.)
Alternatively if the argument zlim is given, it should be a vector of length 2 specifying
an interval of real numbers. This interval will be used instead of the range of pixel
values. The interval from zlim[1] to zlim[2] will be mapped to the colours in col.
This facility enables the user to plot several images using a consistent colour map.
Alternatively if the argument breaks is given, then this specifies the endpoints of the
subintervals that are mapped to each colour. This is incompatible with zlim.
The arguments col and zlim or breaks are passed to the function [Link].
For examples of the use of these arguments, see [Link].

Other graphical parameters controlling the display of both the pixel image and the ribbon
are passed through the ... arguments directly to the function [Link].
To suppress the axis tick marks and labels, set axes=FALSE.

Value
none.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link], [Link], [Link]
[Link] 407

Examples
# an image
Z <- setcov(owin())
plot(Z)
plot(Z, col=[Link](128), axes=FALSE)

[Link] Plot a fitted cluster point process

Description
Plots a fitted cluster point process model, displaying the fitted intensity and the fitted
K-function.

Usage
## S3 method for class 'kppm':
plot(x, ..., what=c("intensity", "K"))

Arguments
x Fitted cluster point process model. An object of class "kppm".
... Arguments passed to [Link] and [Link] to control the plot.
what Character vector determining what will be plotted.

Details
This is a method for the generic function plot for the class "kppm" of fitted cluster point
process models.
The argument x should be a cluster point process model (object of class "kppm") obtained
using the function kppm.
By default, this command will first plot the fitted intensity of the model, using [Link],
and then plot the empirical and fitted inhomogeneous K-functions, using [Link].
The choice of plots (and the order in which they are displayed) is controlled by the argument
what. The options (partially matched) are "intensity" and "K".
The option what="intensity" will be ignored if the model is stationary.

Value
Null.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
kppm, [Link], [Link]
408 [Link]

Examples
data(redwood)
fit <- kppm(redwood, ~1, "Thomas")
plot(fit)

[Link] Plot a Spatial Kolmogorov-Smirnov Test

Description
Plot the result of a spatial Kolmogorov-Smirnov test

Usage
## S3 method for class 'kstest':
plot(x, ...,
lwd=par("lwd"), col=par("col"), lty=par("lty"),
lwd0=lwd, col0=col, lty0=lty)

Arguments
x Object to be plotted. An object of class "kstest" produced by a method
for kstest.
... extra arguments that will be passed to the plotting function [Link].
col,lwd,lty The width, colour and type of lines used to plot the empirical distribution.
col0,lwd0,lty0
The width, colour and type of lines used to plot the predicted distribution.

Details
This is the plot method for the class "kstest". An object of this class represents the
outcome of a spatial Kolmogorov-Smirnov test, computed by kstest.
The plot displays the two cumulative distribution functions that are compared by the test:
namely the empirical cumulative distribution function of the covariate at the data points,
and the predicted cumulative distribution function of the covariate under the model, both
plotted against the value of the covariate.

Value
NULL.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
kstest
[Link] 409

Examples
# synthetic data: nonuniform Poisson process
X <- rpoispp(function(x,y) { 100 * exp(x) }, win=square(1))

# fit uniform Poisson process


fit0 <- ppm(X, ~1)

# test covariate = x coordinate


xcoord <- function(x,y) { x }

# test wrong model


k <- kstest(fit0, xcoord)

# plot result of test


plot(k, lwd0=3)

[Link] Plot a List of Things

Description
Plots a list of things

Usage
## S3 method for class 'listof':
plot(x, ..., main, arrange=TRUE,
nrows=NULL, ncols=NULL, [Link]=NULL, [Link]=c(2,1,1,2))

Arguments
x An object of the class "listof". Essentially a list of objects.
... Arguments passed to plot when generating each plot panel.
main Overall heading for the plot.
arrange Logical flag indicating whether to plot the objects side-by-side on a single
page (arrange=TRUE) or plot them individually in a succession of frames
(arrange=FALSE).
nrows,ncols Optional. The number of rows/columns in the plot layout (assuming
arrange=TRUE). You can specify either or both of these numbers.
[Link] Optional. A character string, or a vector of character strings, giving the
headings for each of the objects.
[Link] Value of the graphics parameter mar controlling the size of the margins
outside each plot panel. See the help file for par.

Details
This is the plot method for the class "listof".
An object of class "listof" (defined in the base R package) represents a list of objects,
all belonging to a common class. The base R package defines a method for printing these
410 [Link]

objects, [Link], but does not define a method for plot. So here we have provided
a method for plot.
In the spatstat package, the function [Link] produces an object of class "listof",
essentially a list of pixel images. These images can be plotted in a nice arrangement using
[Link]. See the Example.

Value
Null.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
# Multitype point pattern
data(amacrine)
plot(density(split(amacrine)))

[Link] Plot a Spatial Window

Description
Plot a two-dimensional window of observation for a spatial point pattern

Usage
## S3 method for class 'owin':
plot(x, main, add=FALSE, ..., box, edge=0.04,
hatch=FALSE, angle=45, spacing=diameter(x)/50)

Arguments
x The window to be plotted. An object of class owin, or data which can be
converted into this format by [Link]().
main text to be displayed as a title above the plot.
add logical flag: if TRUE, draw the window in the current plot; if FALSE, gen-
erate a new plot.
... extra arguments passed to the generic plot function.
box logical flag; if TRUE, plot the enclosing rectangular box
edge nonnegative number; the plotting region will have coordinate limits that
are 1 + edge times as large as the limits of the rectangular box that
encloses the pattern.
[Link] 411

hatch logical flag; if TRUE, the interior of the window will be shaded by a grid
of parallel lines.
angle orientation of the shading lines (in degrees anticlockwise from the x axis)
when hatch=TRUE.
spacing spacing between the shading lines, when hatch=TRUE.

Details
This is the plot method for the class owin. The action is to plot the boundary of the
window on the current plot device, using equal scales on the x and y axes.
If the window x is of type "rectangle" or "polygonal", the boundary of the window
is plotted as a polygon or series of polygons. If x is of type "mask" the discrete raster
approximation of the window is displayed as a binary image (white inside the window,
black outside).
Graphical parameters controlling the display (e.g. setting the colours) may be passed di-
rectly via the ... arguments, or indirectly reset using [Link].
When x is of type "rectangle" or "polygonal", it is plotted by the R function polygon. To
control the appearance (colour, fill density, line density etc) of the polygon plot, determine
the required argument of polygon and pass it through ... For example, to paint the
interior of the polygon in red, use the argument col="red". To draw the polygon edges in
green, use border="green". To suppress the drawing of polygon edges, use border=NA.
When x is of type "mask", it is plotted by [Link]. The appearance of the image plot
can be controlled by passing arguments to [Link] through .... The default ap-
pearance can also be changed by setting the parameter [Link] of [Link].
To zoom in (to view only a subset of the window at higher magnification), use the graphical
arguments xlim and ylim to specify the desired rectangular field of view. (The actual field
of view may be larger, depending on the graphics device).

Value
none.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], polygon, [Link], [Link]

Examples
# rectangular window
data(nztrees)
plot(nztrees$window)
abline(v=148, lty=2)

# polygonal window
data(demopat)
w <- demopat$window
plot(w)
plot(w, col="red", border="green", lwd=2)
412 [Link]

plot(w, hatch=TRUE, lwd=2)

# binary mask
we <- erosion(w, 100, FALSE)
plot(we)
[Link]([Link]=list(col=grey(c(0.5,1))))
plot(we)

[Link] Plot a plotppm Object Created by [Link]

Description
The function [Link] produces objects which specify plots of fitted point process models.
The function [Link] carries out the actual plotting of these objects.

Usage
## S3 method for class 'plotppm':
plot(x, data = NULL, trend = TRUE, cif = TRUE,
se = TRUE, pause = interactive(),
how = c("persp", "image", "contour"), ...)

Arguments
x An object of class plotppm produced by [Link]() .
data The point pattern (an object of class ppp) to which the point process
model was fitted (by ppm).
trend Logical scalar; should the trend component of the fitted model be plotted?
cif Logical scalar; should the complete conditional intensity of the fitted
model be plotted?
se Logical scalar; should the estimated standard error of the fitted intensity
be plotted?
pause Logical scalar indicating whether to pause with a prompt after each plot.
Set pause=FALSE if plotting to a file.
how Character string or character vector indicating the style or styles of plots
to be performed.
... Extra arguments to the plotting functions persp, image and contour.

Details
If argument data is supplied then the point pattern will be superimposed on the image and
contour plots.
Sometimes a fitted model does not have a trend component, or the trend component may
constitute all of the conditional intensity (if the model is Poisson). In such cases the object
x will not contain a trend component, or will contain only a trend component. This will
also be the case if one of the arguments trend and cif was set equal to FALSE in the call
to [Link]() which produced x. If this is so then only the item which is present will be
plotted. Explicitly setting trend=TRUE, or cif=TRUE, respectively, will then give an error.
plot.pp3 413

Value
None.

Warning
Arguments which are passed to persp, image, and contour via the . . . argument get passed
to any of the other functions listed in the how argument, and won’t be recognized by them.
This leads to a lot of annoying but harmless warning messages. Arguments to persp may be
supplied via [Link]() which alleviates the warning messages in this instance.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link]()

Examples
## Not run:
data(cells)
Q <- quadscheme(cells)
m <- ppm(Q, ~1, Strauss(0.05))
mpic <- plot(m)
# Perspective plot only, with altered parameters:
plot(mpic,how="persp", theta=-30,phi=40,d=4)
# All plots, with altered parameters for perspective plot:
[Link]([Link]=list(theta=-30,phi=40,d=4))
plot(mpic)

## End(Not run)

plot.pp3 Plot a three-dimensional point pattern

Description
Plots a three-dimensional point pattern.

Usage
## S3 method for class 'pp3':
plot(x, ...)

Arguments
x Three-dimensional point pattern (object of class "pp3").
... Arguments passed to scatterplot3d controlling the plot.
414 [Link]

Details
This is the plot method for objects of class "pp3".
This function requires the scatterplot3d package. The coordinates of the point pattern are
passed to the function scatterplot3d along with any extra arguments ....

Value
Null.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
pp3

[Link] plot a Fitted Point Process Model

Description
Given a fitted point process model obtained by ppm, create spatial trend and conditional
intensity surfaces of the model, in a form suitable for plotting, and (optionally) plot these
surfaces.

Usage
## S3 method for class 'ppm':
plot(x, ngrid = c(40,40), superimpose = TRUE,
trend = TRUE, cif = TRUE, se = TRUE, pause = interactive(),
how=c("persp","image", "contour"), [Link] = TRUE,
locations = NULL, covariates=NULL, ...)

Arguments
x A fitted point process model, typically obtained from the model-fitting
algorithm ppm. An object of class "ppm".
ngrid The dimensions for a grid on which to evaluate, for plotting, the spatial
trend and conditional intensity. A vector of 1 or 2 integers. If it is of
length 1, ngrid is replaced by c(ngrid,ngrid).
superimpose logical flag; if TRUE (and if plot=TRUE) the original data point pattern
will be superimposed on the plots.
trend logical flag; if TRUE, the spatial trend surface will be produced.
cif logical flag; if TRUE, the conditional intensity surface will be produced.
se logical flag; if TRUE, the estimated standard error of the spatial trend
surface will be produced.
pause logical flag indicating whether to pause with a prompt after each plot. Set
pause=FALSE if plotting to a file. (This flag is ignored if plot=FALSE).
[Link] 415

how character string or character vector indicating the style or styles of plots
to be performed. Ignored if plot=FALSE.
[Link] logical scalar; should a plot be produced immediately?
locations If present, this determines the locations of the pixels at which predictions
are computed. It must be a binary pixel image (an object of class "owin"
with type "mask"). (Incompatible with ngrid).
covariates Values of external covariates required by the fitted model. Passed to
[Link].
... extra arguments to the plotting functions persp, image and contour.

Details

This is the plot method for the class "ppm" (see [Link] for details of this class).
It invokes [Link] to compute the spatial trend and conditional intensity of the fit-
ted point process model. See [Link] for more explanation about spatial trend and
conditional intensity.
The default action is to create a rectangular grid of points in (the bounding box of) the
observation window of the data point pattern, and evaluate the spatial trend and conditional
intensity of the fitted spatial point process model x at these locations. If the argument
locations= is supplied, then the spatial trend and conditional intensity are calculated at
the grid of points specified by this argument.
The argument locations, if present, should be a binary image mask (an object of class
"owin" and type "mask"). This determines a rectangular grid of locations, or a subset of
such a grid, at which predictions will be computed. Binary image masks are conveniently
created using [Link].
The argument covariates gives the values of any spatial covariates at the prediction lo-
cations. If the trend formula in the fitted model involves spatial covariates (other than the
Cartesian coordinates x, y) then covariates is required.
The argument covariates has the same format and interpretation as in [Link]. It
may be either a data frame (the number of whose rows must match the number of pixels
in locations multiplied by the number of possible marks in the point pattern), or a list of
images. If argument locations is not supplied, and covariates is supplied, then it must
be a list of images.
If the fitted model was a marked (multitype) point process, then predictions are made for
each possible mark value in turn.
If the fitted model had no spatial trend, then the default is to omit calculating this (flat)
surface, unless trend=TRUE is set explicitly.
If the fitted model was Poisson, so that there were no spatial interactions, then the condi-
tional intensity and spatial trend are identical, and the default is to omit the conditional
intensity, unless cif=TRUE is set explicitly.
If [Link]=TRUE then [Link]() is called upon to plot the class plotppm object
which is produced. (That object is also returned, silently.)
Plots are produced successively using persp, image and contour (or only a selection of
these three, if how is given). Extra graphical parameters controlling the display may be
passed directly via the arguments ... or indirectly reset using [Link].
416 [Link]

Value
An object of class plotppm. Such objects may be plotted by [Link]().
This is a list with components named trend and cif, either of which may be missing. They
will be missing if the corresponding component does not make sense for the model, or if the
corresponding argument was set equal to FALSE.
Both trend and cif are lists of images. If the model is an unmarked point process, then
they are lists of length 1, so that trend[[1]] is an image of the spatial trend and cif[[1]]
is an image of the conditional intensity.
If the model is a marked point process, then trend[[i]] is an image of the spatial trend for
the mark m[i], and cif[[1]] is an image of the conditional intensity for the mark m[i],
where m is the vector of levels of the marks.

Warnings
See warnings in [Link].

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], ppm, [Link], [Link], [Link], persp, image, contour, plot,
[Link]

Examples
## Not run:
data(cells)
m <- ppm(cells, ~1, Strauss(0.05))
pm <- plot(m) # The object ``pm'' will be plotted as well as saved
# for future plotting.

## End(Not run)

[Link] plot a Spatial Point Pattern

Description
Plot a two-dimensional spatial point pattern

Usage
## S3 method for class 'ppp':
plot(x, main, ..., chars=NULL, cols=NULL,
[Link]=TRUE, add=FALSE, maxsize=NULL, markscale=NULL)
[Link] 417

Arguments
x The spatial point pattern to be plotted. An object of class "ppp", or data
which can be converted into this format by [Link]().
main text to be displayed as a title above the plot.
... extra arguments that will be passed to the plotting functions [Link],
points and/or symbols.
chars plotting character(s) used to plot points.
cols the colour(s) used to plot points.
[Link] logical flag; if TRUE, plot points using a different plotting symbol for each
mark; if FALSE, only the locations of the points will be plotted, using
points().
add logical flag; if TRUE, just the points are plotted, over the existing plot. A
new plot is not created, and the window is not plotted.
maxsize maximum size of the circles/squares plotted when x is a marked point
pattern with numerical marks. Incompatible with markscale.
markscale physical scale factor determining the sizes of the circles/squares plotted
when x is a marked point pattern with numerical marks. Incompatible
with maxsize.

Details
This is the plot method for point pattern datasets (of class "ppp", see [Link]).
First the observation window x$window is plotted. Then the points themselves are plotted,
in a fashion that depends on their marks, as follows.
unmarked point pattern: If the point pattern does not have marks, or if [Link] =
FALSE, then the locations of all points will be plotted using a single plot character
multitype point pattern: If x$marks is a factor, then each level of the factor is repre-
sented by a different plot character.
continuous marks: If x$marks is a numeric vector, the marks are rescaled to the unit
interval and each point is represented by a circle with radius proportional to the
rescaled mark (if the value is positive) or a square with side proportional to the absolute
value of the rescaled mark (if the value is negative).
other kinds of marks: If x$marks is neither numeric nor a factor, then each possible
mark will be represented by a different plotting character. The default is to represent
the ith smallest mark value by points(..., pch=i).
Plotting of the window x$window is performed by [Link]. This plot may be modified
through the ... arguments. In particular the extra argument border determines the colour
of the window.
Plotting of the points themselves is performed by the function points, except for the case
of continuous marks, where it is performed by symbols. Their plotting behaviour may be
modified through the ... arguments.
The argument chars determines the plotting character or characters used to display the
points (in all cases except for the case of continuous marks). For an unmarked point
pattern, this should be a single integer or character determining a plotting character (see
par("pch")). For a multitype point pattern, chars should be a vector of integers or
characters, of the same length as levels(x$marks), and then the ith level or type will be
plotted using character chars[i].
418 [Link]

If chars is absent, but there is an extra argument pch, then this will determine the plotting
character for all points.
The argument cols determines the colour or colours used to display the points. For an
unmarked point pattern, or a marked point pattern with continuous marks, this should be
a character string determining a colour. For a multitype point pattern, cols should be a
character vector, of the same length as levels(x$marks). The ith level or type will be
plotted using colour cols[i].
If cols is absent, the colour used to plot all the points may be determined by the extra
argument fg (for multitype point patterns) or the extra argument col (for all other cases).
Note that col will also reset the colour of the window.
The arguments maxsize and markscale incompatible. They control the physical size of the
circles and squares which represent the marks in a point pattern with continuous marks. If
markscale is given, then a mark value of m is plotted as a circle of radius m * markscale
(if m is positive) or a square of side abs(m) * markscale (if m is negative). If maxsize is
given, then the largest mark in absolute value, mmax=max(abs(x$marks)), will be scaled to
have physical size maxsize.
The user can set the default values of these plotting parameters using [Link]("[Link]").
To zoom in (to view only a subset of the point pattern at higher magnification), use the
graphical arguments xlim and ylim to specify the rectangular field of view.
The value returned by this plot function can be used to make a suitable legend, as shown
in the examples.

Value
NULL, or a vector giving the correspondence between mark values and plotting characters.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
iplot, [Link], plot, par, points, [Link], symbols

Examples
data(cells)
plot(cells)

plot(cells, pch=16)

# make the plotting symbols larger (for publication at reduced scale)


plot(cells, cex=2)

# set it in [Link]
oldopt <- [Link]([Link]=list(cex=2))
plot(cells)
[Link](oldopt)

# multitype
data(lansing)
plot(lansing)
[Link] 419

# marked by a real number


data(longleaf)
plot(longleaf)

# just plot the points


plot(longleaf, [Link]=FALSE)
plot(unmark(longleaf)) # equivalent

# controlling COLOURS of points


plot(cells, cols="blue")
plot(lansing, cols=c("black", "yellow", "green",
"blue","red","pink"))
plot(longleaf, fg="blue")

# make window purple


plot(lansing, border="purple")
# make everything purple
plot(lansing, border="purple", cols="purple", [Link]="purple")

# controlling PLOT CHARACTERS


plot(lansing, chars = 11:16)
plot(lansing, chars = c("o","h","m",".","o","o"))

# controlling MARK SCALE


plot(longleaf, markscale=0.1)

# draw circles of DIAMETER equal to nearest neighbour distance


plot(cells %mark% nndist(cells), markscale=1/2)

# making the legend


data(amacrine)
v <- plot(amacrine)
legend(0.2, 1.2, pch=v, legend=names(v))

[Link] plot a Spatial Line Segment Pattern

Description
Plot a two-dimensional line segment pattern

Usage
## S3 method for class 'psp':
plot(x, ..., add=FALSE)

Arguments
x The line segment pattern to be plotted. An object of class "psp", or data
which can be converted into this format by [Link]().
... extra arguments that will be passed to the plotting functions segments
(to plot the segments) and [Link] (to plot the observation window).
add Logical. If TRUE, the current plot is not erased; the segments are plotted
on top of the current plot, and the window is not plotted.
420 [Link]

Details
This is the plot method for line segment pattern datasets (of class "psp", see [Link]).
It plots both the observation window x$window and the line segments themselves.
Plotting of the window x$window is performed by [Link]. This plot may be modified
through the ... arguments.
Plotting of the points themselves is performed by the standard R function segments. Its
plotting behaviour may also be modified through the ... arguments.

Value
NULL

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], plot, par, [Link], symbols

Examples
a <- psp(runif(20), runif(20), runif(20), runif(20), window=owin())
plot(a)
plot(a, main="My title")
plot(a, col="blue")
plot(a, lwd=3)

[Link] plot a Spatial Quadrature Scheme

Description
Plot a two-dimensional spatial quadrature scheme.

Usage
## S3 method for class 'quad':
plot(x, ..., main=deparse(substitute(x)), dum=list())

Arguments
x The spatial quadrature scheme to be plotted. An object of class "quad".
... extra arguments controlling the plotting of the data points of the quadra-
ture scheme.
dum list of extra arguments controlling the plotting of the dummy points of
the quadrature scheme. See below.
main text to be displayed as a title above the plot.
[Link] 421

Details
This is the plot method for quadrature schemes (objects of class "quad", see [Link]).
First the data points of the quadrature scheme are plotted (in their observation window)
using [Link] with any arguments specified in ...
Then the dummy points of the quadrature scheme are plotted using [Link] with any
arguments specified in dum.
By default the dummy points are superimposed onto the plot of data points. This can be
overridden by including the argument add=FALSE in the list dum as shown in the examples.
In this case the data and dummy point patterns are plotted separately.
See par and [Link] for other possible arguments controlling the plots.

Value
NULL.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], par

Examples
data(nztrees)
Q <- quadscheme(nztrees)

plot(Q, main="NZ trees: quadrature scheme")

oldpar <- par(mfrow=c(2,1))


plot(Q, main="NZ trees", dum=list(add=FALSE))
par(oldpar)

[Link] Plot a List of Point Patterns

Description
Plots a list of point patterns.

Usage
## S3 method for class 'splitppp':
plot(x, ..., main, arrange=TRUE,
nrows=NULL, ncols=NULL, [Link]=NULL, [Link])
422 [Link]

Arguments

x A named list of point patterns, typically obtained from [Link].


... Arguments passed to [Link] which control the appearance of each plot
panel.
main Overall heading for the plot.
arrange Logical flag indicating whether to plot the point patterns side-by-side on
a single page (arrange=TRUE) or plot them individually in a succession of
frames (arrange=FALSE).
nrows,ncols Optional. The number of rows/columns in the plot layout (assuming
arrange=TRUE). You can specify either or both of these numbers.
[Link] Optional. A character string, or a vector of character strings, giving the
headings for each of the point patterns.
[Link] Optional value of the graphics parameter mar controlling the size of the
margins outside each plot panel. See the help file for par.

Details

This is the plot method for the class "splitppp". It is typically used to plot the result of
the function [Link] but it may also be used to plot any list of point patterns created
by the user.
The argument x should be a named list of point patterns (objects of class "ppp", see
[Link]). Each of these point patterns will be plotted in turn using [Link].

Value

Null.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [Link], [Link]

Examples

# Multitype point pattern


data(amacrine)
plot(split(amacrine))
[Link] 423

[Link] Plot a tessellation

Description
Plots a tessellation.

Usage
## S3 method for class 'tess':
plot(x, ..., main, add=FALSE, col=NULL)

Arguments
x Tessellation (object of class "tess") to be plotted.
... Arguments controlling the appearance of the plot.
main Heading for the plot. A character string.
add Logical. Determines whether the tessellation plot is added to the existing
plot.
col Colour of the tile boundaries. A character string. Ignored for pixel tes-
sellations.

Details
This is a method for the generic plot function for the class "tess" of tessellations (see
tess).
The arguments ... control the appearance of the plot. They are passed to segments,
[Link] or [Link], depending on the type of tessellation.

Value
None.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
tess

Examples
A <- tess(xgrid=0:4,ygrid=0:4)
plot(A, col="blue", lwd=2, lty=2)
B <- A[c(1, 2, 5, 7, 9)]
plot(B, hatch=TRUE)
v <- [Link](function(x,y){factor(round(5 * (x^2 + y^2)))}, W=owin())
levels(v) <- letters[seq(length(levels(v)))]
E <- tess(image=v)
plot(E)
424 pointsOnLines

pointsOnLines Place Points Evenly Along Specified Lines

Description
Given a line segment pattern, place a series of points at equal distances along each line
segment.

Usage
pointsOnLines(X, eps = NULL, np = 1000)

Arguments
X A line segment pattern (object of class "psp").
eps Spacing between successive points.
np Approximate total number of points (incompatible with eps).

Details
For each line segment in the pattern X, a succession of points is placed along the line
segment. These points are equally spaced at a distance eps, except for the first and last
points in the sequence.
The spacing eps is measured in coordinate units of X.
If eps is not given, then it is determined by eps = len/np where len is the total length of
the segments in X. The actual number of points will then be slightly larger than np.

Value
A point pattern (object of class "ppp") in the same window as X.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
psp, ppp, runifpointOnLines

Examples
X <- psp(runif(20), runif(20), runif(20), runif(20), window=owin())
Y <- pointsOnLines(X, eps=0.05)
plot(X, main="")
plot(Y, add=TRUE, pch="+")
Poisson 425

Poisson Poisson Point Process Model

Description
Creates an instance of the Poisson point process model which can then be fitted to point
pattern data.

Usage
Poisson()

Details
The function ppm, which fits point process models to point pattern data, requires an argu-
ment interaction of class "interact" describing the interpoint interaction structure of
the model to be fitted. The appropriate description of the Poisson process is provided by
the value of the function Poisson.
This works for all types of Poisson processes including multitype and nonstationary Poisson
processes.

Value
An object of class "interact" describing the interpoint interaction structure of the Poisson
point process (namely, there are no interactions).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, Strauss, StraussHard

Examples
data(nztrees)
ppm(nztrees, ~1, Poisson())
# fit the stationary Poisson process to 'nztrees'
# no edge correction needed

data(longleaf)

longadult <- longleaf[longleaf$marks >= 30, ]


longadult <- unmark(longadult)
ppm(longadult, ~ x, Poisson())
# fit the nonstationary Poisson process
# with intensity lambda(x,y) = exp( a + bx)

data(lansing)
# trees marked by species

ppm(lansing, ~ marks, Poisson())


426 ponderosa

# fit stationary marked Poisson process


# with different intensity for each species

## Not run:
ppm(lansing, ~ marks * polynom(x,y,3), Poisson())

## End(Not run)
# fit nonstationary marked Poisson process
# with different log-cubic trend for each species

ponderosa Ponderosa Pine Tree Point Pattern

Description
The data record the locations of 108 Ponderosa Pine (Pinus ponderosa) trees in a 120 metre
square region in the Klamath National Forest in northern California, published as Figure 2
of Getis and Franklin (1987).
Franklin et al. (1985) determined the locations of approximately 5000 trees from United
States Forest Service aerial photographs and digitised them for analysis. Getis and Franklin
(1987) selected a 120 metre square subregion that appeared to exhibit clustering. This
subregion is the ponderosa dataset.
In principle these data are equivalent to Figure 2 of Getis and Franklin (1987) but they are
not exactly identical; some of the spatial locations appear to be slightly perturbed.
The data points identified as A, B, C on Figure 2 of Getis and Franklin (1987) correspond
to points numbered 42, 7 and 77 in the dataset respectively.

Usage
data(ponderosa)

Format
Typing data(ponderosa) gives access to two objects, ponderosa and [Link].
The dataset ponderosa is a spatial point pattern (object of class "ppp") representing the
point pattern of tree positions. See [Link] for details of the format.
The dataset [Link] is a list containing supplementary data. The entry id con-
tains the index numbers of the three special points A, B, C in the point pattern. The entry
plotit is a function that can be called to produce a nice plot of the point pattern.

Source
Prof. Janet Franklin, University of California, Santa Barbara

References
Franklin, J., Michaelsen, J. and Strahler, A.H. (1985) Spatial analysis of density dependent
pattern in coniferous forest stands. Vegetatio 64, 29–36.
Getis, A. and Franklin, J. (1987) Second-order neighbourhood analysis of mapped point
patterns. Ecology 68, 473–477.
pp3 427

Examples
data(ponderosa)
[Link]$plotit()

pp3 Three Dimensional Point Pattern

Description
Create a three-dimensional point pattern

Usage
pp3(x, y, z, ...)

Arguments
x,y,z Numeric vectors of equal length, containing Cartesian coordinates of points
in three-dimensional space.
... Arguments passed to as.box3 to determine the three-dimensional box in
which the points have been observed.

Details
An object of class "pp3" represents a pattern of points in three-dimensional space. The
points are assumed to have been observed by exhaustively inspecting a three-dimensional
rectangular box. The boundaries of the box are included as part of the dataset.

Value
Object of class "pp3" representing a three dimensional point pattern. Also belongs to class
"ppx".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
box3, ppx

Examples
X <- pp3(runif(10), runif(10), runif(10), box3(c(0,1)))
428 ppm

ppm Fit Point Process Model to Data

Description
Fits a point process model to an observed point pattern

Usage
ppm(Q, trend=~1, interaction=Poisson(),
...,
covariates=NULL,
correction="border",
rbord=reach(interaction),
[Link]=FALSE,
method="mpl",
forcefit=FALSE,
gcontrol=list(),
nsim=100, nrmh=1e5, start=NULL, control=list(nrep=nrmh),
verb=TRUE)

Arguments
Q A data point pattern (of class "ppp") to which the model will be fitted,
or a quadrature scheme (of class "quad") containing this pattern.
trend An R formula object specifying the spatial trend to be fitted. The default
formula, ~1, indicates the model is stationary and no trend is to be fitted.
interaction An object of class "interact" describing the point process interaction
structure, or NULL indicating that a Poisson process (stationary or non-
stationary) should be fitted.
... Ignored.
covariates The values of any spatial covariates (other than the Cartesian coordinates)
required by the model. Either a data frame, or a list whose entries are
images, functions or single numbers. See Details.
correction The name of the edge correction to be used. The default is "border" in-
dicating the border correction. Other possibilities may include "Ripley",
"isotropic", "translate" and "none", depending on the interaction.
rbord If correction = "border" this argument specifies the distance by which
the window should be eroded for the border correction.
[Link] Logical flag; if TRUE then computations are performed using gam instead
of glm.
method The method used to fit the model. Options are "mpl" for the method of
Maximum PseudoLikelihood, and "ho" for the Huang-Ogata approximate
maximum likelihood method.
forcefit Logical flag for internal use. If forcefit=FALSE, some trivial models will
be fitted by a shortcut. If forcefit=TRUE, the generic fitting method will
always be used.
ppm 429

gcontrol Optional. List of parameters passed to [Link] (or passed to [Link]


if [Link]=TRUE) controlling the model-fitting algorithm.
nsim Number of simulated realisations to generate (for method="ho")
nrmh Number of Metropolis-Hastings iterations for each simulated realisation
(for method="ho")
start,control Arguments passed to rmh controlling the behaviour of the Metropolis-
Hastings algorithm (for method="ho")
verb Logical flag indicating whether to print progress reports (for method="ho")

Details
This function fits a point process model to an observed point pattern. The model may
include spatial trend, interpoint interaction, and dependence on covariates.

basic use: In basic use, Q is a point pattern dataset (an object of class "ppp") to which
we wish to fit a model.
The syntax of ppm() is closely analogous to the R functions glm and gam. The analogy
is:

glm ppm
formula trend
family interaction

The point process model to be fitted is specified by the arguments trend and interaction
which are respectively analogous to the formula and family arguments of glm().
Systematic effects (spatial trend and/or dependence on spatial covariates) are specified
by the argument trend. This is an R formula object, which may be expressed in terms
of the Cartesian coordinates x, y, the marks marks, or the variables in covariates
(if supplied), or both. It specifies the logarithm of the first order potential of the
process. The formula should not use any names beginning with .mpl as these are
reserved for internal use. If trend is absent or equal to the default, ~1, then the model
to be fitted is stationary (or at least, its first order potential is constant).
Stochastic interactions between random points of the point process are defined by
the argument interaction. This is an object of class "interact" which is ini-
tialised in a very similar way to the usage of family objects in glm and gam. The
families currently available are: Poisson, Strauss, StraussHard, MultiStrauss,
MultiStraussHard, Softcore, DiggleGratton, Pairwise, PairPiece, AreaInter,
Geyer, BadGey, SatPiece, LennardJones, Saturated, OrdThresh, and Ord. See the
examples below.
If interaction is missing or NULL, then the model to be fitted has no interpoint in-
teractions, that is, it is a Poisson process (stationary or nonstationary according to
trend). In this case the method of maximum pseudolikelihood coincides with maxi-
mum likelihood.
The fitted point process model returned by this function can be printed (by the print
method [Link]) to inspect the fitted parameter values. If a nonparametric spatial
trend was fitted, this can be extracted using the predict method [Link].
Models with covariates: To fit a model involving spatial covariates other than the Carte-
sian coordinates x and y, the values of the covariates should be supplied in the argu-
ment covariates. Note that it is not sufficient to have observed the covariate only
at the points of the data point pattern; the covariate must also have been observed at
other locations in the window.
430 ppm

Typically the argument covariates is a list, with names corresponding to variables


in the trend formula. The entries in the list are pixel images (giving the values of
a spatial covariate at a fine grid of locations) or functions (which can be evaluated
at any location (x,y) to obtain the value of the spatial covariate) or single numbers
(indicating a covariate that is constant in this dataset). Each entry in the list must
be an image (object of class "im", see [Link]), or a function(x,y), or a single
number. The software will look up the pixel values of each image at the required
locations (quadrature points). In this case the argument Q may be either a quadrature
scheme or a point pattern.
If covariates is a list, the list entries should have names corresponding to the names
of covariates in the model formula trend. The variable names x, y and marks are
reserved for the Cartesian coordinates and the mark values, and these should not be
used for variables in covariates.
If covariates is a data frame, Q must be a quadrature scheme (see under Quadrature
Schemes below). Then covariates must have as many rows as there are points in Q.
The ith row of covariates should contain the values of spatial variables which have
been observed at the ith point of Q.
Quadrature schemes: In advanced use, Q may be a ‘quadrature scheme’. This was orig-
inally just a technicality but it has turned out to have practical uses, as we explain
below.
Quadrature schemes are required for our implementation of the method of maximum
pseudolikelihood. The definition of the pseudolikelihood involves an integral over the
spatial window containing the data. In practice this integral must be approximated
by a finite sum over a set of quadrature points. We use the technique of Baddeley and
Turner (2000), a generalisation of the Berman-Turner (1992) device. In this technique
the quadrature points for the numerical approximation include all the data points
(points of the observed point pattern) as well as additional ‘dummy’ points.
A quadrature scheme is an object of class "quad" (see [Link]) which specifies
both the data point pattern and the dummy points for the quadrature scheme, as well
as the quadrature weights associated with these points. If Q is simply a point pattern
(of class "ppp", see [Link]) then it is interpreted as specifying the data points
only; a set of dummy points specified by [Link]() is added, and the default
weighting rule is invoked to compute the quadrature weights.
Finer quadrature schemes (i.e. those with more dummy points) generally yield a better
approximation, at the expense of higher computational load.
Complete control over the quadrature scheme is possible. See quadscheme for an
overview. Use quadscheme(X, D, method="dirichlet") to compute quadrature weights
based on the Dirichlet tessellation, or quadscheme(X, D, method="grid") to com-
pute quadrature weights by counting points in grid squares, where X and D are the
patterns of data points and dummy points respectively. Alternatively use pixelquad
to make a quadrature scheme with a dummy point at every pixel in a pixel image.
A practical advantage of quadrature schemes arises when we want to fit a model in-
volving covariates (e.g. soil pH). Suppose we have only been able to observe the
covariates at a small number of locations. Suppose [Link] is a data frame containing
the values of the covariates at the data points (i.e.\ [Link][i,] contains the obser-
vations for the ith data point) and [Link] is another data frame (with the same
columns as [Link]) containing the covariate values at another set of points whose
locations are given by the point pattern Y. Then setting Q = quadscheme(X,Y) com-
bines the data points and dummy points into a quadrature scheme, and covariates =
rbind([Link], [Link]) combines the covariate data frames. We can then fit the
model by calling ppm(Q, ..., covariates).
ppm 431

Model-fitting technique: The model may be fitted either by the method of maximum
pseudolikelihood (Besag, 1975) or by the approximate maximum likelihood method of
Huang and Ogata (1999). Maximum pseudolikelihood is much faster, but has poorer
statistical properties.
In either case, the algorithm will begin by fitting the model by maximum pseudolike-
lihood. By default the algorithm returns the maximum pseudolikelihood fit.
Maximum pseudolikelihood is equivalent to maximum likelihood for Poisson point
processes.
Note that the method of maximum pseudolikelihood is believed to be inefficient and
biased for point processes with strong interpoint interactions. In such cases, the Huang-
Ogata approximate maximum likelihood method should be used, although maximum
pseudolikelihood may also be used profitably for model selection in the initial phases
of modelling.
Huang-Ogata method: If method="ho" then the model will be fitted using the Huang-
Ogata (1999) approximate maximum likelihood method. First the model is fitted by
maximum pseudolikelihood as described above, yielding an initial estimate of the pa-
rameter vector θ0 . From this initial model, nsim simulated realisations are generated.
The score and Fisher information of the model at θ = θ0 are estimated from the simu-
lated realisations. Then one step of the Fisher scoring algorithm is taken, yielding an
updated estimate θ1 . The corresponding model is returned.
Simulated realisations are generated using rmh. The iterative behaviour of the Metropolis-
Hastings algorithm is controlled by the arguments start and control which are passed
to rmh.
As a shortcut, the argument nrmh determines the number of Metropolis-Hastings iter-
ations run to produce one simulated realisation (if control is absent). Also if start
is absent or equal to NULL, it defaults to list([Link]=N) where N is the number of
points in the data point pattern.
Edge correction Edge correction should be applied to the sufficient statistics of the
model, to reduce bias. The argument correction is the name of an edge correction
method. The default correction="border" specifies the border correction, in which
the quadrature window (the domain of integration of the pseudolikelihood) is obtained
by trimming off a margin of width rbord from the observation window of the data
pattern. Not all edge corrections are implemented (or implementable) for arbitrary
windows. Other options depend on the argument interaction, but these generally
include correction="periodic" (the periodic or toroidal edge correction in which
opposite edges of a rectangular window are identified) and correction="translate"
(the translation correction, see Baddeley 1998 and Baddeley and Turner 2000). For
pairwise interaction models there is also Ripley’s isotropic correction, identified by
correction="isotropic" or "Ripley".

Value
An object of class "ppm" describing a fitted point process model.
The fitted parameters can be obtained just by printing this object. Fitted spatial trends
can be extracted using the predict method for this object (see [Link]).
See [Link] for details of the format of this object.

Warnings
The implementation of the Huang-Ogata method is experimental.
432 ppm

See the comments above about the possible inefficiency and bias of the maximum pseudo-
likelihood estimator.
The accuracy of the Berman-Turner approximation to the pseudolikelihood depends on the
number of dummy points used in the quadrature scheme. The number of dummy points
should at least equal the number of data points.
The parameter values of the fitted model do not necessarily determine a valid point process.
Some of the point process models are only defined when the parameter values lie in a certain
subset. For example the Strauss process only exists when the interaction parameter γ is
less than or equal to 1, corresponding to a value of ppm()$theta[2] less than or equal
to 0. The current version of ppm maximises the pseudolikelihood without constraining the
parameters, and does not apply any checks for sanity after fitting the model.
The trend formula should not use any variable names beginning with the prefixes .mpl
or Interaction as these names are reserved for internal use. The data frame covariates
should have as many rows as there are points in Q. It should not contain variables called x,
y or marks as these names are reserved for the Cartesian coordinates and the marks.
If the model formula involves one of the functions poly(), bs() or ns() (e.g. applied
to spatial coordinates x and y), the fitted coefficients can be misleading. The resulting
fit is not to the raw spatial variates (x, x^2, x*y, etc.) but to a transformation of these
variates. The transformation is implemented by poly() in order to achieve better numerical
stability. However the resulting coefficients are appropriate for use with the transformed
variates, not with the raw variates. This affects the interpretation of the constant term in
the fitted model, logbeta. Conventionally, β is the background intensity, i.e. the value
taken by the conditional intensity function when all predictors (including spatial or “trend”
predictors) are set equal to 0. However the coefficient actually produced is the value that
the log conditional intensity takes when all the predictors, including the transformed spatial
predictors, are set equal to 0, which is not the same thing.
Worse still, the result of [Link] can be completely wrong if the trend formula contains
one of the functions poly(), bs() or ns(). This is a weakness of the underlying function
[Link].
If you wish to fit a polynomial trend, we offer an alternative to poly(), namely polynom(),
which avoids the difficulty induced by transformations. It is completely analogous to poly
except that it does not orthonormalise. The resulting coefficient estimates then have their
natural interpretation and can be predicted correctly. Numerical stability may be compro-
mised.
Values of the maximised pseudolikelihood are not comparable if they have been obtained
with different values of rbord.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A. and Turner, R. Practical maximum pseudolikelihood for spatial point patterns.
Australian and New Zealand Journal of Statistics 42 (2000) 283–322.
Berman, M. and Turner, T.R. Approximating point process likelihoods with GLIM. Applied
Statistics 41 (1992) 31–38.
Besag, J. Statistical analysis of non-lattice data. The Statistician 24 (1975) 179-195.
ppm 433

Diggle, P.J., Fiksel, T., Grabarnik, P., Ogata, Y., Stoyan, D. and Tanemura, M. On pa-
rameter estimation for pairwise interaction processes. International Statistical Review 62
(1994) 99-117.
Huang, F. and Ogata, Y. Improvements of the maximum pseudo-likelihood estimators in
various spatial statistical models. Journal of Computational and Graphical Statistics 8
(1999) 510-530.
Jensen, J.L. and Moeller, M. Pseudolikelihood for exponential family models of spatial point
processes. Annals of Applied Probability 1 (1991) 445–461.
Jensen, J.L. and Kuensch, H.R. On asymptotic normality of pseudo likelihood estimates for
pairwise interaction processes, Annals of the Institute of Statistical Mathematics 46 (1994)
475-486.

See Also
ppp, quadscheme, [Link], Poisson, Strauss, StraussHard, MultiStrauss, MultiStraussHard,
Softcore, DiggleGratton, Pairwise, PairPiece, AreaInter, Geyer, BadGey, LennardJones,
Saturated, OrdThresh, Ord

Examples
data(nztrees)
ppm(nztrees)
# fit the stationary Poisson process
# to point pattern 'nztrees'

## Not run:
Q <- quadscheme(nztrees)
ppm(Q)
# equivalent.

## End(Not run)

ppm(nztrees, ~ x)
# fit the nonstationary Poisson process
# with intensity function lambda(x,y) = exp(a + bx)
# where x,y are the Cartesian coordinates
# and a,b are parameters to be estimated

ppm(nztrees, ~ polynom(x,2))
# fit the nonstationary Poisson process
# with intensity function lambda(x,y) = exp(a + bx + cx^2)

## Not run:
library(splines)
ppm(nztrees, ~ bs(x,df=3))

## End(Not run)
# WARNING: do not use [Link]() on this result
# Fits the nonstationary Poisson process
# with intensity function lambda(x,y) = exp(B(x))
# where B is a B-spline with df = 3

ppm(nztrees, ~1, Strauss(r=10), rbord=10)


# Fit the stationary Strauss process with interaction range r=10
# using the border method with margin rbord=10
434 [Link]

ppm(nztrees, ~ x, Strauss(13), correction="periodic")


# Fit the nonstationary Strauss process with interaction range r=13
# and exp(first order potential) = activity = beta(x,y) = exp(a+bx)
# using the periodic correction.

# Huang-Ogata fit:
## Not run: ppm(nztrees, ~1, Strauss(r=10), method="ho")

# COVARIATES
#
X <- rpoispp(42)
weirdfunction <- function(x,y){ 10 * x^2 + 5 * sin(10 * y) }
#
# (a) covariate values as function
ppm(X, ~ y + Z, covariates=list(Z=weirdfunction))
#
# (b) covariate values in pixel image
Zimage <- [Link](weirdfunction, [Link]())
ppm(X, ~ y + Z, covariates=list(Z=Zimage))
#
# (c) covariate values in data frame
Q <- quadscheme(X)
xQ <- [Link](Q)
yQ <- [Link](Q)
Zvalues <- weirdfunction(xQ,yQ)
ppm(Q, ~ y + Z, covariates=[Link](Z=Zvalues))
# Note Q not X

## MULTITYPE POINT PROCESSES ###


data(lansing)
# Multitype point pattern --- trees marked by species

# fit stationary marked Poisson process


# with different intensity for each species
## Not run: ppm(lansing, ~ marks, Poisson())

# fit nonstationary marked Poisson process


# with different log-cubic trend for each species
## Not run: ppm(lansing, ~ marks * polynom(x,y,3), Poisson())

[Link] Class of Fitted Point Process Models

Description
A class ppm to represent a fitted stochastic model for a point process. The output of ppm.
[Link] 435

Details
An object of class ppm represents a stochastic point process model that has been fitted to
a point pattern dataset. Typically it is the output of the model fitter, ppm.
There are methods [Link], [Link], [Link], [Link] and [Link] for the
generic functions print, plot, predict, fitted and coef respectively.
See also (for example) Strauss to understand how to specify a point process model with
unknown parameters.
Information about the data (to which the model was fitted) can be extracted using [Link],
[Link] and [Link].
If you really need to get at the internals, a ppm object contains at least the following entries:

coef the fitted regular parameters (as returned by glm)


trend the trend formula or NULL
interaction the point process interaction family (an object of class "interact") or NULL
Q the quadrature scheme used
maxlogpl the maximised value of log pseudolikelihood
correction name of edge correction method used

See ppm for explanation of these concepts. The irregular parameters (e.g. the interaction
radius of the Strauss process) are encoded in the interaction entry. However see the
Warnings.

Warnings
The internal representation may change in the next few releases of the spatstat package.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, [Link], [Link], [Link], [Link], [Link].

Examples
data(cells)
fit <- ppm(cells, ~ x, Strauss(0.1), correction="periodic")
fit
coef(fit)
## Not run:
pred <- predict(fit)

## End(Not run)
pred <- predict(fit, ngrid=20, type="trend")
## Not run:
plot(fit)

## End(Not run)
436 ppp

ppp Create a Point Pattern

Description
Creates an object of class "ppp" representing a point pattern dataset in the two-dimensional
plane.

Usage
ppp(x,y, ..., window, marks, check=TRUE)

Arguments
x Vector of x coordinates of data points
y Vector of y coordinates of data points
window window of observation, an object of class "owin"
... arguments passed to owin to create the window, if window is missing
marks (optional) vector of mark values
check Logical flag indicating whether to check that all the (x, y) points lie inside
the specified window. Do not set this to FALSE unless you are sure that
this check is unnecessary.

Details
In the spatstat library, a point pattern dataset is described by an object of class "ppp".
This function creates such objects.
The vectors x and y must be numeric vectors of equal length. They are interpreted as the
cartesian coordinates of the points in the pattern.
A point pattern dataset is assumed to have been observed within a specific region of the
plane called the observation window. An object of class "ppp" representing a point pattern
contains information specifying the observation window. This window must always be
specified when creating a point pattern dataset; there is intentionally no default action of
“guessing” the window dimensions from the data points alone.
You can specify the observation window in several (mutually exclusive) ways:
ˆ xrange, yrange specify a rectangle with these dimensions;
ˆ poly specifies a polygonal boundary. If the boundary is a single polygon then poly
must be a list with components x,y giving the coordinates of the vertices. If the
boundary consists of several disjoint polygons then poly must be a list of such lists so
that poly[[i]]$x gives the x coordinates of the vertices of the ith boundary polygon.
ˆ mask specifies a binary pixel image with entries that are TRUE if the corresponding
pixel is inside the window.
ˆ window is an object of class "owin" (see [Link]) specifying the window.
The arguments xrange, yrange or poly or mask are passed to the window creator function
owin for interpretation. See owin for further details.
The argument window, if given, must be an object of class "owin". It is a full descrip-
tion of the window geometry, and could have been obtained from owin or [Link], or by
ppp 437

just extracting the observation window of another point pattern, or by manipulating such
windows. See owin or the Examples below.
The points with coordinates x and y must lie inside the specified window, in order to define
a valid object of this class. Any points which do not lie inside the window will be removed
from the point pattern, and a warning will be issued. See the section on Rejected Points.
The name of the unit of length for the x and y coordinates can be specified in the dataset,
using the argument unitname, which is passed to owin. See the examples below, or the
help file for owin.
The optional argument marks is given if the point pattern is marked, i.e. if each data point
carries additional information. For example, points which are classified into two or more
different types, or colours, may be regarded as having a mark which identifies which colour
they are. Data recording the locations and heights of trees in a forest can be regarded as a
marked point pattern where the mark is the tree height.
In the current implementation, marks must be a vector, of the same length as x and y, which
is interpreted so that marks[i] is the mark attached to the point (x[i],y[i]). If the mark
is a real number then marks should be a numeric vector, while if the mark takes only a
finite number of possible values (e.g. colours or types) then marks should be a factor.
See [Link] for a description of the class "ppp".
Users would normally invoke ppp to create a point pattern, but the functions [Link] and
scanpp may sometimes be convenient.

Value

An object of class "ppp" describing a point pattern in the two-dimensional plane (see
[Link]).

Rejected points

The points with coordinates x and y must lie inside the specified window, in order to define
a valid object of class "ppp". Any points which do not lie inside the window will be removed
from the point pattern, and a warning will be issued.
The rejected points are still accessible: they are stored as an attribute of the point pattern
called "rejects" (which is an object of class "ppp" containing the rejected points in a large
window). However, rejected points in a point pattern will be ignored by all other functions
except [Link].
To remove the rejected points altogether, use [Link]. To include the rejected points, you
will need to find a larger window that contains them, and use this larger window in a call
to ppp.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [Link], [Link], owin, [Link]


438 [Link]

Examples
# some arbitrary coordinates in [0,1]
x <- runif(20)
y <- runif(20)

# the following are equivalent


X <- ppp(x, y, c(0,1), c(0,1))
X <- ppp(x, y)
X <- ppp(x, y, window=owin(c(0,1),c(0,1)))

# specify that the coordinates are given in metres


X <- ppp(x, y, c(0,1), c(0,1), unitname=c("metre","metres"))

## Not run: plot(X)

# marks
m <- sample(1:2, 20, replace=TRUE)
m <- factor(m, levels=1:2)
X <- ppp(x, y, c(0,1), c(0,1), marks=m)
## Not run: plot(X)

# polygonal window
X <- ppp(x, y, poly=list(x=c(0,10,0), y=c(0,0,10)))
## Not run: plot(X)

# copy the window from another pattern


data(cells)
X <- ppp(x, y, window=cells$window)

[Link] Class of Point Patterns

Description
A class "ppp" to represent a two-dimensional point pattern. Includes information about
the window in which the pattern was observed. Optionally includes marks.

Details
This class represents a two-dimensional point pattern dataset. It specifies
ˆ the locations of the points
ˆ the window in which the pattern was observed
ˆ optionally, a “mark” attached to each point (extra information such as a type label).

If X is an object of type ppp, it contains the following elements:

x vector of x coordinates of data points


y vector of y coordinates of data points
n number of points
window window of observation
(an object of class owin)
marks optional vector of marks
[Link] 439

Users are strongly advised not to manipulate these entries directly.


Objects of class "ppp" may be created by the function ppp and converted from other types of
data by the function [Link]. Note that you must always specify the window of observation;
there is intentionally no default action of “guessing” the window dimensions from the data
points alone.
Standard point pattern datasets provided with the package include amacrine, betacells,
bramblecanes, cells, demopat, ganglia, lansing, longleaf, nztrees, redwood, simdat
and swedishpines. Use data(xxx) to access the dataset xxx.
Point patterns may be scanned from your own data files by scanpp or by using [Link]
and [Link].
They may be manipulated by the functions [.ppp and superimpose.
Point pattern objects can be plotted just by typing plot(X) which invokes the plot method
for point pattern objects, [Link]. See [Link] for further information.
There are also methods for summary and print for point patterns. Use summary(X) to see
a useful description of the data.
Patterns may be generated at random by runifpoint, rpoispp, rMaternI, rMaternII,
rSSI, rNeymanScott, rMatClust, and rThomas.
Most functions which are intended to operate on a window (of class owin) will, if presented
with a ppp object instead, automatically extract the window information from the point
pattern.

Warnings
The internal representation of marks is likely to change in the next release of this package.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, ppp, [Link], [.ppp

Examples
x <- runif(100)
y <- runif(100)
X <- ppp(x, y, c(0,1),c(0,1))
X
## Not run: plot(X)
mar <- sample(1:3, 100, replace=TRUE)
mm <- ppp(x, y, c(0,1), c(0,1), marks=mar)
## Not run: plot(mm)
# points with mark equal to 2
ss <- mm[ mm$marks == 2 , ]
## Not run: plot(ss)
# left half of pattern 'mm'
lu <- owin(c(0,0.5),c(0,1))
mmleft <- mm[ , lu]
## Not run: plot(mmleft)
## Not run:
# input data from file
440 pppdist

qq <- scanpp("[Link]", [Link]())

# interactively build a point pattern


plot([Link]())
X <- [Link](locator(10), [Link]())
plot(X)

## End(Not run)

pppdist Distance Between Two Point Patterns

Description
Given two point patterns, find the distance between them based on optimal point matching.

Usage
pppdist(X, Y, type = "spa", cutoff = 1, q = 1, matching = TRUE,
ccode = TRUE, precision = NULL, approximation = 10,
[Link] = FALSE, timelag = 0)

Arguments
X,Y Two point patterns (objects of class "ppp").
type A character string giving the type of distance to be computed. One of
"spa" (default), "ace" or "mat", indicating whether the algorithm should
find the optimal matching based on ”subpattern assignment”, ”assignment
only if cardinalities are equal” or ”mass transfer”. See details below.
cutoff The value > 0 at which interpoint distances are cut off.
q The order of the average that is applied to the interpoint distances. May
be Inf, in which case the maximum of the interpoint distances is taken.
matching Logical. Whether to return the optimal matching or only the associated
distance.
ccode Logical. If FALSE, R code is used which allows for higher precision, but is
much slower.
precision Index controlling accuracy of algorithm. The q-th powers of interpoint
distances will be rounded to the nearest multiple of 10^(-precision).
There is a sensible default which depends on ccode.
approximation If q = Inf, compute distance based on the optimal matching for the
corresponding distance of order approximation. Can be Inf, but this
makes computations extremely slow.
[Link] Logical. Whether to display a plot showing the iterative solution of the
restricted primal problem.
timelag Time lag, in seconds, between successive displays of the iterative solution
of the restricted primal problem.
pppdist 441

Details
Computes the distance between point patterns X and Y based on finding the matching
between them which minimizes the average of the distances between matched points (if
q=1), the maximum distance between matched points (if q=Inf), and in general the q-th
order average (i.e. the 1/qth power of the sum of the qth powers) of the distances between
matched points. Distances between matched points are Euclidean distances cut off at the
value of cutoff.
The parameter type controls the behaviour of the algorithm if the cardinalities of the point
patterns are different. For the type "spa" (subpattern assignment) the subpattern of the
point pattern with the larger cardinality n that is closest to the point pattern with the
smaller cardinality m is determined; then the q-th order average is taken over n values:
the m distances of matched points and n − m ”penalty distances” of value cutoff for the
unmatched points. For the type "ace" (assignment only if cardinalities equal) the matching
is empty and the distance returned is equal to cutoff if the cardinalities differ. For the type
"mat" (mass transfer) each point pattern is assumed to have total mass m (= the smaller
cardinality) distributed evenly among its points; the algorithm finds then the ”mass transfer
plan” that minimizes the q-th order weighted average of the distances, where the weights
are given by the transferred mass divided by m. The result is a fractional matching (each
match of two points has a weight in (0, 1]) with the minimized quantity as the associated
distance.
The computations for all three types rely heavily on a specialized primal-dual algorithm
(described in Luenberger (2003), Section 5.9) for Hitchcock’s problem of optimal transport
of a product from a number of suppliers to a number of (e.g. vending) locations. The C
implementation used by default can handle patterns with a few hundreds of points, but
should not be used with thousands of points. By setting [Link] = TRUE, some
insight in the working of the algorithm can be gained.
For moderate and large values of q there can be numerical issues based on the fact that the
q-th powers of distances are taken and some positive values enter the optimization algorithm
as zeroes because they are too small in comparison with the larger values. In this case the
number of zeroes introduced is given in a warning message, and it is possible then that the
matching obtained is not optimal and the associated distance is only a strict upper bound
of the true distance. As a general guideline (which can be very wrong in special situations)
a small number of zeroes (up to about 50 percent of the smaller point pattern cardinality
m) usually still results in the right matching, and the number can even be quite a bit higher
and usually still provides a highly accurate upper bound for the distance. These numerical
problems can be reduced by enforcing (much slower) R code via the argument ccode =
FALSE.
For q = Inf there is no fast algorithm available, which is why approximation is normally
used: for finding the optimal matching, q is set to the value of approximation. The result-
ing distance is still given as the maximum rather than the q-th order average in the cor-
responding distance computation. If approximation = Inf, approximation is suppressed
and a very inefficient exhaustive search for the best matching is performed.
The value of precision should normally not be supplied by the user. If ccode = TRUE,
this value is preset to the highest exponent of 10 that the C code still can handle (usually
9). If ccode = FALSE, the value is preset according to q (usually 15 if q is small), which
can sometimes be changed to obtain less severe warning messages.

Value
Normally an object of class pppmatching that contains detailed information about the pa-
rameters used and the resulting distance. See [Link] for details. If matching
442 pppdist

= FALSE, only the numerical value of the distance is returned.

Author(s)

Dominic Schuhmacher <dominic@[Link]> [Link]

References

Hitchcock F.L. (1941), The distribution of a product from several sources to numerous
localities, J. Math. Physics 20, 224–230.
Luenberger D.G. (2003). Linear and nonlinear programming. Second edition. Kluwer.

See Also
[Link] matchingdist

Examples
# equal cardinalities
X <- runifpoint(100)
Y <- runifpoint(100)
m <- pppdist(X, Y)
m
## Not run:
plot(m)

## End(Not run)

# differing cardinalities
X <- runifpoint(14)
Y <- runifpoint(10)
m1 <- pppdist(X, Y, type="spa")
m2 <- pppdist(X, Y, type="ace")
m3 <- pppdist(X, Y, type="mat")
summary(m1)
summary(m2)
summary(m3)
## Not run:
m1$matrix
m2$matrix
m3$matrix

## End(Not run)

# q = Inf
X <- runifpoint(10)
Y <- runifpoint(10)
mx1 <- pppdist(X, Y, q=Inf)$matrix
mx2 <- pppdist(X, Y, q=Inf, ccode=FALSE, approximation=50)$matrix
mx3 <- pppdist(X, Y, q=Inf, approximation=Inf)$matrix
((mx1 == mx2) && (mx2 == mx3))
# TRUE if approximations are good
pppmatching 443

pppmatching Create a Point Matching

Description
Creates an object of class "pppmatching" representing a matching of two planar point
patterns (objects of class "ppp").

Usage
pppmatching(X, Y, am, type = NULL, cutoff = NULL, q = NULL,
mdist = NULL)

Arguments
X,Y Two point patterns (objects of class "ppp").
am An X$n by Y$n matrix with entries ≥ 0 that specifies which points are
matched and with what weight; alternatively, an object that can be co-
erced to this form by [Link].
type A character string giving the type of the matching. One of "spa", "ace"
or "mat", or NULL for a generic or unknown matching.
cutoff, q Numerical values specifying the cutoff value > 0 for interpoint distances
and the order q ∈ [1, ∞] of the average that is applied to them. NULL if
not applicable or unknown.
mdist Numerical value for the distance to be associated with the matching.

Details
The argument am is interpreted as a ”generalized adjacency matrix”: if the [i,j]-th entry
is positive, then the i-th point of X and the j-th point of Y are matched and the value of
the entry gives the corresponding weight of the match. For an unweighted matching all the
weights should be set to 1.
The remaining arguments are optional and allow to save additional information about the
matching. See the help files for pppdist and matchingdist for details on the meaning of
these parameters.

Author(s)
Dominic Schuhmacher <dominic@[Link]> [Link]

See Also
[Link] matchingdist

Examples
# a random unweighted complete matching
X <- runifpoint(10)
Y <- runifpoint(10)
am <- r2dtable(1, rep(1,10), rep(1,10))[[1]]
# generates a random permutation matrix
444 [Link]

m <- pppmatching(X, Y, am)


summary(m)
m$matrix
## Not run:
plot(m)

## End(Not run)

# a random weighted complete matching


X <- runifpoint(7)
Y <- runifpoint(7)
am <- r2dtable(1, rep(10,7), rep(10,7))[[1]]/10
# generates a random doubly stochastic matrix
m2 <- pppmatching(X, Y, am)
summary(m2)
m2$matrix
## Not run:
# Note: plotting does currently not distinguish
# between different weights
plot(m2)

## End(Not run)

[Link] Class of Point Matchings

Description
A class "pppmatching" to represent a matching of two planar point patterns. Optionally
includes information about the construction of the matching and its associated distance
between the point patterns.

Details
This class represents a (possibly weighted and incomplete) matching between two planar
point patterns (objects of class "ppp").
A matching can be thought of as a bipartite weighted graph where the vertices are given
by the two point patterns and edges of positive weights are drawn each time a point of the
first point pattern is ”matched” with a point of the second point pattern.
If m is an object of type pppmatching, it contains the following elements

pp1, pp2 the two point patterns to be matched (vertices)


matrix a matrix specifying which points are matched
and with what weights (edges)
type (optional) a character string for the type of
the matching (one of "spa", "ace" or "mat")
cutoff (optional) cutoff value for interpoint distances
q (optional) the order for taking averages of
interpoint distances
distance (optional) the distance associated with the matching

The element matrix is a ”generalized adjacency matrix”. The numbers of rows and columns
ppx 445

match the cardinalities of the first and second point patterns, respectively. The [i,j]-th
entry is positive if the i-th point of X and the j-th point of Y are matched (zero otherwise)
and its value then gives the corresponding weight of the match. For an unweighted matching
all the weights are set to 1.
The optional elements are for saving details about matchings in the context of optimal point
matching techniques. type can be one of "spa" (for ”subpattern assignment”), "ace" (for
”assignment only if cardinalities differ”) or "mat" (for ”mass transfer”). cutoff is a positive
numerical value that specifies the maximal interpoint distance and q is a value in [1, ∞]
that gives the order of the average applied to the interpoint distances. See the help files for
pppdist and matchingdist for detailed information about these elements.
Objects of class "pppmatching" may be created by the function pppmatching, and are most
commonly obtained as output of the function pppdist. There are methods plot, print
and summary for this class.

Author(s)
Dominic Schuhmacher <dominic@[Link]> [Link]

See Also
matchingdist pppmatching

Examples
# a random complete unweighted matching
X <- runifpoint(10)
Y <- runifpoint(10)
am <- r2dtable(1, rep(1,10), rep(1,10))[[1]]
# generates a random permutation matrix
m <- pppmatching(X, Y, am)
summary(m)
m$matrix
## Not run:
plot(m)

## End(Not run)

# an optimal complete unweighted matching


m2 <- pppdist(X,Y)
summary(m2)
m2$matrix
## Not run:
plot(m2)

## End(Not run)

ppx Multidimensional Space-Time Point Pattern

Description
Creates a multidimensional space-time point pattern with any kind of coordinates and
marks.
446 ppx

Usage
ppx(data, domain=NULL, spatial = NULL, temporal = NULL)

Arguments
data The coordinates and marks of the points. A [Link] or hyperframe.
domain Optional. The space-time domain containing the points. An object in
some appropriate format, or NULL.
spatial Character vector giving the names of the columns of data that should be
interpreted as spatial coordinates.
temporal Character vector giving the names of the columns of data that should be
interpreted as temporal coordinates.

Details
An object of class "ppx" represents a marked point pattern in multidimensional space
and/or time. There may be any number of spatial coordinates, any number of temporal
coordinates, and any number of mark variables. The individual marks may be atomic
(numeric values, factor values, etc) or objects of any kind.
The argument data should contain the coordinates and marks of the points. It should be
a [Link] or more generally a hyperframe (see hyperframe) with one row of data for
each point.
Each column of data is either a spatial coordinate, a temporal coordinate, or a mark vari-
able. The argument spatial determines which columns are interpreted as spatial coordi-
nates: if it is present, spatial should be a character vector matching the names of columns
of data. Similarly the argument temporal determines which columns are interpreted as
temporal coordinates.
If both spatial and temporal are missing or NULL then it is assumed that all columns of
data are spatial coordinates. If temporal is missing or NULL then it is assumed that no
columns of data are temporal coordinates.

Value
An object of class "ppx".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
pp3

Examples
df <- [Link](x=runif(4),y=runif(4),z=runif(4))
X <- ppx(data=df, t="z")
X

val <- runif(4)


E <- lapply(val, function(s) { rpoispp(s) })
[Link] 447

hf <- hyperframe(t=val, e=[Link](E))


Z <- ppx(data=hf, domain=c(0,1))
Z

[Link] Prediction from a Fitted Cluster Point Process Model

Description
Given a fitted cluster point process model, this function computes the fitted intensity of
the model.

Usage
## S3 method for class 'kppm':
predict(object, ...)

Arguments
object Fitted cluster point process model. An object of class "kppm".
... Arguments passed to [Link].

Details
This is a method for the generic function predict. The argument object should be a
cluster point process model (object of class "kppm") obtained using the function kppm.
Prediction computes the intensity of the fitted model. The algorithm calls [Link] to
compute the intensity.

Value
Usually a pixel image (object of class "im").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
kppm, [Link], [Link]

Examples
data(redwood)
fit <- kppm(redwood, ~x, "Thomas")
v <- predict(fit)
448 [Link]

[Link] Prediction from a Fitted Point Process Model

Description
Given a fitted point process model obtained by ppm, evaluate the spatial trend or the
conditional intensity of the model at new locations.

Usage
## S3 method for class 'ppm':
predict(object, window, ngrid=NULL, locations=NULL,
covariates=NULL, type="trend", ..., check=TRUE, repair=TRUE)

Arguments
object A fitted point process model, typically obtained from the model-fitting
algorithm ppm. An object of class "ppm" (see [Link]).
window A window (object of class "owin") delimiting the locations where predic-
tions should be computed. Defaults to the window of the original data
used to fit the model object.
ngrid Dimensions of a rectangular grid of locations inside window where the pre-
dictions should be computed. An integer, or an integer vector of length
2, specifying the number of grid points in the y and x directions. (Incom-
patible with locations)
locations Data giving the x, y coordinates (and marks, if required) at which predic-
tions should be computed. Either a data frame or a binary image mask.
(Incompatible with ngrid)
covariates Values of external covariates required by the model. Either a data frame
or a list of images. See Details.
type Character string. Indicates which property of the fitted model should be
predicted. Options are "trend" for the spatial trend, "cif" or "lambda"
for the conditional intensity, and "se" for the standard error of the fitted
spatial trend.
... Ignored.
check Logical value indicating whether to check the internal format of object.
If there is any possibility that this object has been restored from a dump
file, or has otherwise lost track of the environment where it was originally
computed, set check=TRUE.
repair Logical value indicating whether to repair the internal format of object,
if it is found to be damaged.

Details
This function computes the spatial trend and the conditional intensity of a fitted spatial
point process model, and the standard error of the estimate of spatial trend. See Baddeley
and Turner (2000) for explanation and examples.
Given a point pattern dataset, we may fit a point process model to the data using the
model-fitting algorithm ppm. This returns an object of class "ppm" representing the fitted
[Link] 449

point process model (see [Link]). The parameter estimates in this fitted model can
be read off simply by printing the ppm object. The spatial trend and conditional intensity
of the fitted model are evaluated using this function [Link].
The default action is to create a rectangular grid of points in the observation window of the
data point pattern, and evaluate the spatial trend at these locations.
The argument type specifies the values that are computed:

If type="trend": the “spatial trend” of the fitted model is evaluated at each required
spatial location u.
If type="cif": the conditional intensity λ(u, X) of the fitted model is evaluated at each
required spatial location u, with respect to the data point pattern X.
If type="se": the estimated (asymptotic) standard error of the fitted spatial trend is eval-
uated at each required spatial location u. This is available only for Poisson point
process models.

Note that the “spatial trend” is the same as the intensity function if the fitted model object
is a Poisson point process. However, if the model is not a Poisson process, then the “spatial
trend” is the (exponentiated) first order potential and not the intensity of the process. [For
example if we fit the stationary Strauss process with parameters β and γ, then the spatial
trend is constant and equal to β, while the intensity is a smaller value that is not easy to
compute. ]
The spatial locations where predictions are required, are determined by the (incompatible)
arguments ngrid and locations.

ˆ If the argument ngrid is present, then predictions are performed at a rectangular grid
of locations in the window window. The result of prediction will be a pixel image or
images.
ˆ If locations is present, then predictions will be performed at the spatial locations
given by this dataset. These may be an arbitrary list of spatial locations, or they may
be a rectangular grid. The result of prediction will be either a numeric vector or a
pixel image or images.
ˆ If neither ngrid nor locations is given, then ngrid is assumed. It defaults to 50.

The argument locations may be a data frame or list specifying arbitrary locations, or a
binary image mask (an object of class "owin" with type "mask") specifying (a subset of) a
rectangular grid of locations.
If locations is a data frame or list, then it must contain vectors locations$x and
locations$y specifying the x, y coordinates of the prediction locations. Additionally, if the
model is a marked point process, then locations must also contain a factor locations$marks
specifying the marks of the prediction locations. These vectors must have equal length. The
result of prediction will be a vector of predicted values, of the same length.
If locations is a binary image mask, then prediction will be performed at each pixel in this
binary image where the pixel value is TRUE (in other words, at each pixel that is inside the
window). If the fitted model is an unmarked point process, then the result of prediction will
be an image. If the fitted model is a marked point process, then prediction will be performed
for each possible value of the mark at each such location, and the result of prediction will
be a list of images, one for each mark value.
The argument covariates gives the values of any spatial covariates at the prediction lo-
cations. If the trend formula in the fitted model involves spatial covariates (other than the
Cartesian coordinates x, y) then covariates is required.
450 [Link]

The format and use of covariates are analogous to those of the argument of the same
name in ppm. It is either a data frame or a list of images.
If covariates is a list of images, then the names of the entries should correspond to the
names of covariates in the model formula trend. Each entry in the list must be an image
object (of class "im", see [Link]). The software will look up the pixel values of each
image at the quadrature points.
If covariates is a data frame, then the ith row of covariates is assumed to contain covari-
ate data for the ith location. When locations is a data frame, this just means that each
row of covariates contains the covariate data for the location specified in the correspond-
ing row of locations. When locations is a binary image mask, the row covariates[i,]
must correspond to the location x[i],y[i] where x = [Link](raster.x(locations))
and y = [Link](raster.y(locations)).
Note that if you only want to use prediction in order to generate a plot of the predicted
values, it may be easier to use [Link] which calls this function and plots the results.

Value
If locations is given and is a data frame: a vector of predicted values for the spatial
locations (and marks, if required) given in locations.
If ngrid is given, or if locations is given and is a binary image mask: If object is an
unmarked point process, the result is a pixel image object (of class "im", see [Link])
containing the predictions. If object is a multitype point process, the result is a list of
pixel images, containing the predictions for each type at the same grid of locations.
The “predicted values” are either values of the spatial trend (if type="trend"), values of
the conditional intensity (if type="cif" or type="lambda"), or estimates of standard error
for the fitted spatial trend (if type="se").

Warnings
The current implementation invokes [Link] so that prediction is wrong if the
trend formula in object involves terms in ns(), bs() or poly(). This is a weakness of
[Link] itself!
Error messages may be very opaque, as they tend to come from deep in the workings of
[Link]. If you are passing the covariates argument and the function crashes, it is
advisable to start by checking that all the conditions listed above are satisfied.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A. and Turner, R. Practical maximum pseudolikelihood for spatial point patterns.
Australian and New Zealand Journal of Statistics 42 (2000) 283–322.
Berman, M. and Turner, T.R. Approximating point process likelihoods with GLIM. Applied
Statistics 41 (1992) 31–38.

See Also
ppm, [Link], [Link], [Link], [Link]
[Link] 451

Examples
data(cells)
m <- ppm(cells, ~ polynom(x,y,2), Strauss(0.05))
trend <- predict(m, type="trend")
## Not run:
image(trend)
points(cells)

## End(Not run)
cif <- predict(m, type="cif")
## Not run:
persp(cif)

## End(Not run)
data(japanesepines)
mj <- ppm(japanesepines, ~harmonic(x,y,2))
se <- predict(mj, type="se")

# prediction at arbitrary locations


predict(mj, locations=[Link](x=0.3, y=0.4))

X <- runifpoint(5, japanesepines$window)


predict(mj, locations=X)
predict(mj, locations=X, type="se")

# multitype
data(amacrine)
ma <- ppm(amacrine, ~marks,
MultiStrauss(c("off","on"),matrix(0.06, 2, 2)))
predict(ma)
predict(ma, type="cif")
predict(ma, locations=[Link](x=0.8, y=0.5,marks="on"), type="cif")

[Link] Print Brief Details of an Image

Description
Prints a very brief description of a pixel image object.

Usage
## S3 method for class 'im':
print(x, ...)

Arguments
x Pixel image (object of class "im").
... Ignored.
452 [Link]

Details
A very brief description of the pixel image x is printed.
This is a method for the generic function print.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
print, [Link], [Link]

Examples
data(letterR)
U <- [Link](letterR)
U

[Link] Print Brief Details of a Spatial Window

Description
Prints a very brief description of a window object.

Usage
## S3 method for class 'owin':
print(x, ...)

Arguments
x Window (object of class "owin").
... Ignored.

Details
A very brief description of the window x is printed.
This is a method for the generic function print.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
print, [Link], [Link]
[Link] 453

Examples
owin() # the unit square

data(demopat)
W <- demopat$window
W # just says it is polygonal
[Link](W) # just says it is a binary image

[Link] Print a Fitted Point Process Model

Description

Default print method for a fitted point process model.

Usage

## S3 method for class 'ppm':


print(x,...)

Arguments

x A fitted point process model, typically obtained from the model-fittingg


algorithm ppm. An object of class "ppm".
... Ignored.

Details

This is the print method for the class "ppm". It prints information about the fitted model
in a sensible format.
See [Link] for details of the class "ppm".

Value

none.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

ppm, [Link], [Link], [Link]


454 [Link]

Examples
## Not run:
data(cells)
Q <- quadscheme(cells)
m <- ppm(Q, ~1, Strauss(0.05))
m

## End(Not run)

[Link] Print Brief Details of a Point Pattern Dataset

Description
Prints a very brief description of a point pattern dataset.

Usage
## S3 method for class 'ppp':
print(x, ...)

Arguments
x Point pattern (object of class "ppp").
... Ignored.

Details
A very brief description of the point pattern x is printed.
This is a method for the generic function print.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
print, [Link], [Link]

Examples
data(cells) # plain vanilla point pattern
cells

data(lansing) # multitype point pattern


lansing

data(longleaf) # numeric marks


longleaf

data(demopat) # weird polygonal window


demopat
[Link] 455

[Link] Print Brief Details of a Line Segment Pattern Dataset

Description
Prints a very brief description of a line segment pattern dataset.

Usage
## S3 method for class 'psp':
print(x, ...)

Arguments
x Line segment pattern (object of class "psp").
... Ignored.

Details
A very brief description of the line segment pattern x is printed.
This is a method for the generic function print.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
print, [Link], [Link]

Examples
a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
a

[Link] Print a Quadrature Scheme

Description
print method for a quadrature scheme.

Usage
## S3 method for class 'quad':
print(x,...)
456 profilepl

Arguments
x A quadrature scheme object, typically obtained from quadscheme. An
object of class "quad".
... Ignored.

Details
This is the print method for the class "quad". It prints simple information about the
quadrature scheme.
See [Link] for details of the class "quad".

Value
none.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
quadscheme, [Link], [Link], [Link]

Examples
data(cells)
Q <- quadscheme(cells)
Q

profilepl Profile Maximum Pseudolikelihood

Description
Fits point process models by profile maximum pseudolikelihood

Usage
profilepl(s, f, ..., rbord = NULL, verbose = TRUE)

Arguments
s Data frame containing values of the irregular parameters over which the
profile pseudolikelihood will be computed.
f Function (such as Strauss) that generates an interpoint interaction ob-
ject, given the values of the irregular parameters.
... Data passed to ppm to fit the model.
rbord Radius for border correction (same for all models). If omitted, this will
be computed from the interactions.
verbose Logical flag indicating whether to print progress reports.
profilepl 457

Details
The model-fitting function ppm fits point process models to point pattern data. However,
only the ‘regular’ parameters of the model can be fitted by ppm. The model may also depend
on ‘irregular’ parameters that must be fixed in any call to ppm.
This function profilepl is a wrapper which finds the values of the irregular parameters
that give the best fit. It uses the method of maximum profile pseudolikelihood.
The argument f would typically be one of the functions Strauss, StraussHard, Softcore,
DiggleGratton, Geyer, LennardJones or OrdThresh. For the moment, assume this is so.
The argument s must be a data frame whose columns contain values of the irregular pa-
rameters. The names of the columns of s must match the argument names of f.
To apply the method of profile maximum pseudolikelihood, each row of s will be taken
in turn; the parameter values in this row will be passed to f, resulting in an interaction
object. Then ppm will be applied to the data ... using this interaction; this results in a
fitted point process model. The value of the log pseudolikelihood from this model is stored.
After all rows of s have been processed in this way, the row giving the maximum value of
log pseudolikelihood will be found.
The object returned by profilepl contains the profile pseudolikelihood function, the best
fitting model, and other data. It can be plotted (yielding a plot of the log pseudolikelihood
values against the irregular parameters) or printed (yielding information about the best
fitting values of the irregular parameters).
In general, f may be any function that will return an interaction object (object of class
"interact") that can be used in a call to ppm. Each argument of f must be a single value.

Value
An object of class "profilepl". There are methods for plot and print for this class.
The components of the object include

fit Best-fitting model


param The data frame s

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
data(cells)

# one irregular parameter


s <- [Link](r=seq(0.05,0.15, by=0.01))

ps <- profilepl(s, Strauss, cells)


ps
plot(ps)

# two irregular parameters


s <- [Link](r=seq(0.05,0.15, by=0.01),sat=1:3)

pg <- profilepl(s, Geyer, cells)


pg
458 progressreport

plot(pg)
## Not run:
pg$fit

## End(Not run)

progressreport Print Progress Reports

Description
Prints Progress Reports during a loop or iterative calculation.

Usage
progressreport(i, n, every = max(1, ceiling(n/100)), nperline =
min(charsperline, every * ceiling(charsperline/(every + 3))),
charsperline = 60, style=[Link]("progress"))

Arguments
i Integer. The current iteration number (from 1 to n).
n Integer. The (maximum) number of iterations to be computed.
every Optional integer. The number of iterations between successive reports.
nperline Optional integer. The maximum number of reports to be printed per line
of output.
charsperline Optional integer. The number of characters in a line of output.
style Character string determining the style of display. See Details.

Details
This is a convenient function for reporting progress during an iterative sequence of calcula-
tions or a suite of simulations.
If style="txtbar" then txtProgressBar is used to represent progress as a bar made of
text characters in the R interpreter window.
If style="tty", then progress reports are printed using cat. This only seems to work well
under Linux.

Value
Null.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
for(i in 1:40) progressreport(i, 40)
project2segment 459

project2segment Move Point To Nearest Line

Description
Given a point pattern and a line segment pattern, this function moves each point to the
closest location on a line segment.

Usage
project2segment(X, Y)

Arguments
X A point pattern (object of class "ppp").
Y A line segment pattern (object of class "psp").

Details
For each point x in the point pattern X, this function finds the closest line segment y
in the line segment pattern Y. It then ‘projects’ the point x onto the line segment y by
finding the position z along y which is closest to x. This position z is returned, along with
supplementary information.

Value
A list with the following components. Each component has length equal to the number of
points in X, and its entries correspond to the points of X.

Xproj Point pattern (object of class "ppp" containing the projected points.
mapXY Integer vector identifying the nearest segment to each point.
d Numeric vector of distances from each point of X to the corresponding
projected point.
tp Numeric vector giving the scaled parametric coordinate 0 ≤ tp ≤ 1 of the
position of the projected point along the segment.

For example suppose mapXY[2] = 5 and tp[2] = 0.33. Then Y[5] is the line segment
lying closest to X[2]. The projection of the point X[2] onto the segment Y[5] is the point
Xproj[2], which lies one-third of the way between the first and second endpoints of the
line segment Y[5].

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
nearestsegment for a faster way to determine which segment is closest to each point.
460 psp

Examples
X <- rstrat(square(1), 5)
Y <- [Link](matrix(runif(20), 5, 4), window=owin())
plot(Y, lwd=3, col="green")
plot(X, add=TRUE, col="red", pch=16)
v <- project2segment(X,Y)
Xproj <- v$Xproj
plot(Xproj, add=TRUE, pch=16)
arrows(X$x, X$y, Xproj$x, Xproj$y, angle=10, length=0.15, col="red")

psp Create a Line Segment Pattern

Description
Creates an object of class "psp" representing a line segment pattern in the two-dimensional
plane.

Usage
psp(x0,y0, x1, y1, window, marks=NULL,
check=[Link]("checksegments"))

Arguments
x0 Vector of x coordinates of first endpoint of each segment
y0 Vector of y coordinates of first endpoint of each segment
x1 Vector of x coordinates of second endpoint of each segment
y1 Vector of y coordinates of second endpoint of each segment
window window of observation, an object of class "owin"
marks (optional) vector of mark values
check Logical value indicating whether to check that the line segments lie inside
the window.

Details
In the spatstat library, a spatial pattern of line segments is described by an object of class
"psp". This function creates such objects.
The vectors x0, y0, x1 and y1 must be numeric vectors of equal length. They are interpreted
as the cartesian coordinates of the endpoints of the line segments.
A line segment pattern is assumed to have been observed within a specific region of the
plane called the observation window. An object of class "psp" representing a point pattern
contains information specifying the observation window. This window must always be
specified when creating a point pattern dataset; there is intentionally no default action of
“guessing” the window dimensions from the data points alone.
The argument window must be an object of class "owin". It is a full description of the
window geometry, and could have been obtained from owin or [Link], or by just extracting
the observation window of another dataset, or by manipulating such windows. See owin or
the Examples below.
[Link] 461

The optional argument marks is given if the line segment pattern is marked, i.e. if each line
segment carries additional information. For example, line segments which are classified into
two or more different types, or colours, may be regarded as having a mark which identifies
which colour they are.
In the current implementation, marks must be a vector, of the same length as x0, which is
interpreted so that marks[i] is the mark attached to the ith line segment. If the mark is
a real number then marks should be a numeric vector, while if the mark takes only a finite
number of possible values (e.g. colours or types) then marks should be a factor.
See [Link] for a description of the class "psp".
Users would normally invoke psp to create a line segment pattern, and the function [Link]
to convert data in another format into a line segment pattern.

Value
An object of class "psp" describing a line segment pattern in the two-dimensional plane
(see [Link]).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link], owin, [Link]

Examples
X <- psp(runif(20), runif(20), runif(20), runif(20), window=owin())

[Link] Class of Line Segment Patterns

Description
A class "psp" to represent a spatial pattern of line segments in the plane. Includes infor-
mation about the window in which the pattern was observed. Optionally includes marks.

Details
An object of this class represents a two-dimensional pattern of line segments. It specifies
ˆ the locations of the line segments (both endpoints)
ˆ the window in which the pattern was observed
ˆ optionally, a “mark” attached to each line segment (extra information such as a type
label).
If X is an object of type psp, it contains the following elements:

ends data frame with entries x0, y0, x1, y1


giving coordinates of segment endpoints
window window of observation
462 [Link]

(an object of class owin)


n number of line segments
marks optional vector of marks

Users are strongly advised not to manipulate these entries directly.


Objects of class "psp" may be created by the function psp and converted from other types of
data by the function [Link]. Note that you must always specify the window of observation;
there is intentionally no default action of “guessing” the window dimensions from the line
segments alone.
Subsets of a line segment pattern may be obtained by the functions [.psp and [Link].
Line segment pattern objects can be plotted just by typing plot(X) which invokes the plot
method for line segment pattern objects, [Link]. See [Link] for further information.
There are also methods for summary and print for line segment patterns. Use summary(X)
to see a useful description of the data.
Utilities for line segment patterns include [Link] (to compute the midpoints of each
segment), [Link], (to compute the length of each segment), [Link], (to compute
the angle of orientation of each segment), and [Link] to compute the distance map
of a line segment pattern.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
psp, [Link], [.psp

Examples
# creating
a <- psp(runif(20),runif(20),runif(20),runif(20), window=owin())
# converting from other formats
a <- [Link](matrix(runif(80), ncol=4), window=owin())
a <- [Link]([Link](x0=runif(20), y0=runif(20),
x1=runif(20), y1=runif(20)), window=owin())
# clipping
w <- owin(c(0.1,0.7), c(0.2, 0.8))
b <- [Link](a, w)
b <- a[w]
# the last two lines are equivalent.

[Link] Q-Q Plot of Residuals from Fitted Point Process Model

Description
Given a point process model fitted to a point pattern, produce a Q-Q plot based on residuals
from the model.
[Link] 463

Usage
[Link](fit, nsim=100, expr=NULL, ..., type="raw",
style="mean", fast=TRUE, verbose=TRUE, [Link]=TRUE,
dimyx=NULL, nrep=if(fast) 5e4 else 1e5,
control=list(nrep=nrep,expand=[Link](fit),
periodic=([Link](fit)$type=="rectangle")),
saveall=FALSE,
monochrome=FALSE,
limcol=if(monochrome) "black" else "red",
maxerr=max(100, ceiling(nsim/10)),
check=TRUE, repair=TRUE)

Arguments
fit The fitted point process model, which is to be assessed using the Q-Q
plot. An object of class "ppm". Smoothed residuals obtained from this
fitted model will provide the “data” quantiles for the Q-Q plot.
nsim The number of simulations from the “reference” point process model.
expr Determines the simulation mechanism which provides the “theoretical”
quantiles for the Q-Q plot. See Details.
... Arguments passed to [Link] influencing the computation of resid-
uals.
type String indicating the type of residuals or weights to be used. Current
options are "eem" for the Stoyan-Grabarnik exponential energy weights,
"raw" for the raw residuals, "inverse" for the inverse-lambda residuals,
and "pearson" for the Pearson residuals. A partial match is adequate.
style Character string controlling the type of Q-Q plot. Options are "classical"
and "mean". See Details.
fast Logical flag controlling the speed and accuracy of computation. Use
fast=TRUE for interactive use and fast=FALSE for publication standard
plots. See Details.
verbose Logical flag controlling whether the algorithm prints progress reports dur-
ing long computations.
[Link] Logical flag controlling whether the function produces a plot or simply
returns a value (silently).
dimyx Dimensions of the pixel grid on which the smoothed residual field will be
calculated. A vector of two integers.
nrep If control is absent, then nrep gives the number of iterations of the
Metropolis-Hastings algorithm that should be used to generate one simu-
lation of the fitted point process.
control List of parameters controlling the Metropolis-Hastings algorithm rmh which
generates each simulated realisation from the model (unless the model is
Poisson). This list becomes the argument control of [Link]. It
overrides nrep.
saveall Logical flag indicating whether to save all the intermediate calculations.
monochrome Logical flag indicating whether the plot should be in black and white
(monochrome=TRUE), or in colour (monochrome=FALSE).
limcol String. The colour to be used when plotting the 95-percent limit curves.
464 [Link]

maxerr Maximum number of failures tolerated while generating simulated reali-


sations. See Details.
check Logical value indicating whether to check the internal format of fit. If
there is any possibility that this object has been restored from a dump
file, or has otherwise lost track of the environment where it was originally
computed, set check=TRUE.
repair Logical value indicating whether to repair the internal format of fit, if
it is found to be damaged.

Details
This function generates a Q-Q plot of the residuals from a fitted point process model. It
is an addendum to the suite of diagnostic plots produced by the function [Link],
kept separate because it is computationally intensive. The quantiles of the theoretical
distribution are estimated by simulation.
In classical statistics, a Q-Q plot of residuals is a useful diagnostic for checking the dis-
tributional assumptions. Analogously, in spatial statistics, a Q-Q plot of the (smoothed)
residuals from a fitted point process model is a useful way to check the interpoint interaction
part of the model (Baddeley et al, 2005). The systematic part of the model (spatial trend,
covariate effects, etc) is assessed using other plots made by [Link].
The argument fit represents the fitted point process model. It must be an object of
class "ppm" (typically produced by the maximum pseudolikelihood fitting algorithm ppm).
Residuals will be computed for this fitted model using [Link], and the residuals
will be kernel-smoothed to produce a “residual field”. The values of this residual field will
provide the “data” quantiles for the Q-Q plot.
The argument expr is not usually specified. It provides a way to modify the “theoretical”
or “reference” quantiles for the Q-Q plot.
In normal usage we set expr=NULL. The default is to generate nsim simulated realisations
of the fitted model fit, re-fit this model to each of the simulated patterns, evaluate the
residuals from these fitted models, and use the kernel-smoothed residual field from these
fitted models as a sample from the reference distribution for the Q-Q plot.
In advanced use, expr may be an expression. It will be re-evaluated nsim times, and
should include random computations so that the results are not identical each time. The
result of evaluating expr should be either a point pattern (object of class "ppp") or a fitted
point process model (object of class "ppm"). If the value is a point pattern, then the original
fitted model fit will be fitted to this new point pattern using [Link], to yield another
fitted model. Smoothed residuals obtained from these nsim fitted models will yield the
“theoretical” quantiles for the Q-Q plot.
Simulation is performed (if expr=NULL) using the Metropolis-Hastings algorithm rmh. Each
simulated realisation is the result of running the Metropolis-Hastings algorithm from an
independent random starting state each time. The iterative and termination behaviour of
the Metropolis-Hastings algorithm are governed by the argument control. See rmhcontrol
for information about this argument. As a shortcut, the argument nrep determines the
number of Metropolis-Hastings iterations used to generate each simulated realisation, if
control is absent.
By default, simulations are generated in an expanded window. Use the argument control
to change this, as explained in the section on Warning messages.
The argument type selects the type of residual or weight that will be computed. For options,
see [Link].
[Link] 465

The argument style determines the type of Q-Q plot. It is highly recommended to use the
default, style="mean".

style="classical" The quantiles of the residual field for the data (on the y axis) are
plotted against the quantiles of the pooled simulations (on the x axis). This plot is
biased, and therefore difficult to interpret, because of strong autocorrelations in the
residual field and the large differences in sample size.
style="mean" The order statistics of the residual field for the data are plotted against the
sample means, over the nsim simulations, of the corresponding order statistics of the
residual field for the simulated datasets. Dotted lines show the 2.5 and 97.5 percentiles,
over the nsim simulations, of each order statistic.

The argument fast is a simple way to control the accuracy and speed of computation. If
fast=FALSE, the residual field is computed on a fine grid of pixels (by default 100 by 100
pixels, see below) and the Q-Q plot is based on the complete set of order statistics (usually
10,000 quantiles). If fast=TRUE, the residual field is computed on a coarse grid (at most
40 by 40 pixels) and the Q-Q plot is based on the percentiles only. This is about 7 times
faster. It is recommended to use fast=TRUE for interactive data analysis and fast=FALSE
for definitive plots for publication.
The argument dimyx gives full control over the resolution of the pixel grid used to calculate
the smoothed residuals. Its interpretation is the same as the argument dimyx to the function
[Link]. Note that dimyx[1] is the number of pixels in the y direction, and dimyx[2] is the
number in the x direction. If dimyx is not present, then the default pixel grid dimensions
are controlled by [Link]("npixel").
Since the computation is so time-consuming, [Link] returns a list containing all the
data necessary to re-display the Q-Q plot. It is advisable to assign the result of [Link]
to something (or use .[Link] if you forgot to.) The return value is an object of class
"qqppm". There are methods for [Link] and [Link]. See the Examples.
The argument saveall is usually set to FALSE. If saveall=TRUE, then the intermediate
results of calculation for each simulated realisation are saved and returned. The return
value includes a 3-dimensional array sim containing the smoothed residual field images for
each of the nsim realisations. When saveall=TRUE, the return value is an object of very
large size, and should not be saved on disk.
Errors may occur during the simulation process, because random data are generated. For
example:

ˆ one of the simulated patterns may be empty.


ˆ one of the simulated patterns may cause an error in the code that fits the point process
model.
ˆ the user-supplied argument expr may have a bug.

Empty point patterns do not cause a problem for the code, but they are reported. Other
problems that would lead to a crash are trapped; the offending simulated data are discarded,
and the simulation is retried. The argument maxerr determines the maximum number of
times that such errors will be tolerated (mainly as a safeguard against an infinite loop).

Value
An object of class "qqppm" containing the information needed to reproduce the Q-Q plot.
Entries x and y are numeric vectors containing quantiles of the simulations and of the data,
respectively.
466 [Link]

Side Effects
Produces a Q-Q plot if [Link] is TRUE.

Warning messages
A warning message will be issued if any of the simulations trapped an error (a potential
crash).
A warning message will be issued if all, or many, of the simulated point patterns are empty.
This usually indicates a problem with the simulation procedure.
The default behaviour of [Link] is to simulate patterns on an expanded window
(specified through the argument control) in order to avoid edge effects. The model’s
trend is extrapolated over this expanded window. If the trend is strongly inhomogeneous,
the extrapolated trend may have very large (or even infinite) values. This can cause the
simulation algorithm to produce empty patterns.
The only way to suppress this problem entirely is to prohibit the expansion of the window,
by setting the control argument to something like control=list(nrep=1e6, expand=1).
Here expand=1 means there will be no expansion. See rmhcontrol for more information
about the argument control.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial
point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.
Stoyan, D. and Grabarnik, P. (1991) Second-order characteristics for stochastic structures
connected with Gibbs point processes. Mathematische Nachrichten, 151:95–100.

See Also
[Link], lurking, [Link], eem, [Link], ppm, rmh, rmhcontrol

Examples
data(cells)

fit <- ppm(cells, ~1, Poisson())


[Link](fit) # no suggestion of departure from stationarity
## Not run: [Link](fit, 80) # strong evidence of non-Poisson interaction

## Not run:
[Link](fit, type="pearson")
[Link](fit, type="pearson")

## End(Not run)

###########################################
## oops, I need the plot coordinates
mypreciousdata <- .[Link]
[Link] 467

## Not run: mypreciousdata <- [Link](fit, type="pearson")

plot(mypreciousdata)

######################################################
# Q-Q plots based on fixed n
# The above QQ plots used simulations from the (fitted) Poisson process.
# But I want to simulate conditional on n, instead of Poisson
# Do this by setting rmhcontrol(p=1)
fixit <- list(p=1)
## Not run: [Link](fit, 100, control=fixit)

######################################################
# Inhomogeneous Poisson data
X <- rpoispp(function(x,y){1000 * exp(-3*x)}, 1000)
plot(X)
# Inhomogeneous Poisson model
fit <- ppm(X, ~x, Poisson())
## Not run: [Link](fit, 100)

# conclusion: fitted inhomogeneous Poisson model looks OK

######################################################
# Advanced use of 'expr' argument
#
# set the initial conditions in Metropolis-Hastings algorithm
#
expr <- expression(rmh(fit, start=list([Link]=42), verbose=FALSE))
## Not run: [Link](fit, 100, expr)

[Link] Class of Quadrature Schemes

Description
A class "quad" to represent a quadrature scheme.

Details
A (finite) quadrature scheme is a list of quadrature points uj and associated weights wj
which is used to approximate an integral by a finite sum:
Z X
f (x)dx ≈ f (uj )wj
j

Given a point pattern dataset, a Berman-Turner quadrature scheme is one which includes
all these data points, as well as a nonzero number of other (“dummy”) points.
These quadrature schemes are used to approximate the pseudolikelihood of a point process,
in the method of Baddeley and Turner (2000) (see Berman and Turner (1992)). Accuracy
and computation time both increase with the number of points in the quadrature scheme.
468 [Link]

An object of class "quad" represents a Berman-Turner quadrature scheme. It can be passed


as an argument to the model-fitting function ppm, which requires a quadrature scheme.
An object of this class contains at least the following elements:

data: an object of class "ppp"


giving the locations (and marks) of the data points.
dummy: an object of class "ppp"
giving the locations (and marks) of the dummy points.
w: vector of nonnegative weights for the quadrature points

Users are strongly advised not to manipulate these entries directly.


The domain of quadrature is specified by dummy$window while the observation window (if
this needs to be specified separately) is taken to be data$window.
The weights vector w may also have an attribute attr(w, "zeroes") equivalent to the
logical vector (w == 0). If this is absent then all points are known to have positive weights.
To create an object of class "quad", users would typically call the high level function
quadscheme. (They are actually created by the low level function quad.)
Entries are extracted from a "quad" object by the functions [Link], [Link], [Link] and
[Link], which extract the x coordinates, y coordinates, weights, and marks, respec-
tively. The function [Link] returns the total number of quadrature points (dummy plus
data).
An object of class "quad" can be converted into an ordinary point pattern by the function
[Link] which simply takes the union of the data and dummy points.
Quadrature schemes can be plotted using [Link] (a method for the generic plot).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
quadscheme, ppm

[Link] Extract Quadrature Scheme Used to Fit a Point Process Model

Description
Given a fitted point process model, this function extracts the quadrature scheme used to
fit the model.

Usage
[Link](object, drop=FALSE)
[Link] 469

Arguments

object fitted point process model (an object of class "ppm").


drop Logical value determining whether to delete quadrature points that were
not used to fit the model.

Details

An object of class "ppm" represents a point process model that has been fitted to data. It
is typically produced by the model-fitting algorithm ppm.
The maximum pseudolikelihood algorithm in ppm approximates the pseudolikelihood inte-
gral by a sum over a finite set of quadrature points, which is constructed by augmenting the
original data point pattern by a set of “dummy” points. The fitted model object returned by
ppm contains complete information about this quadrature scheme. See ppm or [Link]
for further information.
This function [Link] extracts the quadrature scheme. A typical use of this function
would be to inspect the quadrature scheme (points and weights) to gauge the accuracy of
the approximation to the exact pseudolikelihood.
It may happen that some quadrature points are not actually used in fitting the model
(typically because the value of a covariate is NA at these points). The argument drop
specifies whether these unused quadrature points shall be deleted (drop=TRUE) or retained
(drop=FALSE) in the return value.
See [Link] for a list of all operations that can be performed on objects of class "ppm".
See [Link] for a list of all operations that can be performed on objects of class
"quad".

Value

A quadrature scheme (object of class "quad").

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [Link], ppm

Examples
data(cells)
fit <- ppm(cells, ~1, Strauss(r=0.1))
Q <- [Link](fit)
## Not run: plot(Q)
Q$data$n
Q$dummy$n
470 [Link]

[Link] Chi-Squared Dispersion Test for Spatial Point Pattern Based on


Quadrat Counts

Description
Performs a chi-squared test of Complete Spatial Randomness for a given point pattern,
based on quadrat counts. Alternatively performs a chi-squared goodness-of-fit test of a
fitted inhomogeneous Poisson model.

Usage
[Link](X, ...)
## S3 method for class 'ppp':
[Link](X, nx=5, ny=nx, ..., xbreaks=NULL, ybreaks=NULL, tess=NULL)
## S3 method for class 'ppm':
[Link](X, nx=5, ny=nx, ..., xbreaks=NULL, ybreaks=NULL, tess=NULL)

Arguments
X A point pattern (object of class "ppp") to be subjected to the goodness-of-
fit test. Alternatively a fitted point process model (object of class "ppm")
to be tested.
nx,ny Numbers of quadrats in the x and y directions. Incompatible with xbreaks
and ybreaks.
... Ignored.
xbreaks Optional. Numeric vector giving the x coordinates of the boundaries of
the quadrats. Incompatible with nx.
ybreaks Optional. Numeric vector giving the y coordinates of the boundaries of
the quadrats. Incompatible with ny.
tess Tessellation (object of class "tess") determining the quadrats. Incom-
patible with nx, ny, xbreaks, ybreaks.

Details
These functions perform χ2 tests of goodness-of-fit for a point process model, based on
quadrat counts.
The function [Link] is generic, with methods for point patterns (class "ppp"), split
point patterns (class "splitppp") and point process models (class "ppm").
ˆ if X is a point pattern, we test the null hypothesis that the data pattern is a realisation
of Complete Spatial Randomness (the uniform Poisson point process). Marks in the
point pattern are ignored.
ˆ if X is a split point pattern, then for each of the component point patterns (taken sepa-
rately) we test the null hypotheses of Complete Spatial Randomness. See [Link]
for documentation.
ˆ If X is a fitted point process model, then it should be a Poisson point process model.
The data to which this model was fitted are extracted from the model object, and are
treated as the data point pattern for the test. We test the null hypothesis that the
data pattern is a realisation of the (inhomogeneous) Poisson point process specified by
X.
[Link] 471

In all cases, the window of observation is divided into tiles, and the number of data points in
each tile is counted, as described in quadratcount. The quadrats are rectangular by default,
or may be regions of arbitrary shape specified by the argument tess. The expected number
of points in each quadrat is also calculated, as determined by CSR (in the first case) or by
the fitted model (in the second case). Then we perform the χ2 test of goodness-of-fit to the
quadrat counts.
The return value is an object of class "htest". Printing the object gives comprehensible
output about the outcome of the test.
The return value also belongs to the special class "[Link]". Plotting the object will
display the quadrats, annotated by their observed and expected counts and the Pearson
residuals. See the examples.

Value
An object of class "htest". See [Link] for explanation.
The return value is also an object of the special class "[Link]", and there is a plot
method for this class. See the examples.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], quadratcount, quadrats, quadratresample, [Link], kstest.
To test a Poisson point process model against a specific alternative, use [Link].

Examples
data(simdat)
[Link](simdat)
[Link](simdat, 4, 3)

# fitted model: inhomogeneous Poisson


fitx <- ppm(simdat, ~x, Poisson())
[Link](fitx)

te <- [Link](simdat, 4)
residuals(te) # Pearson residuals

plot(te)

plot(simdat, pch="+", cols="green", lwd=2)


plot(te, add=TRUE, col="red", cex=1.4, lty=2, lwd=3)

sublab <- eval(substitute(expression(p[chi^2]==z),


list(z=signif(te$[Link],3))))
title(sub=sublab, [Link]=3)

# quadrats of irregular shape


B <- dirichlet(runifpoint(6, simdat$window))
qB <- [Link](simdat, tess=B)
plot(simdat, main="[Link](simdat, tess=B)", pch="+")
plot(qB, add=TRUE, col="red", lwd=2, cex=1.2)
472 [Link]

[Link]
Chi-Squared Test of CSR for Split Point Pattern

Description
Performs a chi-squared test of Complete Spatial Randomness for each of the component
patterns in a split point pattern.

Usage
## S3 method for class 'splitppp':
[Link](X, ...)

Arguments
X A split point pattern (object of class "splitppp"), each component of
which will be subjected to the goodness-of-fit test.
... Arguments passed to [Link].

Details
The function [Link] is generic, with methods for point patterns (class "ppp"), split
point patterns (class "splitppp") and point process models (class "ppm").
If X is a split point pattern, then for each of the component point patterns (taken separately)
we test the null hypotheses of Complete Spatial Randomness. The method [Link]
is applied to each component point pattern.
The return value is a list of objects, each giving the result of one of the tests.

Value
A list of objects, each giving the result of one of the hypothesis tests. Each component
object is of class "htest" and "[Link]". The list itself is of class "listof" so that
it can be printed and plotted.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], quadratcount, quadrats, quadratresample, [Link], kstest.
To test a Poisson point process model against a specific alternative, use [Link].

Examples
data(humberside)
qH <- [Link](split(humberside), 2, 3)
plot(qH)
qH
quadratcount 473

quadratcount Quadrat counting for a point pattern

Description
Divides window into quadrats and counts the numbers of points in each quadrat.

Usage
quadratcount(X, ...)
## S3 method for class 'ppp':
quadratcount(X, nx=5, ny=nx, ...,
xbreaks=NULL, ybreaks=NULL, tess=NULL)
## S3 method for class 'splitppp':
quadratcount(X, ...)

Arguments
X A point pattern (object of class "ppp") or a split point pattern (object of
class "splitppp").
nx,ny Numbers of rectangular quadrats in the x and y directions. Incompatible
with xbreaks and ybreaks.
... Additional arguments passed to [Link].
xbreaks Numeric vector giving the x coordinates of the boundaries of the rectan-
gular quadrats. Incompatible with nx.
ybreaks Numeric vector giving the y coordinates of the boundaries of the rectan-
gular quadrats. Incompatible with ny.
tess Tessellation (object of class "tess") determining the quadrats. Incom-
patible with nx,ny,xbreaks,ybreaks.

Details
Quadrat counting is an elementary technique for analysing spatial point patterns. See
Diggle (2003).
If X is a point pattern, then by default, the window containing the point pattern X is
divided into an nx * ny grid of rectangular tiles or ‘quadrats’. (If the window is not a
rectangle, then these tiles are intersected with the window.) The number of points of X
falling in each quadrat is counted. These numbers are returned as a contingency table.
If xbreaks is given, it should be a numeric vector giving the x coordinates of the quadrat
boundaries. If it is not given, it defaults to a sequence of nx+1 values equally spaced over
the range of x coordinates in the window X$window.
Similarly if ybreaks is given, it should be a numeric vector giving the y coordinates of the
quadrat boundaries. It defaults to a vector of ny+1 values equally spaced over the range of
y coordinates in the window. The lengths of xbreaks and ybreaks may be different.
Alternatively, quadrats of any shape may be used. The argument tess can be a tessellation
(object of class "tess") whose tiles will serve as the quadrats.
The algorithm counts the number of points of X falling in each quadrat, and returns these
counts as a contingency table.
474 quadratcount

The return value is a table which can be printed neatly. The return value is also a
member of the special class "quadratcount". Plotting the object will display the quadrats,
annotated by their counts. See the examples.
If X is a split point pattern (object of class "splitppp" then quadrat counting will be
performed on each of the components point patterns, and the resulting contingency tables
will be returned in a list. This list can be printed or plotted.
Marks attached to the points are ignored by [Link]. To obtain a separate
contingency table for each type of point in a multitype point pattern, first separate the
different points using [Link], then apply [Link]. See the Examples.

Value
The value of [Link] is a contingency table containing the number of points in
each quadrat. The table is also an object of the special class "quadratcount" and there is
a plot method for this class.
The value of [Link] is a list of such contingency tables, each containing
the quadrat counts for one of the component point patterns in X. This list also has the class
"listof" which has print and plot methods.

Note
To perform a chi-squared test based on the quadrat counts, use [Link].

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 2003.
Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of
geometrical statistics. John Wiley and Sons.

See Also
[Link], quadrats, quadratresample, miplot

Examples
X <- runifpoint(50)
quadratcount(X)
quadratcount(X, 4, 5)
quadratcount(X, xbreaks=c(0, 0.3, 1), ybreaks=c(0, 0.4, 0.8, 1))
qX <- quadratcount(X, 4, 5)

# plotting:
plot(X, pch="+")
plot(qX, add=TRUE, col="red", cex=1.5, lty=2)

# irregular window
data(humberside)
plot(humberside)
qH <- quadratcount(humberside, 2, 3)
quadratresample 475

plot(qH, add=TRUE, col="blue", cex=1.5, lwd=2)

# multitype - split
plot(quadratcount(split(humberside), 2, 3))

# quadrats determined by tessellation:


B <- dirichlet(runifpoint(6))
qX <- quadratcount(X, tess=B)
plot(X, pch="+")
plot(qX, add=TRUE, col="red", cex=1.5, lty=2)

quadratresample Resample a Point Pattern by Resampling Quadrats

Description
Given a point pattern dataset, create a resampled point pattern by dividing the window
into rectangular quadrats and randomly resampling the list of quadrats.

Usage
quadratresample(X, nx, ny=nx, ..., replace = FALSE, nsamples = 1)

Arguments
X A point pattern dataset (object of class "ppp").
nx,ny Numbers of quadrats in the x and y directions.
... Ignored.
replace Logical value. Specifies whether quadrats should be sampled with or
without replacement.
nsamples Number of randomised point patterns to be generated.

Details
This command implements a very simple bootstrap resampling procedure for spatial point
patterns X.
The dataset X must be a point pattern (object of class "ppp") and its observation window
must be a rectangle.
The window is first divided into N = nx * ny rectangular tiles (quadrats) of equal size and
shape. To generate one resampled point pattern, a random sample of N quadrats is selected
from the list of N quadrats, with replacement (if replace=TRUE) or without replacement
(if replace=FALSE). The ith quadrat in the original dataset is then replaced by the ith
sampled quadrat, after the latter is shifted so that it occupies the correct spatial position.
The quadrats are then reconstituted into a point pattern inside the same window as X.
If replace=FALSE, this procedure effectively involves a random permutation of the quadrats.
The resulting resampled point pattern has the same number of points as X. If replace=TRUE,
the number of points in the resampled point pattern is random.

Value
A point pattern (if nsamples = 1) or a list of point patterns (if nsamples > 1).
476 quadrats

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
quadrats, quadratcount

Examples
data(bei)
quadratresample(bei, 6, 3)

quadrats Divide Region into Quadrats

Description
Divides window into rectangular quadrats and returns the quadrats as a tessellation.

Usage
quadrats(X, nx = 5, ny = nx, xbreaks = NULL, ybreaks = NULL, keepempty=FALSE)

Arguments
X A window (object of class "owin") or anything that can be coerced to a
window using [Link], such as a point pattern.
nx,ny Numbers of quadrats in the x and y directions. Incompatible with xbreaks
and ybreaks.
xbreaks Numeric vector giving the x coordinates of the boundaries of the quadrats.
Incompatible with nx.
ybreaks Numeric vector giving the y coordinates of the boundaries of the quadrats.
Incompatible with ny.
keepempty Logical value indicating whether to delete or retain empty quadrats. See
Details.

Details
If the window X is a rectangle, it is divided into an nx * ny grid of rectangular tiles or
‘quadrats’.
If X is not a rectangle, then the bounding rectangle of X is first divided into an nx * ny
grid of rectangular tiles, and these tiles are then intersected with the window X.
The resulting tiles are returned as a tessellation (object of class "tess") which can be
plotted and used in other analyses.
If xbreaks is given, it should be a numeric vector giving the x coordinates of the quadrat
boundaries. If it is not given, it defaults to a sequence of nx+1 values equally spaced over
the range of x coordinates in the window X$window.
quadscheme 477

Similarly if ybreaks is given, it should be a numeric vector giving the y coordinates of the
quadrat boundaries. It defaults to a vector of ny+1 values equally spaced over the range of
y coordinates in the window. The lengths of xbreaks and ybreaks may be different.
By default (if keepempty=FALSE), any rectangular tile which does not intersect the window
X is ignored, and only the non-empty intersections are treated as quadrats, so the tessella-
tion may consist of fewer than nx * ny tiles. If keepempty=TRUE, empty intersections are
retained, and the tessellation always contains exactly nx * ny tiles, some of which may be
empty.

Value
A tessellation (object of class "tess") as described under tess.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
tess, quadratcount, [Link], quadratresample

Examples
W <- square(10)
Z <- quadrats(W, 4, 5)
plot(Z)

data(letterR)
plot(quadrats(letterR, 5, 7))

quadscheme Generate a Quadrature Scheme from a Point Pattern

Description
Generates a quadrature scheme (an object of class "quad") from point patterns of data and
dummy points.

Usage
quadscheme(data, dummy, method="grid", ...)

Arguments
data The observed data point pattern. An object of class "ppp" or in a format
recognised by [Link]()
dummy The pattern of dummy points for the quadrature. An object of class "ppp"
or in a format recognised by [Link]() Defaults to [Link](data,
...)
method The name of the method for calculating quadrature weights: either "grid"
or "dirichlet".
... Parameters of the weighting method (see below) and parameters for con-
structing the dummy points if necessary.
478 quadscheme

Details
This is the primary method for producing a quadrature schemes for use by ppm.
The function ppm fits a point process model to an observed point pattern using the Berman-
Turner quadrature approximation (Berman and Turner, 1992; Baddeley and Turner, 2000)
to the pseudolikelihood of the model. It requires a quadrature scheme consisting of the orig-
inal data point pattern, an additional pattern of dummy points, and a vector of quadrature
weights for all these points. Such quadrature schemes are represented by objects of class
"quad". See [Link] for a description of this class.
Quadrature schemes are created by the function quadscheme. The arguments data and
dummy specify the data and dummy points, respectively. There is a sensible default for
the dummy points (provided by [Link]). Alternatively the dummy points may be
specified arbitrarily and given in any format recognised by [Link]. There are also functions
for creating dummy patterns including corners, gridcentres, stratrand and spokes.
The quadrature region is the region over which we are integrating, and approximating
integrals by finite sums. If dummy is a point pattern object (class "ppp") then the quadrature
region is taken to be dummy$window. If dummy is just a list of x, y coordinates then the
quadrature region defaults to the observation window of the data pattern, data$window.
If dummy is missing, then the optional arguments (for ...) include an argument nd. An
nd[1] by nd[2] grid of dummy points is generated by [Link].
If method = "grid" then the optional arguments (for ...) are (nd, ntile). The quadra-
ture region (see below) is divided into an ntile[1] by ntile[2] grid of rectangular tiles.
The weight for each quadrature point is the area of a tile divided by the number of quadra-
ture points in that tile.
If method="dirichlet" then the optional arguments are (exact=TRUE, nd). The quadra-
ture points (both data and dummy) are used to construct the Dirichlet tessellation. The
quadrature weight of each point is the area of its Dirichlet tile inside the quadrature region.
If exact == TRUE then this area is computed exactly using the package deldir; otherwise
it is computed approximately by discretisation.

Value
An object of class "quad" describing the quadrature scheme (data points, dummy points,
and quadrature weights) suitable as the argument Q of the function ppm() for fitting a point
process model.
The quadrature scheme can be inspected using the print and plot methods for objects of
class "quad".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A. and Turner, R. Practical maximum pseudolikelihood for spatial point patterns.
Australian and New Zealand Journal of Statistics 42 (2000) 283–322.
Berman, M. and Turner, T.R. Approximating point process likelihoods with GLIM. Applied
Statistics 41 (1992) 31–38.
[Link] 479

See Also
ppm, [Link], [Link], gridweights, [Link], corners, gridcentres,
stratrand, spokes

Examples
data(simdat)

# grid weights
Q <- quadscheme(simdat)
Q <- quadscheme(simdat, method="grid")
Q <- quadscheme(simdat, nd=50) # 1 dummy point per tile
Q <- quadscheme(simdat, ntile=25, nd=50) # 4 dummy points per tile

# Dirichlet weights
Q <- quadscheme(simdat, method="dirichlet", exact=FALSE)

# random dummy pattern


## Not run:
D <- runifpoint(250, simdat$window)
Q <- quadscheme(simdat, D, method="dirichlet", exact=FALSE)

## End(Not run)

# polygonal window
data(demopat)
X <- unmark(demopat)
Q <- quadscheme(X)

# mask window
X$window <- [Link](X$window)
Q <- quadscheme(X)

[Link] Sample Quantiles of Pixel Image

Description
Compute the sample quantiles of the pixel values of a given pixel image.

Usage
## S3 method for class 'im':
quantile(x, ...)

Arguments
x A pixel image. An object of class "im".
... Optional arguments passed to [Link]. They determine the
probabilities for which quantiles should be computed. See [Link].
480 raster.x

Details
This simple function applies the generic quantile operation to the pixel values of the image
x.
This function is a convenient way to inspect an image and to obtain summary statistics.
See the examples.

Value
A vector of quantiles.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
quantile, [Link], [Link]

Examples
# artificial image data
Z <- setcov(square(1))

# find the quartiles


quantile(Z)

# find the deciles


quantile(Z, probs=(0:10)/10)

raster.x Cartesian Coordinates for a Pixel Raster

Description
Returns a matrix giving the x (or y) coordinates of each pixel in a binary pixel image.

Usage
raster.x(w)
raster.y(w)

Arguments
w A window (an object of class "owin") of type "mask" representing a binary
pixel image.

Details
The argument w should be a window (an object of class "owin", see [Link] for
details). A window of type "mask" represents a binary pixel image. This function returns
a matrix of the same dimensions as the binary pixel image itself, with entries giving the x
coordinate (for raster.x) or y coordinate (for raster.y) of each pixel in the image.
rcell 481

Value

A matrix of the same dimensions as the pixel grid in w, and giving the value of the x (or y)
coordinate of each pixel in the raster.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

owin, [Link]

Examples
u <- owin(c(-1,1),c(-1,1)) # square of side 2
w <- [Link](u, eps=0.01) # 200 x 200 grid
X <- raster.x(w)
Y <- raster.y(w)
disc <- owin(c(-1,1), c(-1,1), mask=(X^2 + Y^2 <= 1))
## Not run: plot(disc)
# approximation to the unit disc

rcell Simulate Baddeley-Silverman Cell Process

Description

Generates a random point pattern, a simulated realisation of the Baddeley-Silverman cell


process model.

Usage

rcell(win=square(1), nx, ny=nx, dx=NULL, dy=NULL)

Arguments

win A window. An object of class owin, or data in any format acceptable to


[Link]().
dx Width of the cells. Incompatible with nx.
dy Height of the cells. Incompatible with ny.
nx Number of columns of cells in the window. Incompatible with dx.
ny Number of rows of cells in the window. Incompatible with dy.
482 reach

Details
This function generates a simulated realisation of the “cell process” (Baddeley and Silver-
man, 1984), a random point process with the same second-order properties as the uniform
Poisson process. In particular, the K function of this process is identical to the K function
of the uniform Poisson process (aka Complete Spatial Randomness). The same holds for
the pair correlation function and all other second-order properties. The cell process is a
counterexample to the claim that the K function completely characterises a point pattern.
A cell process is generated by dividing space into equal rectangular tiles. In each tile, a
random number N of points is placed, where N takes the values 0, 1 and 10 with probabilities
1/10, 8/9 and 1/90 respectively. The points within a tile are independent and uniformly
distributed in that tile, and the numbers of points in different tiles are independent random
integers.
In the function rcell the tile dimensions are determined by the quantities dx, dy if they
are present. If they are absent, then the grid spacing is determined so that there will be
nx columns and ny rows of tiles in the bounding rectangle of win. The cell process is then
generated in these tiles.
Some of the resulting random points may lie outside the window win: if they do, they are
deleted. The result is a point pattern inside the window win.

Value
A point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A.J. and Silverman, B.W. (1984) A cautionary example on the use of second-order
methods for analyzing point patterns. Biometrics 40, 1089-1094.

See Also
rstrat, rsyst, runifpoint, Kest

Examples
X <- rcell(nx=15)
plot(X)
plot(Kest(X))

reach Interaction Distance of a Point Process

Description
Computes the interaction distance of a point process.
reach 483

Usage
reach(x, ...)
## S3 method for class 'ppm':
reach(x, ..., epsilon=0)
## S3 method for class 'interact':
reach(x, ...)
## S3 method for class 'rmhmodel':
reach(x, ...)

Arguments
x Either a fitted point process model (object of class "ppm"), an interpoint
interaction (object of class "interact") or a point process model for
simulation (object of class "rmhmodel").
epsilon Numerical threshold below which interaction is treated as zero. See de-
tails.
... Other arguments are ignored.

Details
The ‘interaction distance’ or ‘interaction range’ of a point process model is the smallest
distance D such that any two points in the process which are separated by a distance
greater than D do not interact with each other.
For example, the interaction range of a Strauss process (see Strauss) with parameters
β, γ, r is equal to r, unless γ = 1 in which case the model is Poisson and the interaction
range is 0. The interaction range of a Poisson process is zero. The interaction range of
the Ord threshold process (see OrdThresh) is infinite, since two points may interact at any
distance apart.
The function reach(x) is generic, with methods for the case where x is
ˆ a fitted point process model (object of class "ppm", usually obtained from the model-
fitting function ppm);
ˆ an interpoint interaction structure (object of class "interact"), created by one of
the functions Poisson, Strauss, StraussHard, MultiStrauss, MultiStraussHard,
Softcore, DiggleGratton, Pairwise, PairPiece, Geyer, LennardJones, Saturated,
OrdThresh or Ord;
ˆ a point process model for simulation (object of class "rmhmodel"), usually obtained
from rmhmodel.
When x is an "interact" object, reach(x) returns the maximum possible interaction
range for any point process model with interaction structure given by x. For example,
reach(Strauss(0.2)) returns 0.2.
When x is a "ppm" object, reach(x) returns the interaction range for the point process
model represented by x. For example, a fitted Strauss process model with parameters
beta,gamma,r will return either 0 or r, depending on whether the fitted interaction param-
eter gamma is equal or not equal to 1.
For some point process models, such as the soft core process (see Softcore), the interaction
distance is infinite, because the interaction terms are positive for all pairs of points. A
practical solution is to compute the distance at which the interaction contribution from a
pair of points falls below a threshold epsilon, on the scale of the log conditional intensity.
This is done by setting the argument epsilon to a positive value.
484 [Link]

Value
The interaction distance, or NA if this cannot be computed from the information given.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, Poisson, Strauss, StraussHard, MultiStrauss, MultiStraussHard, Softcore, DiggleGratton,
Pairwise, PairPiece, Geyer, LennardJones, Saturated, OrdThresh, Ord, rmhmodel

Examples
reach(Poisson())
# returns 0

reach(Strauss(r=7))
# returns 7
data(swedishpines)
fit <- ppm(swedishpines, ~1, Strauss(r=7))
reach(fit)
# returns 7

reach(OrdThresh(42))
# returns Inf

reach(MultiStrauss(1:2, matrix(c(1,3,3,1),2,2)))
# returns 3

[Link] Reduced Sample Estimator using Histogram Data

Description
Compute the Reduced Sample estimator of a survival time distribution function, from
histogram data

Usage
[Link](nco, cen, ncc, show=FALSE, uppercen=0)

Arguments
nco vector of counts giving the histogram of uncensored observations (those
survival times that are less than or equal to the censoring time)
cen vector of counts giving the histogram of censoring times
ncc vector of counts giving the histogram of censoring times for the uncensored
observations only
uppercen number of censoring times greater than the rightmost histogram break-
point (if there are any)
show Logical value controlling the amount of detail returned by the function
value (see below)
redwood 485

Details
This function is needed mainly for internal use in spatstat, but may be useful in other
applications where you want to form the reduced sample estimator from a huge dataset.
Suppose Ti are the survival times of individuals i = 1, . . . , M with unknown distribution
function F (t) which we wish to estimate. Suppose these times are right-censored by random
censoring times Ci . Thus the observations consist of right-censored survival times T̃i =
min(Ti , Ci ) and non-censoring indicators Di = 1{Ti ≤ Ci } for each i.
If the number of observations M is large, it is efficient to use histograms. Form the histogram
cen of all censoring times Ci . That is, obs[k] counts the number of values Ci in the interval
(breaks[k],breaks[k+1]] for k > 1 and [breaks[1],breaks[2]] for k = 1. Also form
the histogram nco of all uncensored times, i.e. those T̃i such that Di = 1, and the histogram
of all censoring times for which the survival time is uncensored, i.e. those Ci such that
Di = 1. These three histograms are the arguments passed to [Link].
The return value rs is the reduced-sample estimator of the distribution function F (t).
Specifically, rs[k] is the reduced sample estimate of F(breaks[k+1]). The value is exact,
i.e. the use of histograms does not introduce any approximation error.
Note that, for the results to be valid, either the histogram breaks must span the censoring
times, or the number of censoring times that do not fall in a histogram cell must have been
counted in uppercen.

Value
If show = FALSE, a numeric vector giving the values of the reduced sample estimator. If
show=TRUE, a list with three components which are vectors of equal length,
rs Reduced sample estimate of the survival time c.d.f. F (t)
numerator numerator of the reduced sample estimator
denominator denominator of the reduced sample estimator

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

redwood California Redwoods Point Pattern (Ripley’s Subset)

Description
Locations of 62 seedlings and saplings of California redwood trees.
The data represent the locations of 62 seedlings and saplings of California redwood trees
in a square sampling region. They originate from Strauss (1975); the present data are a
subset extracted by Ripley (1977) in a subregion that has been rescaled to a unit square.
There are many further analyses of this dataset. It is often used as a canonical example of
a clustered point pattern (see e.g. Diggle, 1983).
The original, full redwood dataset is supplied in the spatstat library as redwoodfull.
486 redwoodfull

Usage
data(redwood)

Format
An object of class "ppp" representing the point pattern of tree locations. The window has
been rescaled to the unit square.
See [Link] for details of the format of a point pattern object.

Source
Strauss (1975), subset extracted by Ripley (1977)

References
Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.
Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal
Statistical Society, Series B 39, 172–212.
Strauss, D.J. (1975) A model for clustering. Biometrika 63, 467–475.

See Also
redwoodfull

redwoodfull California Redwoods Point Pattern (Entire Dataset)

Description
These data represent the locations of 195 seedlings and saplings of California redwood trees
in a square sampling region. They were described and analysed by Strauss (1975). This is
the “full” dataset; most writers have analysed a subset extracted by Ripley (1977) which is
available as redwood.
Strauss (1975) divided the sampling region into two subregions I and II demarcated by a
diagonal line across the region. The spatial pattern appears to be slightly regular in region
I and strongly clustered in region II.
The dataset redwoodfull contains the full point pattern of 195 trees. The auxiliary in-
formation about the subregions is contained in [Link], which is a list with
entries

diag The coordinates of the diagonal boundary


between regions I and II
regionI Region I as a window object
regionII Region II as a window object
regionR Ripley’s subrectangle (approximate)
plot Function to plot the full data and auxiliary markings

Ripley (1977) extracted a subset of these data, containing 62 points, lying within a square
subregion which overlaps regions I and II. He rescaled the data to the unit square. This has
redwoodfull 487

been re-analysed many times, and is the dataset usually known as “the redwood data” in
the spatial statistics literature. The exact dataset used by Ripley is supplied in the spatstat
library as redwood. There are some minor inconsistencies with redwood since it originates
from a different digitisation.
The approximate position of the square chosen by Ripley within the redwoodfull pattern
is indicated by the window [Link]$regionR.

Usage
data(redwoodfull)

Format
The dataset redwoodfull is an object of class "ppp" representing the point pattern of tree
locations. The window has been rescaled to the unit square. See [Link] for details of
the format of a point pattern object.
The dataset [Link] is a list with entries

diag coordinates of endpoints of a line,


in format list(x=numeric(2),y=numeric(2))
regionI a window object
regionII a window object
regionR a window object
plot Function with no arguments

Source

Strauss (1975). The plot of the data published by Strauss (1975) was scanned and digitised
by Sandra Pereira, University of Western Australia, 2002.

References

Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.
Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal
Statistical Society, Series B 39, 172–212.
Strauss, D.J. (1975) A model for clustering. Biometrika 63, 467–475.

See Also

redwood

Examples
data(redwoodfull)
plot(redwoodfull)
[Link]$plot()
# extract the pattern in region II
redwoodII <- redwoodfull[, [Link]$regionII]
488 [Link]

[Link] Reset Values in Subset of Image

Description

Reset the values in a subset of a pixel image.

Usage

## S3 replacement method for class 'im':


x[i] <- value

Arguments

x A two-dimensional pixel image. An object of class "im".


i Object defining the subregion or subset to be extracted. Either a spatial
window (an object of class "owin") or a point pattern (an object of class
"ppp") or something that can be converted into a point pattern by [Link].
value Vector of replacement values (short vectors will be recycled).

Details

This function changes some of the pixel values in a pixel image. The image X must be an
object of class "im" representing a pixel image defined inside a rectangle in two-dimensional
space (see [Link]).
The subset to be changed is determined by the argument i.
If i is a spatial window (an object of class "owin"), the values of the image inside this
window are changed.
If i is a point pattern (an object of class "ppp", or something that can be converted into a
point pattern by [Link]), then the values of the pixel image at the points of this pattern
are changed.

Value

The image x with the values replaced.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [.im, [Link], [Link], [Link]


rescale 489

Examples
# make up an image
X <- setcov([Link]())
plot(X)

# a rectangular subset
W <- owin(c(0,0.5),c(0.2,0.8))
X[W] <- 2
plot(X)

# a polygonal subset
data(letterR)
R <- affine(letterR, diag(c(1,1)/2), c(-2,-0.7))
X[R] <- 3
plot(X)

# a point pattern
P <- rpoispp(20)
X[P] <- 10
plot(X)

# change pixel value at a specific location


X[list(x=0.1,y=0.2)] <- 7

rescale Convert dataset to another unit of length

Description
Converts between different units of length in a spatial dataset, such as a point pattern or a
window.

Usage
rescale(X, s)

Arguments
X Any suitable dataset representing a two-dimensional object, such as a
point pattern (object of class "ppp"), or a window (object of class "owin").
s Conversion factor: the new units are s times the old units.

Details
This is generic. Methods are provided for point patterns ([Link]) and windows
([Link]).
The spatial coordinates in the dataset X will be re-expressed in terms of a new unit of length
that is s times the current unit of length given in X.
For example if X is a dataset giving coordinates in metres, then rescale(X,1000) will
divide the coordinate values by 1000 to obtain coordinates in kilometres, and the unit name
will be changed from "metres" to "1000 metres".
490 [Link]

Value
Another object of the same type, representing the same data, but expressed in the new
units.

Note
The result of this operation is equivalent to the original dataset. If you want to actually
change the coordinates by a linear transformation, producing a dataset that is not equivalent
to the original one, use affine.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
unitname, [Link], [Link], affine, rotate, shift

[Link] Convert Pixel Image to Another Unit of Length

Description
Converts a pixel image to another unit of length.

Usage
## S3 method for class 'im':
rescale(X, s)

Arguments
X Pixel image (object of class "im").
s Conversion factor: the new units are s times the old units.

Details
This is a method for the generic function rescale.
The spatial coordinates of the pixels in X will be re-expressed in terms of a new unit of
length that is s times the current unit of length given in X. (Thus, the coordinate values
are divided by s, while the unit value is multiplied by s).
The result is a pixel image representing the same data but re-expressed in a different unit.
Pixel values are unchanged.

Value
Another pixel image (of class "im"), containing the same pixel values, but with pixel coor-
dinates expressed in the new units.
[Link] 491

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
im, rescale, unitname, [Link]

Examples
# Bramble Canes data: 1 unit = 9 metres
data(bramblecanes)
# distance transform
Z <- distmap(bramblecanes)
# convert to metres
# first alter the pixel values
Zm <- [Link](9 * Z)
# now rescale the pixel coordinates
Zm <- rescale(Zm, 1/9)

[Link] Convert Window to Another Unit of Length

Description
Converts a window to another unit of length.

Usage
## S3 method for class 'owin':
rescale(X, s)

Arguments
X Window (object of class "owin").
s Conversion factor: the new units are s times the old units.

Details
This is a method for the generic function rescale.
The spatial coordinates in the window X (and its window) will be re-expressed in terms
of a new unit of length that is s times the current unit of length given in X. (Thus, the
coordinate values are divided by s, while the unit value is multiplied by s).
The result is a window representing the same region of space, but re-expressed in a different
unit.

Value
Another window object (of class "owin") representing the same window, but expressed in
the new units.
492 [Link]

Note
The result of this operation is equivalent to the original window. If you want to actually
change the coordinates by a linear transformation, producing a window that is larger or
smaller than the original one, use affine.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
unitname, rescale, [Link], affine, rotate, shift

Examples
data(swedishpines)
W <- swedishpines$window
W
# coordinates are in decimetres (0.1 metre)
# convert to metres
rescale(W, 10)

[Link] Convert Point Pattern to Another Unit of Length

Description
Converts a point pattern dataset to another unit of length.

Usage
## S3 method for class 'ppp':
rescale(X, s)

Arguments
X Point pattern (object of class "ppp").
s Conversion factor: the new units are s times the old units.

Details
This is a method for the generic function rescale.
The spatial coordinates in the point pattern X (and its window) will be re-expressed in
terms of a new unit of length that is s times the current unit of length given in X. (Thus,
the coordinate values are divided by s, while the unit value is multiplied by s).
The result is a point pattern representing the same data but re-expressed in a different
unit.
Mark values are unchanged.
[Link] 493

Value
Another point pattern (of class "ppp"), representing the same data, but expressed in the
new units.

Note
The result of this operation is equivalent to the original point pattern. If you want to
actually change the coordinates by a linear transformation, producing a point pattern that
is not equivalent to the original one, use affine.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
unitname, rescale, [Link], affine, rotate, shift

Examples
# Bramble Canes data: 1 unit = 9 metres
data(bramblecanes)
# convert to metres
bram <- rescale(bramblecanes, 1/9)

[Link] Convert Line Segment Pattern to Another Unit of Length

Description
Converts a line segment pattern dataset to another unit of length.

Usage
## S3 method for class 'psp':
rescale(X, s)

Arguments
X Line segment pattern (object of class "psp").
s Conversion factor: the new units are s times the old units.

Details
This is a method for the generic function rescale.
The spatial coordinates in the line segment pattern X (and its window) will be re-expressed
in terms of a new unit of length that is s times the current unit of length given in X. (Thus,
the coordinate values are divided by s, while the unit value is multiplied by s).
The result is a line segment pattern representing the same data but re-expressed in a
different unit.
Mark values are unchanged.
494 [Link]

Value
Another line segment pattern (of class "psp"), representing the same data, but expressed
in the new units.

Note
The result of this operation is equivalent to the original segment pattern. If you want to
actually change the coordinates by a linear transformation, producing a segment pattern
that is not equivalent to the original one, use affine.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
units, affine, rotate, shift

Examples
data(copper)
X <- copper$Lines
X
# data are in km
# convert to metres
rescale(X, 1/1000)

[Link] Convert Window Back To Rectangle

Description
Determines whether the given window is really a rectangle aligned with the coordinate axes,
and if so, converts it to a rectangle object.

Usage
[Link](W)

Arguments
W A window (object of class "owin").

Details
This function decides whether the window W is actually a rectangle aligned with the coor-
dinate axes. This will be true if W is
ˆ a rectangle (window object of type "rectangle");
ˆ a polygon (window object of type "polygonal" with a single polygonal boundary)
that is a rectangle aligned with the coordinate axes;
ˆ a binary mask (window object of type "mask") in which all the pixel entries are TRUE.
[Link] 495

If so, the function returns this rectangle, a window object of type "rectangle". If not, the
function returns W.

Value
Another object of class "owin" representing the same window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
w <- owin(poly=list(x=c(0,1,1,0),y=c(0,0,1,1)))
rw <- [Link](w)

w <- [Link]([Link]())
rw <- [Link](w)

[Link] Residuals for Fitted Point Process Model

Description
Given a point process model fitted to a point pattern, compute residuals.

Usage
## S3 method for class 'ppm':
residuals(object, type="raw", ..., check=TRUE, drop=FALSE,
fittedvalues=[Link](object, check=check, drop=drop))

Arguments
object The fitted point process model (an object of class "ppm") for which resid-
uals should be calculated.
type String indicating the type of residuals to be calculated. Current options
are "raw", "inverse" and "pearson". A partial match is adequate.
... Ignored.
check Logical value indicating whether to check the internal format of object.
If there is any possibility that this object has been restored from a dump
file, or has otherwise lost track of the environment where it was originally
computed, set check=TRUE.
drop Logical value determining whether to delete quadrature points that were
not used to fit the model. See [Link] for explanation.
fittedvalues Vector of fitted values for the conditional intensity at the quadrature
points, from which the residuals will be computed. For expert use only.
496 [Link]

Details
This function computes several kinds of residuals for the fit of a point process model to
a spatial point pattern dataset (Baddeley et al, 2005). Use [Link] to produce
diagnostic plots based on these residuals.
The argument object must be a fitted point process model (object of class "ppm"). Such
objects are produced by the maximum pseudolikelihood fitting algorithm ppm). This fitted
model object contains complete information about the original data pattern.
Residuals are attached both to the data points and to some other points in the window of
observation (namely, to the dummy points of the quadrature scheme used to fit the model).
If the fitted model is correct, then the sum of the residuals over all (data and dummy)
points in a spatial region B has mean zero. For further explanation, see Baddeley et al
(2005).
The type of residual is chosen by the argument type. Current options are

"raw": the raw residuals


rj = zj − wj λj
at the quadrature points uj , where zj is the indicator equal to 1 if uj is a data point
and 0 if uj is a dummy point; wj is the quadrature weight attached to uj ; and

λj = λ̂(uj , x)

is the conditional intensity of the fitted model at uj . These are the spatial analogue
of the martingale residuals of a one-dimensional counting process.
"inverse": the ‘inverse-lambda’ residuals (Baddeley et al, 2005)
(I) rj zj
rj = = − wj
λj λj

obtained by dividing the raw residuals by the fitted conditional intensity. These are a
counterpart of the exponential energy marks (see eem).
"pearson": the Pearson residuals (Baddeley et al, 2005)
(P ) rj zj p
rj = p = p − wj λj
λj λj

obtained by dividing the raw residuals by the square root of the fitted conditional
intensity. The Pearson residuals are standardised, in the sense that if the model (true
and fitted) is Poisson, then the sum of the Pearson residuals in a spatial region B has
variance equal to the area of B.

Use [Link] to produce diagnostic plots based on these residuals.

Value
A vector containing the (discretised) residuals.
Entries in this vector correspond to the quadrature points (data or dummy points) used to fit
the model. The quadrature points can be extracted from object by [Link]([Link](object)).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
residualspaper 497

References
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial
point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

See Also
[Link], [Link], ppm

Examples
data(cells)
fit <- ppm(cells, ~x, Strauss(r=0.15))

rp <- [Link](fit, type="pe")


sum(rp) # should be close to 0

# extract quadrature points to which the residuals correspond


quadpoints <- [Link]([Link](fit))

# plot residuals as marks attached to the quadrature points


quadmarked <- setmarks(quadpoints, rp)
plot(quadmarked)

residualspaper Data and Code From JRSS Discussion Paper on Residuals

Description
This dataset contains the point patterns used as examples in the paper of Baddeley et al
(2005). [Figure 2 is already available in spatstat as the copper dataset.]
R code is also provided to reproduce all the Figures displayed in Baddeley et al (2005).
The component plotfig is a function, which can be called with a numeric or character
argument specifying the Figure or Figures that should be plotted. See the Examples.

Usage
data(residualspaper)

Format
residualspaper is a list with the following components:

Fig1 The locations of Japanese pine seedlings and saplings from Figure 1 of the paper. A
point pattern (object of class "ppp").
Fig3 The Chorley-Ribble data from Figure 3 of the paper. A list with three components,
lung, larynx and incin. Each is a matrix with 2 columns giving the coordinates of the
lung cancer cases, larynx cancer cases, and the incinerator, respectively. Coordinates
are Eastings and Northings in km.
Fig4a The synthetic dataset in Figure 4 (a) of the paper.
Fig4b The synthetic dataset in Figure 4 (b) of the paper.
Fig4c The synthetic dataset in Figure 4 (c) of the paper.
498 rGaussPoisson

Fig11 The covariate displayed in Figure 11. A pixel image (object of class "im") whose
pixel values are distances to the nearest line segment in the copper data.
plotfig A function which will compute and plot any of the Figures from the paper. The
argument of plotfig is either a numeric vector or a character vector, specifying the
Figure or Figures to be plotted. See the Examples.

Source
Figure 1: Prof M. Numata. Data kindly supplied by Professor Y. Ogata with kind permis-
sion of Prof M. Tanemura.
Figure 3: Professor P.J. Diggle (rescaled by Adrian Baddeley)
Figure 4 (a,b,c): Adrian Baddeley

References
Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial
point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

Examples

## Not run:
data(residualspaper)

X <- residualspaper$Fig4a
summary(X)
plot(X)

# reproduce all Figures


residualspaper$plotfig()

# reproduce Figures 1 to 10
residualspaper$plotfig(1:10)

# reproduce Figure 7 (a)


residualspaper$plotfig("7a")

## End(Not run)

rGaussPoisson Simulate Gauss-Poisson Process

Description
Generate a random point pattern, a simulated realisation of the Gauss-Poisson Process.

Usage
rGaussPoisson(kappa, r, p2, win = owin(c(0,1),c(0,1)))
ripras 499

Arguments
kappa Intensity of the Poisson process of cluster centres. A single positive num-
ber, a function, or a pixel image.
r Diameter of each cluster that consists of exactly 2 points.
p2 Probability that a cluster contains exactly 2 points.
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link].

Details
This algorithm generates a realisation of the Gauss-Poisson point process inside the window
win. The process is constructed by first generating a Poisson point process of parent points
with intensity kappa. Then each parent point is either retained (with probability 1 - p2)
or replaced by a pair of points at a fixed distance r apart (with probability p2). In the case
of clusters of 2 points, the line joining the two points has uniform random orientation.
In this implementation, parent points are not restricted to lie in the window; the parent
process is effectively the uniform Poisson process on the infinite plane.

Value
The simulated point pattern (an object of class "ppp").
Additionally, some intermediate results of the simulation are returned as attributes of this
point pattern. See rNeymanScott.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rpoispp, rThomas, rMatClust, rNeymanScott

Examples
pp <- rGaussPoisson(30, 0.07, 0.5)

ripras Estimate window from points alone

Description
Given an observed pattern of points, computes the Ripley-Rasson estimate of the spatial
domain from which they came.

Usage
ripras(x, y=NULL, shape="convex", f)
500 ripras

Arguments

x vector of x coordinates of observed points, or a 2-column matrix giving


x,y coordinates, or a list with components x,y giving coordinates (such
as a point pattern object of class "ppp".)
y (optional) vector of y coordinates of observed points, if x is a vector.
shape String indicating the type of window to be estimated: either "convex" or
"rectangle".
f (optional) scaling factor. See Details.

Details

Given an observed pattern of points with coordinates given by x and y, this function com-
putes an estimate due to Ripley and Rasson (1977) of the spatial domain from which the
points came.
The points are assumed to have been generated independently and uniformly distributed
inside an unknown domain D.
If shape="convex" (the default), the domain D is assumed to be a convex set. The maxi-
mum likelihood estimate of D is the convex hull of the points (computed by [Link]).
Analogously to the problems of estimating the endpoint of a uniform distribution, the MLE
is not optimal. Ripley and Rasson’s estimator is a rescaled copy of the convex hull, centred
at the centroid of the convex hull. The scaling factor is 1/sqrt(1 − m/n) where n is the
number of data points and m the number of vertices of the convex hull. The scaling factor
may be overridden using the argument f.
If shape="rectangle", the domain D is assumed to be a rectangle with sides parallel to
the coordinate axes. The maximum likelihood estimate of D is the bounding box of the
points (computed by [Link]). The Ripley-Rasson estimator is a rescaled copy
of the bounding box, with scaling factor 1/sqrt(1 − 4/n) where n is the number of data
points, centred at the centroid of the bounding box. The scaling factor may be overridden
using the argument f.

Value

A window (an object of class "owin").

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Ripley, B.D. and Rasson, J.-P. (1977) Finding the edge of a Poisson forest. Journal of
Applied Probability, 14, 483 – 491.

See Also

owin, [Link], [Link], [Link]


rjitter 501

Examples
x <- runif(30)
y <- runif(30)
w <- ripras(x,y)
plot(owin(), main="ripras(x,y)")
plot(w, add=TRUE)
points(x,y)

X <- rpoispp(15)
plot(X, main="ripras(X)")
plot(ripras(X), add=TRUE)

# two points insufficient


ripras(c(0,1),c(0,0))
# triangle
ripras(c(0,1,0.5), c(0,0,1))
# three collinear points
ripras(c(0,0,0), c(0,1,2))

rjitter Random Perturbation of a Point Pattern

Description
Applies independent random displacements to each point in a point pattern.

Usage
rjitter(X, radius, retry=TRUE, giveup = 10000)

Arguments
X A point pattern (object of class "ppp").
radius Scale of perturbations. A positive numerical value. The displacement
vectors will be uniformly distributed in a circle of this radius.
retry What to do when a perturbed point lies outside the window of the original
point pattern. If retry=FALSE, the point will be lost; if retry=TRUE, the
algorithm will try again.
giveup Maximum number of unsuccessful attempts.

Details
Each of the points in the point pattern X is subjected to an independent random displace-
ment. The displacement vectors are uniformly distributed in a circle of radius radius.
If a displaced point lies outside the window, then if retry=FALSE the point will be lost.
However if retry=TRUE, the algorithm will try again: each time a perturbed point lies
outside the window, the algorithm will reject it and generate another proposed perturbation
of the original point, until one lies inside the window, or until giveup unsuccessful attempts
have been made. In the latter case, any unresolved points will be included without any
perturbation. The return value will always be a point pattern with the same number of
points as X.
502 rlabel

Value
A point pattern (object of class "ppp") in the same window as X.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
X <- rsyst(owin(), 10, 10)
Y <- rjitter(X, 0.02)
plot(Y)

rlabel Random Re-Labelling of Point Pattern

Description
Randomly allocates marks to a point pattern, or permutes the existing marks, or resamples
from the existing marks.

Usage
rlabel(X, labels=marks(X), permute=TRUE)

Arguments
X Point pattern (object of class "ppp").
labels Vector of values from which the new marks will be drawn at random.
Defaults to the vector of existing marks.
permute Logical value indicating whether to generate new marks by randomly
permuting labels or by drawing a random sample with replacement.

Details
This very simple function allocates random marks to an existing point pattern X. It is useful
for hypothesis testing purposes.
In the simplest case, the command rlabel(X) yields a point pattern obtained from X by
randomly permuting the marks of the points.
If permute=TRUE, then labels should be a vector of length equal to the number of points in
X. The result of rlabel will be a point pattern with locations given by X and marks given
by a random permutation of labels (i.e. a random sample without replacement).
If permute=FALSE, then labels may be a vector of any length. The result of rlabel will
be a point pattern with locations given by X and marks given by a random sample from
labels (with replacement).

Value
A marked point pattern.
rlinegrid 503

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
setmarks to assign arbitrary marks.

Examples
data(amacrine)

# Randomly permute the marks "on" and "off"


# Result always has 142 "off" and 152 "on"
Y <- rlabel(amacrine)

# randomly allocate marks "on" and "off"


# with probabilities p(off) = 0.48, p(on) = 0.52
Y <- rlabel(amacrine, permute=FALSE)

# randomly allocate marks "A" and "B" with equal probability


data(cells)
Y <- rlabel(cells, labels=factor(c("A", "B")), permute=FALSE)

rlinegrid Generate grid of parallel lines with random displacement

Description
Generates a grid of parallel lines, equally spaced, inside the specified window.

Usage
rlinegrid(angle = 45, spacing = 0.1, win = owin())

Arguments
angle Common orientation of the lines, in degrees anticlockwise from the x axis.
spacing Spacing between successive lines.
win Window in which to generate the lines. An object of class "owin" or
something acceptable to [Link].

Details
The grid is randomly displaced from the origin.

Value
A line segment pattern (object of class "psp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
504 rMatClust

See Also
psp, rpoisline

Examples
plot(rlinegrid(30, 0.05))

rMatClust Simulate Matern Cluster Process

Description
Generate a random point pattern, a simulated realisation of the Mat\’ern Cluster Process.

Usage
rMatClust(kappa, r, mu, win = owin(c(0,1),c(0,1)))

Arguments
kappa Intensity of the Poisson process of cluster centres. A single positive num-
ber, a function, or a pixel image.
r Radius parameter of the clusters.
mu Mean number of points per cluster (a single positive number) or reference
intensity for the cluster points (a function or a pixel image).
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link].

Details
This algorithm generates a realisation of Mat\’ern’s cluster process inside the window win.
The process is constructed by first generating a Poisson point process of “parent” points
with intensity kappa. Then each parent point is replaced by a random cluster of points,
the number of points in each cluster being random with a Poisson (mu) distribution, and
the points being placed independently and uniformly inside a disc of radius r centred on
the parent point.
In this implementation, parent points are not restricted to lie in the window; the parent
process is effectively the uniform Poisson process on the infinite plane.
This classical model can be fitted to data by the method of minimum contrast, using
[Link] or kppm.
The algorithm can also generate spatially inhomogeneous versions of the Mat\’ern cluster
process:

ˆ The parent points can be spatially inhomogeneous. If the argument kappa is a


function(x,y) or a pixel image (object of class "im"), then it is taken as specify-
ing the intensity function of an inhomogeneous Poisson process that generates the
parent points.
rMaternI 505

ˆ The offspring points can be inhomogeneous. If the argument mu is a function(x,y)


or a pixel image (object of class "im"), then it is interpreted as the reference density
for offspring points, in the sense of Waagepetersen (2006). For a given parent point,
the offspring constitute a Poisson process with intensity function equal to the average
value of mu inside the disc of radius r centred on the parent point, and zero intensity
outside this disc.

When the parents are homogeneous (kappa is a single number) and the offspring are inho-
mogeneous (mu is a function or pixel image), the model can be fitted to data using kppm, or
using [Link] applied to the inhomogeneous K function.

Value
The simulated point pattern (an object of class "ppp").
Additionally, some intermediate results of the simulation are returned as attributes of this
point pattern. See rNeymanScott.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Mat\’ern, B. (1960) Spatial Variation. Meddelanden fraan Statens Skogsforskningsinstitut,
volume 59, number 5. Statens Skogsforskningsinstitut, Sweden.
Mat\’ern, B. (1986) Spatial Variation. Lecture Notes in Statistics 36, Springer-Verlag, New
York.
Waagepetersen, R. (2006) An estimating function approach to inference for inhomogeneous
Neyman-Scott processes. Submitted for publication.

See Also
rpoispp, rThomas, rGaussPoisson, rNeymanScott, [Link], kppm.

Examples
# homogeneous
X <- rMatClust(10, 0.05, 4)
# inhomogeneous
Z <- [Link](function(x,y){ 4 * exp(2 * x - 1) }, owin())
Y <- rMatClust(10, 0.05, Z)

rMaternI Simulate Matern Model I

Description
Generate a random point pattern, a simulated realisation of the Mat\’ern Model I inhibition
process model.
506 rMaternII

Usage
rMaternI(kappa, r, win = owin(c(0,1),c(0,1)))

Arguments
kappa Intensity of the Poisson process of proposal points. A single positive
number.
r Inhibition distance.
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link].

Details
This algorithm generates a realisation of Mat\’ern’s Model I inhibition process inside the
window win.
The process is constructed by first generating a uniform Poisson point process of “proposal”
points with intensity kappa inside the window. A proposal point is deleted if it lies within
r units’ distance of another proposal point. Otherwise it is retained. The retained points
constitute Mat\’ern’s Model I.

Value
The simulated point pattern (an object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rpoispp, rMatClust

Examples
pp <- rMaternI(20, 0.05)

rMaternII Simulate Matern Model II

Description
Generate a random point pattern, a simulated realisation of the Mat\’ern Model II inhibition
process.

Usage
rMaternII(kappa, r, win = owin(c(0,1),c(0,1)))
rmh 507

Arguments
kappa Intensity of the Poisson process of proposal points. A single positive
number.
r Inhibition distance.
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link].

Details
This algorithm generates a realisation of Mat\’ern’s Model II inhibition process inside the
window win.
The process is constructed by first generating a uniform Poisson point process of “proposal”
points with intensity kappa inside the window. Then each proposal point is marked by an
“arrival time”, a number uniformly distributed in [0, 1] independently of other variables.
A proposal point is deleted if it lies within r units’ distance of another proposal point
that has an earlier arrival time. Otherwise it is retained. The retained points constitute
Mat\’ern’s Model II.
The difference between Mat\’ern’s Model I and II is the italicised statement above. Model
II has a higher intensity for the same parameter values.

Value
The simulated point pattern (an object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rpoispp, rMatClust, rMaternI

Examples
pp <- rMaternII(20, 0.05)

rmh Simulate point patterns using the Metropolis-Hastings algorithm.

Description
Generic function for running the Metropolis-Hastings algorithm to produce simulated real-
isations of a point process model.

Usage
rmh(model, ...)
508 [Link]

Arguments
model The point process model to be simulated.
... Further arguments controlling the simulation.

Details
The Metropolis-Hastings algorithm can be used to generate simulated realisations from a
wide range of spatial point processes. For caveats, see below.
The function rmh is generic; it has methods [Link] (for objects of class "ppm") and
[Link] (the default). The actual implementation of the Metropolis-Hastings algo-
rithm is contained in [Link]. For details of its use, see [Link] or [Link].
[If the model is a Poisson process, then Metropolis-Hastings is not used; the Poisson model
is generated directly using rpoispp or rmpoispp.]
In brief, the Metropolis-Hastings algorithm is a Markov Chain, whose states are spatial
point patterns, and whose limiting distribution is the desired point process. After running
the algorithm for a very large number of iterations, we may regard the state of the algorithm
as a realisation from the desired point process.
However, there are difficulties in deciding whether the algorithm has run for “long enough”.
The convergence of the algorithm may indeed be extremely slow. No guarantees of conver-
gence are given!
While it is fashionable to decry the Metropolis-Hastings algorithm for its poor convergence
and other properties, it has the advantage of being easy to implement for a wide range of
models.

Value
A point pattern, in the form of an object of class "ppp". See [Link] for details.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link]

Examples
# See examples in [Link] and [Link]

[Link] Simulate Point Process Models using the Metropolis-Hastings Al-


gorithm.

Description
Generates a random point pattern, simulated from a chosen point process model, using the
Metropolis-Hastings algorithm.
[Link] 509

Usage
## Default S3 method:
rmh(model, start, control, verbose=TRUE, ...)

Arguments
model Data specifying the point process model that is to be simulated.
start Data determining the initial state of the algorithm.
control Data controlling the iterative behaviour and termination of the algorithm.
verbose Logical flag indicating whether to print progress reports.
... Further arguments which will be passed to any trend functions in model.

Details
This function generates simulated realisations from any of a range of spatial point processes,
using the Metropolis-Hastings algorithm. It is the default method for the generic function
rmh.
This function executes a Metropolis-Hastings algorithm with birth, death and shift propos-
als as described in Geyer and Moller (1994).
The argument model specifies the point process model to be simulated. It is either a list,
or an object of class "rmhmodel", with the following components:

cif A character string specifying the choice of interpoint interaction for the point process.
par Parameter values for the conditional intensity function.
w (Optional) window in which the pattern is to be generated. An object of class "owin",
or data acceptable to [Link].
trend Data specifying the spatial trend in the model, if it has a trend. This may be a
function, a pixel image (of class "im"), (or a list of functions or images if the model is
multitype).
If the trend is a function or functions, any auxiliary arguments ... to [Link]
will be passed to these functions, which should be of the form function(x, y, ...).
types List of possible types, for a multitype point process.

For full details of these parameters, see rmhmodel.


The argument start determines the initial state of the Metropolis-Hastings algorithm. It
is either a list, or an object of class "rmhstart", with the following components:

[Link] Number of points in the initial point pattern. A single integer, or a vector of
integers giving the numbers of points of each type in a multitype point pattern. In-
compatible with [Link].
[Link] Initial point pattern configuration. Incompatible with [Link].
[Link] may be a point pattern (an object of class "ppp"), or data which can be
coerced to this class by [Link], or an object with components x and y, or a two-
column matrix. In the last two cases, the window for the pattern is determined by
model$w. In the first two cases, if model$w is also present, then the final simulated
pattern will be clipped to the window model$w.
510 [Link]

For full details of these parameters, see rmhstart.


The third argument control controls the simulation procedure (including conditional sim-
ulation), iterative behaviour, and termination of the Metropolis-Hastings algorithm. It is
either a list, or an object of class "rmhcontrol", with components:
p The probability of proposing a “shift” (as opposed to a birth or death) in the Metropolis-
Hastings algorithm.
q The conditional probability of proposing a death (rather than a birth) given that birth/death
has been chosen over shift.
nrep The number of repetitions or iterations to be made by the Metropolis-Hastings algo-
rithm. It should be large.
expand Either a numerical expansion factor, or a window (object of class "owin"). Indi-
cates that the process is to be simulated on a larger domain than the original data
window w, then clipped to w when the algorithm has finished.
If the model has a trend, then in order for expansion to be feasible, the trend must be
given either as a function, or an image whose bounding box is large enough to contain
the expanded window.
periodic A logical scalar; if periodic is TRUE we simulate a process on the torus formed
by identifying opposite edges of a rectangular window.
ptypes A vector of probabilities (summing to 1) to be used in assigning a random type to
a new point.
fixall A logical scalar specifying whether to condition on the number of points of each type.
nverb An integer specifying how often “progress reports” (which consist simply of the
number of repetitions completed) should be printed out. If nverb is left at 0, the
default, the simulation proceeds silently.
[Link] If this argument is present, then conditional simulation will be performed, and
[Link] specifies the conditioning points and the type of conditioning.
For full details of these parameters, see rmhcontrol.

Value
A point pattern (an object of class "ppp", see [Link]).
The returned value has an attribute info containing modified versions of the arguments
model, start, and control which together specify the exact simulation procedure.
The value of .[Link] at the start of the simulations is also saved and returned as an
attribute seed.

Conditional Simulation
There are several kinds of conditional simulation.
ˆ Simulation conditional upon the number of points, that is, holding the number of points
fixed. To do this, set control$p (the probability of a shift) equal to 1. The number
of points is then determined by the starting state, which may be specified either by
setting start$[Link] to be a scalar, or by setting the initial pattern start$[Link].
ˆ In the case of multitype processes, it is possible to simulate the model conditionally
upon the number of points of each type, i.e. holding the number of points of each
type to be fixed. To do this, set control$p equal to 1 and control$fixall to be
TRUE. The number of points is then determined by the starting state, which may be
specified either by setting start$[Link] to be an integer vector, or by setting the
initial pattern start$[Link].
[Link] 511

ˆ Simulation conditional on the configuration observed in a sub-window, that is, requir-


ing that, inside a specified sub-window V , the simulated pattern should agree with
a specified point pattern [Link] do this, set control$[Link] to equal the specified
point pattern y, making sure that it is an object of class "ppp" and that the window
[Link](control$[Link]) is the conditioning window V .
ˆ Simulation conditional on the presence of specified points, that is, requiring that the
simulated pattern should include a specified set of points. This is simulation from the
Palm distribution of the point process given a pattern y. To do this, set control$[Link]
to be a [Link] containing the coordinates (and marks, if appropriate) of the spec-
ified points.

For further information, see rmhcontrol.


Note that, when we simulate conditionally on the number of points, or conditionally on the
number of points of each type, no expansion of the window is possible.

Warnings

There is never a guarantee that the Metropolis-Hastings algorithm has converged to its
limiting distribution.
If start$[Link] is specified then expand is set equal to 1 and simulation takes place in
[Link]$window. Any specified value for expand is simply ignored.
The presence of both a component w of model and a non-null value for [Link]$window
makes sense ONLY if w is contained in [Link]$window.
For multitype processes make sure that, even if there is to be no trend corresponding to a
particular type, there is still a component (a NULL component) for that type, in the list.

Other models

In theory, any finite point process model can be simulated using the Metropolis-Hastings
algorithm, provided the conditional intensity is uniformly bounded.
In practice, the list of point process models that can be simulated using [Link] is
limited to those that have been implemented in the package’s internal C code. More options
will be added in the future.
Note that the lookup conditional intensity function permits the simulation (in theory, to
any desired degree of approximation) of any pairwise interaction process for which the
interaction depends only on the distance between the pair of points.

Reproducible simulations

If the user wants the simulation to be exactly reproducible (e.g. for a figure in a journal
article, where it is useful to have the figure consistent from draft to draft) then the state
of the random number generator should be set before calling [Link]. This can be
done either by calling [Link] or by assigning a value to .[Link]. In the examples
below, we use [Link].
If a simulation has been performed and the user now wants to repeat it exactly, the random
seed should be extracted from the simulated point pattern X by seed <- attr(x, "seed"),
then assigned to the system random nunber state by .[Link] <- seed before calling
[Link].
512 [Link]

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283 – 322.
Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.
Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statis-
tical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.
Diggle, P.J., Gates, D.J., and Stibbard, A. (1987) A nonparametric estimator for pairwise-
interaction point processes. Biometrika 74, 763 – 770.
Geyer, C.J. and Moller, J. (1994) Simulation procedures and likelihood inference for spatial
point processes. Scandinavian Journal of Statistics 21, 359–373.
Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E.
Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry:
Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and
Applied Probability, number 80. Pages 79–140.

See Also
rmh, [Link], rStrauss, ppp, ppm, Strauss, Softcore, StraussHard, MultiStrauss,
MultiStraussHard, DiggleGratton

Examples
## Not run:
nr <- 1e5
nv <- 5000

## End(Not run)

[Link](961018)

# Strauss process.
mod01 <- list(cif="strauss",par=c(beta=2,gamma=0.2,r=0.7),
w=c(0,10,0,10))
[Link] <- rmh(model=mod01,start=list([Link]=80),
control=list(nrep=nr,nverb=nv))

# Strauss process, conditioning on n = 80:


[Link] <- rmh(model=mod01,start=list([Link]=80),
control=list(p=1,nrep=nr,nverb=nv))

# Strauss process equal to pure hardcore:


mod02 <- list(cif="strauss",par=c(beta=2,gamma=0,r=0.7),w=c(0,10,0,10))
[Link] <- rmh(model=mod02,start=list([Link]=60),
control=list(nrep=nr,nverb=nv))

# Strauss process in a polygonal window.


x <- c(0.55,0.68,0.75,0.58,0.39,0.37,0.19,0.26,0.42)
y <- c(0.20,0.27,0.68,0.99,0.80,0.61,0.45,0.28,0.33)
[Link] 513

mod03 <- list(cif="strauss",par=c(beta=2000,gamma=0.6,r=0.07),


w=owin(poly=list(x=x,y=y)))
[Link] <- rmh(model=mod03,start=list([Link]=90),
control=list(nrep=nr,nverb=nv))

# Strauss process in a polygonal window, conditioning on n = 80.


[Link] <- rmh(model=mod03,start=list([Link]=90),
control=list(p=1,nrep=nr,nverb=nv))

# Strauss process, starting off from [Link], but with the


# polygonal window replace by a rectangular one. At the end,
# the generated pattern is clipped to the original polygonal window.
xxx <- [Link]
xxx$window <- [Link](c(0,1,0,1))
[Link] <- rmh(model=mod03,start=list([Link]=xxx),
control=list(nrep=nr,nverb=nv))

# Strauss with hardcore:


mod04 <- list(cif="straush",par=c(beta=2,gamma=0.2,r=0.7,hc=0.3),
w=c(0,10,0,10))
[Link] <- rmh(model=mod04,start=list([Link]=70),
control=list(nrep=nr,nverb=nv))

# Another Strauss with hardcore (with a perhaps surprising result):


mod05 <- list(cif="straush",par=c(beta=80,gamma=0.36,r=45,hc=2.5),
w=c(0,250,0,250))
[Link] <- rmh(model=mod05,start=list([Link]=250),
control=list(nrep=nr,nverb=nv))

# Pure hardcore (identical to [Link]).


mod06 <- list(cif="straush",par=c(beta=2,gamma=1,r=1,hc=0.7),
w=c(0,10,0,10))
[Link] <- rmh(model=mod06,start=list([Link]=60),
control=list(nrep=nr,nverb=nv))

# Soft core:
par3 <- c(0.8,0.1,0.5)
w <- c(0,10,0,10)
mod07 <- list(cif="sftcr",par=c(beta=0.8,sigma=0.1,kappa=0.5),
w=c(0,10,0,10))
[Link] <- rmh(model=mod07,start=list([Link]=70),
control=list(nrep=nr,nverb=nv))

# Area-interaction process:
mod42 <- rmhmodel(cif="areaint",par=c(beta=2,eta=1.6,r=0.7),
w=c(0,10,0,10))
[Link] <- rmh(model=mod42,start=list([Link]=70),
control=list(nrep=nr,nverb=nv))

# Multitype Strauss:
beta <- c(0.027,0.008)
gmma <- matrix(c(0.43,0.98,0.98,0.36),2,2)
r <- matrix(c(45,45,45,45),2,2)
mod08 <- list(cif="straussm",par=list(beta=beta,gamma=gmma,radii=r),
w=c(0,250,0,250))
[Link] <- rmh(model=mod08,start=list([Link]=80),
514 [Link]

control=list(ptypes=c(0.75,0.25),nrep=nr,nverb=nv))

# Multitype Strauss conditioning upon the total number


# of points being 80:
[Link] <- rmh(model=mod08,start=list([Link]=80),
control=list(p=1,ptypes=c(0.75,0.25),nrep=nr,
nverb=nv))

# Conditioning upon the number of points of type 1 being 60


# and the number of points of type 2 being 20:
[Link] <- rmh(model=mod08,start=list([Link]=c(60,20)),
control=list(fixall=TRUE,p=1,ptypes=c(0.75,0.25),
nrep=nr,nverb=nv))

# Multitype Strauss hardcore:


rhc <- matrix(c(9.1,5.0,5.0,2.5),2,2)
mod09 <- list(cif="straushm",par=list(beta=beta,gamma=gmma,
iradii=r,hradii=rhc),w=c(0,250,0,250))
[Link] <- rmh(model=mod09,start=list([Link]=80),
control=list(ptypes=c(0.75,0.25),nrep=nr,nverb=nv))

# Multitype Strauss hardcore with trends for each type:


beta <- c(0.27,0.08)
tr3 <- function(x,y){x <- x/250; y <- y/250;
exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
}
# log quadratic trend
tr4 <- function(x,y){x <- x/250; y <- y/250;
exp(-0.6*x+0.5*y)}
# log linear trend
mod10 <- list(cif="straushm",par=list(beta=beta,gamma=gmma,
iradii=r,hradii=rhc),w=c(0,250,0,250),
trend=list(tr3,tr4))
[Link] <- rmh(model=mod10,start=list([Link]=350),
control=list(ptypes=c(0.75,0.25),
nrep=nr,nverb=nv))

# Multitype Strauss hardcore with trends for each type, given as images:
bigwin <- square(250)
i1 <- [Link](tr3, bigwin)
i2 <- [Link](tr4, bigwin)
mod11 <- list(cif="straushm",par=list(beta=beta,gamma=gmma,
iradii=r,hradii=rhc),w=bigwin,
trend=list(i1,i2))
[Link] <- rmh(model=mod11,start=list([Link]=350),
control=list(ptypes=c(0.75,0.25),expand=1,
nrep=nr,nverb=nv))

# Diggle, Gates, and Stibbard:


mod12 <- list(cif="dgs",par=c(beta=3600,rho=0.08),w=c(0,1,0,1))
[Link] <- rmh(model=mod12,start=list([Link]=300),
control=list(nrep=nr,nverb=nv))

# Diggle-Gratton:
mod13 <- list(cif="diggra",
par=c(beta=1800,kappa=3,delta=0.02,rho=0.04),
w=square(1))
[Link] 515

[Link] <- rmh(model=mod13,start=list([Link]=300),


control=list(nrep=nr,nverb=nv))

# Geyer:
mod14 <- list(cif="geyer",par=c(beta=1.25,gamma=1.6,r=0.2,sat=4.5),
w=c(0,10,0,10))
[Link] <- rmh(model=mod14,start=list([Link]=200),
control=list(nrep=nr,nverb=nv))

# Geyer; same as a Strauss process with parameters


# (beta=2.25,gamma=0.16,r=0.7):

mod15 <- list(cif="geyer",par=c(beta=2.25,gamma=0.4,r=0.7,sat=10000),


w=c(0,10,0,10))
[Link] <- rmh(model=mod15,start=list([Link]=200),
control=list(nrep=nr,nverb=nv))

mod16 <- list(cif="geyer",par=c(beta=8.1,gamma=2.2,r=0.08,sat=3))


data(redwood)
[Link] <- rmh(model=mod16,start=list([Link]=redwood),
control=list(periodic=TRUE,nrep=nr,nverb=nv))

# Geyer, starting from the redwood data set, simulating


# on a torus, and conditioning on n:
[Link] <- rmh(model=mod16,start=list([Link]=redwood),
control=list(p=1,periodic=TRUE,nrep=nr,nverb=nv))

# Lookup (interaction function h_2 from page 76, Diggle (2003)):


r <- seq(from=0,to=0.2,length=101)[-1] # Drop 0.
h <- 20*(r-0.05)
h[r<0.05] <- 0
h[r>0.10] <- 1
mod17 <- list(cif="lookup",par=list(beta=4000,h=h,r=r),w=c(0,1,0,1))
[Link] <- rmh(model=mod17,start=list([Link]=100),
control=list(nrep=nr,nverb=nv))

# Strauss with trend


tr <- function(x,y){x <- x/250; y <- y/250;
exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
}
beta <- 0.3
gmma <- 0.5
r <- 45
mod17 <- list(cif="strauss",par=c(beta=beta,gamma=gmma,r=r),
w=square(1), trend=tr3)
[Link] <- rmh(model=mod17,start=list([Link]=90),
control=list(nrep=nr,nverb=nv))
# Baddeley-Geyer
r <- seq(0,0.2,length=8)[-1]
gmma <- c(0.5,0.6,0.7,0.8,0.7,0.6,0.5)
mod18 <- list(cif="badgey",par=list(beta=4000, gamma=gmma,r=r,sat=5),
w=square(1))
[Link] <- rmh(model=mod18,start=list([Link]=100),
control=list(nrep=nr,nverb=nv))
mod19 <- list(cif="badgey",
par=list(beta=4000, gamma=gmma,r=r,sat=1e4),
w=square(1))
516 [Link]

[Link](1329)
[Link] <- rmh(model=mod18,start=list([Link]=100),
control=list(nrep=nr,nverb=nv))

# Check:
h <- ((prod(gmma)/cumprod(c(1,gmma)))[-8])^2
hs <- stepfun(r,c(h,1))
mod20 <- list(cif="lookup",par=list(beta=4000,h=hs),w=square(1))
[Link](1329)
[Link] <- rmh(model=mod20,start=list([Link]=100),
control=list(nrep=nr,nverb=nv))
# [Link] and [Link] will be identical.

mod21 <- list(cif="badgey",par=list(beta=300,gamma=c(1,0.4,1),


r=c(0.035,0.07,0.14),sat=5), w=square(1))
[Link] <- rmh(model=mod21,start=list([Link]=100),
control=list(nrep=nr,nverb=nv))
# Same result as Geyer model with beta=300, gamma=0.4, r=0.07,
# sat = 5 (if seeds and control parameters are the same)

# Or more simply:
mod22 <- list(cif="badgey",
par=list(beta=300,gamma=0.4,r=0.07, sat=5),
w=square(1))
[Link] <- rmh(model=mod22,start=list([Link]=100),
control=list(nrep=nr,nverb=nv))
# Same again --- i.e. the BadGey model includes the Geyer model.

[Link] Simulate from a Fitted Point Process Model

Description
Given a point process model fitted to data, generate a random simulation of the model,
using the Metropolis-Hastings algorithm.

Usage
## S3 method for class 'ppm':
rmh(model,start=NULL,
control=rmhcontrol(),
..., verbose=TRUE, project=TRUE)

Arguments
model A fitted point process model (object of class "ppm", see [Link])
which it is desired to simulate. This fitted model is usually the result of
a call to ppm. See Details below.
start Data determining the initial state of the Metropolis-Hastings algorithm.
See rmhstart for description of these arguments. Defaults to list([Link]=[Link](model
control Data controlling the running of the Metropolis-Hastings algorithm. See
rmhcontrol for description of these arguments.
[Link] 517

... Further arguments passed to [Link].


verbose Logical flag indicating whether to print progress reports.
project Logical flag indicating what to do if the fitted model is invalid (in the
sense that the values of the fitted coefficients do not specify a valid point
process). If project=TRUE the closest valid model will be simulated; if
project=FALSE an error will occur.

Details
This function generates simulated realisations from a point process model that has been
fitted to point pattern data. It is a method for the generic function rmh for the class "ppm"
of fitted point process models. To simulate other kinds of point process models, see rmh or
[Link].
The argument model describes the fitted model. It must be an object of class "ppm" (see
[Link]), and will typically be the result of a call to the point process model fitting
function ppm.
The current implementation enables simulation from any fitted model involving the inter-
actions DiggleGratton, Geyer, MultiStrauss, MultiStraussHard, PairPiece, Poisson,
Strauss, StraussHard and Softcore, including nonstationary models. See the examples.
It is possible that the fitted coefficients of a point process model may be “illegal”, i.e. that
there may not exist a mathematically well-defined point process with the given parameter
values. For example, a Strauss process with interaction parameter γ > 1 does not exist, but
the model-fitting procedure used in ppm will sometimes produce values of γ greater than
1. In such cases, if project=FALSE then an error will occur, while if project=TRUE then
[Link] will find the nearest legal model and simulate this model instead. (The nearest
legal model is obtained by projecting the vector of coefficients onto the set of valid coefficient
vectors. The result is usually the Poisson process with the same fitted intensity.)
The arguments start and control are lists of parameters determining the initial state
and the iterative behaviour, respectively, of the Metropolis-Hastings algorithm. They are
passed directly to rmhstart and rmhcontrol respectively. See rmhstart and rmhcontrol
for details of these parameters.
Note that if you specify control$expand > 1 (so that the model will be simulated on a win-
dow larger than the original data window) then the model must be capable of extrapolation
to this larger window. This excludes models which depend on external covariates.
After extracting the relevant information from the fitted model object model, [Link]
simply invokes the default rmh algorithm [Link], unless the model is Poisson.
If the model is Poisson then the Metropolis-Hastings algorithm is not needed, and the model
is simulated directly, using one of rpoispp, rmpoispp, rpoint or rmpoint.
See [Link] for further information about the implementation, or about the Metropolis-
Hastings algorithm.

Value
A point pattern (an object of class "ppp"; see [Link]).

Warnings
See Warnings in [Link].
518 [Link]

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], rmh, rmhmodel, rmhcontrol, rmhstart, [Link], [Link], ppm,
PairPiece, Poisson, Strauss, StraussHard, Softcore, Geyer, AreaInter, DiggleGratton

Examples
data(swedishpines)
X <- swedishpines
plot(X, main="Swedish Pines data")

# Poisson process
fit <- ppm(X, ~1, Poisson())
Xsim <- rmh(fit)
plot(Xsim, main="simulation from fitted Poisson model")

# Strauss process
fit <- ppm(X, ~1, Strauss(r=7))
Xsim <- rmh(fit, control=list(nrep=1e3))
plot(Xsim, main="simulation from fitted Strauss model")

## Not run:
# Strauss process simulated on a larger window
# then clipped to original window
Xsim <- rmh(fit, control=list(nrep=1e3, expand=2, periodic=TRUE))

# Strauss - hard core process


fit <- ppm(X, ~1, StraussHard(r=7,hc=2))
Xsim <- rmh(fit, start=list([Link]=X$n), control=list(nrep=1e3))
plot(Xsim, main="simulation from fitted Strauss hard core model")

# Geyer saturation process


fit <- ppm(X, ~1, Geyer(r=7,sat=2))
Xsim <- rmh(fit, start=list([Link]=X$n), control=list(nrep=1e3))
plot(Xsim, main="simulation from fitted Geyer model")

# Area-interaction process
fit <- ppm(X, ~1, AreaInter(r=7))
Xsim <- rmh(fit, start=list([Link]=X$n), control=list(nrep=1e3))
plot(Xsim, main="simulation from fitted area-interaction model")

# soft core interaction process


Q <- quadscheme(X, nd=50)
fit <- ppm(Q, ~1, Softcore(kappa=0.1), correction="isotropic")
Xsim <- rmh(fit, start=list([Link]=X$n), control=list(nrep=1e3))
plot(Xsim, main="simulation from fitted Soft Core model")

data(cells)
plot(cells)
# Diggle-Gratton pairwise interaction model
fit <- ppm(cells, ~1, DiggleGratton(0.05, 0.1))
Xsim <- rmh(fit, start=list([Link]=cells$n), control=list(nrep=1e3))
rmhcontrol 519

plot(Xsim, main="simulation from fitted Diggle-Gratton model")

X <- rSSI(0.05, 100)


plot(X, main="new data")

# piecewise-constant pairwise interaction function


fit <- ppm(X, ~1, PairPiece(seq(0.02, 0.1, by=0.01)))
Xsim <- rmh(fit, control=list(nrep=1e3))
plot(Xsim, main="simulation from fitted pairwise model")

# marked point pattern


data(amacrine)
Y <- amacrine
plot(Y, main="Amacrine data")

# marked Poisson models


fit <- ppm(Y)
Ysim <- rmh(fit)
plot(Ysim, main="simulation from ppm(Y)")

fit <- ppm(Y,~marks)


Ysim <- rmh(fit)
plot(Ysim, main="simulation from ppm(Y, ~marks)")

fit <- ppm(Y,~polynom(x,y,2))


Ysim <- rmh(fit)
plot(Ysim, main="simulation from ppm(Y, ~polynom(x,y,2))")

fit <- ppm(Y,~marks+polynom(x,y,2))


Ysim <- rmh(fit)
plot(Ysim, main="simulation from ppm(Y, ~marks+polynom(x,y,2))")

fit <- ppm(Y,~marks*polynom(x,y,2))


Ysim <- rmh(fit)
plot(Ysim, main="simulation from ppm(Y, ~marks*polynom(x,y,2))")

# multitype Strauss models


MS <- MultiStrauss(types = levels(Y$marks),
radii=matrix(0.07, ncol=2, nrow=2))
fit <- ppm(Y, ~marks, MS)
Ysim <- rmh(fit, control=list(nrep=1e3))
plot(Ysim, main="simulation from fitted Multitype Strauss")

fit <- ppm(Y,~marks*polynom(x,y,2), MS)


Ysim <- rmh(fit, control=list(nrep=1e3))
plot(Ysim, main="simulation from fitted inhomogeneous Multitype Strauss")

## End(Not run)

rmhcontrol Set Control Parameters for Metropolis-Hastings Algorithm.

Description
Sets up a list of parameters controlling the iterative behaviour of the Metropolis-Hastings
algorithm.
520 rmhcontrol

Usage
rmhcontrol(...)
## Default S3 method:
rmhcontrol(..., p=0.9, q=0.5, nrep=5e5,
expand=NULL, periodic=FALSE, ptypes=NULL,
[Link]=NULL, fixall=FALSE, nverb=0)

Arguments
... Arguments passed to methods.
p Probability of proposing a shift (as against a birth/death)
q Conditional probability of proposing a death given that a birth or death
will be proposed
nrep Total number of steps (proposals) of Metropolis-Hastings algorithm that
should be run
expand Either a numerical expansion factor, or a window (object of class "owin"),
specifying that simulations are to be performed in a domain larger than
the original data window, then clipped to the original data window.
periodic (Logical) whether to simulate “periodically”, i.e. on a torus formed by
identifying opposite edges of a rectangle.
ptypes For multitype point processes, the distribution of the mark attached to a
new random point (when a birth is proposed)
[Link] Conditioning points for conditional simulation.
fixall (Logical) for multitype point processes, whether to fix the number of
points of each type.
nverb Progress reports will be printed every nverb iterations

Details
The Metropolis-Hastings algorithm, implemented as rmh, generates simulated realisations of
point process models. This function rmhcontrol sets up a list of parameters which control
the iterative behaviour and termination of the Metropolis-Hastings algorithm, for use in a
subsequent call to rmh. It also checks that the parameters are valid.
(A separate function rmhstart determines the initial state of the algorithm, and rmhmodel
determines the model to be simulated.)
The parameters are as follows:

p The probability of proposing a “shift” (as opposed to a birth or death) in the Metropolis-
Hastings algorithm.
If p = 1 then the algorithm only alters existing points, so the number of points never
changes, i.e. we are simulating conditionally upon the number of points. The number
of points is determined by the initial state (specified by rmhstart).
If p = 1 and fixall=TRUE and the model is a multitype point process model, then the
algorithm only shifts the locations of existing points and does not alter their marks
(types). This is equivalent to simulating conditionally upon the number of points of
each type. These numbers are again specified by the initial state.
If p = 1 then no expansion of the simulation window is allowed (see expand below).
q The conditional probability of proposing a death (rather than a birth) given that a shift
is not proposed. This is of course ignored if p is equal to 1.
rmhcontrol 521

nrep The number of repetitions or iterations to be made by the Metropolis-Hastings algo-


rithm. It should be large.
expand Either a numerical expansion factor, or a window (object of class "owin"). Indi-
cates that the process is to be simulated on a larger domain than the original data
window w, then clipped to w when the algorithm has finished. This would often be
done in order to approximate the simulation of a stationary process (Geyer, 1999) or
more generally a process existing in the whole plane, rather than just in the window
w.
If expand is a window object, it is taken as the larger domain in which simulation
is performed. If expand is numeric, it is interpreted as the factor by which the area
of the enclosing box of the window w is to be expanded (i.e. width and height are
stretched by the same factor sqrt(area)). The expansion is computed by the function
[Link].
If expand equals 1 then no expansion is performed. Any value of expand smaller than
1 is ignored and treated as 1.
Expansion is not permitted if the number of points has been fixed by setting p = 1 or
if the starting configuration has been specified via the argument [Link] in rmhstart.
In these cases expand defaults to 1.
Otherwise, expand defaults to 2.
periodic A logical scalar; if periodic is TRUE we simulate a process on the torus formed
by identifying opposite edges of a rectangular window. This window could be the
“original” window if that window is rectangular, or the bounding box of that window,
or an expansion of the bounding box (when expand is greater than 1). In the latter
two cases the simulated pattern is clipped to the original window.
ptypes A vector of probabilities (summing to 1) to be used in assigning a random type to
a new point. Defaults to a vector each of whose entries is 1/nt where nt is the number
of types for the process. Convergence of the simulation algorithm should be improved
if ptypes is close to the relative frequencies of the types which will result from the
simulation.
[Link] If this argument is given, then conditional simulation will be performed, and
[Link] specifies the location of the fixed points as well as the type of condition-
ing. It should be either a point pattern (object of class "ppp") or a list(x,y) or a
[Link]. See the section on Conditional Simulation.
fixall A logical scalar specifying whether to condition on the number of points of each
type. Meaningful only if a marked process is being simulated, and if p = 1. A warning
message is given if fixall is set equal to TRUE when it is not meaningful.
nverb An integer specifying how often “progress reports” (which consist simply of the
number of repetitions completed) should be printed out. If nverb is left at 0, the
default, the simulation proceeds silently.

Value
An object of class "rmhcontrol", which is essentially a list of parameter values for the
algorithm.
There is a print method for this class, which prints a sensible description of the parameters
chosen.

Conditional Simulation
For a Gibbs point process X, the Metropolis-Hastings algorithm easily accommodates sev-
eral kinds of conditional simulation:
522 rmhcontrol

conditioning on the total number of points: We fix the total number of points N (X)
to be equal to n. We simulate from the conditional distribution of X given N (X) = n.
conditioning on the number of points of each type: In a multitype point process,
where Yj denotes the process of points of type j, we fix the number N (Yj ) of points
of type j to be equal to nj , for j = 1, 2, . . . , m. We simulate from the conditional
distribution of X given N (Yj ) = nj for j = 1, 2, . . . , m.
conditioning on the realisation in a subwindow: We require that the point process
X should, within a specified sub-window V , coincide with a specified point pattern y.
We simulate from the conditional distribution of X given X ∩ V = y.
Palm conditioning: We require that the point process X include a specified list of points
y. We simulate from the point process with probability density g(x) = cf (x ∪ y) where
f is the probability density of the original process X, and c is a normalising constant.

To achieve each of these types of conditioning we do as follows:

conditioning on the total number of points: Set p=1. The number of points is deter-
mined by the initial state of the simulation: see rmhstart.
conditioning on the number of points of each type: Set p=1 and fixall=TRUE. The
number of points of each type is determined by the initial state of the simulation: see
rmhstart.
conditioning on the realisation in a subwindow: Set [Link] to be a point pattern
(object of class "ppp"). Its window V=[Link]$window becomes the conditioning sub-
window V .
Palm conditioning: Set [Link] to be a list(x,y) or [Link] with two columns
containing the coordinates of the points, or a list(x,y,marks) or [Link] with
three columns containing the coordinates and marks of the points.

The arguments [Link], p and fixall can be combined.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E.
Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry:
Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and
Applied Probability, number 80. Pages 79–140.

See Also
rmh, rmhmodel, rmhstart, [Link]

Examples
# parameters given as named arguments
c1 <- rmhcontrol(p=0.3,periodic=TRUE,nrep=1e6,nverb=1e5)

# parameters given as a list


liz <- list(p=0.9, nrep=1e4)
c2 <- rmhcontrol(liz)
rmhmodel 523

# parameters given in rmhcontrol object


c3 <- rmhcontrol(c1)

rmhmodel Define Point Process Model for Metropolis-Hastings Simulation.

Description

Builds a description of a point process model for use in simulating the model by the
Metropolis-Hastings algorithm.

Usage

rmhmodel(...)

Arguments

... Arguments specifying the point process model in some format.

Details

Simulated realisations of many point process models can be generated using the Metropolis-
Hastings algorithm rmh. The algorithm requires the model to be specified in a particular
format: an object of class "rmhmodel".
The function rmhmodel takes a description of a point process model in some other format,
and converts it into an object of class "rmhmodel". It also checks that the parameters of
the model are valid.
The function rmhmodel is generic, with methods for

fitted point process models: an object of class "ppm", obtained by a call to the model-
fitting function ppm. See [Link].
lists: a list of parameter values in a certain format. See [Link].
default: parameter values specified as separate arguments to .... See [Link].

Value

An object of class "rmhmodel", which is essentially a list of parameter values for the model.
There is a print method for this class, which prints a sensible description of the model
chosen.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>
524 [Link]

References

Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.
Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statis-
tical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.
Diggle, P.J., Gates, D.J., and Stibbard, A. (1987) A nonparametric estimator for pairwise-
interaction point processes. Biometrika 74, 763 – 770. Scandinavian Journal of Statistics
21, 359–373.
Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E.
Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry:
Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and
Applied Probability, number 80. Pages 79–140.

See Also

[Link], [Link], [Link], rmh, rmhcontrol, rmhstart, ppm,


Strauss, Softcore, StraussHard, MultiStrauss, MultiStraussHard, DiggleGratton,
PairPiece

[Link] Build Point Process Model for Metropolis-Hastings Simulation.

Description

Builds a description of a point process model for use in simulating the model by the
Metropolis-Hastings algorithm.

Usage

## Default S3 method:
rmhmodel(...,
cif=NULL, par=NULL, w=NULL, trend=NULL, types=NULL)

Arguments

... Ignored.
cif Character string specifying the choice of model
par Parameters of the model
w Spatial window in which to simulate
trend Specification of the trend in the model
types A vector of factor levels defining the possible marks, for a multitype pro-
cess.
[Link] 525

Details
The generic function rmhmodel takes a description of a point process model in some format,
and converts it into an object of class "rmhmodel" so that simulations of the model can be
generated using the Metropolis-Hastings algorithm rmh.
This function [Link] is the default method. It builds a description of the point
process model from the simple arguments listed.
The argument cif is a character string specifying the choice of interpoint interaction for
the point process. The current options are
’strauss’ The Strauss process
’straush’ The Strauss process with hard core
’sftcr’ The Softcore process
’straussm’ The multitype Strauss process
’straushm’ Multitype Strauss process with hard core
’dgs’ Diggle, Gates and Stibbard (1987) process
’diggra’ Diggle and Gratton (1984) process
’geyer’ Saturation process (Geyer, 1999).
’lookup’ General isotropic pairwise interaction process, with the interaction function spec-
ified via a “lookup table”.
’areaint’ Area-interaction process.
’badgey’ Baddeley-Geyer (hybrid Geyer) process.
The argument par supplies parameter values appropriate to the conditional intensity func-
tion being invoked. These are:
areaint: (Area-interaction process.) A named vector with components beta,eta,r which
are respectively the “base” intensity, the scaled interaction parameter and the interac-
tion radius.
badgey: (Baddeley-Geyer process.) A name list with components beta (the “base” inten-
sity), gamma (a vector of non-negative interaction parameters), r (a vector of interaction
radii, of the same length as gamma, in increasing order), and sat (the saturation pa-
rameter(s); this may be a scalar, or a vector of the same length as gamma and r; all
values should be at least 1). Note that because of the presence of “saturation” the
gamma values are permitted to be larger than 1.
strauss: (Strauss process.) A named vector with components beta,gamma,r which are
respectively the “base” intensity, the pairwise interaction parameter and the interaction
radius. Note that gamma must be less than or equal to 1. (Note that there is also an
algorithm for perfect simulation of the Strauss process, rStrauss)
straush: (Strauss process with hardcore.) A named vector with entries beta,gamma,r,hc
where beta, gamma, and r are as for the Strauss process, and hc is the hardcore radius.
Of course hc must be less than r.
sftcr: (Softcore process.) A named vector with components beta,sigma,kappa. Again
beta is a “base” intensity. The pairwise interaction between two points u 6= v is
(  2/κ )
σ
exp −
||u − v||

Note that it is necessary that 0 < κ < 1.


526 [Link]

straussm: (Multitype Strauss process.) A named list with components


ˆ beta: A vector of “base” intensities, one for each possible type.
ˆ gamma: A symmetric matrix of interaction parameters, with γij pertaining to
the interaction between type i and type j.
ˆ radii: A symmetric matrix of interaction radii, with entries rij pertaining to
the interaction between type i and type j.
straushm: (Multitype Strauss process with hardcore.) A named list with components
beta and gamma as for straussm and two “radii” components:
ˆ iradii: the interaction radii
ˆ hradii: the hardcore radii
which are both symmetric matrices of nonnegative numbers. The entries of hradii
must be less than the corresponding entries of iradii.
dgs: (Diggle, Gates, and Stibbard process. See Diggle, Gates, and Stibbard (1987)) A
named vector with components beta and rho. This process has pairwise interaction
function equal to  
πt
e(t) = sin2

for t < ρ, and equal to 1 for t ≥ ρ.
diggra: (Diggle-Gratton process. See Diggle and Gratton (1984) and Diggle, Gates and
Stibbard (1987).) A named vector with components beta, kappa, delta and rho.
This process has pairwise interaction function e(t) equal to 0 for t < δ, equal to
 κ
t−δ
ρ−δ

for δ ≤ t < ρ, and equal to 1 for t ≥ ρ. Note that here we use the symbol κ where
Diggle, Gates, and Stibbard use β since we reserve the symbol β for an intensity
parameter.
geyer: (Geyer’s saturation process. See Geyer (1999).) A named vector with components
beta, gamma, r, and sat. The components beta, gamma, r are as for the Strauss model,
and sat is the “saturation” parameter. The model is Geyer’s “saturation” point process
model, a modification of the Strauss process in which we effectively impose an upper
limit (sat) on the number of neighbours which will be counted as close to a given
point.
Explicitly, a saturation point process with interaction radius r, saturation threshold
s, and parameters β and γ, is the point process in which each point xi in the pattern
X contributes a factor
βγ min(s,t(xi ,X))
to the probability density of the point pattern, where t(xi , X) denotes the number of
“r-close neighbours” of xi in the pattern X.
If the saturation threshold s is infinite, the Geyer process reduces to a Strauss process
with interaction parameter γ 2 rather than γ.
lookup: (Arbitrary pairwise interaction process with isotropic interaction.) A named list
with components beta, r, and h, or just with components beta and h.
This model is the pairwise interaction process with an isotropic interaction given by
any chosen function H. Each pair of points xi , xj in the point pattern contributes a
factor H(d(xi , xj )) to the probability density, where d denotes distance and H is the
pair interaction function.
[Link] 527

The component beta is a (positive) scalar which determines the “base” intensity of the
process.
In this implementation, H must be a step function. It is specified by the user in one
of two ways.
ˆ as a vector of values: If r is present, then r is assumed to give the locations of
jumps in the function H, while the vector h gives the corresponding values of the
function.
Specifically, the interaction function H(t) takes the value h[1] for distances t in
the interval [0, r[1]); takes the value h[i] for distances t in the interval [r[i-
1], r[i]) where i = 2, . . . , n; and takes the value 1 for t ≥ r[n]. Here n denotes
the length of r.
The components r and h must be numeric vectors of equal length. The r values
must be strictly positive, and sorted in increasing order.
The entries of h must be non-negative. If any entry of h is greater than 1, then
the entry h[1] must be 0 (otherwise the specified process is non-existent).
Greatest efficiency is achieved if the values of r are equally spaced.
[Note: The usage of r and h has changed from the previous usage in spatstat
versions 1.4-7 to 1.5-1, in which ascending order was not required, and in which
the first entry of r had to be 0.]
ˆ as a stepfun object: If r is absent, then h must be an object of class "stepfun"
specifying a step function. Such objects are created by stepfun.
The stepfun object h must be right-continuous (which is the default using stepfun.)
The values of the step function must all be nonnegative. The values must all be
less than 1 unless the function is identically zero on some initial interval [0, r).
The rightmost value (the value of h(t) for large t) must be equal to 1.
Greatest efficiency is achieved if the jumps (the “knots” of the step function) are
equally spaced.

The optional argument trend determines the spatial trend in the model, if it has one. It
should be a function or image (or a list of such, if the model is multitype) to provide the
value of the trend at an arbitrary point.

trend given as a function: A trend function may be a function of any number of argu-
ments, but the first two must be the x, y coordinates of a point. Auxiliary arguments
may be passed to the trend function at the time of simulation, via the ... argument
to rmh.
The function must be vectorized. That is, it must be capable of accepting vector
valued x and y arguments. Put another way, it must be capable of calculating the
trend value at a number of points, simultaneously, and should return the vector of
corresponding trend values.
trend given as an image: An image (see [Link]) provides the trend values at a grid
of points in the observation window and determines the trend value at other points as
the value at the nearest grid point.

Note that the trend or trends must be non-negative; no checking is done for this.
The optional argument w specifies the window in which the pattern is to be generated. If
specified, it must be in a form which can be coerced to an object of class owin by [Link].
The optional argument types specifies the possible types in a multitype point process. If
the model being simulated is multitype, and types is not specified, then this vector defaults
to 1:ntypes where ntypes is the number of types.
528 [Link]

Value
An object of class "rmhmodel", which is essentially a list of parameter values for the model.
There is a print method for this class, which prints a sensible description of the model
chosen.

Warnings in Respect of “lookup”


For the lookup cif, the entries of the r component of par must be strictly positive and
sorted into ascending order.
Note that if you specify the lookup pairwise interaction function via stepfun() the argu-
ments x and y which are passed to stepfun() are slightly different from r and h: length(y)
is equal to 1+length(x); the final entry of y must be equal to 1 — i.e. this value is explicitly
supplied by the user rather than getting tacked on internally.
The step function returned by stepfun() must be right continuous (this is the default
behaviour of stepfun()) otherwise an error is given.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.
Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statis-
tical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.
Diggle, P.J., Gates, D.J., and Stibbard, A. (1987) A nonparametric estimator for pairwise-
interaction point processes. Biometrika 74, 763 – 770. Scandinavian Journal of Statistics
21, 359–373.
Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E.
Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry:
Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and
Applied Probability, number 80. Pages 79–140.

See Also
rmh, rmhcontrol, rmhstart, ppm, AreaInter, Strauss, Softcore, StraussHard, MultiStrauss,
MultiStraussHard, DiggleGratton, PairPiece

Examples
# Strauss process:
mod01 <- rmhmodel(cif="strauss",par=c(beta=2,gamma=0.2,r=0.7),
w=c(0,10,0,10))
# The above could also be simulated using 'rStrauss'

# Strauss with hardcore:


mod04 <- rmhmodel(cif="straush",par=c(beta=2,gamma=0.2,r=0.7,hc=0.3),
w=owin(c(0,10),c(0,5)))

# Soft core:
par3 <- c(0.8,0.1,0.5)
w <- square(10)
[Link] 529

mod07 <- rmhmodel(cif="sftcr",


par=c(beta=0.8,sigma=0.1,kappa=0.5),
w=w)

# Area-interaction process:
mod42 <- rmhmodel(cif="areaint",par=c(beta=2,eta=1.6,r=0.7),
w=c(0,10,0,10))

# Baddeley-Geyer process:
mod99 <- rmhmodel(cif="badgey",par=list(beta=0.3,
gamma=c(0.2,1.8,2.4),r=c(0.035,0.07,0.14),sat=5),
w=[Link]())

# Multitype Strauss:
beta <- c(0.027,0.008)
gmma <- matrix(c(0.43,0.98,0.98,0.36),2,2)
r <- matrix(c(45,45,45,45),2,2)
mod08 <- rmhmodel(cif="straussm",
par=list(beta=beta,gamma=gmma,radii=r),
w=square(250))
# specify types
mod09 <- rmhmodel(cif="straussm",
par=list(beta=beta,gamma=gmma,radii=r),
w=square(250),
types=c("A", "B"))

# Multitype Strauss hardcore with trends for each type:


beta <- c(0.27,0.08)
ri <- matrix(c(45,45,45,45),2,2)
rhc <- matrix(c(9.1,5.0,5.0,2.5),2,2)
tr3 <- function(x,y){x <- x/250; y <- y/250;
exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
}
# log quadratic trend
tr4 <- function(x,y){x <- x/250; y <- y/250;
exp(-0.6*x+0.5*y)}
# log linear trend
mod10 <- rmhmodel(cif="straushm",par=list(beta=beta,gamma=gmma,
iradii=ri,hradii=rhc),w=c(0,250,0,250),
trend=list(tr3,tr4))

# Lookup (interaction function h_2 from page 76, Diggle (2003)):


r <- seq(from=0,to=0.2,length=101)[-1] # Drop 0.
h <- 20*(r-0.05)
h[r<0.05] <- 0
h[r>0.10] <- 1
mod17 <- rmhmodel(cif="lookup",par=list(beta=4000,h=h,r=r),w=c(0,1,0,1))

[Link] Define Point Process Model for Metropolis-Hastings Simulation.

Description
Given a list of parameters, builds a description of a point process model for use in simulating
the model by the Metropolis-Hastings algorithm.
530 [Link]

Usage
## S3 method for class 'list':
rmhmodel(model, ...)

Arguments
model A list of parameters. See Details.
... There should be no other arguments.

Details
The generic function rmhmodel takes a description of a point process model in some format,
and converts it into an object of class "rmhmodel" so that simulations of the model can be
generated using the Metropolis-Hastings algorithm rmh.
This function [Link] is the method for lists. The argument model should be a
named list of parameters of the form
list(cif, par, w, trend, types)
where cif and par are required and the others are optional. For details about these
components, see [Link].

Value
An object of class "rmhmodel", which is essentially a validated list of parameter values for
the model.
There is a print method for this class, which prints a sensible description of the model
chosen.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.
Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statis-
tical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.
Diggle, P.J., Gates, D.J., and Stibbard, A. (1987) A nonparametric estimator for pairwise-
interaction point processes. Biometrika 74, 763 – 770. Scandinavian Journal of Statistics
21, 359–373.
Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E.
Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry:
Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and
Applied Probability, number 80. Pages 79–140.

See Also
rmhmodel, [Link], [Link], rmh, rmhcontrol, rmhstart, ppm, Strauss,
Softcore, StraussHard, MultiStrauss, MultiStraussHard, DiggleGratton, PairPiece
[Link] 531

Examples

# Strauss process:
mod01 <- list(cif="strauss",par=c(beta=2,gamma=0.2,r=0.7),
w=c(0,10,0,10))
mod01 <- rmhmodel(mod01)

# Strauss with hardcore:


mod04 <- list(cif="straush",par=c(beta=2,gamma=0.2,r=0.7,hc=0.3),
w=owin(c(0,10),c(0,5)))
mod04 <- rmhmodel(mod04)

# Soft core:
par3 <- c(0.8,0.1,0.5)
w <- square(10)
mod07 <- list(cif="sftcr",
par=c(beta=0.8,sigma=0.1,kappa=0.5),
w=w)
mod07 <- rmhmodel(mod07)

# Multitype Strauss:
beta <- c(0.027,0.008)
gmma <- matrix(c(0.43,0.98,0.98,0.36),2,2)
r <- matrix(c(45,45,45,45),2,2)
mod08 <- list(cif="straussm",
par=list(beta=beta,gamma=gmma,radii=r),
w=square(250))
mod08 <- rmhmodel(mod08)

# specify types
mod09 <- rmhmodel(list(cif="straussm",
par=list(beta=beta,gamma=gmma,radii=r),
w=square(250),
types=c("A", "B")))

# Multitype Strauss hardcore with trends for each type:


beta <- c(0.27,0.08)
ri <- matrix(c(45,45,45,45),2,2)
rhc <- matrix(c(9.1,5.0,5.0,2.5),2,2)
tr3 <- function(x,y){x <- x/250; y <- y/250;
exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
}
# log quadratic trend
tr4 <- function(x,y){x <- x/250; y <- y/250;
exp(-0.6*x+0.5*y)}
# log linear trend
mod10 <- list(cif="straushm",par=list(beta=beta,gamma=gmma,
iradii=ri,hradii=rhc),w=c(0,250,0,250),
trend=list(tr3,tr4))
mod10 <- rmhmodel(mod10)

# Lookup (interaction function h_2 from page 76, Diggle (2003)):


r <- seq(from=0,to=0.2,length=101)[-1] # Drop 0.
h <- 20*(r-0.05)
h[r<0.05] <- 0
h[r>0.10] <- 1
mod17 <- list(cif="lookup",par=list(beta=4000,h=h,r=r),w=c(0,1,0,1))
532 [Link]

mod17 <- rmhmodel(mod17)

[Link] Interpret Fitted Model for Metropolis-Hastings Simulation.

Description
Converts a fitted point process model into a format that can be used to simulate the model
by the Metropolis-Hastings algorithm.

Usage
## S3 method for class 'ppm':
rmhmodel(model, win, ..., verbose=TRUE, project=TRUE,
control=rmhcontrol())

Arguments
model Fitted point process model (object of class "ppm").
win Optional. Window in which the simulations should be generated.
... Ignored.
verbose Logical flag indicating whether to print progress reports while the model
is being converted.
project Logical flag indicating what to do if the fitted model does not correspond
to a valid point process. See Details.
control Parameters determining the iterative behaviour of the simulation algo-
rithm. Passed to rmhcontrol.

Details
The generic function rmhmodel takes a description of a point process model in some format,
and converts it into an object of class "rmhmodel" so that simulations of the model can be
generated using the Metropolis-Hastings algorithm rmh.
This function [Link] is the method for the class "ppm" of fitted point process models.
The argument model should be a fitted point process model (object of class "ppm") typically
obtained from the model-fitting function ppm. This will be converted into an object of class
"rmhmodel".
The optional argument win specifies the window in which the pattern is to be generated. If
specified, it must be in a form which can be coerced to an object of class owin by [Link].
Not all fitted point process models obtained from ppm can be simulated. We have not yet
implemented simulation code for the LennardJones and OrdThresh models.
It is also possible that a fitted point process model obtained from ppm may not correspond to
a valid point process. For example a fitted model with the Strauss interpoint interaction
may have any value of the interaction parameter γ; however the Strauss process is not
well-defined for γ > 1 (Kelly and Ripley, 1976).
The argument project determines what to do in such cases. If project=FALSE, a fatal
error will occur. If project=TRUE, the fitted model parameters will be adjusted to the
nearest values which do correspond to a valid point process. For example a Strauss process
with γ > 1 will be projected to a Strauss process with γ = 1, equivalent to a Poisson
process.
rmhstart 533

Value
An object of class "rmhmodel", which is essentially a list of parameter values for the model.
There is a print method for this class, which prints a sensible description of the model
chosen.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.
Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statis-
tical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.
Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E.
Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry:
Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and
Applied Probability, number 80. Pages 79–140.
Kelly, F.P. and Ripley, B.D. (1976) On Strauss’s model for clustering. Biometrika 63,
357–360.

See Also
rmhmodel, [Link], [Link], rmh, rmhcontrol, rmhstart, ppm, AreaInter,
BadGey, Geyer, Strauss, Softcore, StraussHard, MultiStrauss, MultiStraussHard,
DiggleGratton, PairPiece

Examples
data(cells)
fit <- ppm(cells, ~1, Strauss(0.07))
mod1 <- rmhmodel(fit)

fit2 <- ppm(cells, ~x, Geyer(0.07, 2))


mod2 <- rmhmodel(fit2)

# Then rmh(mod1), etc

rmhstart Determine Initial State for Metropolis-Hastings Simulation.

Description
Builds a description of the initial state for the Metropolis-Hastings algorithm.

Usage
rmhstart(start, ...)
## Default S3 method:
rmhstart(start=NULL, ..., [Link]=NULL, [Link]=NULL)
534 rmhstart

Arguments
start An existing description of the initial state in some format. Incompatible
with the arguments listed below.
... There should be no other arguments.
[Link] Number of initial points (to be randomly generated). Incompatible with
[Link].
[Link] Initial point pattern configuration. Incompatible with [Link].

Details
Simulated realisations of many point process models can be generated using the Metropolis-
Hastings algorithm implemented in rmh.
This function rmhstart creates a full description of the initial state of the Metropolis-
Hastings algorithm, including possibly the initial state of the random number generator, for
use in a subsequent call to rmh. It also checks that the initial state is valid.
The initial state should be specified either by the first argument start or by the other
arguments [Link], [Link] etc.
If start is a list, then it should have components named [Link] or [Link], with the
same interpretation as described below.
The arguments are:
[Link] The number of “initial” points to be randomly (uniformly) generated in the simu-
lation window w. Incompatible with [Link].
For a multitype point process, [Link] may be a vector (of length equal to the number
of types) giving the number of points of each type to be generated.
If expansion of the simulation window is selected (see the argument expand to rmhcontrol),
then [Link] will be multiplied by the expansion factor (ratio of the areas of the ex-
panded window and original window).
For faster convergence of the Metropolis-Hastings algorithm, the value of [Link]
should be roughly equal to (an educated guess at) the expected number of points
which will be generated inside the window.
[Link] Initial point pattern configuration. Incompatible with [Link].
[Link] may be a point pattern (an object of class ppp), or an object which can be
coerced to this class by [Link], or a dataset containing vectors x and y.
If [Link] is specified, then expansion of the simulation window (the argument expand
of rmhcontrol) is not permitted.

The parameters [Link] and [Link] are incompatible.

Value
An object of class "rmhstart", which is essentially a list of parameters describing the initial
point pattern and (optionally) the initial state of the random number generator.
There is a print method for this class, which prints a sensible description of the initial
state.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
rMosaicField 535

See Also
rmh, rmhcontrol, rmhmodel

Examples
# 30 random points
a <- rmhstart([Link]=30)

# a particular point pattern


data(cells)
b <- rmhstart([Link]=cells)

rMosaicField Mosaic Random Field

Description
Generate a realisation of a random field which is piecewise constant on the tiles of a given
tessellation.

Usage
rMosaicField(X,
rgen = function(n) { sample(0:1, n, replace = TRUE)},
...,
rgenargs=NULL)

Arguments
X A tessellation (object of class "tess").
... Arguments passed to [Link] determining the pixel resolution.
rgen Function that generates random values for the tiles of the tessellation.
rgenargs List containing extra arguments that should be passed to rgen (typically
specifying parameters of the distribution of the values).

Details
This function generates a realisation of a random field which is piecewise constant on the
tiles of the given tessellation X. The values in each tile are independent and identically
distributed.

Value
A pixel image (object of class "im").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rpoislinetess, rMosaicSet
536 rMosaicSet

Examples
X <- rpoislinetess(3)
plot(rMosaicField(X, runif))
plot(rMosaicField(X, runif, dimyx=256))
plot(rMosaicField(X, rnorm, rgenargs=list(mean=10, sd=2)))

plot(rMosaicField(dirichlet(runifpoint(30)), rnorm))

rMosaicSet Mosaic Random Set

Description
Generate a random set by taking a random selection of tiles of a given tessellation.

Usage
rMosaicSet(X, p=0.5)

Arguments
X A tessellation (object of class "tess").
p Probability of including a given tile. A number strictly between 0 and 1.

Details
Given a tessellation X, this function randomly selects some of the tiles of X, including each
tile with probability p independently of the other tiles. The selected tiles are then combined
to form a set in the plane.
One application of this is Switzer’s (1965) example of a random set which has a Markov
property. It is constructed by generating X according to a Poisson line tessellation (see
rpoislinetess).

Value
A window (object of class "owin").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Switzer, P. A random set process in the plane with a Markovian property. Annals of
Mathematical Statistics 36 (1965) 1859–1863.

See Also
rpoislinetess, rMosaicField
rmpoint 537

Examples
# Switzer's random set
X <- rpoislinetess(3)
plot(rMosaicSet(X, 0.5), col="green", border=NA)

# another example
plot(rMosaicSet(dirichlet(runifpoint(30)), 0.4))

rmpoint Generate N Random Multitype Points

Description
Generate a random multitype point pattern with a fixed number of points, or a fixed number
of points of each type.

Usage
rmpoint(n, f=1, fmax=NULL, win=[Link](),
types, ptypes,
..., giveup=1000, verbose=FALSE)

Arguments
n Number of marked points to generate. Either a single number specifying
the total number of points, or a vector specifying the number of points of
each type.
f The probability density of the multitype points, usually un-normalised.
Either a constant, a vector, a function f(x,y,m, ...), a pixel image, a
list of functions f(x,y,...) or a list of pixel images.
fmax An upper bound on the values of f. If missing, this number will be
estimated.
win Window in which to simulate the pattern. Ignored if f is a pixel image
or list of pixel images.
types All the possible types for the multitype pattern.
ptypes Optional vector of probabilities for each type.
... Arguments passed to f if it is a function.
giveup Number of attempts in the rejection method after which the algorithm
should stop trying to generate new points.
verbose Flag indicating whether to report details of performance of the simulation
algorithm.

Details
This function generates random multitype point patterns consisting of a fixed number of
points.
Three different models are available:
538 rmpoint

I. Random location and type: If n is a single number and the argument ptypes is miss-
ing, then n independent, identically distributed random multitype points are gener-
ated. Their locations (x[i],y[i]) and types m[i] have joint probability density
proportional to f (x, y, m).
II. Random type, and random location given type: If n is a single number and ptypes
is given, then n independent, identically distributed random multitype points are gen-
erated. Their types m[i] have probability distribution ptypes. Given the types, the
locations (x[i],y[i]) have conditional probability density proportional to f (x, y, m).
III. Fixed types, and random location given type: If n is a vector, then we gener-
ate n[i] independent, identically distributed random points of type types[i]. For
points of type m the conditional probability density of location (x, y) is proportional
to f (x, y, m).

Note that the density f is normalised in different ways in Model I and Models II and III.
In Model I the normalised joint density is g(x, y, m) = f (x, y, m)/Z where
XZ Z
Z= λ(x, y, m)dx dy
m

while in Models II and III the normalised conditional density is g(x, y | m) = f (x, y, m)/Zm
where Z Z
Zm = λ(x, y, m)dx dy.

In Model I, the marginal distribution of types is pm = Zm /Z.


The unnormalised density f may be specified in any of the following ways.

single number: If f is a single number, the conditional density of location given type
is uniform. That is, the points of each type are uniformly distributed. In Model
I, the marginal distribution of types is also uniform (all possible types have equal
probability).
vector: If f is a numeric vector, the conditional density of location given type is uniform.
That is, the points of each type are uniformly distributed. In Model I, the marginal
distribution of types is proportional to the vector f. In Model II, the marginal distri-
bution of types is ptypes, that is, the values in f are ignored.
function: If f is a function, it will be called in the form f(x,y,m,...) at spatial location
(x,y) for points of type m. In Model I, the joint probability density of location and
type is proportional to f(x,y,m,...). In Models II and III, the conditional probability
density of location (x,y) given type m is proportional to f(x,y,m,...). The function
f must work correctly with vectors x, y and m, returning a vector of function values.
(Note that m will be a factor with levels types.) The value fmax must be given and
must be an upper bound on the values of f(x,y,m,...) for all locations (x, y) inside
the window win and all types m. The argument types must be given.
list of functions: If f is a list of functions, then the functions will be called in the form
f[[i]](x,y,...) at spatial location (x,y) for points of type types[i]. In Model I,
the joint probability density of location and type is proportional to f[[m]](x,y,...).
In Models II and III, the conditional probability density of location (x,y) given type
m is proportional to f[[m]](x,y,...). The function f[[i]] must work correctly with
vectors x and y, returning a vector of function values. The value fmax must be given
and must be an upper bound on the values of f[[i]](x,y,...) for all locations (x,
y) inside the window win. The argument types defaults to seq(f).
rmpoint 539

pixel image: If f is a pixel image object of class "im" (see [Link]), the unnormalised
density at a location (x,y) for points of any type is equal to the pixel value of f for
the pixel nearest to (x,y). In Model I, the marginal distribution of types is uniform.
The argument win is ignored; the window of the pixel image is used instead. The
argument types must be given.
list of pixel images: If f is a list of pixel images, then the image f[[i]] determines the
density values of points of type types[i]. The argument win is ignored; the window
of the pixel image is used instead. The argument types defaults to factor(seq(f)).

The implementation uses the rejection method. For Model I, rmpoispp is called repeatedly
until n points have been generated. It gives up after giveup calls if there are still fewer than
n points. For Model II, the types are first generated according to ptypes, then the locations
of the points of each type are generated using rpoint. For Model III, the locations of the
points of each type are generated using rpoint.

Value
The simulated point pattern (an object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples

abc <- c("a","b","c")

##### Model I

rmpoint(25, types=abc)
rmpoint(25, 1, types=abc)
# 25 points, equal probability for each type, uniformly distributed locations

rmpoint(25, function(x,y,m) {rep(1, length(x))}, types=abc)


# same as above
rmpoint(25, list(function(x,y){rep(1, length(x))},
function(x,y){rep(1, length(x))},
function(x,y){rep(1, length(x))}),
types=abc)
# same as above

rmpoint(25, function(x,y,m) { x }, types=abc)


# 25 points, equal probability for each type,
# locations nonuniform with density proportional to x

rmpoint(25, function(x,y,m) { ifelse(m == "a", 1, x) }, types=abc)


rmpoint(25, list(function(x,y) { rep(1, length(x)) },
function(x,y) { x },
function(x,y) { x }),
types=abc)
540 rmpoint

# 25 points, UNEQUAL probabilities for each type,


# type "a" points uniformly distributed,
# type "b" and "c" points nonuniformly distributed.

##### Model II

rmpoint(25, 1, types=abc, ptypes=rep(1,3)/3)


rmpoint(25, 1, types=abc, ptypes=rep(1,3))
# 25 points, equal probability for each type,
# uniformly distributed locations

rmpoint(25, function(x,y,m) {rep(1, length(x))}, types=abc, ptypes=rep(1,3))


# same as above
rmpoint(25, list(function(x,y){rep(1, length(x))},
function(x,y){rep(1, length(x))},
function(x,y){rep(1, length(x))}),
types=abc, ptypes=rep(1,3))
# same as above

rmpoint(25, function(x,y,m) { x }, types=abc, ptypes=rep(1,3))


# 25 points, equal probability for each type,
# locations nonuniform with density proportional to x

rmpoint(25, function(x,y,m) { ifelse(m == "a", 1, x) }, types=abc, ptypes=rep(1,3))


# 25 points, EQUAL probabilities for each type,
# type "a" points uniformly distributed,
# type "b" and "c" points nonuniformly distributed.

###### Model III

rmpoint(c(12, 8, 4), 1, types=abc)


# 12 points of type "a",
# 8 points of type "b",
# 4 points of type "c",
# each uniformly distributed

rmpoint(c(12, 8, 4), function(x,y,m) { ifelse(m=="a", 1, x)}, types=abc)


rmpoint(c(12, 8, 4), list(function(x,y) { rep(1, length(x)) },
function(x,y) { x },
function(x,y) { x }),
types=abc)

# 12 points of type "a", uniformly distributed


# 8 points of type "b", nonuniform
# 4 points of type "c", nonuniform

#########

## Randomising an existing point pattern:


data(demopat)
X <- demopat

# same numbers of points of each type, uniform random locations (Model III)
rmpoint(table(X$marks), 1, types=levels(X$marks), win=X$window)

# same total number of points, distribution of types estimated from X,


rmpoispp 541

# uniform random locations (Model II)


rmpoint(X$n, 1, types=levels(X$marks), win=X$window,
ptypes=table(X$marks))

rmpoispp Generate Multitype Poisson Point Pattern

Description
Generate a random point pattern, a realisation of the (homogeneous or inhomogeneous)
multitype Poisson process.

Usage
rmpoispp(lambda, lmax=NULL, win, types, ...)

Arguments
lambda Intensity of the multitype Poisson process. Either a single positive num-
ber, a vector, a function(x,y,m, ...), a pixel image, a list of functions
function(x,y, ...), or a list of pixel images.
lmax An upper bound for the value of lambda. May be omitted
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link]. Ignored if lambda is a pixel image or
list of images.
types All the possible types for the multitype pattern.
... Arguments passed to lambda if it is a function.

Details
This function generates a realisation of the marked Poisson point process with intensity
lambda.
Note that the intensity function λ(x, y, m) is the average number of points of type m per
unit area near the location (x, y). Thus a marked point process with a constant intensity of
10 and three possible types will have an average of 30 points per unit area, with 10 points
of each type on average.
The intensity function may be specified in any of the following ways.

single number: If lambda is a single number, then this algorithm generates a realisation
of the uniform marked Poisson process inside the window win with intensity lambda
for each type. The total intensity of points of all types is lambda * length(types).
The argument types must be given and determines the possible types in the multitype
pattern.
vector: If lambda is a numeric vector, then this algorithm generates a realisation of the
stationary marked Poisson process inside the window win with intensity lambda[i]
for points of type types[i]. The total intensity of points of all types is sum(lambda).
The argument types defaults to seq(lambda).
542 rmpoispp

function: If lambda is a function, the process has intensity lambda(x,y,m,...) at spatial


location (x,y) for points of type m. The function lambda must work correctly with
vectors x, y and m, returning a vector of function values. (Note that m will be a factor
with levels equal to types.) The value lmax, if present, must be an upper bound on
the values of lambda(x,y,m,...) for all locations (x, y) inside the window win and
all types m. The argument types must be given.
list of functions: If lambda is a list of functions, the process has intensity lambda[[i]](x,y,...)
at spatial location (x,y) for points of type types[i]. The function lambda[[i]] must
work correctly with vectors x and y, returning a vector of function values. The value
lmax, if given, must be an upper bound on the values of lambda(x,y,...) for all lo-
cations (x, y) inside the window win. The argument types defaults to seq(lambda).
pixel image: If lambda is a pixel image object of class "im" (see [Link]), the intensity
at a location (x,y) for points of any type is equal to the pixel value of lambda for the
pixel nearest to (x,y). The argument win is ignored; the window of the pixel image
is used instead. The argument types must be given.
list of pixel images: If lambda is a list of pixel images, then the image lambda[[i]] de-
termines the intensity of points of type types[i]. The argument win is ignored;
the window of the pixel image is used instead. The argument types defaults to
seq(lambda).
If lmax is missing, an approximate upper bound will be calculated.
To generate an inhomogeneous Poisson process the algorithm uses “thinning”: it first gen-
erates a uniform Poisson process of intensity lmax for points of each type m, then ran-
domly deletes or retains each point independently, with retention probability p(x, y, m) =
λ(x, y, m)/lmax.

Value
The simulated multitype point pattern (an object of class "ppp" with a component marks
which is a factor).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rpoispp for unmarked Poisson point process; rmpoint for a fixed number of random marked
points; [Link], [Link].

Examples
# uniform bivariate Poisson process with total intensity 100 in unit square
pp <- rmpoispp(50, types=c("a","b"))

# stationary bivariate Poisson process with intensity A = 30, B = 70


pp <- rmpoispp(c(30,70), types=c("A","B"))
pp <- rmpoispp(c(30,70))

# works in any window


data(letterR)
pp <- rmpoispp(c(30,70), win=letterR, types=c("A","B"))
rNeymanScott 543

# inhomogeneous lambda(x,y,m)
# note argument 'm' is a factor
lam <- function(x,y,m) { 50 * (x^2 + y^3) * ifelse(m=="A", 2, 1)}
pp <- rmpoispp(lam, win=letterR, types=c("A","B"))
# extra arguments
lam <- function(x,y,m,scal) { scal * (x^2 + y^3) * ifelse(m=="A", 2, 1)}
pp <- rmpoispp(lam, win=letterR, types=c("A","B"), scal=50)

# list of functions lambda[[i]](x,y)


lams <- list(function(x,y){50 * x^2}, function(x,y){20 * abs(y)})
pp <- rmpoispp(lams, win=letterR, types=c("A","B"))
pp <- rmpoispp(lams, win=letterR)
# functions with extra arguments
lams <- list(function(x,y,scal){5 * scal * x^2},
function(x,y, scal){2 * scal * abs(y)})
pp <- rmpoispp(lams, win=letterR, types=c("A","B"), scal=10)
pp <- rmpoispp(lams, win=letterR, scal=10)

# florid example
lams <- list(function(x,y){
100*exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
}
# log quadratic trend
,
function(x,y){
100*exp(-0.6*x+0.5*y)
}
# log linear trend
)
X <- rmpoispp(lams, win=[Link](), types=c("on", "off"))

# pixel image
Z <- [Link](function(x,y){30 * (x^2 + y^3)}, letterR)
pp <- rmpoispp(Z, types=c("A","B"))

# list of pixel images


ZZ <- list(
[Link](function(x,y){20 * (x^2 + y^3)}, letterR),
[Link](function(x,y){40 * (x^3 + y^2)}, letterR))
pp <- rmpoispp(ZZ, types=c("A","B"))
pp <- rmpoispp(ZZ)

rNeymanScott Simulate Neyman-Scott Process

Description
Generate a random point pattern, a realisation of the Neyman-Scott cluster process.

Usage
rNeymanScott(kappa, rmax, rcluster, win = owin(c(0,1),c(0,1)), ..., lmax=NULL)
544 rNeymanScott

Arguments
kappa Intensity of the Poisson process of cluster centres. A single positive num-
ber, a function, or a pixel image.
rmax Maximum radius of a random cluster.
rcluster A function which generates random clusters.
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link].
... Arguments passed to rcluster
lmax Optional. Upper bound on the values of kappa when kappa is a function
or pixel image.

Details
This algorithm generates a realisation of the general Neyman-Scott process, with the cluster
mechanism given by the function rcluster. The clusters must have a finite maximum
possible radius rmax.
First, the algorithm generates a Poisson point process of “parent” points with intensity
kappa. Here kappa may be a single positive number, a function kappa(x, y), or a pixel
image object of class "im" (see [Link]). See rpoispp for details.
Second, each parent point is replaced by a random cluster of points, created by calling the
function rcluster. These clusters are combined together to yield a single point pattern
which is then returned as the result of rNeymanScott.
The function rcluster should expect to be called as rcluster(xp[i],yp[i],...) for
each parent point at a location (xp[i],yp[i]). The return value of rcluster should be
a list with elements x,y which are vectors of equal length giving the absolute x and y
coordinates of the points in the cluster.
If the return value of rcluster is a point pattern (object of class "ppp") then it may have
marks. The result of rNeymanScott will then be a marked point pattern.
If required, the intermediate stages of the simulation (the parents and the individual clus-
ters) can also be extracted from the return value of rNeymanScott through the attributes
"parents" and "parentid". The attribute "parents" is the point pattern of parent points.
The attribute "parentid" is an integer vector specifying the parent for each of the points
in the simulated pattern.

Value
The simulated point pattern (an object of class "ppp").
Additionally, some intermediate results of the simulation are returned as attributes of this
point pattern: see Details.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rpoispp, rThomas, rGaussPoisson, rMatClust
rotate 545

Examples
# each cluster consist of 10 points in a disc of radius 0.2
nclust <- function(x0, y0, radius, n) {
return(runifdisc(n, radius, centre=c(x0, y0)))
}
plot(rNeymanScott(10, 0.2, nclust, radius=0.2, n=5))

# multitype Neyman-Scott process (each cluster is a multitype process)


nclust2 <- function(x0, y0, radius, n, types=c("a", "b")) {
X <- runifdisc(n, radius, centre=c(x0, y0))
M <- sample(types, n, replace=TRUE)
marks(X) <- M
return(X)
}
plot(rNeymanScott(15,0.1,nclust2, radius=0.1, n=5))

rotate Rotate

Description
Applies a rotation to any two-dimensional object, such as a point pattern or a window.

Usage
rotate(X, ...)

Arguments
X Any suitable dataset representing a two-dimensional object, such as a
point pattern (object of class "ppp"), or a window (object of class "owin").
... Data specifying the rotation.

Details
This is generic. Methods are provided for point patterns ([Link]) and windows
([Link]).

Value
Another object of the same type, representing the result of rotating X through the specified
angle.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]
546 [Link]

[Link] Rotate a Window

Description
Rotates a window

Usage
## S3 method for class 'owin':
rotate(X, angle=pi/2, ...)

Arguments
X A window (object of class "owin").
angle Angle of rotation.
... Ignored.

Details
Rotates the window by the specified angle. Angles are measured in radians, anticlockwise.
The default is to rotate the window 90 degrees anticlockwise. The centre of rotation is the
origin.
Rotation of binary image masks is not yet implemented.

Value
Another object of class "owin" representing the rotated window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link]

Examples
w <- owin(c(0,1),c(0,1))
v <- rotate(w, pi/3)
## Not run:
plot(v)

## End(Not run)
[Link] 547

[Link] Rotate a Point Pattern

Description
Rotates a point pattern

Usage
## S3 method for class 'ppp':
rotate(X, angle=pi/2, ...)

Arguments
X A point pattern (object of class "ppp").
angle Angle of rotation.
... Ignored.

Details
The points of the pattern, and the window of observation, are rotated about the origin by
the angle specified. Angles are measured in radians, anticlockwise. The default is to rotate
the pattern 90 degrees anticlockwise. If the points carry marks, these are preserved.
Rotation of binary image masks is not yet implemented.

Value
Another object of class "ppp" representing the rotated point pattern.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]

Examples
data(cells)
X <- rotate(cells, pi/3)
## Not run:
plot(X)

## End(Not run)
548 [Link]

[Link] Rotate a Line Segment Pattern

Description
Rotates a line segment pattern

Usage
## S3 method for class 'psp':
rotate(X, angle=pi/2, ...)

Arguments
X A line segment pattern (object of class "psp").
angle Angle of rotation.
... Ignored.

Details
The line segments of the pattern, and the window of observation, are rotated about the
origin by the angle specified. Angles are measured in radians, anticlockwise. The default is
to rotate the pattern 90 degrees anticlockwise. If the line segments carry marks, these are
preserved.
Rotation of binary image masks is not yet implemented.

Value
Another object of class "psp" representing the rotated line segment pattern.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
oldpar <- par(mfrow=c(2,1))
X <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
plot(X, main="original")
Y <- rotate(X, pi/4)
plot(Y, "rotated")
par(oldpar)
rpoint 549

rpoint Generate N Random Points

Description
Generate a random point pattern containing n independent, identically distributed random
points with any specified distribution.

Usage
rpoint(n, f, fmax=NULL, win=[Link](), ..., giveup=1000, verbose=FALSE)

Arguments
n Number of points to generate.
f The probability density of the points, possibly un-normalised. Either a
constant, a function f(x,y,...), or a pixel image object.
fmax An upper bound on the values of f. If missing, this number will be
estimated.
win Window in which to simulate the pattern. Ignored if f is a pixel image.
... Arguments passed to the function f.
giveup Number of attempts in the rejection method after which the algorithm
should stop trying to generate new points.
verbose Flag indicating whether to report details of performance of the simulation
algorithm.

Details
This function generates n independent, identically distributed random points with common
probability density proportional to f.
The argument f may be

a numerical constant: uniformly distributed random points will be generated.


a function: random points will be generated in the window win with probability density
proportional to f(x,y,...) where x and y are the cartesian coordinates. The function
f must accept two vectors of coordinates x,y and return the corresponding vector of
function values. Additional arguments ... of any kind may be passed to the function.
a pixel image: if f is a pixel image object of class "im" (see [Link]) then random
points will be generated in the window of this pixel image, with probability density
proportional to the pixel values of f.

The algorithm is as follows:

ˆ If f is a constant, we invoke runifpoint.


ˆ If f is a function, then we use the rejection method. Proposal points are generated
from the uniform distribution. A proposal point (x, y) is accepted with probability
f(x,y,...)/fmax and otherwise rejected. The algorithm continues until n points
have been accepted. It gives up after giveup * n proposals if there are still fewer
than n points.
550 rpoisline

ˆ If f is a pixel image, then a random sequence of pixels is selected (using sample) with
probabilities proportional to the pixel values of f. Then for each pixel in the sequence
we generate a uniformly distributed random point in that pixel.

The algorithm for pixel images is more efficient than that for functions.

Value
The simulated point pattern (an object of class "ppp").

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], runifpoint

Examples
# 100 uniform random points in the unit square
X <- rpoint(100)

# 100 random points with probability density proportional to x^2 + y^2


X <- rpoint(100, function(x,y) { x^2 + y^2}, 1)

# `fmax' may be omitted


X <- rpoint(100, function(x,y) { x^2 + y^2})

# irregular window
data(letterR)
X <- rpoint(100, function(x,y) { x^2 + y^2}, win=letterR)

# make a pixel image


Z <- setcov(letterR)
# 100 points with density proportional to pixel values
X <- rpoint(100, Z)

rpoisline Generate Poisson Random Line Process

Description

Generate a random pattern of line segments obtained from the Poisson line process.

Usage

rpoisline(lambda, win=owin())
rpoislinetess 551

Arguments
lambda Intensity of the Poisson line process. A positive number.
win Window in which to simulate the pattern. An object of class "owin"
or something acceptable to [Link]. Currently, the window must be a
rectangle.

Details
This algorithm generates a realisation of the uniform Poisson line process, and clips it to
the window win.
The argument lambda must be a positive number. It controls the intensity of the process.
The expected number of lines intersecting a convex region of the plane is equal to lambda
times the perimeter length of the region. The expected total length of the lines crossing a
region of the plane is equal to lambda * pi times the area of the region.

Value
A line segment pattern (an object of class "psp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
psp

Examples
# uniform Poisson line process with intensity 10,
# clipped to the unit square
rpoisline(10)

rpoislinetess Poisson Line Tessellation

Description
Generate a tessellation delineated by the lines of the Poisson line process

Usage
rpoislinetess(lambda, win = owin())

Arguments
lambda Intensity of the Poisson line process. A positive number.
win Window in which to simulate the pattern. An object of class "owin"
or something acceptable to [Link]. Currently, the window must be a
rectangle.
552 rpoispp

Details
This algorithm generates a realisation of the uniform Poisson line process, and divides the
window win into tiles separated by these lines.
The argument lambda must be a positive number. It controls the intensity of the process.
The expected number of lines intersecting a convex region of the plane is equal to lambda
times the perimeter length of the region. The expected total length of the lines crossing a
region of the plane is equal to lambda * pi times the area of the region.

Value
A tessellation (object of class "tess").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rpoisline to generate the lines only.

Examples
X <- rpoislinetess(3)
plot([Link](X), main="rpoislinetess(3)")
plot(X, add=TRUE)

rpoispp Generate Poisson Point Pattern

Description
Generate a random point pattern using the (homogeneous or inhomogeneous) Poisson pro-
cess. Includes CSR (complete spatial randomness).

Usage
rpoispp(lambda, lmax, win, ...)

Arguments
lambda Intensity of the Poisson process. Either a single positive number, a
function(x,y, ...), or a pixel image.
lmax An upper bound for the value of lambda(x,y), if lambda is a function.
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link]. Ignored if lambda is a pixel image.
... Arguments passed to lambda if it is a function.
rpoispp 553

Details
If lambda is a single number, then this algorithm generates a realisation of the uniform
Poisson process (also known as Complete Spatial Randomness, CSR) inside the window
win with intensity lambda (points per unit area).
If lambda is a function, then this algorithm generates a realisation of the inhomogeneous
Poisson process with intensity function lambda(x,y,...) at spatial location (x,y) inside
the window win. The function lambda must work correctly with vectors x and y. The value
lmax must be given and must be an upper bound on the values of lambda(x,y,...) for
all locations (x, y) inside the window win.
If lambda is a pixel image object of class "im" (see [Link]), this algorithm generates a
realisation of the inhomogeneous Poisson process with intensity equal to the pixel values of
the image. (The value of the intensity function at an arbitrary location is the pixel value
of the nearest pixel.) The argument win is ignored; the window of the pixel image is used
instead.
To generate an inhomogeneous Poisson process the algorithm uses “thinning”: it first gen-
erates a uniform Poisson process of intensity lmax, then randomly deletes or retains each
point, independently of other points, with retention probability p(x, y) = λ(x, y)/lmax.
For marked point patterns, use rmpoispp.

Value
The simulated point pattern (an object of class "ppp").

Warning
Note that lambda is the intensity, that is, the expected number of points per unit area.
The total number of points in the simulated pattern will be random with expected value
mu = lambda * a where a is the area of the window win.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rmpoispp for Poisson marked point patterns, runifpoint for a fixed number of independent
uniform random points; rpoint, rmpoint for a fixed number of independent random points
with any distribution; rMaternI, rMaternII, rSSI, rStrauss, rstrat for random point
processes with spatial inhibition or regularity; rThomas, rGaussPoisson, rMatClust, rcell
for random point processes exhibiting clustering; [Link] for Gibbs processes. See also
[Link], [Link].

Examples
# uniform Poisson process with intensity 100 in the unit square
pp <- rpoispp(100)

# uniform Poisson process with intensity 1 in a 10 x 10 square


pp <- rpoispp(1, win=owin(c(0,10),c(0,10)))
# plots should look similar !

# inhomogeneous Poisson process in unit square


554 rpoispp3

# with intensity lambda(x,y) = 100 * exp(-3*x)


# Intensity is bounded by 100
pp <- rpoispp(function(x,y) {100 * exp(-3*x)}, 100)

# How to tune the coefficient of x


lamb <- function(x,y,a) { 100 * exp( - a * x)}
pp <- rpoispp(lamb, 100, a=3)

# pixel image
Z <- [Link](function(x,y){100 * sqrt(x+y)}, [Link]())
pp <- rpoispp(Z)

rpoispp3 Generate Poisson Point Pattern in Three Dimensions

Description
Generate a random three-dimensional point pattern using the homogeneous Poisson process.

Usage
rpoispp3(lambda, domain = box3())

Arguments
lambda Intensity of the Poisson process. A single positive number.
domain Three-dimensional box in which the process should be generated. An
object of class "box3".

Details
This function generates a realisation of the homogeneous Poisson process in three dimen-
sions, with intensity lambda (points per unit volume).
The realisation is generated inside the three-dimensional region domain which currently
must be a rectangular box (object of class "box3").

Value
The simulated three-dimensional point pattern (an object of class "pp3").

Note
The intensity lambda is the expected number of points per unit volume.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
runifpoint3, pp3, box3
rpoisppOnLines 555

Examples
X <- rpoispp3(50)

rpoisppOnLines Generate Poisson Point Pattern on Line Segments

Description
Given a line segment pattern, generate a Poisson random point pattern on the line segments.

Usage
rpoisppOnLines(lambda, L, lmax = NULL, ...)

Arguments
lambda Intensity of the Poisson process. A single number, a function(x,y), or
a pixel image (object of class "im").
L Line segment pattern (object of class "psp") on which the points should
be generated.
lmax Maximum possible value of lambda if it is a function or a pixel image.
... Additional arguments passed to lambda if it is a function.

Details
This command generates a Poisson point process on the one-dimensional system of line
segments in L. The result is a point pattern consisting of points lying on the line segments
in L. The number of random points falling on any given line segment follows a Poisson
distribution. The patterns of points on different segments are independent.
The intensity lambda is the expected number of points per unit length of line segment. It
may be constant, or it may depend on spatial location.
The argument lambda may be a single number, or a function(x,y), or a pixel image
(object of class "im"). In the two latter cases, the rejection method is used.
The rejection method requires knowledge of lmax, the maximum possible value of lambda.
If lmax is not given, it will be computed approximately, by sampling many values of lambda.

Value
A point pattern (object of class "ppp") in the same window as L.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
psp, ppp, runifpointOnLines, rpoispp
556 rshift

Examples
L <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
plot(L, main="")

# uniform intensity
Y <- rpoisppOnLines(4, L)
plot(Y, add=TRUE, pch="+")

# intensity is a function
Y <- rpoisppOnLines(function(x,y){ 10 * x^2}, L, 10)
plot(L, main="")
plot(Y, add=TRUE, pch="+")

# intensity is an image
Z <- [Link](function(x,y){10 * sqrt(x+y)}, [Link]())
Y <- rpoisppOnLines(Z, L, 10)
plot(L, main="")
plot(Y, add=TRUE, pch="+")

rshift Random Shift

Description
Randomly shifts the points of a point pattern or line segment pattern. Generic.

Usage
rshift(X, ...)

Arguments
X Pattern to be subjected to a random shift. A point pattern (class "ppp"),
a line segment pattern (class "psp") or an object of class "splitppp".
... Arguments controlling the generation of the random shift vector, or spec-
ifying which parts of the pattern will be shifted.

Details
This operation applies a random shift (vector displacement) to the points in a point pattern,
or to the segments in a line segment pattern.
The argument X may be

ˆ a point pattern (an object of class "ppp")


ˆ a line segment pattern (an object of class "psp")
ˆ an object of class "splitppp" (basically a list of point patterns, obtained from [Link]).

The function rshift is generic, with methods for the three classes "ppp", "psp" and
"splitppp".
See the help pages for these methods, [Link], [Link] and [Link], for
further information.
[Link] 557

Value
An object of the same type as X.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

[Link] Randomly Shift a Point Pattern

Description
Randomly shifts the points of a point pattern.

Usage
## S3 method for class 'ppp':
rshift(X, ..., which=NULL, group)

Arguments
X Point pattern to be subjected to a random shift. An object of class "ppp"
... Arguments that determine the random shift. See Details.
group Optional. Factor specifying a grouping of the points of X, or NULL in-
dicating that all points belong to the same group. Each group will be
shifted together, and separately from other groups. By default, points in
a marked point pattern are grouped according to their mark values, while
points in an unmarked point pattern are treated as a single group.
which Optional. Identifies which groups of the pattern will be shifted, while
other groups are not shifted. A vector of levels of group.

Details
This operation randomly shifts the locations of the points in a point pattern.
The function rshift is generic. This function [Link] is the method for point patterns.
The most common use of this function is to shift the points in a multitype point pattern.
By default, points of the same type are shifted in parallel (i.e. points of a common type
are shifted by a common displacement vector), and independently of other types. This
is useful for testing the hypothesis of independence of types (the null hypothesis that the
sub-patterns of points of each type are independent point processes).
In general the points of X are divided into groups, then the points within a group are
shifted by a common random displacement vector. Different groups of points are shifted
independently. The grouping is determined as follows:

ˆ If the argument group is present, then this determines the grouping.


558 [Link]

ˆ Otherwise, if X is a multitype point pattern, the marks determine the grouping.


ˆ Otherwise, all points belong to a single group.
The argument group should be a factor, of length equal to the number of points in X.
Alternatively group may be NULL, which specifies that all points of X belong to a single
group.
By default, every group of points will be shifted. The argument which indicates that only
some of the groups should be shifted, while other groups should be left unchanged. which
must be a vector of levels of group (for example, a vector of types in a multitype pattern)
indicating which groups are to be shifted.
The displacement vector, i.e. the vector by which the data points are shifted, is generated
at random. Parameters that control the randomisation and the handling of edge effects are
passed through the ... argument. They are
radius,width,height Parameters of the random shift vector.
edge String indicating how to deal with edges of the pattern. Options are "torus",
"erode" and "none".
clip Optional. Window to which the final point pattern should be clipped.
If the window is a rectangle, the default behaviour is to generate a displacement vector
at random with equal probability for all possible displacements. This means that the x
and y coordinates of the displacement vector are independent random variables, uniformly
distributed over the range of possible coordinates.
Alternatively, the displacement vector can be generated by another random mechanism,
controlled by the arguments radius, width and height.
rectangular: if width and height are given, then the displacement vector is uniformly
distributed in a rectangle of these dimensions, centred at the origin. The maximum
possible displacement in the x direction is width/2. The maximum possible displace-
ment in the y direction is height/2. The x and y displacements are independent. (If
width and height are actually equal to the dimensions of the observation window,
then this is equivalent to the default.)
radial: if radius is given, then the displacement vector is generated by choosing a random
point inside a disc of the given radius, centred at the origin, with uniform probability
density over the disc. Thus the argument radius determines the maximum possible
displacement distance. The argument radius is incompatible with the arguments
width and height.
The argument edge controls what happens when a shifted point lies outside the window of
X. Options are:
”none”: Points shifted outside the window of X simply disappear.
”torus”: Toroidal or periodic boundary. Treat opposite edges of the window as identical, so
that a point which disappears off the right-hand edge will re-appear at the left-hand
edge. This is called a “toroidal shift” because it makes the rectangle topologically
equivalent to the surface of a torus (doughnut).
The window must be a rectangle. Toroidal shifts are undefined if the window is non-
rectangular.
”erode”: Clip the point pattern to a smaller window.
If the random displacements are generated by a radial mechanism (see above), then
the window of X is eroded by a distance equal to the value of the argument radius,
using erosion.
[Link] 559

If the random displacements are generated by a rectangular mechanism, then the


window of X is (if it is not rectangular) eroded by a distance max(height,width)
using erosion; or (if it is rectangular) trimmed by a margin of width width at the left
and right sides and trimmed by a margin of height height at the top and bottom.
The rationale for this is that the clipping window is the largest window for which edge
effects can be ignored.
The optional argument clip specifies a smaller window to which the pattern should be
restricted.

Value
A point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rshift, [Link]

Examples
data(amacrine)

# random toroidal shift


# shift "on" and "off" points separately
X <- rshift(amacrine)

# shift "on" points and leave "off" points fixed


X <- rshift(amacrine, which="on")

# shift all points simultaneously


X <- rshift(amacrine, group=NULL)

# maximum displacement distance 0.1 units


X <- rshift(amacrine, radius=0.1)

# shift with erosion


X <- rshift(amacrine, radius=0.1, edge="erode")

[Link] Randomly Shift a Line Segment Pattern

Description
Randomly shifts the segments in a line segment pattern.

Usage
## S3 method for class 'psp':
rshift(X, ..., group=NULL, which=NULL)
560 [Link]

Arguments
X Line segment pattern to be subjected to a random shift. An object of
class "psp".
... Arguments controlling the randomisation and the handling of edge effects.
See [Link].
group Optional. Factor specifying a grouping of the line segments of X, or NULL
indicating that all line segments belong to the same group. Each group
will be shifted together, and separately from other groups.
which Optional. Identifies which groups of the pattern will be shifted, while
other groups are not shifted. A vector of levels of group.

Details
This operation randomly shifts the locations of the line segments in a line segment pattern.
The function rshift is generic. This function [Link] is the method for line segment
patterns.
The line segments of X are first divided into groups, then the line segments within a group
are shifted by a common random displacement vector. Different groups of line segments are
shifted independently. If the argument group is present, then this determines the grouping.
Otherwise, all line segments belong to a single group.
The argument group should be a factor, of length equal to the number of line segments in
X. Alternatively group may be NULL, which specifies that all line segments of X belong to a
single group.
By default, every group of line segments will be shifted. The argument which indicates that
only some of the groups should be shifted, while other groups should be left unchanged.
which must be a vector of levels of group indicating which groups are to be shifted.
The displacement vector, i.e. the vector by which the data line segments are shifted, is gen-
erated at random. The default behaviour is to generate a displacement vector at random
with equal probability for all possible displacements. This means that the x and y coordi-
nates of the displacement vector are independent random variables, uniformly distributed
over the range of possible coordinates.
Alternatively, the displacement vector can be generated by another random mechanism,
controlled by the arguments radius, width and height.
rectangular: if width and height are given, then the displacement vector is uniformly
distributed in a rectangle of these dimensions, centred at the origin. The maximum
possible displacement in the x direction is width/2. The maximum possible displace-
ment in the y direction is height/2. The x and y displacements are independent. (If
width and height are actually equal to the dimensions of the observation window,
then this is equivalent to the default.)
radial: if radius is given, then the displacement vector is generated by choosing a ran-
dom line segment inside a disc of the given radius, centred at the origin, with uniform
probability density over the disc. Thus the argument radius determines the maxi-
mum possible displacement distance. The argument radius is incompatible with the
arguments width and height.
The argument edge controls what happens when a shifted line segment lies partially or
completely outside the window of X. Currently the only option is "erode" which specifies
that the segments will be clipped to a smaller window.
The optional argument clip specifies a smaller window to which the pattern should be
restricted.
[Link] 561

Value
A line segment pattern (object of class "psp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rshift, [Link]

Examples
X <- psp(runif(20), runif(20), runif(20), runif(20), window=owin())
Y <- rshift(X, radius=0.1)

[Link] Randomly Shift a List of Point Patterns

Description
Randomly shifts each point pattern in a list of point patterns.

Usage
## S3 method for class 'splitppp':
rshift(X, ..., which=seq(X))

Arguments
X An object of class "splitppp". Basically a list of point patterns.
... Parameters controlling the generation of the random shift vector and the
handling of edge effects. See [Link].
which Optional. Identifies which patterns will be shifted, while other patterns
are not shifted. Any valid subset index for X.

Details
This operation applies a random shift to each of the point patterns in the list X.
The function rshift is generic. This function [Link] is the method for objects
of class "splitppp", which are essentially lists of point patterns, created by the function
[Link].
By default, every pattern in the list X will be shifted. The argument which indicates that
only some of the patterns should be shifted, while other groups should be left unchanged.
which can be any valid subset index for X.
Each point pattern in the list X (or each pattern in X[which]) is shifted by a random
displacement vector. The shifting is performed by [Link].
See the help page for [Link] for details of the other arguments.
562 rSSI

Value
Another object of class "splitppp".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rshift, [Link]

Examples
data(amacrine)
Y <- split(amacrine)

# random toroidal shift


# shift "on" and "off" points separately
X <- rshift(Y)

# shift "on" points and leave "off" points fixed


X <- rshift(Y, which="on")

# maximum displacement distance 0.1 units


X <- rshift(Y, radius=0.1)

# shift with erosion


X <- rshift(Y, radius=0.1, edge="erode")

rSSI Simulate Simple Sequential Inhibition

Description
Generate a random point pattern, a realisation of the Simple Sequential Inhibition (SSI)
process.

Usage
rSSI(r, n, win = owin(c(0,1),c(0,1)), giveup = 1000, [Link]=NULL)

Arguments
r Inhibition distance.
n Number of points to generate.
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link].
giveup Number of rejected proposals after which the algorithm should terminate.
[Link] Optional. Initial configuration of points. A point pattern (object of class
"ppp").
rstrat 563

Details
This algorithm generates a realisation of the Simple Sequential Inhibition point process
inside the window win.
Starting with an empty window (or with the point pattern [Link] if specified), the algo-
rithm adds points one-by-one. Each new point is generated uniformly in the window and
independently of preceding points. If the new point lies closer than r units from an existing
point, then it is rejected and another random point is generated.
The algorithm terminates either when the desired number n of points is reached, or when
the current point configuration has not changed for giveup iterations.

Value
The simulated point pattern (an object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rpoispp, rMaternI, rMaternII.

Examples
pp <- rSSI(0.05, 200)
## Not run: plot(pp)

rstrat Simulate Stratified Random Point Pattern

Description
Generates a “stratified random” pattern of points in a window, by dividing the window into
rectangular tiles and placing k random points independently in each tile.

Usage
rstrat(win=square(1), nx, ny=nx, k = 1)

Arguments
win A window. An object of class owin, or data in any format acceptable to
[Link]().
nx Number of tiles in each column.
ny Number of tiles in each row.
k Number of random points to generate in each tile.
564 rStrauss

Details

This function generates a random pattern of points in a “stratified random” sampling design.
It can be useful for generating random spatial sampling points.
The bounding rectangle of win is divided into a regular nx × ny grid of rectangular tiles.
In each tile, k random points are generated independently with a uniform distribution in
that tile.
Some of these grid points may lie outside the window win: if they do, they are deleted.
The result is a point pattern inside the window win.
This function is useful in creating dummy points for quadrature schemes (see quadscheme)
as well as in simulating random point patterns.

Value

A point pattern (object of class "ppp").

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

rsyst, runifpoint, quadscheme

Examples
X <- rstrat(nx=10)
plot(X)

# polygonal boundary
data(letterR)
X <- rstrat(letterR, 5, 10, k=3)
plot(X)

rStrauss Perfect Simulation of the Strauss Process

Description

Generate a random pattern of points, a simulated realisation of the Strauss process, using
a perfect simulation algorithm.

Usage

rStrauss(beta, gamma = 1, R = 0, W = owin())


rStrauss 565

Arguments

beta intensity parameter (a positive number).


gamma interaction parameter (a number between 0 and 1, inclusive).
R interaction radius (a non-negative number).
W window (object of class "owin") in which to generate the random pattern.
Currently this must be a rectangular window.

Details

This function generates a realisation of the Strauss point process in the window W using a
‘perfect simulation’ algorithm.
The Strauss process (Strauss, 1975; Kelly and Ripley, 1976) is a model for spatial inhibition,
ranging from a strong ‘hard core’ inhibition to a completely random pattern according to
the value of gamma.
The Strauss process with interaction radius R and parameters β and γ is the pairwise
interaction point process with probability density

f (x1 , . . . , xn ) = αβ n(x) γ s(x)

where x1 , . . . , xn represent the points of the pattern, n(x) is the number of points in the
pattern, s(x) is the number of distinct unordered pairs of points that are closer than R units
apart, and α is the normalising constant. Intuitively, each point of the pattern contributes
a factor β to the probability density, and each pair of points closer than r units apart
contributes a factor γ to the density.
The interaction parameter γ must be less than or equal to 1 in order that the process be
well-defined (Kelly and Ripley, 1976). This model describes an “ordered” or “inhibitive”
pattern. If γ = 1 it reduces to a Poisson process (complete spatial randomness) with
intensity β. If γ = 0 it is called a “hard core process” with hard core radius R/2, since no
pair of points is permitted to lie closer than R units apart.
The simulation algorithm used to generate the point pattern is ‘dominated coupling from the
past’ as implemented by Berthelsen and Moller (2002, 2003). This is a ‘perfect simulation’ or
‘exact simulation’ algorithm, so called because the output of the algorithm is guaranteed to
have the correct probability distribution exactly (unlike the Metropolis-Hastings algorithm
used in rmh, whose output is only approximately correct).
The implementation is currently experimental.
There is a tiny chance that the algorithm will run out of space before it has terminated. If
this occurs, an error message will be generated.

Value

A point pattern (object of class "ppp").

Author(s)

Kasper Klitgaard Berthelsen <[Link]@[Link]>, adapted for spatstat by


Adrian Baddeley <adrian@[Link]> [Link]
566 rsyst

References

Berthelsen, K.K. and Moller, J. (2002) A primer on perfect simulation for spatial point
processes. Bulletin of the Brazilian Mathematical Society 33, 351-367.
Berthelsen, K.K. and Moller, J. (2003) Likelihood and non-parametric Bayesian MCMC
inference for spatial point processes based on perfect simulation and path sampling. Scan-
dinavian Journal of Statistics 30, 549-564.
Kelly, F.P. and Ripley, B.D. (1976) On Strauss’s model for clustering. Biometrika 63,
357–360.
Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial
Point Processes. Chapman and Hall/CRC.
Strauss, D.J. (1975) A model for clustering. Biometrika 63, 467–475.

See Also

rmh

Examples
X <- rStrauss(0.05,0.2,1.5,square(141.4))
Z <- rStrauss(100,0.7,0.05)

rsyst Simulate systematic random point pattern

Description

Generates a “systematic random” pattern of points in a window, consisting of a grid of


equally-spaced points with a random common displacement.

Usage

rsyst(win=square(1), nx, ny=nx, dx=NULL, dy=NULL)

Arguments

win A window. An object of class owin, or data in any format acceptable to


[Link]().
dx Spacing of grid points in x direction. Incompatible with nx.
dy Spacing of grid points in y direction. Incompatible with ny.
nx Number of columns of grid points in the window. Incompatible with dx.
ny Number of rows of grid points in the window. Incompatible with dy.
rthin 567

Details
This function generates a “systematic random” pattern of points in the window win. The
pattern consists of a rectangular grid of points with a random common displacement.
The grid spacing is determined by the distances dx, dy if they are present. If they are
absent, then the grid spacing is determined so that there will be nx columns and ny rows
of grid points in the bounding rectangle of win.
The grid is then given a random displacement (the common displacement of the grid points
is a uniformly distributed random vector in the tile of dimensions dx, dy).
Some of the resulting grid points may lie outside the window win: if they do, they are
deleted. The result is a point pattern inside the window win.
This function is useful in creating dummy points for quadrature schemes (see quadscheme)
as well as in simulating random point patterns.

Value
A point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rstrat, runifpoint, quadscheme

Examples
X <- rsyst(nx=10)
plot(X)

# polygonal boundary
data(letterR)
X <- rsyst(letterR, 5, 10)
plot(X)

rthin Random Thinning

Description
Applies independent random thinning to a point pattern.

Usage
rthin(X, P, ...)
568 rthin

Arguments
X A point pattern (object of class "ppp") that will be thinned.
P Data giving the retention probabilities, i.e. the probability that each point
in X will be retained. Either a single number, or a vector of numbers, or
a function(x,y), or a pixel image (object of class "im").
... Additional arguments passed to P, if it is a function.

Details
In a random thinning operation, each point of the pattern X is randomly either deleted or
retained (i.e. not deleted). The result is a point pattern, consisting of those points of X
that were retained.
Independent random thinning means that the retention/deletion of each point is indepen-
dent of other points.
The argument P determines the probability of retaining each point. It may be
a single number, so that each point will be retained with the same probability P;
a vector of numbers, so that the ith point of X will be retained with probability P[i];
a function P(x,y), so that a point at a location (x,y) will be retained with probability
P(x,y);
a pixel image, containing values of the retention probability for all locations in a region
encompassing the point pattern.
If P is a function, it should be ‘vectorised’, that is, it should accept vector arguments x,y and
should yield a numeric vector of the same length. The function may have extra arguments
which are passed through the ... argument.

Value
A point pattern (object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
data(redwood)
plot(redwood, main="thinning")

# delete 20% of points


Y <- rthin(redwood, 0.8)
points(Y, col="green", cex=1.4)

# function
f <- function(x,y) { ifelse(x < 0.4, 1, 0.5) }
Y <- rthin(redwood, f)

# pixel image
Z <- [Link](f, redwood$window)
Y <- rthin(redwood, Z)
rThomas 569

rThomas Simulate Thomas Process

Description
Generate a random point pattern, a realisation of the Thomas cluster process.

Usage
rThomas(kappa, sigma, mu, win = owin(c(0,1),c(0,1)))

Arguments
kappa Intensity of the Poisson process of cluster centres. A single positive num-
ber.
sigma Standard deviation of displacement of a point from its cluster centre.
mu Expected number of points per cluster.
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link].

Details
This algorithm generates a realisation of the Thomas process, a special case of the Neyman-
Scott process.
The algorithm generates a uniform Poisson point process of “parent” points with intensity
kappa. Then each parent point is replaced by a random cluster of points, the number
of points per cluster being Poisson (mu) distributed, and their positions being isotropic
Gaussian displacements from the cluster parent location.
This classical model can be fitted to data by the method of minimum contrast, using
[Link] or kppm.
The algorithm can also generate spatially inhomogeneous versions of the Thomas process:
ˆ The parent points can be spatially inhomogeneous. If the argument kappa is a
function(x,y) or a pixel image (object of class "im"), then it is taken as specify-
ing the intensity function of an inhomogeneous Poisson process that generates the
parent points.
ˆ The offspring points can be inhomogeneous. If the argument mu is a function(x,y)
or a pixel image (object of class "im"), then it is interpreted as the reference density
for offspring points, in the sense of Waagepetersen (2006). For a given parent point,
the offspring constitute a Poisson process with intensity function equal to mu(x,y) *
f(x,y) where f is the Gaussian density centred at the parent point.
When the parents are homogeneous (kappa is a single number) and the offspring are inho-
mogeneous (mu is a function or pixel image), the model can be fitted to data using kppm, or
using [Link] applied to the inhomogeneous K function.

Value
The simulated point pattern (an object of class "ppp").
Additionally, some intermediate results of the simulation are returned as attributes of this
point pattern. See rNeymanScott.
570 runifdisc

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Waagepetersen, R. (2006) An estimating function approach to inference for inhomogeneous
Neyman-Scott processes. Submitted for publication.

See Also
rpoispp, rMatClust, rGaussPoisson, rNeymanScott, [Link], kppm

Examples
#homogeneous
X <- rThomas(10, 0.2, 5)
#inhomogeneous
Z <- [Link](function(x,y){ 5 * exp(2 * x - 1) }, owin())
Y <- rThomas(10, 0.2, Z)

runifdisc Generate N Uniform Random Points in a Disc

Description
Generate a random point pattern containing n independent uniform random points in a
circular disc.

Usage
runifdisc(n, radius=1, centre=c(0,0), ...)

Arguments
n Number of points.
radius Radius of the circle.
centre Coordinates of the centre of the circle.
... Arguments passed to disc controlling the accuracy of approximation to
the circle.

Details
This function generates n independent random points, uniformly distributed in a circular
disc.
It is faster (for a circular window) than the general code used in runifpoint.
To generate random points in an ellipse, first generate points in a circle using runifdisc,
then transform to an ellipse using affine, as shown in the examples.
To generate random points in other windows, use runifpoint. To generate non-uniform
random points, use rpoint.
runifpoint 571

Value
The simulated point pattern (an object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
disc, runifpoint, rpoint

Examples
# 100 random points in the unit disc
plot(runifdisc(100))
# 42 random points in the ellipse with major axis 3 and minor axis 1
X <- runifdisc(42)
Y <- affine(X, mat=diag(c(3,1)))
plot(Y)

runifpoint Generate N Uniform Random Points

Description
Generate a random point pattern containing n independent uniform random points.

Usage
runifpoint(n, win=owin(c(0,1),c(0,1)), giveup=1000)

Arguments
n Number of points.
win Window in which to simulate the pattern. An object of class "owin" or
something acceptable to [Link].
giveup Number of attempts in the rejection method after which the algorithm
should stop trying to generate new points.

Details
This function generates n independent random points, uniformly distributed in the window
win. (For nonuniform distributions, see rpoint.)
The algorithm depends on the type of window, as follows:
ˆ If win is a rectangle then n independent random points, uniformly distributed in
the rectangle, are generated by assigning uniform random values to their cartesian
coordinates.
ˆ If win is a binary image mask, then a random sequence of pixels is selected (using
sample) with equal probabilities. Then for each pixel in the sequence we generate a
uniformly distributed random point in that pixel.
572 runifpoint3

ˆ If win is a polygonal window, the algorithm uses the rejection method. It finds a rect-
angle enclosing the window, generates points in this rectangle, and tests whether they
fall in the desired window. It gives up when giveup * n tests have been performed
without yielding n successes.
The algorithm for binary image masks is faster than the rejection method but involves
discretisation.

Value
The simulated point pattern (an object of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], rpoispp, rpoint

Examples
# 100 random points in the unit square
pp <- runifpoint(100)
# irregular window
data(letterR)
# polygonal
pp <- runifpoint(100, letterR)
# binary image mask
pp <- runifpoint(100, [Link](letterR))

runifpoint3 Generate N Uniform Random Points in Three Dimensions

Description
Generate a random point pattern containing n independent, uniform random points in three
dimensions.

Usage
runifpoint3(n, domain = box3())

Arguments
n Number of points to be generated.
domain Three-dimensional box in which the process should be generated. An
object of class "box3".

Details
This function generates n independent random points, uniformly distributed in the three-
dimensional box domain.
runifpointOnLines 573

Value
The simulated point pattern (an object of class "pp3").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
rpoispp3, pp3, box3

Examples
X <- runifpoint3(50)

runifpointOnLines Generate N Uniform Random Points On Line Segments

Description
Given a line segment pattern, generate a random point pattern consisting of n points
uniformly distributed on the line segments.

Usage
runifpointOnLines(n, L)

Arguments
n Number of points to generate.
L Line segment pattern (object of class "psp") on which the points should
lie.

Details
This command generates a point pattern consisting of n independent random points, each
point uniformly distributed on the line segment pattern. This means that, for each random
point,
ˆ the probability of falling on a particular segment is proportional to the length of the
segment; and
ˆ given that the point falls on a particular segment, it has uniform probability density
along that segment.

Value
A point pattern (object of class "ppp") with the same window as L.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
574 SatPiece

See Also
psp, ppp, pointsOnLines, runifpoint

Examples
X <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
Y <- runifpointOnLines(20, X)
plot(X, main="")
plot(Y, add=TRUE)

SatPiece Piecewise Constant Saturated Pairwise Interaction Point Process


Model

Description
Creates an instance of a saturated pairwise interaction point process model with piecewise
constant potential function. The model can then be fitted to point pattern data.

Usage
SatPiece(r, sat)

Arguments
r vector of jump points for the potential function
sat vector of saturation values, or a single saturation value

Details
This is a generalisation of the Geyer saturation point process model, described in Geyer,
to the case of multiple interaction distances. It can also be described as the saturated
analogue of a pairwise interaction process with piecewise-constant pair potential, described
in PairPiece.
The saturated point process with interaction radii r1 , . . . , rk , saturation thresholds s1 , . . . , sk ,
intensity parameter β and interaction parameters γ1 , . . . , gammak , is the point process in
which each point xi in the pattern X contributes a factor
v (xi ,X) v (xi ,X)
βγ1 1 . . . gammakk

to the probability density of the point pattern, where

vj (xi , X) = min(sj , tj (xi , X))

where tj (xi , X) denotes the number of points in the pattern X which lie at a distance
between rj−1 and rj from the point xi . We take r0 = 0 so that t1 (xi , X) is the number of
points of X that lie within a distance r1 of the point xi .
SatPiece is used to fit this model to data. The function ppm(), which fits point process
models to point pattern data, requires an argument of class "interact" describing the
interpoint interaction structure of the model to be fitted. The appropriate description of
the piecewise constant Saturated pairwise interaction is yielded by the function SatPiece().
See the examples below.
SatPiece 575

Simulation of this point process model is not yet implemented. This model is not locally
stable (the conditional intensity is unbounded).
The argument r specifies the vector of interaction distances. The entries of r must be
strictly increasing, positive numbers.
The argument sat specifies the vector of saturation parameters. It should be a vector of the
same length as r, and its entries should be nonnegative numbers. Thus sat[1] corresponds
to the distance range from 0 to r[1], and sat[2] to the distance range from r[1] to r[2],
etc. Alternatively sat may be a single number, and this saturation value will be applied to
every distance range.
Infinite values of the saturation parameters are also permitted; in this case vj (xi , X) =
tj (xi , X) and there is effectively no ‘saturation’ for the distance range in question. If all
the saturation parameters are set to Inf then the model is effectively a pairwise interaction
process, equivalent to PairPiece (however the interaction parameters γ obtained from
SatPiece are the square roots of the parameters γ obtained from PairPiece).
If r is a single number, this model is virtually equivalent to the Geyer process, see Geyer.

Value

An object of class "interact" describing the interpoint interaction structure of a point


process.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]> in collaboration with Hao Wang and Jeff
Picka

See Also

ppm, [Link], Geyer, PairPiece, BadGey.

Examples

SatPiece(c(0.1,0.2), c(1,1))
# prints a sensible description of itself
SatPiece(c(0.1,0.2), 1)
data(cells)
ppm(cells, ~1, SatPiece(c(0.07, 0.1, 0.13), 2))
# fit a stationary piecewise constant Saturated pairwise interaction process

## Not run:
ppm(cells, ~polynom(x,y,3), SatPiece(c(0.07, 0.1, 0.13), 2))
# nonstationary process with log-cubic polynomial trend

## End(Not run)
576 scanpp

Saturated Saturated Pairwise Interaction model

Description
Experimental.

Usage
Saturated(pot, name)

Arguments
pot An S language function giving the user-supplied pairwise interaction po-
tential.
name Character string.

Details
This is experimental. It constructs a member of the “saturated pairwise”family [Link].

Value
An object of class "interact" describing the interpoint interaction structure of a point
process.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, [Link], Geyer, SatPiece, [Link]

scanpp Read Point Pattern From Data File

Description
Reads a point pattern dataset from a text file.

Usage
scanpp(filename, window, header=TRUE, dir="", multitype=FALSE)
scanpp 577

Arguments

filename String name of the file containing the coordinates of the points in the
point pattern, and their marks if any.
window Window for the point pattern. An object of class "owin".
header Logical flag indicating whether the first line of the file contains headings
for the columns. Passed to [Link].
dir String containing the path name of the directory in which filename is to
be found. Default is the current directory.
multitype Logical flag indicating whether marks are to be interpreted as a factor
(multitype = TRUE) or as numerical values (multitype = FALSE).

Details

This simple function reads a point pattern dataset from a file containing the cartesian
coordinates of its points, and optionally the mark values for these points.
The file identified by filename in directory dir should be a text file that can be read using
[Link]. Thus, each line of the file (except possibly the first line) contains data for
one point in the point pattern. Data are arranged in columns. There should be either two
columns (for an unmarked point pattern) or three columns (for a marked point pattern).
If header=FALSE then the first two columns of data will be interpreted as the x and y
coordinates of points. A third column, if present, will be interpreted as containing the
marks for these points. The marks will be converted to a factor if multitype = TRUE.
If header=TRUE then the first line of the file should contain string names for each of the
columns of data. If there are columns named x and y then these will be taken as the
cartesian coordinates, and any remaining column will be taken as the marks. If there are
no columns named x and y then the first and second columns will be taken as the cartesian
coordinates.
Note that there is intentionally no default for window. The window of observation should
be specified. If you really need to estimate the window, use the Ripley-Rasson estimator
ripras.

Value

A point pattern (an object of class "ppp", see [Link]).

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], ppp, [Link], ripras


578 [Link]

[Link] Crossing Points in a Line Segment Pattern

Description

Finds any crossing points between the line segments in a line segment pattern.

Usage

[Link](A)

Arguments

A Line segment pattern (object of class "psp").

Details

This function finds any crossing points between different line segments in the line segment
pattern A.
A crossing point occurs whenever one of the line segments in A intersects another line
segment in A, at a nonzero angle of intersection.

Value

Point pattern (object of class "ppp").

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], [Link], [Link].

Examples

a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())


plot(a, col="green", main="[Link]")
P <- [Link](a)
plot(P, add=TRUE, col="red")
setcov 579

setcov Set Covariance of a Window

Description
Computes the set covariance function of a window.

Usage
setcov(W, ...)

Arguments
W A window (object of class "owin".
... Optional arguments passed to [Link] to control the pixel resolution.

Details
The set covariance function of a region W in the plane is the function C(v) defined for each
vector v as the area of the intersection between W and W + v, where W + v is the set
obtained by shifting (translating) W by v.
We may interpret C(v) as the area of the set of all points x in W such that x + v also lies
in W .
This command computes a discretised approximation to the set covariance function of any
plane region W represented as a window object (of class "owin", see [Link]). The
return value is a pixel image (object of class "im") whose greyscale values are values of the
set covariance function.
The set covariance is computed using the Fast Fourier Transform, unless W is a rectangle,
when an exact formula is used.

Value
A pixel image (an object of class "im") representing the set covariance function of W.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, [Link], erosion

Examples
w <- owin(c(0,1),c(0,1))
v <- setcov(w)
plot(v)
580 setmarks

setmarks Set or Reset the Marks in a Point Pattern

Description
Create a marked point pattern from given point locations and given marks.

Usage
setmarks(X, m)
X %mark% m

Arguments
X Point pattern (object of class "ppp")
m Vector of mark values (of any atomic mode)

Details
This function is a shortcut which creates a marked point pattern from a given point pattern
X and a given vector m by attaching the marks in m to the locations of the points in X.
If X is already a marked point pattern, then its marks are ignored and replaced by the
values in m.
If m is a single value, then all points will be given this mark value. Otherwise, m must be
a vector of length equal to the number of points in X, and the point X[i] will receive the
mark m[i].
Use unmark to remove marks. Use ppp to create point patterns in more general situations.

Value
Marked point pattern (object of class "ppp") identical to X except that it has marks equal
to m.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
unmark, [Link], [Link], [Link]

Examples
data(cells)

m <- runif(cells$n)

Y <- setmarks(cells, m)
Y <- cells %mark% m
# equivalent
shapley 581

## Not run: plot(Y)


[Link](Y) #TRUE

shapley Galaxies in the Shapley Supercluster

Description
A point pattern recording the sky positions of 4215 galaxies in the Shapley Supercluster.

Usage
data(shapley)

Format
shapley is an object of class "ppp" representing the point pattern of galaxy locations (see
[Link]).
[Link] is a list containing additional data described under Notes.

Notes
This dataset comes from a survey by Drinkwater et al (2004) of the Shapley Supercluster,
one of the most massive concentrations of galaxies in the local universe. The data give
the sky positions of 4215 galaxies observed using the FLAIR-II spectrograph on the UK
Schmidt Telescope (UKST). They were kindly provided by Dr Michael Drinkwater through
the Centre for Astrostatistics at Penn State University.
Sky positions are given using the coordinates Right Ascension (degrees from 0 to 360) and
Declination (degrees from -90 to 90).
The region covered by the survey was approximately the UKST’s standard quadrilateral
survey fields 382 to 384 and 443 to 446. However, a few of the galaxy positions lie outside
these fields.
The point pattern dataset shapley consists of all 4215 galaxy locations. The observa-
tion window for this pattern is a dilated copy of the convex hull of the galaxy positions,
constructed so that all galaxies lie within the window.
The auxiliary dataset [Link] contains the following components:

UKSTfields a list of seven windows (objects of class "owin") giving the UKST standard
survey fields.
UKSTdomain the union of these seven fields, an object of class "owin".
plotit a function (called without arguments) that will plot the data and the survey fields
in the conventional astronomical presentation, in which Right Ascension is converted
to hours and minutes (1 hour equals 15 degrees) and Right Ascension decreases as we
move to the right of the plot.

Source
M.J. Drinkwater, Department of Physics, University of Queensland
582 shift

References
Drinkwater, M.J., Parker, Q.A., Proust, D., Slezak, E. and Quintana, H. (2004) The large
scale distribution of galaxies in the Shapley Supercluster. Publications of the Astronomical
Society of Australia 21, 89-96. DOI 10.1071/AS03057

Examples
data(shapley)
[Link]$plotit(main="Shapley Supercluster")

shift Apply Vector Translation

Description
Applies a vector shift of the plane to a geometrical object, such as a point pattern or a
window.

Usage
shift(X, ...)

Arguments
X Any suitable dataset representing a two-dimensional object, such as a
point pattern (object of class "ppp"), or a window (object of class "owin").
... Arguments determining the shift vector.

Details
This is generic. Methods are provided for point patterns ([Link]) and windows ([Link]).
The object is translated by the vector vec.

Value
Another object of the same type, representing the result of applying the shift.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], rotate, affine
[Link] 583

[Link] Apply Vector Translation To Pixel Image

Description

Applies a vector shift to a pixel image

Usage

## S3 method for class 'im':


shift(X, vec=c(0,0), ..., origin=NULL)

Arguments

X Pixel image (object of class "im").


vec Vector of length 2 representing a translation.
... Ignored
origin Character string determining a location that will be shifted to the ori-
gin. Options are "centroid", "midpoint" and "bottomleft". Partially
matched.

Details

The spatial location of each pixel in the image is translated by the vector vec. This is a
method for the generic function shift.
If origin is given, then it should be one of the character strings "centroid", "midpoint"
or "bottomleft". The argument vec will be ignored; instead the shift will be performed
so that the specified geometric location is shifted to the origin. If origin="centroid"
then the centroid of the image window will be shifted to the origin. If origin="midpoint"
then the centre of the bounding rectangle of the image will be shifted to the origin. If
origin="bottomleft" then the bottom left corner of the bounding rectangle of the image
will be shifted to the origin.

Value

Another pixel image (of class "im") representing the result of applying the vector shift.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

shift
584 [Link]

Examples
# make up an image
X <- setcov([Link]())
plot(X)

Y <- shift(X, c(10,10))


plot(Y)
# no discernible difference except coordinates are different

shift(X, origin="mid")

[Link] Apply Vector Translation To Window

Description
Applies a vector shift to a window

Usage
## S3 method for class 'owin':
shift(X, vec=c(0,0), ..., origin=NULL)

Arguments
X Window (object of class "owin").
vec Vector of length 2 representing a translation.
... Ignored
origin Character string determining a location that will be shifted to the ori-
gin. Options are "centroid", "midpoint" and "bottomleft". Partially
matched.

Details
The window is translated by the vector vec. This is a method for the generic function
shift.
If origin is given, then it should be one of the character strings "centroid", "midpoint"
or "bottomleft". The argument vec will be ignored; instead the shift will be performed so
that the specified geometric location is shifted to the origin. If origin="centroid" then the
centroid of the window will be shifted to the origin. If origin="midpoint" then the centre of
the bounding rectangle of the window will be shifted to the origin. If origin="bottomleft"
then the bottom left corner of the bounding rectangle of the window will be shifted to the
origin.

Value
Another window (of class "owin") representing the result of applying the vector shift.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
[Link] 585

See Also
shift, [Link], rotate, affine, [Link]

Examples
W <- owin(c(0,1),c(0,1))
X <- shift(W, c(2,3))
## Not run:
plot(W)
# no discernible difference except coordinates are different

## End(Not run)
shift(W, origin="mid")

[Link] Apply Vector Translation To Point Pattern

Description
Applies a vector shift to a point pattern.

Usage
## S3 method for class 'ppp':
shift(X, vec=c(0,0), ..., origin=NULL)

Arguments
X Point pattern (object of class "ppp").
vec Vector of length 2 representing a translation.
... Ignored
origin Character string determining a location that will be shifted to the ori-
gin. Options are "centroid", "midpoint" and "bottomleft". Partially
matched.

Details
The point pattern, and its window, are translated by the vector vec.
This is a method for the generic function shift.
If origin is given, then it should be one of the character strings "centroid", "midpoint"
or "bottomleft". The argument vec will be ignored; instead the shift will be performed so
that the specified geometric location is shifted to the origin. If origin="centroid" then the
centroid of the window will be shifted to the origin. If origin="midpoint" then the centre of
the bounding rectangle of the window will be shifted to the origin. If origin="bottomleft"
then the bottom left corner of the bounding rectangle of the window will be shifted to the
origin.

Value
Another point pattern (of class "ppp") representing the result of applying the vector shift.
586 [Link]

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
shift, [Link], rotate, affine

Examples
data(cells)
X <- shift(cells, c(2,3))
## Not run:
plot(X)
# no discernible difference except coordinates are different

## End(Not run)
plot(cells, pch=16)
plot(shift(cells, c(0.03,0.03)), add=TRUE)

shift(cells, origin="mid")

[Link] Apply Vector Translation To Line Segment Pattern

Description
Applies a vector shift to a line segment pattern.

Usage
## S3 method for class 'psp':
shift(X, vec=c(0,0), ..., origin=NULL)

Arguments
X Line Segment pattern (object of class "psp").
vec Vector of length 2 representing a translation.
... Ignored
origin Character string determining a location that will be shifted to the ori-
gin. Options are "centroid", "midpoint" and "bottomleft". Partially
matched.

Details
The line segment pattern, and its window, are translated by the vector vec.
This is a method for the generic function shift.
If origin is given, then it should be one of the character strings "centroid", "midpoint"
or "bottomleft". The argument vec will be ignored; instead the shift will be performed so
that the specified geometric location is shifted to the origin. If origin="centroid" then the
centroid of the window will be shifted to the origin. If origin="midpoint" then the centre of
simdat 587

the bounding rectangle of the window will be shifted to the origin. If origin="bottomleft"
then the bottom left corner of the bounding rectangle of the window will be shifted to the
origin.

Value
Another line segment pattern (of class "psp") representing the result of applying the vector
shift.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
shift, [Link], [Link], rotate, affine

Examples
X <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
plot(X, col="red")
Y <- shift(X, c(0.05,0.05))
plot(Y, add=TRUE, col="blue")

shift(Y, origin="mid")

simdat Simulated Point Pattern

Description
This point pattern data set was simulated (using the Metropolis-Hastings algorithm) from
a model fitted to the Numata Japanese black pine data set referred to in Baddeley and
Turner (2000).

Usage
data(simdat)

Format
An object of class "ppp" in a square window of size 10 by 10 units.
See [Link] for details of the format of a point pattern object.

Source
Rolf Turner <[Link]@[Link]>

References
Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283–322.
588 [Link]

[Link] Approximate a Polygon by a Simpler Polygon

Description
Given a polygonal window, this function finds a simpler polygon that approximates it.

Usage
[Link](W, dmin)

Arguments
W The polygon which is to be simplied. An object of class "owin".
dmin Numeric value. The smallest permissible length of an edge.

Details
This function simplifies a polygon W by recursively deleting the shortest edge of W until all
remaining edges are longer than the specified minimum length dmin, or until there are only
three edges left.
The argument W must be a window (object of class "owin"). It should be of type "polygonal".
If W is a rectangle, it is returned without alteration.
The simplification algorithm is not yet implemented for binary masks. If W is a mask, an
error is generated.

Value
Another window (object of class "owin") of type "polygonal".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin

Examples
data(letterR)
plot(letterR, col="red")
plot([Link](letterR, 0.3), col="blue", add=TRUE)
data(chorley)
W <- chorley$window
plot(W)
WS <- [Link](W, 2)
plot(WS, add=TRUE, border="green")
points(vertices(WS))
[Link] 589

[Link] Simulate a Fitted Cluster Point Process Model

Description
Generates simulated realisations from a fitted cluster point process model.

Usage
## S3 method for class 'kppm':
simulate(object, nsim = 1, seed=NULL, ...,
window=NULL, covariates=NULL)

Arguments
object Fitted cluster point process model. An object of class "kppm".
nsim Number of simulated realisations.
seed an object specifying whether and how to initialise the random number
generator. Either NULL or an integer that will be used in a call to [Link]
before simulating the point patterns.
... Ignored.
window Optional. Window (object of class "owin") in which the model should be
simulated.
covariates Optional. A named list containing new values for the covariates in the
model.

Details
This function is a method for the generic function simulate for the class "kppm" of fitted
cluster point process models.
Simulations are performed by rThomas or rMatClust depending on the cluster mechanism.
The return value is a list of point patterns. It also carries an attribute "seed" that captures
the initial state of the random number generator. This follows the convention used in
[Link] (see simulate). It can be used to force a sequence of simulations to be
repeated exactly, as shown in the examples for simulate.

Value
A list of length nsim containing simulated point patterns (objects of class "ppp").
The return value also carries an attribute "seed" that captures the initial state of the
random number generator. See Details.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
kppm, [Link], simulate
590 [Link]

Examples
data(redwood)
fit <- kppm(redwood, ~1, "Thomas")
simulate(fit, 2)

[Link] Simulate a Fitted Gibbs Point Process Model

Description
Generates simulated realisations from a fitted Gibbs or Poisson point process model.

Usage
## S3 method for class 'ppm':
simulate(object, nsim=1, ...,
start = NULL,
control = rmhcontrol(),
project=TRUE,
verbose=FALSE, progress=TRUE)

Arguments
object Fitted point process model. An object of class "ppm".
nsim Number of simulated realisations.
start Data determining the initial state of the Metropolis-Hastings algorithm.
See rmhstart for description of these arguments. Defaults to list([Link]=[Link](model
control Data controlling the running of the Metropolis-Hastings algorithm. See
rmhcontrol for description of these arguments.
... Ignored.
verbose Logical flag indicating whether to print progress reports from [Link]
during the simulation of each point pattern.
progress Logical flag indicating whether to print progress reports for the sequence
of simulations.
project Logical flag indicating what to do if the fitted model is invalid (in the
sense that the values of the fitted coefficients do not specify a valid point
process). If project=TRUE the closest valid model will be simulated; if
project=FALSE an error will occur.

Details
This function is a method for the generic function simulate for the class "ppm" of fitted
point process models.
Simulations are performed by [Link].

Value
A list of length nsim containing simulated point patterns (objects of class "ppp").
[Link] 591

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm, [Link], simulate

Examples
data(japanesepines)
fit <- ppm(japanesepines, ~1, Strauss(0.1))
simulate(fit, 2)

[Link] Spatial smoothing of observations at irregular points

Description
Performs spatial smoothing of numeric values observed at a set of irregular locations.

Usage
[Link](X, ..., weights = rep(1, X$n), at="pixels")
markmean(X, ...)
markvar(X, ...)

Arguments
X A marked point pattern (object of class "ppp").
... Arguments passed to [Link] to control the kernel smoothing and
the pixel resolution of the result.
weights Optional weights attached to the observations.
at String specifying whether to compute the intensity values at a grid of
pixel locations (at="pixels") or only at the points of x (at="points").

Details
The function [Link] performs spatial smoothing of numeric values observed at a set
of irregular locations. The functions markmean and markvar are wrappers for [Link]
which compute the spatially-varying mean and variance of the marks of a point pattern.
Smoothing is performed by Gaussian kernel weighting. If the observed values are v1 , . . . , vn
at locations x1 , . . . , xn respectively, then the smoothed value at a location u is (ignoring
edge corrections) P
k(u − xi )vi
g(u) = Pi
i k(u − xi )
where k is a Gaussian kernel.
The argument X must be a marked point pattern (object of class "ppp", see [Link]).
The points of the pattern are taken to be the observation locations xi , and the marks of
the pattern are taken to be the numeric values vi observed at these locations.
592 Softcore

The numerator and denominator are computed by [Link]. The arguments ... con-
trol the smoothing kernel parameters and determine whether edge correction is applied.
See [Link].
The optional argument weights allows numerical weights to be applied to the data. If
a weight wi is associated with location xi , then the smoothed function is (ignoring edge
corrections) P
k(u − xi )vi wi
g(u) = Pi
i k(u − xi )wi

Value
By default, the result is a pixel image (object of class "im"). Pixel values are values of the
interpolated function.
If at="points", the result is a numeric vector of length equal to the number of points in
x. Entries are values of the interpolated function at the points of x.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]. To perform interpolation, see the akima package.

Examples
# Longleaf data - tree locations, marked by tree diameter
data(longleaf)
# Local smoothing of tree diameter
Z <- [Link](longleaf)
# Kernel bandwidth sigma=5
plot([Link](longleaf, 5))
# mark variance
plot(markvar(longleaf))

Softcore The Soft Core Point Process Model

Description
Creates an instance of the Soft Core point process model which can then be fitted to point
pattern data.

Usage
Softcore(kappa)

Arguments
kappa The exponent κ of the Soft Core interaction
Softcore 593

Details
The (stationary) Soft Core point process with parameters β and σ and exponent κ is
the pairwise interaction point process in which each point contributes a factor β to the
probability density of the point pattern, and each pair of points contributes a factor
   
σ 2/κ
exp −
d
to the density, where d is the distance between the two points.
Thus the process has probability density
 
 X σ
2/κ 
f (x1 , . . . , xn ) = αβ n(x) exp −

i<j
||xi − xj || 

where x1 , . . . , xn represent the points of the pattern, n(x) is the number of points in the
pattern, α is the normalising constant, and the sum on the right hand side is over all
unordered pairs of points of the pattern.
This model describes an “ordered” or “inhibitive” process, with the interpoint interaction de-
creasing smoothly with distance. The strength of interaction is controlled by the parameter
σ, a positive real number, with larger values corresponding to stronger interaction; and by
the exponent κ in the range (0, 1), with larger values corresponding to weaker interaction.
If σ = 0 the model reduces to the Poisson point process. If σ > 0, the process is well-defined
only for κ in (0, 1). The limit of the model as κ → 0 is the hard core process with hard core
distance h = σ.
The nonstationary Soft Core process is similar except that the contribution of each indi-
vidual point xi is a function β(xi ) of location, rather than a constant beta.
The function ppm(), which fits point process models to point pattern data, requires an
argument of class "interact" describing the interpoint interaction structure of the model
to be fitted. The appropriate description of the Soft Core process pairwise interaction is
yielded by the function Softcore(). See the examples below.
Note the only argument is the exponent kappa. When kappa is fixed, the model becomes
an exponential family with canonical parameters log β and
2
log γ = log σ
κ
The canonical parameters are estimated by ppm(), not fixed in Softcore().

Value
An object of class "interact" describing the interpoint interaction structure of the Soft
Core process with exponent κ.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

References
Ogata, Y, and Tanemura, M. (1981). Estimation of interaction potentials of spatial point
patterns through the maximum likelihood procedure. Annals of the Institute of Statistical
Mathematics, B 33, 315–338.
594 solutionset

Ogata, Y, and Tanemura, M. (1984). Likelihood analysis of spatial point patterns. Journal
of the Royal Statistical Society, series B 46, 496–518.

See Also
ppm, [Link], [Link]

Examples
data(cells)
ppm(cells, ~1, Softcore(kappa=0.5), correction="isotropic")
# fit the stationary Soft Core process to `cells'

solutionset Evaluate Logical Expression Involving Pixel Images and Return


Region Where Expression is True

Description
Given a logical expression involving one or more pixel images, find all pixels where the
expression is true, and assemble these pixels into a window.

Usage
solutionset(..., envir)

Arguments
... An expression in the R language, involving one or more pixel images.
envir Optional. The environment in which to evaluate the expression.

Details
Given a logical expression involving one or more pixel images, this function will find all
pixels where the expression is true, and assemble these pixels into a spatial window.
Pixel images in spatstat are represented by objects of class "im" (see [Link]). These
are essentially matrices of pixel values, with extra attributes recording the pixel dimensions,
etc.
Suppose X is a pixel image. Then [Link](abs(X) > 3) will find all the pixels in X for
which the pixel value is greater than 3 in absolute value, and return a window containing
all these pixels.
Suppose X and Y are two pixel images with compatible dimensions: they have the same
number of pixels, the same physical size of pixels, and the same bounding box. Then
[Link](X > Y) will find all pixels for which the pixel value of X is greater than the
corresponding pixel value of Y, and return a window containing these pixels.
In general, expr can be any logical expression involving (a) the names of pixel images, (b)
scalar constants, and (c) functions which are vectorised. See the Examples.
The expression expr is evaluated by [Link]. The expression expr must be vectorised.
There must be at least one pixel image in the expression. All images must have compatible
dimensions.
[Link] 595

Value
A spatial window (object of class "owin", see [Link]).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link], levelset

Examples
# test images
X <- [Link](function(x,y) { x^2 - y^2 }, [Link]())
Y <- [Link](function(x,y) { 3 * x + y - 1}, [Link]())

W <- solutionset(abs(X) > 0.1)


W <- solutionset(X > Y)
W <- solutionset(X + Y >= 1)

[Link](solutionset(X < Y))

[Link] Internal Options in Spatstat Package

Description
Allows the user to examine and reset the values of global parameters which control actions
in the spatstat package.

Usage
[Link](...)
[Link]()

Arguments
... Either empty, or a succession of parameter names in quotes, or a succes-
sion of name=value pairs. See below for the parameter names.

Details
The function [Link] allows the user to examine and reset the values of global
parameters which control actions in the spatstat package. It is analogous to the system
function options.
The function [Link] resets all the global parameters in spatstat to their
original, default values.
The global parameters are:
596 [Link]

npixel Controls the number of pixels in the discrete approximation of an irregular window
by a binary pixel image as created by [Link]. Either an integer or a pair of integers
giving the number of pixels in the x and y directions.
maxedgewt Edge correction weights will be trimmed so as not to exceed this value. This
applies to the weights computed by [Link] or [Link] and used in Kest
and its relatives.
[Link] List of arguments to be passed to the function image when displaying a bi-
nary image mask (in [Link] or [Link]). Typically used to reset the colours of
foreground and background.
[Link] List of arguments to be passed to the function persp when displaying a real-
valued image, such as the fitted surfaces in [Link].
[Link] List of arguments controlling the plotting of point patterns by [Link].
[Link] List of arguments controlling contour plots of pixel images by [Link].
[Link] Controls the number of dummy points in a quadrature scheme created by
[Link]. Either an integer or a pair of integers giving the number of dummy
points in the x and y directions.
[Link] Function determining the default colour map for [Link]. When called
with one integer argument n, this function should return a character vector of length
n specifying n different colours.
progress Character string determining the style of progress reports printed by progressreport.
Either "tty" or "txtbar".
checkpolygons Logical flag indicating whether the functions owin and [Link] should
check the validity of polygon data. It is advisable to leave this set to TRUE. If you set
checkpolygons=FALSE, no checking will be performed, making it possible to create
window objects whose topology is garbled. This can be useful for inspecting spatial
data that contain errors, for example, when converting data from shapefiles. However,
other functions in spatstat may return incorrect answers on these data.
checksegments Logical flag indicating whether the functions psp and [Link] should check
the validity of line segment data (in particular, checking that the endpoints of the line
segments are inside the specified window). It is advisable to leave this flag set to TRUE.
gpclib Logical flag indicating whether the polygon clipping library gpclib can be used.
Default is TRUE. If it is set to FALSE then certain polygon operations such as intersection
and union will be approximated by raster operations. The licence for gpclib is not
Free Open Source and explicitly forbids commercial use. See library(help=gpclib).
If you are using spatstat for commercial purposes you will need to set this option to
FALSE.

If no arguments are given, the current values of all parameters are returned, in a list.
If one parameter name is given, the current value of this parameter is returned (not in a
list, just the value).
If several parameter names are given, the current values of these parameters are returned,
in a list.
If name=value pairs are given, the named parameters are reset to the given values, and the
previous values of these parameters are returned, in a list.

Value
Either a list of parameters and their values, or a single value. See Details.
[Link] 597

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
options

Examples
[Link]()

[Link]("npixel")
[Link](npixel=150)
[Link](npixel=c(100,200))

[Link]([Link]=list(col=grey(c(0.5,1))))

[Link]([Link]=list(theta=-30,phi=40,d=4))
# see help([Link]) for other options

[Link] Divide Image Into Sub-images

Description
Divides a pixel image into several sub-images according to the value of a factor, or according
to the tiles of a tessellation.

Usage
## S3 method for class 'im':
split(x, f, ..., drop = FALSE)

Arguments
x Pixel image (object of class "im").
f Splitting criterion. Either a tessellation (object of class "tess") or a pixel
image with factor values.
... Ignored.
drop Logical value determining whether each subset should be returned as a
pixel images (drop=FALSE) or as a one-dimensional vector of pixel values
(drop=TRUE).

Details
This is a method for the generic function split for the class of pixel images. The image x
will be divided into subsets determined by the data f. The result is a list of these subsets.
The splitting criterion may be either
598 [Link]

ˆ a tessellation (object of class "tess"). Each tile of the tessellation delineates a subset
of the spatial domain.
ˆ a pixel image (object of class "im") with factor values. The levels of the factor deter-
mine subsets of the spatial domain.

If drop=FALSE (the default), the result is a list of pixel images, each one a subset of the
pixel image x, obtained by restricting the pixel domain to one of the subsets. If drop=TRUE,
then the pixel values are returned as numeric vectors.

Value

If drop=FALSE, a list of pixel images (objects of class "im"). It is also of class "listof" so
that it can be plotted immediately.
If drop=TRUE, a list of numeric vectors.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

[Link], tess, im

Examples
W <- square(1)
X <- [Link](function(x,y){sqrt(x^2+y^2)}, W)
Y <- dirichlet(runifpoint(12, W))
plot(split(X,Y))

[Link] Divide Point Pattern into Sub-patterns

Description

Divides a point pattern into several sub-patterns, according to their marks, or according to
any user-specified grouping.

Usage

## S3 method for class 'ppp':


split(x, f = marks(x), drop=FALSE, un=NULL, ...)
## S3 method for class 'ppp':
split(x, f = marks(x), drop=FALSE, un=missing(f), ...) <- value
[Link] 599

Arguments
x A two-dimensional point pattern. An object of class "ppp".
f Data determining the grouping. Either a factor, a pixel image with factor
values, or a tessellation.
drop Logical. Determines whether empty groups will be deleted.
un Logical. Determines whether the resulting subpatterns will be unmarked
(i.e. whether marks will be removed from the points in each subpattern).
... Other arguments are ignored.
value List of point patterns.

Details
The function [Link] divides up the points of the point pattern x into several sub-
patterns according to the values of f. The result is a list of point patterns.
The argument f may be

ˆ a factor, of length equal to the number of points in x. The levels of f determine the
destination of each point in x. The ith point of x will be placed in the sub-pattern
[Link](x)$l where l = f[i].
ˆ a pixel image (object of class "im") with factor values. The pixel value of f at each
point of x will be used as the classifying variable.
ˆ a tessellation (object of class "tess"). Each point of x will be classified according to
the tile of the tessellation into which it falls.

If f is missing, then x must be a multitype point pattern (a marked point pattern whose
marks vector is a factor). Then the effect is that the points of each type are separated into
different point patterns.
Some of the sub-patterns created by the split may be empty. If drop=TRUE, then empty
sub-patterns will be deleted from the list. If drop=FALSE then they are retained.
The argument un determines how to handle marks in the case where x is a marked point
pattern. If un=TRUE then the marks of the points will be discarded when they are split into
groups, while if un=FALSE then the marks will be retained.
The result of [Link] has class "splitppp" and can be plotted using [Link].
The assignment function split<-.ppp updates the point pattern x so that it satisfies
split(x, f, drop, un) = value. The argument value is expected to be a list of point
patterns, one for each level of f. These point patterns are expected to be compatible with
the type of data in the original pattern x.
Splitting can also be undone by the function superimpose.

Value
The value of [Link] is a list of point patterns. The components of the list are named
by the levels of f. The list also has the class "splitppp".
The assignment form split<-.ppp returns the updated point pattern x.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
600 spokes

See Also

[Link], [Link], superimpose, im, tess, [Link]

Examples

# (1) Splitting by marks

# Multitype point pattern: separate into types


data(amacrine)
u <- split(amacrine)

# plot them
plot(split(amacrine))

# the following are equivalent:


amon <- split(amacrine)$on
amon <- unmark(amacrine[amacrine$marks == "on"])

# the following are equivalent:


amon <- split(amacrine, un=FALSE)$on
amon <- amacrine[amacrine$marks == "on"]

# Scramble the locations of the 'on' cells


u <- split(amacrine)
u$on <- runifpoint(amon$n, amon$window)
split(amacrine) <- u

# Point pattern with continuous marks


data(longleaf)

# cut the range of tree diameters into three intervals


# using [Link]
long3 <- cut(longleaf, breaks=3)
# now split them
long3split <- split(long3)

# (2) Splitting by a factor

# Unmarked point pattern


data(swedishpines)
# cut & split according to nearest neighbour distance
f <- cut(nndist(swedishpines), 3)
u <- split(swedishpines, f)

# (3) Splitting over a tessellation


tes <- tess(xgrid=seq(0,96,length=5),ygrid=seq(0,100,length=5))
v <- split(swedishpines, tes)

spokes Spokes pattern of dummy points


spokes 601

Description
Generates a pattern of dummy points in a window, given a data point pattern. The dummy
points lie on the radii of circles emanating from each data point.

Usage
spokes(x, y, nrad = 3, nper = 3, fctr = 1.5, Mdefault = 1)

Arguments
x Vector of x coordinates of data points, or a list with components x and
y, or a point pattern (an object of class ppp).
y Vector of y coordinates of data points. Ignored unless x is a vector.
nrad Number of radii emanating from each data point.
nper Number of dummy points per radius.
fctr Scale factor. Length of largest spoke radius is fctr * M where M is the
mean nearest neighbour distance for the data points.
Mdefault Value of M to be used if x has length 1.

Details
This function is useful in creating dummy points for quadrature schemes (see quadscheme).
Given the data points, the function creates a collection of nrad * nper * length(x)
dummy points.
Around each data point (x[i],y[i]) there are nrad * nper dummy points, lying on nrad
radii emanating from (x[i],y[i]), with nper dummy points equally spaced along each
radius.
The (equal) spacing of dummy points along each radius is controlled by the factor fctr.
The distance from a data point to the furthest of its associated dummy points is fctr * M
where M is the mean nearest neighbour distance for the data points.
If there is only one data point the nearest neighbour distance is infinite, so the value
Mdefault will be used in place of M.
If x is a point pattern, then the value returned is also a point pattern, which is clipped
to the window of x. Hence there may be fewer than nrad * nper * length(x) dummy
points in the pattern returned.

Value
If argument x is a point pattern, a point pattern with window equal to that of x. Otherwise
a list with two components x and y. In either case the components x and y of the value are
numeric vectors giving the coordinates of the dummy points.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], quadscheme, [Link], gridcentres, stratrand
602 spruces

Examples
dat <- runifrect(10)
## Not run:
plot(dat)

## End(Not run)
dum <- spokes(dat$x, dat$y)
## Not run:
points(dum$x, dum$y, pch=".")

## End(Not run)
Q <- quadscheme(dat, dum)

spruces Spruces Point Pattern

Description
The data give the locations of Norwegian spruce trees in a natural forest stand in Saxonia,
Germany. Each tree is marked with its diameter at breast height.

Usage
data(spruces)

Format
An object of class "ppp" representing the point pattern of tree locations in a 56 x 38 metre
sampling region. Each tree is marked with its diameter at breast height. All values are
given in metres.
See [Link] for details of the format of a point pattern object. The marks are numeric.
These data have been analysed by Fiksel (1984, 1988), Stoyan et al (1987), Penttinen et al
(1992) and Goulard et al (1996).

Source
Stoyan et al (1987). Original source unknown.

References
Fiksel, T. (1984) Estimation of parameterized pair potentials of marked and nonmarked
Gibbsian point processes. Elektron. Informationsverarb. u. Kybernet. 20, 270–278.
Fiksel, T. (1988) Estimation of interaction potentials of Gibbsian point processes. Statistics
19, 77-86
Goulard, M., S\”arkk\”a, A. and Grabarnik, P. (1996) Parameter estimation for marked
Gibbs point processes through the maximum pseudolikelihood method. Scandinavian Jour-
nal of Statistics 23, 365–379.
Penttinen, A., Stoyan, D. and Henttonen, H. (1992) Marked point processes in forest statis-
tics. Forest Science 38, 806–824.
Stoyan, D., Kendall, W.S. and Mecke, J. (1987) Stochastic Geometry and its Applications.
Wiley.
square 603

Examples
data(spruces)
plot(spruces)
# To reproduce Goulard et al. Figure 3
plot(spruces, maxsize=5*max(spruces$marks))
plot(unmark(spruces), add=TRUE)

square Square Window

Description
Creates a square window

Usage
square(r=1)
[Link]()

Arguments
r The side length of the square.

Details
square is a shortcut for creating a window object representing the square [0, r] × [0, r]. It
is equivalent to the command owin(c(0,r),c(0,r)).
[Link] creates the unit square [0, 1]×[0, 1]. It is equivalent to square(1) or square()
or owin(c(0,1),c(0,1)).
These commands are included mainly to improve the readability of some code.

Value
An object of class "owin" (see [Link]) specifying a window.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], owin

Examples
W <- square(10)
604 stieltjes

stieltjes Compute Integral of Function Against Cumulative Distribution

Description
Computes the Stieltjes integral of a function f with respect to a function M .

Usage
stieltjes(f, M, ...)

Arguments
f The integrand. A function in the R language.
M The cumulative function against which f will be integrated. An object of
class "fv".
... Additional arguments passed to f.

Details
This command computes the Stieltjes integral
Z
I = f (x)dM (x)

of a real-valued function f (x) with respect to a nondecreasing function M (x).


One common use of the Stieltjes integral is to find the mean value of a random variable
from its cumulative distribution function F (x). The mean value is the Stieltjes integral of
f (x) = x with respect to F (x).
The argument f should be a function in the R language. It should accept a numeric vector
argument x and should return a numeric vector of the same length.
The argument M should be a function value table (object of class "fv", see [Link]).
Such objects are returned by the commands link{Kest}, Gest, etc.

Value
A list containing the value of the Stieltjes integral computed using each of the versions of
the function M.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], Gest
Strauss 605

Examples
data(redwood)
# estimate cdf of nearest neighbour distance
G <- Gest(redwood)
# compute estimate of mean nearest neighbour distance
stieltjes(function(x){x}, G)
# estimated probability of a distance in the interval [0.1,0.2]
stieltjes(function(x,a,b){ (x >= a) & (x <= b)}, G, a=0.1, b=0.2)

Strauss The Strauss Point Process Model

Description
Creates an instance of the Strauss point process model which can then be fitted to point
pattern data.

Usage
Strauss(r)

Arguments
r The interaction radius of the Strauss process

Details
The (stationary) Strauss process with interaction radius r and parameters β and γ is the
pairwise interaction point process in which each point contributes a factor β to the probabil-
ity density of the point pattern, and each pair of points closer than r units apart contributes
a factor γ to the density.
Thus the probability density is

f (x1 , . . . , xn ) = αβ n(x) γ s(x)

where x1 , . . . , xn represent the points of the pattern, n(x) is the number of points in the
pattern, s(x) is the number of distinct unordered pairs of points that are closer than r units
apart, and α is the normalising constant.
The interaction parameter γ must be less than or equal to 1 so that this model describes
an “ordered” or “inhibitive” pattern.
The nonstationary Strauss process is similar except that the contribution of each individual
point xi is a function β(xi ) of location, rather than a constant beta.
The function ppm(), which fits point process models to point pattern data, requires an
argument of class "interact" describing the interpoint interaction structure of the model
to be fitted. The appropriate description of the Strauss process pairwise interaction is
yielded by the function Strauss(). See the examples below.
Note the only argument is the interaction radius r. When r is fixed, the model becomes an
exponential family. The canonical parameters log(β) and log(γ) are estimated by ppm(),
not fixed in Strauss().
606 StraussHard

Value

An object of class "interact" describing the interpoint interaction structure of the Strauss
process with interaction radius r.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

ppm, [Link], [Link]

Examples
Strauss(r=0.1)
# prints a sensible description of itself
data(cells)

## Not run:
ppm(cells, ~1, Strauss(r=0.07))
# fit the stationary Strauss process to `cells'

## End(Not run)

ppm(cells, ~polynom(x,y,3), Strauss(r=0.07))


# fit a nonstationary Strauss process with log-cubic polynomial trend

StraussHard The Strauss / Hard Core Point Process Model

Description

Creates an instance of the “Strauss/ hard core” point process model which can then be
fitted to point pattern data.

Usage

StraussHard(r, hc)

Arguments

r The interaction radius of the Strauss interaction


hc The hard core distance
StraussHard 607

Details

A Strauss/hard core process with interaction radius r, hard core distance h < r, and
parameters β and γ, is a pairwise interaction point process in which

ˆ distinct points are not allowed to come closer than a distance h apart
ˆ each pair of points closer than r units apart contributes a factor γ to the probability
density.

This is a hybrid of the Strauss process and the hard core process.
The probability density is zero if any pair of points is closer than h units apart, and otherwise
equals
f (x1 , . . . , xn ) = αβ n(x) γ s(x)

where x1 , . . . , xn represent the points of the pattern, n(x) is the number of points in the
pattern, s(x) is the number of distinct unordered pairs of points that are closer than r units
apart, and α is the normalising constant.
The interaction parameter γ may take any positive value (unlike the case for the Strauss
process). If γ = 1, the process reduces to a classical hard core process. If γ < 1, the
model describes an “ordered” or “inhibitive” pattern. If γ > 1, the model is “ordered” or
“inhibitive” up to the distance h, but has an “attraction” between points lying at distances
in the range between h and r.
The function ppm(), which fits point process models to point pattern data, requires an
argument of class "interact" describing the interpoint interaction structure of the model to
be fitted. The appropriate description of the Strauss/hard core process pairwise interaction
is yielded by the function StraussHard(). See the examples below.
The canonical parameter log(γ) is estimated by ppm(), not fixed in StraussHard().

Value

An object of class "interact" describing the interpoint interaction structure of the“Strauss/hard


core” process with Strauss interaction radius r and hard core distance hc.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283–322.
Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.
Strauss, D.J. (1975) A model for clustering. Biometrika 63, 467–475.

See Also

ppm, [Link], [Link]


608 suffstat

Examples
StraussHard(r=1,hc=0.02)
# prints a sensible description of itself

data(cells)

## Not run:
ppm(cells, ~1, StraussHard(r=0.1, hc=0.05))
# fit the stationary Strauss/hard core process to `cells'

## End(Not run)

ppm(cells, ~ polynom(x,y,3), StraussHard(r=0.1, hc=0.05))


# fit a nonstationary Strauss/hard core process
# with log-cubic polynomial trend

suffstat Sufficient Statistic of Point Process Model

Description
The canonical sufficient statistic of a point process model is evaluated for a given point
pattern.

Usage
suffstat(model, X=[Link](model))

Arguments
model A fitted point process model (object of class "ppm").
X A point pattern (object of class "ppp").

Details
The canonical sufficient statistic of model is evaluated for the point pattern X. This com-
putation is useful for various Monte Carlo methods.
Here model should be a point process model (object of class "ppm", see [Link]),
typically obtained from the model-fitting function ppm. The argument X should be a point
pattern (object of class "ppp").
Every point process model fitted by ppm has a probability density of the form

f (x) = Z(θ) exp(θT S(x))

where x denotes a typical realisation (i.e. a point pattern), θ is the vector of model coef-
ficients, Z(θ) is a normalising constant, and S(x) is a function of the realisation x, called
the “canonical sufficient statistic” of the model.
For example, the stationary Poisson process has canonical sufficient statistic S(x) = n(x),
the number of points in x. The stationary Strauss process with interaction range r (and
fitted with no edge correction) has canonical sufficient statistic S(x) = (n(x), s(x)) where
s(x) is the number of pairs of points in x which are closer than a distance r to each other.
suffstat 609

suffstat(model, X) returns the value of S(x), where S is the canonical sufficient statistic
associated with model, evaluated when x is the given point pattern X. The result is a numeric
vector, with entries which correspond to the entries of the coefficient vector coef(model).
The sufficient statistic S does not depend on the fitted coefficients of the model. However
it does depend on the irregular parameters which are fixed in the original call to ppm, for
example, the interaction range r of the Strauss process.
The sufficient statistic also depends on the edge correction that was used to fit the model.
For example in a Strauss process,

ˆ If the model is fitted with correction="none", the sufficient statistic is S(x) =


(n(x), s(x)) where n(x) is the number of points and s(x) is the number of pairs of
points which are closer than r units apart.
ˆ If the model is fitted with correction="periodic", the sufficient statistic is the same
as above, except that distances are measured in the periodic sense.
ˆ If the model is fitted with correction="translate", then n(x) is unchanged but s(x)
is replaced by a weighted sum (the sum of the translation correction weights for all
pairs of points which are closer than r units apart).
ˆ If the model is fitted with correction="border" (the default), then points lying less
than r units from the boundary of the observation window are treated as fixed. Thus
n(x) is replaced by the number nr (x) of points lying at least r units from the boundary
of the observation window, and s(x) is replaced by the number sr (x) of pairs of points,
which are closer than r units apart, and at least one of which lies more than r units
from the boundary of the observation window.

Non-finite values of the sufficient statistic (NA or -Inf) may be returned if the point pattern
X is not a possible realisation of the model (i.e. if X has zero probability of occurring under
model for all values of the canonical coefficients θ).

Value
A numeric vector of sufficient statistics. The entries correspond to the model coefficients
coef(model).

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
ppm

Examples
data(swedishpines)
fitS <- ppm(swedishpines, ~1, Strauss(7))
X <- rpoispp(summary(swedishpines)$intensity, win=swedishpines$window)
suffstat(fitS, X)
610 [Link]

[Link] Summarizing a Pixel Image

Description
summary method for class "im".

Usage
## S3 method for class 'im':
summary(object, ...)
## S3 method for class 'im':
[Link](x, ...)

Arguments
object A pixel image.
... Ignored.
x Object of class "[Link]" as returned by [Link].

Details
This is a method for the generic summary for the class "im". An object of class "im"
describes a pixel image. See [Link]) for details of this class.
[Link] extracts information about the pixel image, and [Link] prints this
information in a comprehensible format.
In normal usage, [Link] is invoked implicitly when the user calls [Link]
without assigning its value to anything. See the examples.
The information extracted by [Link] includes

range The range of the image values.


mean The mean of the image values.
integral The “integral” of the image values, calculated as the sum of the image values
multiplied by the area of one pixel.
dim The dimensions of the pixel array: dim[1] is the number of rows in the array, corre-
sponding to the y coordinate.

Value
[Link] returns an object of class "[Link]", while [Link] returns
NULL.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
[Link] 611

Examples
# make an image
X <- [Link](function(x,y) {x^2}, [Link]())
# summarize it
summary(X)
# save the summary
s <- summary(X)
# print it
print(X)
s
# extract stuff
X$dim
X$range
X$integral

[Link] Summary of a List of Things

Description
Prints a useful summary of each item in a list of things.

Usage
## S3 method for class 'listof':
summary(object, ...)

Arguments
object An object of class "listof".
... Ignored.

Details
This is a method for the generic function summary.
An object of the class "listof" is effectively a list of things which are all of the same class.
This function extracts a useful summary of each of the items in the list.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
summary, [Link]

Examples
x <- list(A=runif(10), B=runif(10), C=runif(10))
class(x) <- c("listof", class(x))
summary(x)
612 [Link]

[Link] Summary of a Spatial Window

Description

Prints a useful description of a window object.

Usage

## S3 method for class 'owin':


summary(object, ...)

Arguments

object Window (object of class "owin").


... Ignored.

Details

A useful description of the window object is printed.


This is a method for the generic function summary.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

summary, [Link], [Link]

Examples

summary(owin()) # the unit square

data(demopat)
W <- demopat$window # weird polygonal window
summary(W) # describes it

summary([Link](W)) # demonstrates current pixel resolution


[Link] 613

[Link] Summarizing a Fitted Point Process Model

Description
summary method for class "ppm".

Usage
## S3 method for class 'ppm':
summary(object, ..., quick=FALSE)
## S3 method for class 'ppm':
[Link](x, ...)

Arguments
object A fitted point process model.
... Ignored.
quick Logical flag controlling the scope of the summary.
x Object of class "[Link]" as returned by [Link].

Details
This is a method for the generic summary for the class "ppm". An object of class "ppm"
describes a fitted point process model. See [Link]) for details of this class.
[Link] extracts information about the type of model that has been fitted, the data
to which the model was fitted, and the values of the fitted coefficients. (If quick=TRUE then
only the information about the type of model is extracted.)
[Link] prints this information in a comprehensible format.
In normal usage, [Link] is invoked implicitly when the user calls [Link]
without assigning its value to anything. See the examples.

Value
[Link] returns an object of class "[Link]", while [Link] returns
NULL.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
# invent some data
X <- rpoispp(42)
# fit a model to it
fit <- ppm(X, ~x, Strauss(r=0.1))
# summarize the fitted model
summary(fit)
# `quick' option
614 [Link]

summary(fit, quick=TRUE)

# save the full summary


s <- summary(fit)
# print it
print(s)
s
# extract stuff
names(s)
s$args$correction
s$name
s$trend$value

## Not run:
# multitype pattern
data(demopat)
fit <- ppm(demopat, ~marks, Poisson())
summary(fit)

## End(Not run)

[Link] Summary of a Point Pattern Dataset

Description
Prints a useful summary of a point pattern dataset.

Usage
## S3 method for class 'ppp':
summary(object, ..., checkdup=TRUE)

Arguments
object Point pattern (object of class "ppp").
... Ignored.
checkdup Logical value indicating whether to check for the presence of duplicate
points.

Details
A useful summary of the point pattern object is printed.
This is a method for the generic function summary.
If checkdup=TRUE, the pattern will be checked for the presence of dublicate points, using
[Link]. This can be time-consuming if the pattern contains many points, so the
checking can be disabled by setting checkdup=FALSE.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
[Link] 615

See Also
summary, [Link], [Link]

Examples
data(cells) # plain vanilla point pattern
summary(cells)

data(lansing) # multitype point pattern

summary(lansing) # tabulates frequencies of each mark

data(longleaf) # numeric marks

summary(longleaf) # prints [Link](x$marks)

data(demopat) # weird polygonal window


summary(demopat) # describes it

[Link] Summary of a Line Segment Pattern Dataset

Description
Prints a useful summary of a line segment pattern dataset.

Usage
## S3 method for class 'psp':
summary(object, ...)

Arguments
object Line segment pattern (object of class "psp").
... Ignored.

Details
A useful summary of the line segment pattern object is printed.
This is a method for the generic function summary.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
summary, [Link], [Link]

Examples
a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
summary(a) # describes it
616 [Link]

[Link] Summarizing a Quadrature Scheme

Description
summary method for class "quad".

Usage
## S3 method for class 'quad':
summary(object, ..., checkdup=FALSE)
## S3 method for class 'quad':
[Link](x, ..., dp=3)

Arguments
object A quadrature scheme.
... Ignored.
checkdup Logical value indicating whether to test for duplicated points.
dp Number of significant digits to print.
x Object of class "[Link]" returned by [Link].

Details
This is a method for the generic summary for the class "quad". An object of class "quad"
describes a quadrature scheme, used to fit a point process model. See [Link]) for
details of this class.
[Link] extracts information about the quadrature scheme, and [Link]
prints this information in a comprehensible format.
In normal usage, [Link] is invoked implicitly when the user calls [Link]
without assigning its value to anything. See the examples.

Value
[Link] returns an object of class "[Link]", while [Link] re-
turns NULL.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
# make a quadrature scheme
Q <- quadscheme(rpoispp(42))
# summarize it
summary(Q)
# save the summary
s <- summary(Q)
# print it
[Link] 617

print(s)
s
# extract total quadrature weight
s$w$all$sum

[Link] Summary of a Split Point Pattern

Description

Prints a useful summary of a split point pattern.

Usage

## S3 method for class 'splitppp':


summary(object, ...)

Arguments

object Split point pattern (object of class "splitppp", effectively a list of point
patterns, usually created by [Link]).
... Ignored.

Details

This is a method for the generic function summary.


An object of the class "splitppp" is effectively a list of point patterns (objects of class
"ppp") representing different sub-patterns of an original point pattern.
This function extracts a useful summary of each of the sub-patterns.

Author(s)

Adrian Baddeley <adrian@[Link]> [Link]


and Rolf Turner <[Link]@[Link]>

See Also

summary, split, [Link]

Examples
data(amacrine) # multitype point pattern
summary(split(amacrine))
618 superimpose

superimpose Superimpose Several Point Patterns

Description
Superimpose any number of point patterns.

Usage
superimpose(..., W=NULL, check=TRUE)

Arguments
... Any number of arguments, each of which represents a point pattern. Each
argument must be either a point pattern object (of class "ppp") or a
structure containing elements x and y.
W Optional. Window for the resulting point pattern. An object of class
"owin", or something acceptable to [Link].
check Logical value (passed to ppp) determining whether to check the geomet-
rical validity of the resulting point pattern.

Details
This function is used to superimpose two or more point patterns (see also concatxy).
Each of the arguments in ... is either a point pattern object (of class "ppp") or a structure
containing (at least) the elements x and y. The point patterns are not required to have the
same window of observation.
The window for the superimposed point pattern is specified by W. Its default value is the
union of the windows of all the point patterns.
If any of the arguments is a marked point pattern, then all of them must be. In that case,
the result is also a marked point pattern.
If the arguments are given in the form name=value, then the names will be used as marks
attached to the corresponding points. See the last line in the Examples.

Value
A point pattern (object of class "ppp") representing the superposition (union) of all the
point patterns.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
concatxy, quadscheme.
See superimposePSP for superimposing patterns of line segments.
superimposePSP 619

Examples
dat <- runifrect(30)
xy <- list(x=runif(10),y=runif(10))
new <- superimpose(dat, xy)
## Not run: plot(new)

# how to make a 2-type point pattern with types "a" and "b"
u <- superimpose(a = rpoispp(10), b = rpoispp(20))

# how to make a 2-type point pattern with types 1 and 2


u <- superimpose("1" = rpoispp(10), "2" = rpoispp(20))

superimposePSP Superimpose Several Line Segment Patterns

Description
Superimpose any number of line segment patterns.

Usage
superimposePSP(..., W=NULL, check=TRUE)

Arguments
... Any number of arguments, each of which is a line segment pattern (object
of class "psp").
W Optional. Window for the resulting line segment pattern. An object of
class "owin", or something acceptable to [Link].
check Logical value (passed to psp) determining whether to check the geomet-
rical validity of the resulting line segment pattern.

Details
This function is used to superimpose two or more line segment patterns.
Each of the arguments in ... is a line segment pattern object (of class "psp"). The line
segment patterns are not required to have the same window of observation.
The window for the superimposed line segment pattern is specified by W. Its default value
is the union of the windows of all the line segment patterns.
If any of the arguments is a marked line segment pattern, then all of them must be. In that
case, the result is also a marked line segment pattern.

Value
A line segment pattern (object of class "psp") representing the superposition (union) of all
the line segment patterns.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
620 swedishpines

See Also
superimpose for superimposing point patterns.

Examples
X <- rpoisline(10)
Y <- [Link](matrix(runif(40), 10, 4), window=owin())
Z <- superimposePSP(X, Y)

swedishpines Swedish Pines Point Pattern

Description
The data give the locations of pine saplings in a Swedish forest.

Usage
data(swedishpines)

Format
An object of class "ppp" representing the point pattern of tree locations in a 10 x 10 metre
square. Cartesian coordinates are in decimetres (multiples of 0.1 metre).
See [Link] for details of the format of a point pattern object.

Note
For previous analyses see Ripley (1981, pp. 172-175), Venables and Ripley (1997, p. 483),
Baddeley and Turner (2000).

Source
Strand (1975), Ripley (1981)

References
Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point
patterns. Australian and New Zealand Journal of Statistics 42, 283–322.
Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.
Strand, L. (1972). A model for stand growth. IUFRO Third Conference Advisory Group of
Forest Statisticians, INRA, Institut National de la Recherche Agronomique, Paris. Pages
207–216.
Venables, W.N. and Ripley, B.D. (1997) Modern applied statistics with S-PLUS. Second
edition. Springer Verlag.
tess 621

tess Create a Tessellation

Description
Creates an object of class "tess" representing a tessellation of a spatial region.

Usage
tess(..., xgrid = NULL, ygrid = NULL, tiles = NULL, image = NULL,
window=NULL)

Arguments
... Ignored.
xgrid,ygrid Cartesian coordinates of vertical and horizontal lines determining a grid
of rectangles. Incompatible with other arguments.
tiles List of tiles in the tessellation. A list, each of whose elements is a window
(object of class "owin"). Incompatible with other arguments.
image Pixel image which specifies the tessellation. Incompatible with other ar-
guments.
window Optional. The spatial region which is tessellated (i.e. the union of all the
tiles). An object of class "owin".

Details
A tessellation is a collection of disjoint spatial regions (called tiles) that fit together to form
a larger spatial region. This command creates an object of class "tess" that represents a
tessellation.
Three types of tessellation are supported:
rectangular: tiles are rectangles, with sides parallel to the x and y axes. They may or
may not have equal size and shape. The arguments xgrid and ygrid determine the
positions of the vertical and horizontal grid lines, respectively. (See quadrats for
another way to do this.)
tile list: tiles are arbitrary spatial regions. The argument tiles is a list of these tiles,
which are objects of class "owin".
pixel image: Tiles are subsets of a fine grid of pixels. The argument image is a pixel
image (object of class "im") with factor values. Each level of the factor represents a
different tile of the tessellation. The pixels that have a particular value of the factor
constitute a tile.
The optional argument window specifies the spatial region formed by the union of all the
tiles. In other words it specifies the spatial region that is divided into tiles by the tessellation.
If this argument is missing or NULL, it will be determined by computing the set union of
all the tiles. This is a time-consuming computation. For efficiency it is advisable to specify
the window. Note that the validity of the window will not be checked.
There are methods for print, plot, [ and [<- for tessellations. Use tiles to extract the
list of tiles in a tessellation.
Tessellations can be used to classify the points of a point pattern, in [Link], [Link]
and [Link].
622 [Link]

Value
An object of class "tess" representing the tessellation.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [.tess, [Link], tiles, [Link], [Link], [Link], [Link], quadrats,
[Link].

Examples
A <- tess(xgrid=0:4,ygrid=0:4)
A
B <- A[c(1, 2, 5, 7, 9)]
B
v <- [Link](function(x,y){factor(round(5 * (x^2 + y^2)))}, W=owin())
levels(v) <- letters[seq(length(levels(v)))]
E <- tess(image=v)
E

[Link] Fit the Thomas Point Process by Minimum Contrast

Description
Fits the Thomas point process to a point pattern dataset by the Method of Minimum
Contrast.

Usage
[Link](X, startpar=c(kappa=1,sigma2=1), lambda=NULL,
q = 1/4, p = 2, rmin = NULL, rmax = NULL, ...)

Arguments
X Data to which the Thomas model will be fitted. Either a point pattern
or a summary statistic. See Details.
startpar Vector of starting values for the parameters of the Thomas process.
lambda Optional. An estimate of the intensity of the point process.
q,p Optional. Exponents for the contrast criterion.
rmin, rmax Optional. The interval of r values for the contrast criterion.
... Optional arguments passed to optim to control the optimisation algo-
rithm. See Details.
[Link] 623

Details

This algorithm fits the Thomas point process model to a point pattern dataset by the
Method of Minimum Contrast, using the K function.
The argument X can be either

a point pattern: An object of class "ppp" representing a point pattern dataset. The K
function of the point pattern will be computed using Kest, and the method of minimum
contrast will be applied to this.
a summary statistic: An object of class "fv" containing the values of a summary statis-
tic, computed for a point pattern dataset. The summary statistic should be the K
function, and this object should have been obtained by a call to Kest or one of its
relatives.

The algorithm fits the Thomas point process to X, by finding the parameters of the Thomas
model which give the closest match between the theoretical K function of the Thomas
process and the observed K function. For a more detailed explanation of the Method of
Minimum Contrast, see mincontrast.
The Thomas point process is described in Moller and Waagepetersen (2003, pp. 61–62).
It is a cluster process formed by taking a pattern of parent points, generated according
to a Poisson process with intensity κ, and around each parent point, generating a random
number of offspring points, such that the number of offspring of each parent is a Poisson
random variable with mean µ, and the locations of the offspring points of one parent are
independent and isotropically Normally distributed around the parent point with standard
deviation σ.
The theoretical K-function of the Thomas process is

1 r2
K(r) = πr2 + (1 − exp(− 2 )).
κ 4σ

The theoretical intensity of the Thomas process is λ = κµ.


In this algorithm, the Method of Minimum Contrast is first used to find optimal values of
the parameters κ and σ 2 . Then the remaining parameter µ is inferred from the estimated
intensity λ.
If the argument lambda is provided, then this is used as the value of λ. Otherwise, if X is
a point pattern, then λ will be estimated from X. If X is a summary statistic and lambda is
missing, then the intensity λ cannot be estimated, and the parameter µ will be returned as
NA.
The remaining arguments rmin,rmax,q,p control the method of minimum contrast; see
mincontrast.
The Thomas process can be simulated, using rThomas.
Homogeneous or inhomogeneous Thomas process models can also be fitted using the func-
tion kppm.
The optimisation algorithm can be controlled through the additional arguments "..."
which are passed to the optimisation function optim. For example, to constrain the param-
eter values to a certain range, use the argument method="L-BFGS-B" to select an optimi-
sation algorithm that respects box constraints, and use the arguments lower and upper to
specify (vectors of) minimum and maximum values for each parameter.
624 tiles

Value
An object of class "minconfit". There are methods for printing and plotting this object.
It contains the following main components:
par Vector of fitted parameter values.
fit Function value table (object of class "fv") containing the observed values
of the summary statistic (observed) and the theoretical values of the
summary statistic computed from the fitted model parameters.

Author(s)
Rasmus Waagepetersen <rw@[Link]> Adapted for spatstat by Adrian Baddeley <adrian@[Link]
[Link]

References
Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial
Point Processes. Chapman and Hall/CRC, Boca Raton.
Waagepetersen, R. (2006). An estimation function approach to inference for inhomogeneous
Neyman-Scott processes. Submitted.

See Also
kppm, [Link], [Link], mincontrast, Kest, rThomas to simulate the fitted
model.

Examples
data(redwood)
u <- [Link](redwood, c(kappa=10, sigma2=0.1))
u
plot(u)

tiles Extract List of Tiles in a Tessellation

Description
Extracts a list of the tiles that make up a tessellation.

Usage
tiles(x)

Arguments
x A tessellation (object of class "tess").

Details
A tessellation is a collection of disjoint spatial regions (called tiles) that fit together to form
a larger spatial region. See tess.
The tiles that make up the tessellation x are returned in a list.
[Link] 625

Value
A list of windows (objects of class "owin").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
tess

Examples
A <- tess(xgrid=0:2,ygrid=0:2)
tiles(A)
v <- [Link](function(x,y){factor(round(x^2 + y^2))}, W=owin())
E <- tess(image=v)
tiles(E)

[Link] Cut margins from rectangle

Description
Trims a margin from a rectangle.

Usage
[Link](W, xmargin=0, ymargin=xmargin)

Arguments
W A window (object of class "owin"). Must be of type "rectangle".
xmargin Width of horizontal margin to be trimmed. A single nonnegative number,
or a vector of length 2 indicating margins of unequal width at left and
right.
ymargin Height of vertical margin to be trimmed. A single nonnegative number,
or a vector of length 2 indicating margins of unequal width at bottom and
top.

Details
This is a simple convenience function to trim off a margin of specified width and height
from each side of a rectangular window. Unequal margins can also be trimmed.

Value
Another object of class "owin" representing the window after margins are trimmed.
626 [Link]

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link]

Examples
w <- square(10)
# trim a margin of width 1 from all four sides
square9 <- [Link](w, 1)

# trim margin of width 3 from the right side


# and margin of height 4 from top edge.
v <- [Link](w, c(0,3), c(0,4))

[Link] Union of Data and Dummy Points

Description
Combines the data and dummy points of a quadrature scheme into a single point pattern.

Usage
[Link](Q)

Arguments
Q A quadrature scheme (an object of class "quad").

Details
The argument Q should be a quadrature scheme (an object of class "quad", see [Link]
for details).
This function combines the data and dummy points of Q into a single point pattern. If
either the data or the dummy points are marked, the result is a marked point pattern.
The function [Link] will perform the same task.

Value
A point pattern (of class "ppp").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link]
[Link] 627

Examples
data(simdat)
Q <- quadscheme(simdat, [Link](simdat))
U <- [Link](Q)
## Not run: plot(U)
# equivalent:
U <- [Link](Q)

[Link] Extract Unique Points from a Spatial Point Pattern

Description
Removes any points that are identical to other points in a spatial point pattern.

Usage
## S3 method for class 'ppp':
unique(x, ...)

Arguments
x A spatial point pattern (object of class "ppp").
... Ignored.

Details
This is a method for the generic function unique for point pattern datasets (of class "ppp",
see [Link]).
Two points in a point pattern are deemed to be identical if their x, y coordinates are the
same, and their marks are also the same (if they carry marks). The Examples section
illustrates how it is possible for a point pattern to contain a pair of identical points.
This function removes duplicate points in x, and returns a point pattern.

Value
Another point pattern object.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link], [Link], [Link]

Examples
X <- ppp(c(1,1,0.5), c(2,2,1), window=square(3))
unique(X)
628 unitname

unitname Name for Unit of Length

Description
Inspect or change the name of the unit of length in a spatial dataset.

Usage
unitname(x)
## S3 method for class 'ppp':
unitname(x)
## S3 method for class 'psp':
unitname(x)
## S3 method for class 'owin':
unitname(x)
## S3 method for class 'im':
unitname(x)
unitname(x) <- value
## S3 replacement method for class 'ppp':
unitname(x) <- value
## S3 replacement method for class 'psp':
unitname(x) <- value
## S3 replacement method for class 'owin':
unitname(x) <- value
## S3 replacement method for class 'im':
unitname(x) <- value

Arguments
x A spatial dataset. Either a point pattern (object of class "ppp"), a line
segment pattern (object of class "psp"), a window (object of class "owin")
or a pixel image (object of class "im").
value Name of the unit of length. See Details.

Details
Spatial datasets in the spatstat package may include the name of the unit of length. This
name is used when printing or plotting the dataset, and in some other applications.
unitname(x) extracts this name, and unitname(x) <- value sets the name to value.
A valid name is either
ˆ a single character string
ˆ a vector of two character strings giving the singular and plural forms of the unit name
ˆ a list of length 3, containing two character strings giving the singular and plural forms
of the basic unit, and a number specifying the multiple of this unit.

Value
The return value of unitname is an object of class "units" containing the name of the unit
of length in x. There are methods for print and summary.
unmark 629

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
owin, ppp

Examples
X <- runifpoint(20)

# if the unit of length is 1 metre:


unitname(X) <- c("metre", "metres")

# if the unit of length is 6 inches:


unitname(X) <- list("inch", "inches", 6)

unmark Remove Marks

Description
Remove the mark information from a spatial dataset.

Usage
unmark(X)
## S3 method for class 'ppp':
unmark(X)
## S3 method for class 'splitppp':
unmark(X)
## S3 method for class 'psp':
unmark(X)

Arguments
X A point pattern (object of class "ppp"), a split point pattern (object of
class "splitppp"), or a line segment pattern (object of class "psp").

Details
A ‘mark’ is a value attached to each point in a spatial point pattern, or attached to each
line segment in a line segment pattern, etc.
The function unmark is a simple way to remove the marks from such a dataset.

Value
An object of the same class as X with any mark information deleted.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
630 [Link]

See Also
[Link], [Link]

Examples
data(lansing)
hicks <- lansing[lansing$marks == "hickory", ]
## Not run:
plot(hicks) # still a marked point pattern, but only 1 value of marks
plot(unmark(hicks)) # unmarked

## End(Not run)

[Link] Update a Fitted Cluster Point Process Model

Description
update method for class "kppm".

Usage
## S3 method for class 'kppm':
update(object, trend = ~1, ..., clusters = NULL)

Arguments
object Fitted cluster point process model. An object of class "kppm", obtained
from kppm.
trend A formula without a left hand side, determining the form of the intensity
of the model.
... Other arguments passed to kppm.
clusters The type of cluster mechanism. A character string. See kppm.

Details
object should be a fitted cluster point process model, obtained from the model-fitting
function kppm. The model will be updated according to the new arguments provided.
The argument trend determines the formula for the intensity in the model. It should be
an R formula without a left hand side. It may include the symbols . and + or - to specify
addition or deletion of terms in the current model formula, as shown in the Examples below.
The model is refitted using kppm.

Value
Another fitted cluster point process model (object of class "kppm".

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>
[Link] 631

See Also
kppm

Examples
data(redwood)
fit <- kppm(redwood, ~1, "Thomas")
fitx <- update(fit, ~ . + x)
fitM <- update(fit, clusters="MatClust")

[Link] Update a Fitted Point Process Model

Description
update method for class "ppm".

Usage
## S3 method for class 'ppm':
update(object, ..., fixdummy=TRUE, [Link]=NULL,
envir=[Link]())

Arguments
object An existing fitted point process model, typically produced by ppm.
... Arguments to be updated in the new call to ppm.
fixdummy Logical flag indicating whether the quadrature scheme for the call to ppm
should use the same set of dummy points as that in the original call.
[Link] Optional. Logical flag indicating whether the model should be refitted
using the internally saved data ([Link]=TRUE) or by re-evaluating
these data in the current frame ([Link]=FALSE).
envir Environment in which to re-evaluate the call to ppm.

Details
This is a method for the generic function update for the class "ppm". An object of class
"ppm" describes a fitted point process model. See [Link]) for details of this class.
[Link] will modify the point process model specified by object according to the new
arguments given, then re-fit it. The actual re-fitting is performed by the model-fitting
function ppm.
If you are comparing several model fits to the same data, or fits of the same model to
different data, it is strongly advisable to use [Link] rather than trying to fit them by
hand. This is because [Link] re-fits the model in a way which is comparable to the
original fit.
The arguments ... are matched to the formal arguments of ppm as follows.
First, all the named arguments in ... are matched with the formal arguments of ppm. Use
name=NULL to remove the argument name from the call.
Second, any unnamed arguments in ... are matched with formal arguments of ppm if the
matching is obvious from the class of the object. Thus ... may contain
632 [Link]

ˆ exactly one argument of class "ppp" or "quad", which will be interpreted as the named
argument Q;
ˆ exactly one argument of class "formula", which will be interpreted as the named
argument trend (or as specifying a change to the trend formula);
ˆ exactly one argument of class "interact", which will be interpreted as the named
argument interaction;
ˆ exactly one argument of class "[Link]", which will be interpreted as the named
argument covariates.
The trend argument can be a formula that specifies a change to the current trend formula.
For example, the formula ~ . + Z specifies that the additional covariate Z will be added
to the right hand side of the trend formula in the existing object.
The argument fixdummy=TRUE ensures comparability of the objects before and after updat-
ing. When fixdummy=FALSE, calling [Link] is exactly the same as calling ppm with
the updated arguments. However, the original and updated models are not strictly com-
parable (for example, their pseudolikelihoods are not strictly comparable) unless they used
the same set of dummy points for the quadrature scheme. Setting fixdummy=TRUE ensures
that the re-fitting will be performed using the same set of dummy points. This is highly
recommended.
The value of [Link] determines where to find data to re-evaluate the model (data for
the arguments mentioned in the original call to ppm that are not overwritten by arguments
to [Link]).
If [Link]=FALSE, then arguments to ppm are re-evaluated in the frame where you
call [Link]. This is like the behaviour of the other methods for update. This means
that if you have changed any of the objects referred to in the call, these changes will be
taken into account. Also if the original call to ppm included any calls to random number
generators, these calls will be recomputed, so that you will get a different outcome of the
random numbers.
If [Link]=TRUE, then arguments to ppm are extracted from internal data stored
inside the current fitted model object. This is useful if you don’t want to re-evaluate
anything. It is also necessary if if object has been restored from a dump file using load or
source. In such cases, we have lost the environment in which object was fitted, and data
cannot be re-evaluated.
By default, if [Link] is missing, [Link] will re-evaluate the arguments if this
is possible, and use internal data if not.

Value
Another fitted point process model (object of class "ppm").

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
data(nztrees)
data(cells)

# fit the stationary Poisson process


fit <- ppm(nztrees, ~ 1)
urkiola 633

# fit a nonstationary Poisson process


fitP <- update(fit, trend=~x)
fitP <- update(fit, ~x)

# change the trend formula: add another term to the trend


fitPxy <- update(fitP, ~ . + y)
# change the trend formula: remove the x variable
fitPy <- update(fitPxy, ~ . - x)

# fit a stationary Strauss process


fitS <- update(fit, interaction=Strauss(13))
fitS <- update(fit, Strauss(13))

# refit using a different edge correction


fitS <- update(fitS, correction="isotropic")

# re-fit the model to a subset


# of the original point pattern
nzw <- owin(c(0,148),c(0,95))
nzsub <- nztrees[,nzw]
fut <- update(fitS, Q=nzsub)
fut <- update(fitS, nzsub)

# WARNING: the point pattern argument is called 'Q'

ranfit <- ppm(rpoispp(42), ~1, Poisson())


ranfit
# different random data!
update(ranfit)
# the original data
update(ranfit, [Link]=TRUE)

urkiola Urkiola Woods Point Pattern

Description
Locations of birch (Betula celtiberica) and oak (Quercus robur ) trees in a secondary wood in
Urkiola Natural Park (Basque country, northern Spain). They are part of a more extensive
dataset collected and analysed by Laskurain (2008). The coordinates of the trees are given
in meters.

Usage
data(urkiola)

Format
An object of class "ppp" representing the point pattern of tree locations. Entries include

x Cartesian x-coordinate of tree


y Cartesian y-coordinate of tree
634 [Link]

marks factor indicating species of each tree

The levels of marks are birch and oak. See [Link] for details of the format of a ppp
object.

Source
N.A. Laskurain. Kindly formatted and communicated by M. de la Cruz Rot

References
Laskurain, N. A. (2008) Dinámica espacio-temporal de un bosque secundario en el Parque
Natural de Urkiola (Bizkaia). Tesis Doctoral. Universidad del Paı́s Vasco /Euskal Herriko
Unibertsitatea.

[Link] Variance-Covariance Matrix for a Fitted Point Process Model

Description
Returns the variance-covariance matrix of the estimates of the parameters of a fitted point
process model.

Usage
## S3 method for class 'ppm':
vcov(object, ..., what = "vcov", verbose = TRUE, gamaction="warn")

Arguments
object A fitted point process model (an object of class "ppm".)
... Ignored.
what Character string (partially-matched) that specifies what matrix is re-
turned. Options are "vcov" for the variance-covariance matrix, "corr"
for the correlation matrix, and "fisher" or "Fisher" for the Fisher in-
formation matrix.
verbose Logical. If TRUE, a message will be printed if various minor problems are
encountered.
gamaction String indicating what to do if object was fitted by gam. Options are
"fatal", "warn" and "silent".

Details
This function computes the asymptotic variance-covariance matrix of the estimates of the
canonical parameters in the point process model object. It is a method for the generic
function vcov.
object should be an object of class "ppm", typically produced by ppm.
The canonical parameters of the fitted model object are the quantities returned by [Link](object).
The function vcov calculates the variance-covariance matrix for these parameters.
The argument what provides three options:
[Link] 635

what="vcov" return the variance-covariance matrix of the parameter estimates


what="corr" return the correlation matrix of the parameter estimates
what="fisher" return the observed Fisher information matrix.

In all three cases, the result is a square matrix. The rows and columns of the matrix
correspond to the canonical parameters given by [Link](object). The row and column
names of the matrix are also identical to the names in [Link](object).
For models fitted by maximum pseudolikelihood (which is the default in ppm), the current
implementation only works for Poisson point processes. The calculations are based on
standard asymptotic theory for the maximum likelihood estimator. The observed Fisher
information matrix of the fitted model object is first computed, by summing over the
Berman-Turner quadrature points in the fitted model. The asymptotic variance-covariance
matrix is calculated as the inverse of the observed Fisher information. The correlation
matrix is then obtained by normalising.
For models fitted by the Huang-Ogata method (method="ho" in the call to ppm), the imple-
mentation works for all models. A Monte Carlo estimate of the Fisher information matrix
is calculated using the results of the original fit.
The argument verbose makes it possible to suppress some diagnostic messages.
The asymptotic theory is not correct if the model was fitted using gam (by calling ppm
with [Link]=TRUE). The argument gamaction determines what to do in this case. If
gamaction="fatal", an error is generated. If gamaction="warn", a warning is issued
and the calculation proceeds using the incorrect theory for the parametric case, which is
probably a reasonable approximation in many applications. If gamaction="silent", the
calculation proceeds without a warning.

Value
A square matrix.

Error messages
An error message that reports system is computationally singular indicates that the de-
terminant of the Fisher information matrix was either too large or too small for reliable
numerical calculation. This can occur either because of numerical overflow or because of
collinearity in the covariates. Most commonly it occurs because of numerical overflow: to
check this, rescale the coordinates of the data points and refit the model. See the Examples.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

Examples
X <- rpoispp(42)
fit <- ppm(X, ~ x + y)
vcov(fit)
vcov(fit, what="Fish")

# example of singular system


data(demopat)
m <- ppm(demopat, ~polynom(x,y,2))
## Not run:
636 vertices

try(v <- vcov(m))

## End(Not run)
# rescale x, y coordinates to range [0,1] x [0,1] approximately
demopat <- rescale(demopat, 10000)
m <- ppm(demopat, ~polynom(x,y,2))
v <- vcov(m)

vertices Vertices of a Window

Description
Finds the vertices of a window

Usage
vertices(w)

Arguments
w A window.

Details
This function computes the vertices (‘corners’) of a spatial window.
The argument w should be a window (an object of class "owin", see [Link] for
details).
If w is a rectangle, the coordinates of the four corner points are returned.
If w is a polygonal window (consisting of one or more polygons), the coordinates of the
vertices of all polygons are returned.
If w is a binary mask, then a ‘boundary pixel’ is defined to be a pixel inside the window
which has at least one neighbour outside the window. The coordinates of the centres of all
boundary pixels are returned.

Value
A list with components x and y giving the coordinates of the vertices.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
[Link].
[Link] 637

Examples
data(letterR)
vert <- vertices(letterR)

plot(letterR, main="Polygonal vertices")


points(vert)
plot(letterR, main="Boundary pixels")
points(vertices([Link](letterR)))

[Link] Evaluate an Expression in a Function Table

Description
Evaluate an R expression in a function value table (object of class "fv").

Usage
## S3 method for class 'fv':
with(data, expr, ..., drop = TRUE)

Arguments
data A function value table (object of class "fv") in which the expression will
be evaluated.
expr The expression to be evaluated. An R language expression, which may
involve the names of columns in data, the special abbreviations ., .x and
.y, and global constants or functions.
... Ignored.
drop Logical value. If the result of evaluating the expression expr is a vector
(rather than a matrix or data frame) then the result will be returned as
a vector if drop=TRUE. Otherwise it will be returned as another function
value table (object of class "fv").

Details
This is a method for the generic command with for an object of class "fv" (function value
table).
An object of class "fv" is a convenient way of storing and plotting several different estimates
of the same function. It is effectively a data frame with extra attributes. See [Link]
for further explanation.
This command makes it possible to perform computations that involve different estimates
of the same function. For example we use it to compute the arithmetic difference between
two different edge-corrected estimates of the K function of a point pattern.
The argument expr should be an R language expression. The expression may involve
ˆ the name of any column in data, referring to one of the estimates of the function;
ˆ the symbol . which stands for all the available estimates of the function;
ˆ the symbol .y which stands for the recommended estimate of the function (in an "fv"
object, one of the estimates is always identified as the recommended estimate);
638 [Link]

ˆ the symbol .x which stands for the argument of the function;


ˆ global constants or functions.
See the Examples.
The expression should be capable of handling vectors and matrices. If the result of evalu-
ating the expression is a matrix or data frame, then it is returned as a new function value
table (object of class "fv"). If the result of evaluation is a vector and drop=TRUE then the
result is returned as a vector.
To perform calculations involving several objects of class "fv", use [Link].

Value
Either a function value table (object of class "fv") or a vector.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
with, [Link], [Link], Kest

Examples
# compute 4 estimates of the K function
X <- rpoispp(42)
K <- Kest(X)
plot(K)

# derive 4 estimates of the L function L(r) = sqrt(K(r)/pi)


L <- with(K, sqrt(./pi))
plot(L)

# compute 4 estimates of V(r) = L(r)/r


V <- with(L, ./.x)
plot(V)

# compute the maximum absolute difference between


# the isotropic and translation correction estimates of K(r)
D <- with(K, max(abs(iso - trans)))

[Link] Evaluate an Expression in Each Row of a Hyperframe

Description
An expression, involving the names of columns in a hyperframe, is evaluated separately for
each row of the hyperframe.

Usage
## S3 method for class 'hyperframe':
with(data, expr, ..., simplify = TRUE, ee = NULL)
[Link] 639

Arguments
data A hyperframe (object of class "hyperframe") containing data.
expr An R language expression to be evaluated.
... Ignored.
simplify Logical. If TRUE, the return value will be simplified to a vector whenever
possible.
ee Alternative form of expr, as an object of class "expression".

Details
This function evaluates the expression expr in each row of the hyperframe data. It is a
method for the generic function with.
The argument expr should be an R language expression in which each variable name is
either the name of a column in the hyperframe data, or the name of an object in the global
environment. The argument ee can be used as an alternative to expr and should be an
expression object (of class "expression").
For each row of data, the expression will be evaluated so that variables which are column
names of data are interpreted as the entries for those columns in the current row.
For example, if a hyperframe h has columns called A and B, then with(h, A != B) inspects
each row of data in turn, tests whether the entries in columns A and B are equal, and
returns the n logical values.

Value
Normally a list of length n (where n is the number of rows) containing the results of
evaluating the expression for each row. If simplify=TRUE and each result is a single atomic
value, then the result is a vector or factor containing the same values.

Author(s)
Adrian Baddeley <adrian@[Link]> [Link]
and Rolf Turner <[Link]@[Link]>

See Also
hyperframe, [Link]

Examples
# generate Poisson point patterns with intensities 10 to 100
H <- hyperframe(L=seq(10,100, by=10))
X <- with(H, rpoispp(L))
Index

∗Topic IO [Link], 508


scanpp, 568 rmhcontrol, 511
∗Topic attribute rmhmodel, 515
[Link], 177 [Link], 516
[Link], 188 [Link], 521
[Link], 221 [Link], 524
[Link], 363 rmhstart, 525
[Link], 426 rMosaicField, 527
[Link], 430 rMosaicSet, 528
[Link], 436 rmpoint, 529
[Link], 453 rmpoispp, 533
[Link], 459 rNeymanScott, 535
∗Topic color rpoint, 541
colourmap, 90 rpoisline, 542
[Link], 391 rpoislinetess, 543
∗Topic datagen rpoispp, 544
box3, 73 rpoispp3, 546
[Link], 112 rpoisppOnLines, 547
disc, 132 rshift, 548
gridcentres, 205 [Link], 549
gridweights, 206 [Link], 551
im, 220 [Link], 553
infline, 223 rSSI, 554
owin, 360 rstrat, 555
pixelquad, 388 rStrauss, 556
pp3, 419 rsyst, 558
ppp, 428 rthin, 559
pppmatching, 435 rThomas, 561
ppx, 437 runifdisc, 562
psp, 452 runifpoint, 563
quadratresample, 467 runifpoint3, 564
quadrats, 468 runifpointOnLines, 565
quadscheme, 469 spokes, 592
rcell, 473 square, 595
rGaussPoisson, 490 tess, 613
rjitter, 493 ∗Topic datasets
rlabel, 494 amacrine, 24
rlinegrid, 495 anemones, 25
rMatClust, 496 ants, 28
rMaternI, 497 bei, 64
rMaternII, 498 betacells, 67
rmh, 499 bramblecanes, 74
[Link], 500 bronzefilter, 75

640
INDEX 641

cells, 78 bermantest, 65
chorley, 81 envelope, 149
copper, 101 [Link], 285
demopat, 116 [Link], 462
finpines, 182 [Link], 464
ganglia, 190 ∗Topic iplot
hamster, 208 clickpoly, 84
heather, 210 clickppp, 85
humberside, 214 [Link], 217
japanesepines, 244 ∗Topic iteration
lansing, 287 applynbd, 31
letterR, 297 envelope, 149
longleaf, 305 ∗Topic manip
murchison, 341 [Link], 30
nbfires, 342 as.box3, 40
nztrees, 355 [Link], 41
ponderosa, 418 [Link], 42
redwood, 477 [Link], 43
redwoodfull, 478 [Link], 44
residualspaper, 489 [Link], 45
shapley, 573 [Link], 47
simdat, 579 [Link], 50
spruces, 594 [Link], 52
swedishpines, 612 [Link], 53
urkiola, 625 [Link], 55
∗Topic hplot [Link], 57
[Link], 97 [Link], 58
[Link], 120 [Link], 76
envelope, 149 [Link], 77
iplot, 231 [Link], 91
istat, 243 [Link], 92
lurking, 306 [Link], 92
[Link], 383 concatxy, 94
[Link], 389 coords, 100
[Link], 391 [Link], 107
[Link], 392 [Link], 111
[Link], 394 delaunay, 113
[Link], 396 dirichlet, 130
[Link], 397 discretise, 134
[Link], 400 [Link], 148
[Link], 401 [Link], 158
[Link], 402 [Link], 159
[Link], 404 [Link], 160
plot.pp3, 405 [Link], 162
[Link], 406 [Link], 163
[Link], 408 [Link], 164
[Link], 411 [Link], 165
[Link], 412 [Link], 168
[Link], 413 [Link], 169
[Link], 415 [Link], 171
[Link], 454 [Link], 173
∗Topic htest [Link], 174
642 INDEX

[Link], 175 [Link], 34


hyperframe, 215 areaGain, 35
im, 220 areaLoss, 39
[Link], 227 [Link], 61
[Link], 232 [Link], 62
[Link], 232 [Link], 63
[Link], 233 border, 70
[Link], 234 [Link], 79
[Link], 235 [Link], 80
[Link], 236 [Link], 86
[Link], 237 closing, 87
[Link], 238 [Link], 93
[Link], 239 connected, 95
[Link], 240 crossdist, 103
[Link], 241 [Link], 104
[Link], 242 [Link], 105
levelset, 298 [Link], 106
lut, 309 deltametric, 114
[Link], 345 diameter, 125
pixellate, 384 diameter.box3, 126
[Link], 385 [Link], 128
[Link], 386 dilation, 129
pointsOnLines, 416 discpartarea, 133
[Link], 460 distfun, 135
raster.x, 472 distmap, 136
[Link], 480 [Link], 137
[Link], 486 [Link], 139
[Link], 570 [Link], 140
setmarks, 572 [Link], 155
shift, 574 erosion, 156
[Link], 575 incircle, 222
[Link], 576 [Link], 225
[Link], 577 [Link], 228
[Link], 578 [Link], 229
solutionset, 586 [Link], 242
[Link], 589 [Link], 294
[Link], 590 matchingdist, 323
superimpose, 610 [Link], 331
superimposePSP, 611 nearestsegment, 346
tiles, 616 nncross, 349
[Link], 617 nndist, 351
[Link], 618 [Link], 352
unitname, 620 nnwhich, 354
unmark, 621 opening, 356
[Link], 629 pairdist, 364
[Link], 630 [Link], 365
∗Topic math [Link], 366
affine, 17 [Link], 367
[Link], 17 perimeter, 382
[Link], 18 pppdist, 432
[Link], 19 project2segment, 451
[Link], 26 quadratcount, 465
INDEX 643

rescale, 481 [Link], 111


[Link], 482 [Link], 120
[Link], 483 DiggleGratton, 127
[Link], 484 [Link], 141
[Link], 485 eem, 143
rotate, 537 effectfun, 144
[Link], 538 [Link], 183
[Link], 539 [Link], 184
[Link], 540 Geyer, 200
setcov, 571 harmonic, 208
[Link], 580 [Link], 225
stieltjes, 596 [Link], 235
vertices, 628 [Link], 238
∗Topic methods [Link], 241
[Link], 15 kppm, 283
[Link], 27 LennardJones, 295
[Link], 49 [Link], 299
[Link], 76 [Link], 304
[Link], 77 lurking, 306
[Link], 88 [Link], 325
[Link], 108 mincontrast, 331
[Link], 109 [Link], 335
[Link], 116 [Link], 336
[Link], 118 MultiStrauss, 338
[Link], 119 MultiStraussHard, 339
[Link], 142 Ord, 357
[Link], 184 [Link], 358
[Link], 213 OrdThresh, 359
[Link], 327 PairPiece, 369
methods.box3, 328 [Link], 370
methods.pp3, 329 Pairwise, 371
[Link], 471 [Link], 373
[Link], 487 [Link], 399
[Link], 583 [Link], 404
[Link], 589 [Link], 406
[Link], 590 Poisson, 417
[Link], 602 ppm, 420
[Link], 603 [Link], 439
[Link], 604 [Link], 440
[Link], 605 [Link], 445
[Link], 606 profilepl, 448
[Link], 607 [Link], 454
[Link], 608 [Link], 460
[Link], 609 reach, 474
[Link], 619 [Link], 487
[Link], 623 residualspaper, 489
[Link], 626 [Link], 508
∗Topic models SatPiece, 566
[Link], 27 Saturated, 568
AreaInter, 37 [Link], 581
BadGey, 60 [Link], 582
[Link], 88 Softcore, 584
644 INDEX

Strauss, 597 miplot, 333


StraussHard, 598 nncorr, 347
suffstat, 600 pcf, 374
[Link], 605 [Link], 375
[Link], 614 [Link], 377
[Link], 622 [Link], 379
[Link], 623 pcfcross, 381
[Link], 626 [Link], 476
∗Topic nonparametric ∗Topic package
allstats, 20 spatstat-package, 2
alltypes, 22 ∗Topic print
blur, 69 [Link], 443
clarkevans, 82 [Link], 444
Emark, 145 [Link], 445
ewcdf, 161 [Link], 446
F3est, 176 [Link], 447
Fest, 179 [Link], 447
fryplot, 186 progressreport, 450
G3est, 189 ∗Topic programming
Gcross, 191 applynbd, 31
Gdot, 194 [Link], 158
Gest, 197 [Link], 159
Gmulti, 202 [Link], 160
Hest, 211 levelset, 298
Iest, 218 markstat, 319
Jcross, 245 marktable, 320
Jdot, 247 solutionset, 586
Jest, 250 [Link], 629
Jmulti, 253 [Link], 630
K3est, 255 ∗Topic smooth
[Link], 256 [Link], 15
Kcross, 258 [Link], 116
[Link], 260 [Link], 118
Kdot, 263 [Link], 119
[Link], 266 [Link], 583
Kest, 269 ∗Topic spatial
[Link], 273 [Link], 15
Kinhom, 274 affine, 17
[Link], 278 [Link], 17
Kmeasure, 279 [Link], 18
Kmulti, 281 [Link], 19
Lcross, 288 allstats, 20
[Link], 290 alltypes, 22
Ldot, 291 amacrine, 24
[Link], 293 anemones, 25
Lest, 296 [Link], 26
Linhom, 301 [Link], 27
localK, 302 ants, 28
markconnect, 310 [Link], 30
markcorr, 313 applynbd, 31
markcorrint, 316 [Link], 34
markvario, 321 areaGain, 35
INDEX 645

AreaInter, 37 coords, 100


areaLoss, 39 copper, 101
as.box3, 40 corners, 102
[Link], 41 crossdist, 103
[Link], 42 [Link], 104
[Link], 43 [Link], 105
[Link], 44 [Link], 106
[Link], 45 [Link], 107
[Link], 47 [Link], 108
[Link], 49 [Link], 109
[Link], 50 [Link], 111
[Link], 52 [Link], 112
[Link], 53 delaunay, 113
[Link], 55 deltametric, 114
[Link], 57 demopat, 116
[Link], 58 [Link], 116
BadGey, 60 [Link], 118
[Link], 61 [Link], 119
[Link], 62 [Link], 120
[Link], 63 diameter, 125
bei, 64 diameter.box3, 126
bermantest, 65 DiggleGratton, 127
betacells, 67 [Link], 128
blur, 69 dilation, 129
border, 70 dirichlet, 130
[Link], 71 [Link], 131
[Link], 72 disc, 132
box3, 73 discpartarea, 133
bramblecanes, 74 discretise, 134
bronzefilter, 75 distfun, 135
[Link], 76 distmap, 136
[Link], 77 [Link], 137
cells, 78 [Link], 139
[Link], 79 [Link], 140
[Link], 80 [Link], 141
chorley, 81 [Link], 142
clarkevans, 82 eem, 143
clickpoly, 84 effectfun, 144
clickppp, 85 Emark, 145
[Link], 86 [Link], 148
closing, 87 envelope, 149
[Link], 88 [Link], 155
colourmap, 90 erosion, 156
[Link], 91 [Link], 158
[Link], 92 [Link], 159
[Link], 92 [Link], 160
[Link], 93 [Link], 162
concatxy, 94 [Link], 163
connected, 95 [Link], 164
[Link], 97 [Link], 165
convexhull, 98 [Link], 168
[Link], 99 [Link], 169
646 INDEX

[Link], 171 [Link], 242


[Link], 173 [Link], 242
[Link], 174 istat, 243
[Link], 175 japanesepines, 244
F3est, 176 Jcross, 245
[Link], 177 Jdot, 247
Fest, 179 Jest, 250
finpines, 182 Jmulti, 253
[Link], 183 K3est, 255
[Link], 184 [Link], 256
fryplot, 186 Kcross, 258
[Link], 188 [Link], 260
G3est, 189 Kdot, 263
ganglia, 190 [Link], 266
Gcross, 191 Kest, 269
Gdot, 194 [Link], 273
Gest, 197 Kinhom, 274
Geyer, 200 [Link], 278
Gmulti, 202 Kmeasure, 279
gpc2owin, 204 Kmulti, 281
gridcentres, 205 kppm, 283
gridweights, 206 [Link], 285
hamster, 208 lansing, 287
harmonic, 208 Lcross, 288
heather, 210 [Link], 290
Hest, 211 Ldot, 291
[Link], 213 [Link], 293
humberside, 214 [Link], 294
hyperframe, 215 LennardJones, 295
[Link], 217 Lest, 296
Iest, 218 letterR, 297
im, 220 levelset, 298
[Link], 221 [Link], 299
incircle, 222 Linhom, 301
infline, 223 localK, 302
[Link], 225 [Link], 304
[Link], 225 longleaf, 305
[Link], 227 lurking, 306
[Link], 228 lut, 309
[Link], 229 markconnect, 310
iplot, 231 markcorr, 313
[Link], 232 markcorrint, 316
[Link], 232 markstat, 319
[Link], 233 marktable, 320
[Link], 234 markvario, 321
[Link], 235 matchingdist, 323
[Link], 236 [Link], 325
[Link], 237 [Link], 327
[Link], 238 methods.box3, 328
[Link], 239 methods.pp3, 329
[Link], 240 [Link], 330
[Link], 241 [Link], 331
INDEX 647

mincontrast, 331 [Link], 404


miplot, 333 plot.pp3, 405
[Link], 335 [Link], 406
[Link], 336 [Link], 408
[Link], 337 [Link], 411
MultiStrauss, 338 [Link], 412
MultiStraussHard, 339 [Link], 413
murchison, 341 [Link], 415
nbfires, 342 pointsOnLines, 416
[Link], 345 Poisson, 417
nearestsegment, 346 ponderosa, 418
nncorr, 347 pp3, 419
nncross, 349 ppm, 420
nndist, 351 [Link], 426
[Link], 352 ppp, 428
nnwhich, 354 [Link], 430
nztrees, 355 pppdist, 432
opening, 356 pppmatching, 435
Ord, 357 [Link], 436
[Link], 358 ppx, 437
OrdThresh, 359 [Link], 439
owin, 360 [Link], 440
[Link], 363 [Link], 443
pairdist, 364 [Link], 444
[Link], 365 [Link], 445
[Link], 366 [Link], 446
[Link], 367 [Link], 447
PairPiece, 369 [Link], 447
[Link], 370 profilepl, 448
Pairwise, 371 project2segment, 451
[Link], 373 psp, 452
pcf, 374 [Link], 453
[Link], 375 [Link], 454
[Link], 377 [Link], 459
[Link], 379 [Link], 460
pcfcross, 381 [Link], 462
perimeter, 382 [Link], 464
[Link], 383 quadratcount, 465
pixellate, 384 quadratresample, 467
[Link], 385 quadscheme, 469
[Link], 386 [Link], 471
pixelquad, 388 raster.x, 472
[Link], 389 rcell, 473
[Link], 391 reach, 474
[Link], 392 [Link], 476
[Link], 394 redwood, 477
[Link], 396 redwoodfull, 478
[Link], 397 [Link], 480
[Link], 399 rescale, 481
[Link], 400 [Link], 482
[Link], 401 [Link], 483
[Link], 402 [Link], 484
648 INDEX

[Link], 485 scanpp, 568


[Link], 486 [Link], 570
[Link], 487 setcov, 571
residualspaper, 489 setmarks, 572
rGaussPoisson, 490 shapley, 573
ripras, 491 shift, 574
rjitter, 493 [Link], 575
rlabel, 494 [Link], 576
rlinegrid, 495 [Link], 577
rMatClust, 496 [Link], 578
rMaternI, 497 simdat, 579
rMaternII, 498 [Link], 580
rmh, 499 [Link], 581
[Link], 500 [Link], 582
[Link], 508 [Link], 583
rmhcontrol, 511 Softcore, 584
rmhmodel, 515 solutionset, 586
[Link], 516 spatstat-package, 2
[Link], 521 [Link], 587
[Link], 524 [Link], 589
rmhstart, 525 [Link], 590
rMosaicField, 527 spokes, 592
rMosaicSet, 528 spruces, 594
rmpoint, 529 square, 595
rmpoispp, 533 stieltjes, 596
rNeymanScott, 535 Strauss, 597
rotate, 537 StraussHard, 598
[Link], 538 suffstat, 600
[Link], 539 [Link], 602
[Link], 540 [Link], 603
rpoint, 541 [Link], 604
rpoisline, 542 [Link], 605
rpoislinetess, 543 [Link], 606
rpoispp, 544 [Link], 607
rpoispp3, 546 [Link], 608
rpoisppOnLines, 547 [Link], 609
rshift, 548 superimpose, 610
[Link], 549 superimposePSP, 611
[Link], 551 swedishpines, 612
[Link], 553 tess, 613
rSSI, 554 [Link], 614
rstrat, 555 tiles, 616
rStrauss, 556 [Link], 617
rsyst, 558 [Link], 618
rthin, 559 [Link], 619
rThomas, 561 unitname, 620
runifdisc, 562 unmark, 621
runifpoint, 563 [Link], 622
runifpoint3, 564 [Link], 623
runifpointOnLines, 565 [Link], 626
SatPiece, 566 vertices, 628
Saturated, 568 [Link], 629
INDEX 649

[Link], 630 allstats, 9, 20


∗Topic univar alltypes, 9, 22, 91, 158, 178, 312,
ewcdf, 161 374–377, 379, 393
[Link], 327 amacrine, 4, 24, 234–238, 240, 431
[Link], 471 anemones, 4, 25
∗Topic utilities [Link], 7, 26, 295, 331, 454
[Link], 71 anova, 28
[Link], 72 [Link], 28
convexhull, 98 [Link], 11, 14, 27, 463, 464
[Link], 99 ants, 4, 28
corners, 102 [Link], 30
[Link], 131 apply, 32, 33, 319, 320
[Link], 141 applynbd, 10, 31, 319–321
gpc2owin, 204 [Link], 6, 34, 125, 363, 383
[Link], 337 areaGain, 35, 40
quadrats, 468 AreaInter, 12, 36, 37, 39, 40, 225, 373,
ripras, 491 421, 425, 510, 520, 525
.[Link], 502, 503 areaLoss, 36, 39
[, 169, 172, 173
as.box3, 8, 40, 73, 74, 126, 419
[.[Link], 165
[Link], 41, 42, 44
[.fasp, 178
[Link], 41
[.fasp ([Link]), 163
[Link]
[.fv ([Link]), 164
([Link]), 44
[.im, 6, 109, 221, 222, 480
[Link], 7, 42
[.im ([Link]), 165
[Link], 8, 43, 44, 45, 216
[.ppp, 4, 110, 173, 431
[.ppp ([Link]), 169 [Link], 43, 44
[.psp, 7, 454 [Link], 6, 15, 45, 161, 220–222, 385–388
[.psp ([Link]), 171 [Link], 6
[.quad ([Link]), 173 [Link], 5, 46, 47
[.splitppp ([Link]), 174 [Link] ([Link]), 386
[.tess, 7, 614 [Link], 6, 46, 47, 52, 61, 62, 87,
[.tess ([Link]), 175 114–117, 119, 129, 132, 134, 135,
[<-.im, 6 137–140, 156, 157, 207, 211, 228,
[<-.im ([Link]), 480 230, 243, 346, 356, 363, 385, 387,
[<-.listof ([Link]), 168 388, 407, 457, 473, 527, 571, 588
[<-.ppp ([Link]), 169 [Link], 6, 49, 221, 222
[<-.quad ([Link]), 173 [Link], 5, 34, 35, 48, 50, 52, 54, 56–58,
[<-.splitppp ([Link]), 174 70–73, 79, 88, 98, 99, 102, 125,
[<-.tess, 7 129, 130, 156, 157, 163, 205, 225,
[<-.tess ([Link]), 175 226, 228, 243, 271, 298, 357,
[<-, 169 361–363, 383, 388, 402, 428, 429,
[<-.im, 166, 167 452, 453, 468, 473, 487, 491, 492,
%mark% (setmarks), 572 495, 496, 498, 499, 501, 519, 524,
533, 536, 543, 544, 554, 555, 558,
abline, 224 561, 563, 571, 588, 610, 611
[Link], 15, 117, 118 [Link], 6, 48, 52, 383
affine, 5, 17, 18–20, 163, 363, 482, [Link], 3, 32, 53, 112, 133, 135, 146, 166,
484–486, 562, 574, 577–579 167, 179, 186, 192, 195, 198, 203,
[Link], 17, 17, 19, 20, 363 218, 219, 246, 248, 250, 251, 254,
[Link], 17, 18, 18, 20 258, 261, 264, 267, 269, 270, 273,
[Link], 7, 19 274, 280, 282, 311, 313, 314, 317,
AIC, 11 321, 334, 409, 429, 431, 469–471,
650 INDEX

480, 501, 526, 569, 618 coords, 8, 100


[Link], 7, 31, 55, 411, 453, 454, 588 copper, 4, 101, 489
[Link], 48, 57, 71, 72, 363 cor, 347, 349
[Link], 7, 58, 230, 614 corners, 12, 102, 113, 470, 471
atan2, 27 crossdist, 9, 103, 104–107, 365–368
[Link], 103, 104, 104, 106
BadGey, 12, 60, 61, 421, 425, 525, 567 [Link], 103, 104, 105, 105
barplot, 213, 214 [Link], 103–105, 106, 106
[Link], 6, 61, 63, 64, 363 [Link], 7, 107, 570
[Link], 6, 62, 62, 64, 363 cut, 109, 110
[Link], 6, 62, 63, 63, 614 [Link], 108, 110
bei, 4, 64 [Link], 6, 108, 220, 222, 472
bermantest, 14, 65, 287, 389, 390 [Link], 5, 10, 78, 109, 170, 592, 613, 614
betacells, 4, 67, 191, 431
blur, 7, 69, 276
data, 4, 431
border, 5, 70
[Link], 215
[Link], 5, 57, 58, 71, 228, 363
[Link], 111, 143, 144, 427
[Link], 71, 72, 72, 99, 492
[Link], 12, 112, 422, 470, 588
box3, 8, 40, 41, 73, 329, 419, 546, 565
delaunay, 5, 8, 113, 130
bramblecanes, 4, 74, 431
deltametric, 114
bronzefilter, 4, 75
demopat, 4, 116, 431
by, 76, 77
density, 119, 146, 147, 311–313, 315, 322,
[Link], 76, 590
380, 381
[Link], 5, 77, 613, 614
[Link], 5, 6, 9, 16, 70, 116, 120,
[Link], 216 122, 262, 268, 275, 276, 388, 583,
cells, 4, 78, 431 584
[Link], 6, 79, 223, 577 [Link], 7, 118
[Link], 463, 464 [Link], 119, 402
[Link], 8, 80, 87 [Link], 14, 120, 143, 144,
chorley, 4, 81 306–309, 455, 456, 458, 488, 489
chull, 232 diameter, 6, 35, 125, 363, 383
clarkevans, 8, 82 diameter.box3, 8, 73, 74, 126
clickpoly, 84, 86 DiggleGratton, 11, 127, 421, 425, 449,
clickppp, 3, 85, 85, 217 475, 476, 504, 509, 510, 516, 520,
[Link], 81, 86 522, 525
[Link], 454 [Link], 6, 128
closing, 5, 87, 357, 363 dilation, 5, 70, 71, 88, 128, 129, 129,
coef, 89, 427 157, 357, 363
[Link], 11, 88, 427, 627 dirichlet, 5, 8, 16, 114, 130
colourmap, 90, 310, 391 [Link], 12, 131, 207, 471
colours, 91 disc, 5, 132, 134, 361, 362, 562, 563
[Link], 91 discpartarea, 133
[Link], 91, 92 discretise, 134
[Link], 7, 92, 161 distfun, 135, 137
[Link], 5, 93, 233, 362, 363 distmap, 9, 114, 115, 128, 136, 136,
concatxy, 94, 610 138–141, 212, 222, 223
connected, 6, 7, 95 [Link], 6, 137, 137, 139, 141
contour, 404, 407, 408 [Link], 137, 138, 139, 141
[Link], 46, 97 [Link], 7, 137–139, 140, 346, 454
[Link], 6, 97, 384, 398, 588 drop1, 11
convexhull, 5, 6, 98, 99 [Link], 141, 427
[Link], 73, 98, 99, 114, 232, 492 [Link], 5, 142, 338, 606, 619
INDEX 651

ecdf, 162 gam, 209


[Link], 588 [Link], 421
[Link], 588 ganglia, 68, 190, 191, 431
eem, 122, 124, 143, 309, 458, 488 Gcross, 9, 23, 24, 191, 195, 197, 202, 204,
effectfun, 11, 144 246
Emark, 10, 145 Gdot, 9, 23, 24, 192, 194, 194, 202, 204,
[Link] (Fest), 179 246, 249, 254
[Link], 7, 148 Gest, 9, 21, 23, 24, 83, 84, 105–107, 153,
envelope, 9, 12–14, 22–24, 149 182, 188, 192–196, 197, 197,
[Link], 6, 129, 155, 157, 363 202–204, 243, 250–253, 272, 352,
[Link], 8, 73, 74 596
[Link] (diameter.box3), 126 Geyer, 12, 60, 61, 200, 201, 359, 370, 371,
erosion, 5, 62, 63, 70, 71, 88, 130, 156, 373, 421, 425, 449, 475, 476, 509,
156, 233, 357, 363, 550, 551, 571 510, 525, 566–568
[Link], 9, 158, 178 glm, 2, 209, 420, 421
[Link], 9, 158, 159, 630 [Link], 421
[Link], 7, 160, 220–222, 483, 586, 587 Gmulti, 9, 10, 192, 194, 195, 197, 202,
ewcdf, 161, 286 246, 249
exactdt, 9 gpc2owin, 204
[Link], 162, 513, 514 gridcenters (gridcentres), 205
[Link], 163 gridcentres, 12, 113, 205, 470, 471, 593
[Link], 164 gridweights, 12, 131, 206, 471
[Link], 165
[Link], 168 hamster, 4, 208
[Link], 169 harmonic, 208
[Link], 171 heather, 210
[Link], 173 Hest, 211
[Link], 174 hist, 180, 193, 196, 198, 203, 213, 214,
[Link], 175 254, 282
[Link], 213, 214
F3est, 10, 176, 190, 256 [Link], 6, 213, 222
[Link], 20, 23, 24, 158, 164, 177, humberside, 4, 214
374, 376, 393 hyperframe, 8, 43–45, 215, 396, 397, 438,
Fest, 9, 21–24, 153, 179, 188, 200, 212, 631
243, 246, 249–254, 272
fft, 280 identify, 217
finpines, 4, 182 [Link], 217
fitin ([Link]), 183 [Link], 5, 85, 86, 217
[Link], 183 Iest, 9, 218
fitted, 427 im, 3, 6, 76, 78, 220, 222, 336, 388, 483,
[Link], 11, 184, 427, 442 590, 592
[Link], 11 [Link], 16, 46, 64, 96–98, 109,
fryplot, 8, 186, 281 118–120, 160, 161, 166, 167, 213,
frypoints (fryplot), 186 214, 220, 221, 221, 234, 280, 281,
[Link], 21, 145, 147, 152, 153, 160, 298, 327, 328, 336, 383, 384, 397,
165, 180, 188, 193, 196, 199, 203, 398, 422, 442, 444, 472, 480, 519,
212, 219, 246, 249, 251, 254, 259, 531, 534, 536, 541, 545, 584, 586,
262, 265, 268, 271, 273, 277, 282, 587, 602
289, 290, 292, 293, 297, 302, 303, image, 397, 404, 407, 408, 588
312, 315, 317, 322, 332, 374, 378, [Link], 46, 391, 398, 403
382, 395, 596, 629, 630 [Link] ([Link]), 397
incircle, 6, 222
G3est, 10, 177, 189, 256 infline, 80, 81, 87, 223
652 INDEX

[Link], 225, 371, 373 Kmeasure, 6, 9, 187, 188, 222, 273, 274,
[Link], 6, 206, 225, 593 279
[Link], 7, 70, 227 Kmulti, 9, 10, 258, 260, 264, 265, 271,
[Link], 6, 228, 230, 233 272, 281, 374, 375, 377–379
[Link], 8, 229, 614 kppm, 10, 13, 283, 326, 327, 333, 399, 439,
iplot, 4, 231, 244, 410 496, 497, 561, 562, 581, 615, 616,
[Link], 6, 98, 232 622, 623
[Link], 232 [Link], 285–287
[Link], 216 kstest, 14, 67, 400, 463, 464
[Link], 7, 233 kstest ([Link]), 285
[Link], 234, 235–237, 572 [Link], 285
[Link], 235, 235, 237
[Link], 235, 236, 572 lansing, 4, 287, 431
[Link], 237, 239, 240 Lcross, 9, 23, 24, 288, 290–292
[Link], 238, 238, 240 [Link], 9, 290, 294
[Link], 238, 239, 239 Ldot, 9, 23, 289, 291, 293, 294
[Link], 240 [Link], 9, 293
[Link], 241 legend, 394
[Link], 242 [Link], 7, 27, 294, 331, 454
[Link], 7 LennardJones, 12, 295, 421, 425, 449,
[Link], 6, 228, 242 475, 476, 524
istat, 8, 231, 243 Lest, 9, 23, 24, 243, 289, 292, 296, 302,
303
japanesepines, 4, 244 letterR, 5, 297
Jcross, 9, 23, 24, 245, 248, 249, 254, 255 levelset, 7, 298, 587
Jdot, 9, 23, 24, 245, 247, 247, 254, 255 [Link], 10, 299, 301, 327, 332, 333,
Jest, 9, 21, 23, 24, 153, 182, 188, 200, 616
218, 219, 243, 245–249, 250, lines, 307
253–255, 272 Linhom, 9, 290, 291, 293, 294, 301
Jmulti, 9, 10, 245, 247–249, 253 lm, 2, 209
load, 624
K3est, 10, 177, 190, 255 localK, 9, 272, 302
[Link], 182, 200, 253, 256, 279, localL, 9
477 localL (localK), 302
Kcross, 9, 23, 24, 147, 258, 261, 263, 264, locator, 84–86
271, 272, 282, 283, 289, 312, 316, loess, 146, 311, 313, 322
321, 322, 374–379, 382 [Link], 11, 304
[Link], 9, 260, 268, 290, 291 longleaf, 4, 234–238, 240, 305, 431
Kdot, 9, 23, 24, 147, 258, 260, 263, 265, lurking, 124, 306, 458
267, 268, 271, 272, 282, 283, 292, lut, 91, 309
312, 316, 322, 374–379
[Link], 9, 266, 293, 294 markconnect, 9, 147, 310, 316, 322, 382
Kest, 9, 21, 23, 24, 92, 146, 153, 158–160, markcorr, 10, 147, 312, 313, 317, 318, 322
182, 187, 188, 200, 243, 253, markcorrint, 10, 316, 316
258–260, 262, 264, 265, 268, 269, markmean, 10
273–275, 277, 281–283, 296, 297, markmean ([Link]), 583
299, 301–303, 311, 315, 325, 327, [Link], 7
332, 365–367, 374–382, 395, 474, marks<-.psp, 7
588, 615, 616, 630 markstat, 10, 33, 319, 321
[Link], 9, 273 marktable, 10, 33, 319, 320, 320
Kinhom, 9, 261, 263, 267, 268, 271, 272, markvar, 10
274, 284, 301, 302, 374–379 markvar ([Link]), 583
[Link], 182, 200, 253, 257, 278, 477 markvario, 10, 147, 312, 316, 321
INDEX 653

matchingdist, 323, 434, 435, 437 Ord, 12, 357, 359, 373, 421, 425, 475, 476
[Link], 10, 284, 301, 325, 332, [Link], 225, 358, 371, 373
333, 496, 497, 616 OrdThresh, 12, 358, 359, 359, 373, 421,
mean, 327, 328 425, 449, 475, 476, 524
[Link], 327, 328 [Link], 228
[Link], 6, 222, 327 owin, 3, 5, 34, 51, 52, 58, 72, 73, 79, 88,
median, 327, 328 93, 94, 98, 99, 102, 125, 129, 130,
[Link], 328 132, 134, 156, 157, 163, 172, 205,
[Link] ([Link]), 327 225, 232, 357, 360, 363, 402, 403,
methods.box3, 328 428–431, 452–454, 473, 492, 555,
methods.pp3, 329 558, 571, 580, 588, 595, 621
[Link], 330 [Link], 35, 46, 48, 50, 51, 54, 57,
[Link], 7, 27, 149, 295, 331, 454 62, 79, 93, 94, 125, 132, 156, 163,
mincontrast, 10, 284, 300, 301, 325–327, 167, 170, 172, 226, 228, 241, 297,
331, 615, 616 298, 345, 346, 361, 362, 363, 383,
miplot, 8, 333, 466 403, 428, 429, 453, 472, 480, 487,
[Link], 335, 337 531, 534, 538, 542, 545, 564, 571,
[Link], 336, 337 587, 595, 618, 628
[Link], 335, 336 owin2gpc (gpc2owin), 204
[Link], 335, 336, 336
[Link], 143, 337, 619 pairdist, 9, 104–107, 352, 364, 367, 368
MultiStrauss, 12, 338, 340, 421, 425, [Link], 364, 365, 365, 367
475, 476, 504, 509, 516, 520, 522, [Link], 364, 365, 366, 368
525 [Link], 364, 365, 367, 367
MultiStraussHard, 12, 339, 421, 425, PairPiece, 11, 60, 61, 359, 369, 373, 421,
475, 476, 504, 509, 516, 520, 522, 425, 475, 476, 509, 510, 516, 520,
525 522, 525, 566, 567
murchison, 4, 341 [Link], 61, 225, 359, 370, 373,
567, 568
nbextras (nbfires), 342 Pairwise, 12, 128, 359, 371, 373, 421,
nbfires, 4, 342 425, 475, 476
[Link] (nbfires), 342 [Link], 38, 202, 225, 296, 339,
[Link] (Gest), 197 340, 359, 370–372, 373, 586, 598,
[Link], 6, 345, 363 599
nearestsegment, 7, 141, 346, 451 par, 85, 86, 392, 396, 401, 410, 412–414
nncorr, 347 pcf, 9, 153, 243, 259, 260, 262, 263, 265,
nncross, 7, 9, 140, 141, 349, 352, 354, 268, 271, 272, 277, 282, 283, 297,
355 302, 374, 376, 378, 379, 381, 382
nndist, 9, 84, 104–107, 199, 200, 351, [Link], 374, 375, 375
353–355, 365–368 [Link], 374, 375, 377
[Link], 353 [Link], 374, 375, 379, 379, 381, 382
[Link], 351, 352, 352 pcfcross, 9, 23, 312, 381
nnmean, 10 perimeter, 6, 35, 125, 363, 382
nnmean (nncorr), 347 persp, 404, 407, 408, 588
nnvario, 10 [Link], 383, 384
nnvario (nncorr), 347 [Link], 6, 98, 222, 383, 398
nnwhich, 9, 199, 200, 352, 354 pixellate, 6, 384, 386–388
nztrees, 4, 355, 431 [Link], 6, 385, 385
[Link], 5, 385, 386, 386
opening, 5, 88, 233, 356, 363 pixelquad, 12, 388, 422
optim, 299, 300, 325, 326, 332, 333, 614, plot, 396, 399, 401, 402, 408, 410, 412,
615 415, 427, 449, 460
options, 587, 589 [Link], 66, 389
654 INDEX

[Link], 91, 391 296, 336, 337, 339, 340, 358, 360,
[Link], 122, 307, 400, 409 370, 372, 407, 408, 423, 425, 426,
[Link] ([Link]), 120 440–442, 445, 458, 461, 489, 508,
[Link], 389 509, 568, 586, 598–600, 605, 623
[Link], 21–24, 178, 392 ppp, 3, 53, 54, 78, 100, 114, 130, 135, 153,
[Link], 9, 21, 152, 153, 180, 199, 212, 362, 416, 425, 428, 431, 504, 547,
219, 251, 271, 289, 292, 297, 302, 566, 569, 572, 610, 621
303, 382, 392, 393, 394, 399 [Link], 25, 26, 29, 33, 53, 54, 63, 64,
[Link], 8, 216, 396, 631 67, 74, 75, 78, 81, 101, 108, 110,
[Link], 6, 98, 166, 167, 222, 384, 397, 112, 113, 116, 118, 120, 142, 143,
415, 588 149, 167, 170, 179, 183, 190, 198,
[Link] (infline), 223 208, 214, 219, 231, 244, 251, 270,
[Link], 10, 284, 399, 439 288, 305, 320, 321, 338, 341, 356,
[Link], 286, 287, 400 362, 409, 410, 414, 418, 422, 429,
[Link], 21, 168, 336, 401, 603 430, 478–480, 502, 509, 510, 531,
[Link], 399 534, 539, 542, 545, 564, 569, 570,
[Link], 5, 363, 402, 409–412, 415, 588 572, 573, 579, 583, 584, 592, 594,
[Link], 404, 407, 408 612, 619, 622, 626
plot.pp3, 8, 405 pppdist, 10, 324, 432, 435, 437
[Link], 11, 399, 404, 405, 406, 427, pppmatching, 435, 437
442, 445, 588 [Link], 324, 433–435, 436
[Link], 4, 217, 231, 403, 408, 413, 414, ppx, 44, 45, 100, 330, 419, 437
429, 431, 588 predict, 427, 439
[Link] ([Link]), 330 [Link], 424, 442
[Link], 7, 411, 454 [Link], 10, 284, 439
[Link], 457 [Link], 11, 145, 185, 186, 407, 408,
[Link], 412, 448, 460 421, 423, 424, 427, 439, 440, 445
[Link], 174, 413, 591, 592 [Link], 376–379
[Link], 7, 415, 614 print, 224, 328–330, 427, 444, 446, 447,
points, 409, 410 449
pointsOnLines, 7, 416, 566 print.box3 (methods.box3), 328
Poisson, 11, 359, 373, 417, 421, 425, 475, [Link], 222, 443
476, 509, 510 [Link] (infline), 223
poly, 424 [Link], 402
polygon, 403 [Link], 363, 444, 446, 447, 604
ponderosa, 4, 418 print.pp3 (methods.pp3), 329
pp3, 3, 8, 41, 73, 74, 100, 330, 406, 419, [Link], 11, 89, 408, 421, 427, 442, 445
438, 546, 565 [Link], 444, 446, 607
ppm, 2, 11, 13, 28, 37, 38, 60, 61, 67, 89, [Link] ([Link]), 330
112, 121, 122, 124, 128, 141–145, [Link], 7, 447, 607
153, 184–186, 201, 202, 209, 235, [Link], 457
238, 284, 287, 295, 296, 305, 306, [Link], 447
308, 309, 335–340, 358, 360, 369, [Link] ([Link]), 602
370, 372, 388, 389, 404, 406, 408, [Link] ([Link]), 605
417, 420, 426, 427, 440, 442, 445, [Link] ([Link]), 608
448, 449, 456, 458, 460, 461, 470, profilepl, 448
471, 475, 476, 488, 489, 504, progressreport, 450, 588
508–510, 515, 516, 520, 522, 524, project2segment, 7, 140, 141, 346, 451
525, 566–568, 583, 585, 586, psp, 3, 7, 31, 56, 57, 87, 416, 452, 454,
597–601, 623, 626, 627 496, 543, 547, 566, 588, 611
[Link], 38, 89, 112, 124, 128, 141, [Link], 56, 57, 101, 108, 119, 149,
142, 144, 184, 186, 202, 241, 242, 172, 341, 412, 453, 453, 540, 570,
INDEX 655

622 ripras, 5, 73, 99, 491, 569


rjitter, 3, 13, 14, 493
[Link], 13, 14, 122, 124, 309, 454 rlabel, 4, 494
quad, 12 rlinegrid, 7, 13, 495
[Link], 54, 103, 113, 131, 173, 206, rMatClust, 3, 11, 13, 326, 327, 431, 491,
207, 388, 389, 413, 422, 448, 459, 496, 498, 499, 536, 545, 562, 581
461, 470, 471, 593, 608, 618 rMaternI, 3, 13, 431, 497, 499, 545, 555
[Link], 185, 308, 336, 337, 427, 460, rMaternII, 3, 13, 431, 498, 545, 555
487 rmh, 4, 13, 152, 421, 423, 455, 456, 458,
[Link], 14, 59, 67, 287, 462, 464, 499, 501, 504, 509, 510, 512,
466, 469 514–517, 519, 520, 522, 524–527,
[Link], 464 557, 558
[Link], 462, 463, 464 [Link], 163, 455, 500, 500, 509,
quadratcount, 9, 59, 334, 463, 464, 465, 510, 545
468, 469 [Link], 11, 12, 370, 500, 504, 508, 582
quadratresample, 13, 14, 463, 464, 466, rmhcontrol, 456, 458, 502, 503, 508–510,
467, 469 511, 516, 520, 522, 524–527, 582
quadrats, 7, 463, 464, 466, 468, 468, 613, rmhmodel, 475, 476, 501, 510, 512, 514,
614 515, 515, 517, 522, 524, 525, 527
quadscheme, 12, 95, 103, 113, 206, 388, [Link], 515, 516, 516, 522,
389, 422, 425, 448, 460, 469, 556, 525
559, 593, 610 [Link], 515, 516, 521, 525
quantile, 472 [Link], 515, 516, 522, 524
[Link], 471
rmhstart, 502, 508–510, 512–514, 516,
[Link], 6, 222, 327, 328, 471 520, 522, 525, 525, 582
rMosaicField, 13, 527, 528
range, 327, 328
rMosaicSet, 13, 527, 528
[Link], 328
[Link] ([Link]), 327 rmpoint, 3, 13, 509, 529, 534, 545
raster.x, 6, 361, 363, 472 rmpoispp, 3, 13, 500, 509, 531, 533, 545
raster.y, 6, 361, 363 rNeymanScott, 3, 13, 431, 491, 497, 535,
raster.y (raster.x), 472 561, 562
rcell, 4, 13, 473, 545 rotate, 5, 17–20, 163, 363, 482, 484–486,
reach, 474 537, 574, 577–579
[Link], 431, 569 [Link], 363, 537, 538, 539, 540
[Link], 182, 200, 253, 257, 272, [Link], 537, 539, 540
279, 476 [Link], 7, 540
redwood, 4, 431, 477, 478, 479 rpoint, 3, 13, 509, 531, 541, 545, 562–564
redwoodfull, 4, 478, 478 rpoisline, 7, 13, 496, 542, 544
[Link], 480 rpoislinetess, 8, 13, 527, 528, 543
rescale, 481, 482–485 rpoispp, 3, 13, 431, 491, 497–500, 509,
[Link], 482 534, 536, 544, 547, 555, 562, 564
[Link], 481, 482, 483, 484, 485 rpoispp3, 8, 546, 565
[Link], 481, 482, 484 rpoisppOnLines, 4, 13, 547
[Link], 485 rshift, 4, 13, 14, 548, 551, 553, 554
[Link], 486 [Link], 548, 549, 549, 552–554
[Link] [Link], 548, 549, 551, 551
([Link]), 587 [Link], 548, 549, 553
[Link], 11, 122, 124, 144, 309, rSSI, 3, 13, 431, 545, 554
337, 456, 458, 487 rstrat, 3, 12, 13, 474, 545, 555, 559
residualspaper, 4, 14, 489 rStrauss, 3, 13, 504, 517, 545, 556
rGaussPoisson, 3, 13, 490, 497, 536, 545, rsyst, 3, 13, 474, 556, 558
562 rthin, 3, 13, 14, 559
656 INDEX

rThomas, 3, 11, 13, 431, 491, 497, 536, spruces, 4, 594


545, 561, 581, 615, 616 square, 5, 361, 362, 595
runifdisc, 3, 13, 562 step, 11
runifpoint, 3, 13, 431, 474, 541, 542, stepfun, 519, 520
545, 556, 559, 562, 563, 563, 566 stieltjes, 596
runifpoint3, 8, 546, 564 stratrand, 113, 206, 470, 471, 593
runifpointOnLines, 4, 13, 416, 547, 565 Strauss, 11, 201, 202, 339, 340, 359, 369,
370, 373, 417, 421, 425, 427, 448,
sample, 542, 563 449, 475, 476, 504, 509, 510, 516,
SatPiece, 12, 61, 202, 359, 370, 371, 421, 520, 522, 524, 525, 597
566, 567, 568 StraussHard, 11, 359, 373, 417, 421, 425,
Saturated, 12, 359, 370, 371, 373, 421, 449, 475, 476, 504, 509, 510, 516,
425, 475, 476, 568 520, 522, 525, 598
scanpp, 431, 568 suffstat, 600
segments, 411, 412, 415 summary, 6, 8, 12, 329, 602–609
[Link], 7, 108, 570 [Link], 214, 222, 327, 328, 444, 602
[Link], 503, 581 [Link], 168, 603
setcov, 6, 222, 571 [Link], 363, 444, 604, 607
setmarks, 3, 5, 495, 572 summary.pp3 (methods.pp3), 329
[Link], 6 [Link], 11, 605
[Link] ([Link]), 228 [Link], 446, 604, 606
shapley, 4, 573 [Link], 7, 27, 295, 331, 447, 607
shift, 5, 17–20, 163, 363, 482, 484–486, [Link], 448, 608
574, 575–579 [Link], 174, 609
[Link], 6, 575 superimpose, 5, 31, 94, 95, 431, 591, 592,
[Link], 363, 574, 576, 578, 579 610, 612
[Link], 574, 577, 577, 579 superimposePSP, 610, 611
[Link], 7, 578 swedishpines, 4, 431, 612
shortside.box3, 8 symbols, 409, 410, 412
shortside.box3 (diameter.box3), 126
simdat, 4, 431, 579 table, 321
[Link], 5, 52, 383, 580 tess, 3, 7, 59, 64, 76, 78, 96, 110, 114,
simulate, 581–583 130, 175, 230, 415, 469, 590, 592,
[Link], 10, 13, 152, 284, 581, 583 613, 616, 617
[Link], 4, 11–13, 510, 581, 582 [Link], 10, 284, 327, 332, 333, 561,
[Link], 9, 70, 117, 118, 388, 583 562, 614
[Link], 376–379 tiles, 7, 613, 614, 616
Softcore, 11, 359, 373, 421, 425, 449, 475, [Link], 617
476, 504, 509, 510, 516, 520, 522, txtProgressBar, 450
525, 584
solutionset, 7, 222, 298, 586 [Link], 6
source, 624 [Link] ([Link]), 228
spatstat (spatstat-package), 2 [Link], 460, 618
spatstat-package, 2 [Link], 5, 143, 338, 619
[Link], 5, 6, 11, 46, 48, 97, [Link] (square), 595
273, 274, 281, 335, 336, 398, 403, unitname, 73, 328–330, 482–485, 620
405, 407, 408, 410, 587 unitname.box3, 8
split, 589, 609 unitname.box3 (methods.box3), 328
[Link], 76, 589 unitname.pp3, 8
[Link], 5, 78, 120, 170, 174, 343, 414, unitname.pp3 (methods.pp3), 329
466, 548, 553, 590, 609, 613, 614 unitname<- (unitname), 620
split<-.ppp ([Link]), 590 unitname<-.box3 (methods.box3), 328
spokes, 12, 113, 470, 471, 592 unitname<-.pp3 (methods.pp3), 329
INDEX 657

unitname<-, 329, 330


units, 486
unmark, 5, 170, 572, 621
[Link], 7
update, 623, 624
[Link], 10, 284, 622
[Link], 11, 456, 623
urkiola, 4, 625

vcov, 626
[Link], 11, 626
vertices, 232, 628
Vmark, 10
Vmark (Emark), 145
volume.box3, 8, 73, 74
volume.box3 (diameter.box3), 126

with, 629–631
[Link], 9, 629
[Link], 8, 216, 397, 630

You might also like