100% found this document useful (12 votes)
84 views

Full Download Introduction to Scientific Programming and Simulation Using R 2nd Edition Owen Jones PDF DOCX

Jones

Uploaded by

suilachelha
Copyright
© © All Rights Reserved
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
100% found this document useful (12 votes)
84 views

Full Download Introduction to Scientific Programming and Simulation Using R 2nd Edition Owen Jones PDF DOCX

Jones

Uploaded by

suilachelha
Copyright
© © All Rights Reserved
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
You are on page 1/ 75

Download the full version of the ebook at ebookfinal.

com

Introduction to Scientific Programming and


Simulation Using R 2nd Edition Owen Jones

https://ebookfinal.com/download/introduction-to-scientific-
programming-and-simulation-using-r-2nd-edition-owen-jones/

OR CLICK BUTTON

DOWNLOAD EBOOK

Download more ebook instantly today at https://ebookfinal.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Introduction to Computation and Programming Using Python


with Application to Understanding Data 2nd edition Edition
Guttag
https://ebookfinal.com/download/introduction-to-computation-and-
programming-using-python-with-application-to-understanding-data-2nd-
edition-edition-guttag/
ebookfinal.com

Introduction to the Simulation of Dynamics Using Simulink


1st Edition Michael A. Gray

https://ebookfinal.com/download/introduction-to-the-simulation-of-
dynamics-using-simulink-1st-edition-michael-a-gray/

ebookfinal.com

An introduction to programming with Mathematica 3rd


Edition Paul R. Wellin

https://ebookfinal.com/download/an-introduction-to-programming-with-
mathematica-3rd-edition-paul-r-wellin/

ebookfinal.com

Practical Programming An Introduction to Computer Science


Using Python 3 Second Edition Paul Gries

https://ebookfinal.com/download/practical-programming-an-introduction-
to-computer-science-using-python-3-second-edition-paul-gries/

ebookfinal.com
Pakistan Eye of the Storm 2nd ed 2003 2nd ed. 2003 Edition
Owen Bennett Jones

https://ebookfinal.com/download/pakistan-eye-of-the-storm-2nd-
ed-2003-2nd-ed-2003-edition-owen-bennett-jones/

ebookfinal.com

Analyzing Linguistic Data A Practical Introduction to


Statistics using R 1st Edition R. H. Baayen

https://ebookfinal.com/download/analyzing-linguistic-data-a-practical-
introduction-to-statistics-using-r-1st-edition-r-h-baayen/

ebookfinal.com

An Introduction to Stata Programming 2nd Edition


Christopher F. Baum

https://ebookfinal.com/download/an-introduction-to-stata-
programming-2nd-edition-christopher-f-baum/

ebookfinal.com

Engineering Materials 2 Third Edition An Introduction to


Microstructures Processing and Design D R H Jones

https://ebookfinal.com/download/engineering-materials-2-third-edition-
an-introduction-to-microstructures-processing-and-design-d-r-h-jones/

ebookfinal.com

Introduction to Hospitality Operations An Indispensible


Guide to the Industry 2nd Edition Peter Jones

https://ebookfinal.com/download/introduction-to-hospitality-
operations-an-indispensible-guide-to-the-industry-2nd-edition-peter-
jones/
ebookfinal.com
Introduction
to Scientific
Programming and
Simulation Using R
Second Edition

K16464_FM.indd 1 5/16/14 7:37 AM


Chapman & Hall/CRC
The R Series

Series Editors
John M. Chambers Torsten Hothorn
Department of Statistics Division of Biostatistics
Stanford University University of Zurich
Stanford, California, USA Switzerland

Duncan Temple Lang Hadley Wickham


Department of Statistics RStudio
University of California, Davis Boston, Massachusetts, USA
Davis, California, USA

Aims and Scope


This book series reflects the recent rapid growth in the development and application
of R, the programming language and software environment for statistical computing
and graphics. R is now widely used in academic research, education, and industry.
It is constantly growing, with new versions of the core software released regularly
and more than 5,000 packages available. It is difficult for the documentation to
keep pace with the expansion of the software, and this vital book series provides a
forum for the publication of books covering many aspects of the development and
application of R.
The scope of the series is wide, covering three main threads:
• Applications of R to specific disciplines such as biology, epidemiology,
genetics, engineering, finance, and the social sciences.
• Using R for the study of topics of statistical methodology, such as linear and
mixed modeling, time series, Bayesian methods, and missing data.
• The development of R, including programming, building packages, and
graphics.
The books will appeal to programmers and developers of R software, as well as
applied statisticians and data analysts in many fields. The books will feature
detailed worked examples and R code fully integrated into the text, ensuring their
usefulness to researchers, practitioners and students.

K16464_FM.indd 2 5/16/14 7:37 AM


Published Titles

Using R for Numerical Analysis in Science and Engineering , Victor A. Bloomfield

Event History Analysis with R, Göran Broström

Computational Actuarial Science with R, Arthur Charpentier

Statistical Computing in C++ and R, Randall L. Eubank and Ana Kupresanin

Reproducible Research with R and RStudio, Christopher Gandrud

Introduction to Scientific Programming and Simulation Using R, Second Edition,


Owen Jones, Robert Maillardet, and Andrew Robinson

Displaying Time Series, Spatial, and Space-Time Data with R,


Oscar Perpiñán Lamigueiro

Programming Graphical User Interfaces with R, Michael F. Lawrence


and John Verzani

Analyzing Baseball Data with R, Max Marchi and Jim Albert

Growth Curve Analysis and Visualization Using R, Daniel Mirman

R Graphics, Second Edition, Paul Murrell

Multiple Factor Analysis by Example Using R, Jérôme Pagès

Customer and Business Analytics: Applied Data Mining for Business Decision
Making Using R, Daniel S. Putler and Robert E. Krider

Implementing Reproducible Research, Victoria Stodden, Friedrich Leisch,


and Roger D. Peng

Dynamic Documents with R and knitr, Yihui Xie

K16464_FM.indd 3 5/16/14 7:37 AM


K16464_FM.indd 4 5/16/14 7:37 AM
Introduction
to Scientific
Programming and
Simulation Using R
Second Edition

Owen Jones, Robert Maillardet,


and Andrew Robinson
University of Melbourne
Parkville, Australia

K16464_FM.indd 5 5/16/14 7:37 AM


CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
© 2014 by Taylor & Francis Group, LLC
CRC Press is an imprint of Taylor & Francis Group, an Informa business

No claim to original U.S. Government works


Version Date: 20140514

International Standard Book Number-13: 978-1-4665-7001-6 (eBook - PDF)

This book contains information obtained from authentic and highly regarded sources. Reasonable
efforts have been made to publish reliable data and information, but the author and publisher cannot
assume responsibility for the validity of all materials or the consequences of their use. The authors and
publishers have attempted to trace the copyright holders of all material reproduced in this publication
and apologize to copyright holders if permission to publish in this form has not been obtained. If any
copyright material has not been acknowledged please write and let us know so we may rectify in any
future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced,
transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or
hereafter invented, including photocopying, microfilming, and recording, or in any information stor-
age or retrieval system, without written permission from the publishers.

For permission to photocopy or use material electronically from this work, please access www.copy-
right.com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222
Rosewood Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that pro-
vides licenses and registration for a variety of users. For organizations that have been granted a pho-
tocopy license by the CCC, a separate system of payment has been arranged.

Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are
used only for identification and explanation without intent to infringe.
Visit the Taylor & Francis Web site at
http://www.taylorandfrancis.com
and the CRC Press Web site at
http://www.crcpress.com
To Charlotte and Indigo

Owen Jones

To Deborah, Simone and André with my love

Robert Maillardet

To my parents Marian and Peter, and my son Felix

Andrew Robinson
Contents

Preface xvii

How to use this book xix

I Programming 1

1 Setting up 3
1.1 Installing R 3
1.2 Starting R 3
1.3 Working directory 4
1.4 Writing scripts 5
1.5 Help 5
1.6 Supporting material 6

2 R as a calculating environment 11
2.1 Arithmetic 11
2.2 Variables 12
2.3 Functions 13
2.4 Vectors 15
2.5 Missing data: NA 18
2.6 Expressions and assignments 20
2.7 Logical expressions 20
2.8 Matrices 23
2.9 The workspace 26
2.10 Exercises 26

ix
x CONTENTS
3 Basic programming 29
3.1 Introduction 29
3.2 Branching with if 31
3.3 Looping with for 33
3.4 Looping with while 37
3.5 Vector-based programming 39
3.6 Program flow 40
3.7 Basic debugging 41
3.8 Good programming habits 43
3.9 Exercises 43

4 I/O: Input and output 49


4.1 Text 49
4.2 Input from a file 51
4.3 Input from the keyboard 53
4.4 Output to a file 55
4.5 Plotting 56
4.6 Exercises 58

5 Programming with functions 61


5.1 Functions 61
5.2 Scope and its consequences 66
5.3 Arguments 68
5.4 Vector-based programming using functions 71
5.5 Recursive programming 74
5.6 Debugging functions 77
5.7 Exercises 79

6 Sophisticated data structures 87


6.1 Factors 87
6.2 Dataframes 90
6.3 Lists 97
6.4 The apply family 101
6.5 Exercises 108
CONTENTS xi
7 Better graphics 113
7.1 Introduction 113
7.2 Graphics parameters: par 115
7.3 Graphical augmentation 117
7.4 Mathematical typesetting 120
7.5 Permanence 122
7.6 Grouped graphs: lattice 123
7.7 3D plots 127
7.8 Exercises 129

8 Pointers to further programming techniques 131


8.1 Packages 131
8.2 Frames and environments 137
8.3 Debugging again 139
8.4 Identifying bottlenecks 141
8.5 Object-oriented programming: S3 142
8.6 Object-oriented programming: S4 148
8.7 Manipulation of data 150
8.8 Compiled code 157
8.9 Further reading 159
8.10 Exercises 160

II Numerical techniques 161

9 Numerical accuracy and program efficiency 163


9.1 Machine representation of numbers 163
9.2 Significant digits 166
9.3 Time 168
9.4 Loops versus vectors 170
9.5 Parallel processing 172
9.6 Memory 174
9.7 Caveat 176
9.8 Exercises 176
xii CONTENTS
10 Root-finding 181
10.1 Introduction 181
10.2 Fixed-point iteration 182
10.3 The Newton–Raphson method 187
10.4 The secant method 190
10.5 The bisection method 192
10.6 Exercises 195

11 Numerical integration 203


11.1 Trapezoidal rule 203
11.2 Simpson’s rule 205
11.3 Adaptive quadrature 210
11.4 Exercises 214

12 Optimisation 219
12.1 Newton’s method for optimisation 220
12.2 The golden-section method 222
12.3 Multivariate optimisation 225
12.4 Steepest ascent 227
12.5 Newton’s method in higher dimensions 230
12.6 Optimisation in R and the wider world 236
12.7 A curve-fitting example 237
12.8 Exercises 238

13 Systems of ordinary differential equations 245


13.1 Euler’s method 247
13.2 Midpoint method 249
13.3 Fourth-order Runge–Kutta 251
13.4 Efficiency 253
13.5 Adaptive step size 256
13.6 Exercises 265
CONTENTS xiii
III Probability and statistics 269

14 Probability 271

14.1 The probability axioms 271

14.2 Conditional probability 274

14.3 Independence 276

14.4 The Law of Total Probability 277

14.5 Bayes’ theorem 278

14.6 Exercises 279

15 Random variables 285

15.1 Definition and distribution function 285

15.2 Discrete and continuous random variables 286

15.3 Empirical cdf’s and histograms 289

15.4 Expectation and finite approximations 290

15.5 Transformations 295

15.6 Variance and standard deviation 300

15.7 The Weak Law of Large Numbers 301

15.8 Exercises 305

16 Discrete random variables 311

16.1 Discrete random variables in R 311

16.2 Bernoulli distribution 312

16.3 Binomial distribution 312

16.4 Geometric distribution 314

16.5 Negative binomial distribution 317

16.6 Poisson distribution 318

16.7 Exercises 321


xiv CONTENTS
17 Continuous random variables 325
17.1 Continuous random variables in R 325
17.2 Uniform distribution 326
17.3 Lifetime models: exponential and Weibull 326
17.4 The Poisson process and the gamma distribution 331
17.5 Sampling distributions: normal, χ2 , and t 336
17.6 Exercises 342

18 Parameter estimation 347


18.1 Point estimation 347
18.2 The Central Limit Theorem 353
18.3 Confidence intervals 358
18.4 Monte Carlo confidence intervals 365
18.5 Exercises 367

19 Markov chains 373


19.1 Introduction to discrete time chains 373
19.2 Basic formulae: discrete time 377
19.3 Classification of states 385
19.4 Limiting behaviour: discrete time 390
19.5 Finite absorbing chains 395
19.6 Introduction to continuous time chains 400
19.7 Rate matrix and associated equations 408
19.8 Limiting behaviour: continuous time 411
19.9 Defining the state space 413
19.10 Simulation 416
19.11 Estimation 422
19.12 Estimating the mean of the limiting distribution 426
19.13 Exercises 434
CONTENTS xv
IV Simulation 441

20 Simulation 443
20.1 Simulating iid uniform samples 443
20.2 Simulating discrete random variables 445
20.3 Inversion method for continuous rv 450
20.4 Rejection method for continuous rv 452
20.5 Simulating normals 458
20.6 Exercises 461

21 Monte Carlo integration 467


21.1 Hit-and-miss method 467
21.2 (Improved) Monte Carlo integration 470
21.3 Exercises 472

22 Variance reduction 475


22.1 Antithetic sampling 475
22.2 Importance sampling 479
22.3 Control variates 484
22.4 Exercises 486

23 Case studies 489


23.1 Introduction 489
23.2 Epidemics 490
23.3 Inventory 502
23.4 Seed dispersal 517

24 Student projects 533


24.1 The level of a dam 533
24.2 Runoff down a slope 537
24.3 Roulette 542
24.4 Buffon’s needle and cross 545
xvi CONTENTS
24.5 The pipe spiders of Brunswick 547
24.6 Insurance risk 553
24.7 Squash 556
24.8 Stock prices 561
24.9 Conserving water 563

Glossary of R commands 569

Programs and functions developed in the text 575

Index 577
Preface

This book has two principal aims: to teach scientific programming and to intro-
duce stochastic modelling. Stochastic modelling, indeed mathematical mod-
elling more generally, is intimately linked to scientific programming because
the numerical techniques of scientific programming enable the practical ap-
plication of mathematical models to real-world problems. In the context of
stochastic modelling, simulation is the numerical technique that enables us to
analyse otherwise intractable models.
Simulation is also the best way we know of developing statistical intuition.
This book assumes that users have completed or are currently undertaking
a first-year university level calculus course. The material is suitable for first
and second year science/engineering/commerce students and masters level stu-
dents in applied disciplines. No prior knowledge of programming or probability
is assumed.
It is possible to use the book for a first course on probability, with an empha-
sis on applications facilitated by simulation. Modern applied probability and
statistics are numerically intensive, and we give an approach that integrates
programming and probability right from the start.
We chose the programming language R because of its programming features.
We do not describe statistical techniques as implemented in R (though many
of them are admittedly quite remarkable), but rather show how to turn algo-
rithms into code. Our intended audience is those who want to make tools, not
just use them.
Complementing the book is a package, spuRs, containing most of the code
and data we use. Instructions for installing it are given in the first chapter. In
the back of the book we also provide an index of the programs developed in
the text and a glossary of R commands.

xvii
xviii PREFACE
Thanks

We would like to thank the many readers of the first edition who have taken
the time to email their personal thanks, and to share their positive learning
experiences using our book. It has been very gratifying to have this contact,
and to feel like we are part of a wider learning community exploring the
beautiful mathematical and computing ideas in this volume. We would also
like to thank those users who have posted so many favourable online reviews,
and instructors who have adopted the book in courses. That is how this book
began—through a successful course—and it is a pleasure to see that being
replicated elsewhere.
ODJ
RJM
APR
November 2013

Thanks from the first edition Much of this book is based on a course given by
the first two authors at the University of Melbourne. The course was developed
over many years, and we owe much to previous lecturers for its fundamental
structure, in particular Steve Carnie and Chuck Miller. We are also indebted to
our proof readers and reviewers: Gad Abraham, Paul Blackwell, Steve Carnie,
Alan Jones, David Rolls, and especially Phil Spector. Olga Borovkova helped
with some of the coding, and we thank John Maindonald for drawing our
attention to playwith.
We would like to acknowledge the dedication and the phenomenal achievement
of the community that has provided the tools that we used to produce this
book. We are especially grateful to R-core, to the LATEX community, the GNU
community, and to Friedrich Leisch for Sweave.
Of course we could not have written the book without the support of our
partners, Charlotte, Deborah, and Grace, or the bewilderment of our offspring,
Indigo, Simone, André, and Felix.
How to use this book

This book has grown out of the notes prepared for a first-year course consist-
ing of 36 lectures, 12 one-hour tutorials, and 12 two-hour lab classes. However
it now contains more material than would fit in such a course, which permits
its use for a variety of course structures, for example to meet prerequisite
requirements for follow-on subjects. We found the lab classes to be particu-
larly important pedagogically, as students learn programming through their
own experimentation. Instructors may straightforwardly compile lab classes
by drawing on the numerous examples and exercises in the text, and these are
supplemented by the programming projects contained in Chapter 24, which
are based on assignments we gave our students.

Core content The following chapters contain our core material for a course
on scientific programming and simulation.

Part I: Core knowledge of R and programming concepts. Chapters 1–6.

Part II: Thinking about mathematics from a numerical point of view: applying
Part I concepts to root finding and numerical integration. Chapters 9–11.

Part III: Essentials of probability, random variables, and expectation required


to understand simulation. Chapters 14–16 plus the uniform distribution.

Part IV: Stochastic modelling and simulation: random number generation,


Monte Carlo integration, case studies and projects. Chapters 20.1–20.2, 21,
23.1–23.2 and 24.

Additional stochastic material The core outlined above only uses discrete
random variables, and for estimation only uses the concept of a sample average
converging to a mean. Chapters 17 and 18 add continuous random variables,
the Central Limit Theorem and confidence intervals. Chapter 19 discusses both
discrete and continuous time Markov chains. Chapters 20.3–20.5 and 22 then
look at simulating continuous random variables and variance reduction. With
some familiarity of continuous random variables the remaining case studies,
Chapter 23.3–23.4, become accessible.

Note that some of the projects in Chapter 24 use continuous random variables,
but can be easily modified to use discrete random variables instead.

xix
xx HOW TO USE THIS BOOK
Additional programming and numerical material For the core material ba-
sic plotting of output is sufficient, but for those wanting to produce more
professional graphics we provide Chapter 7. Chapter 8, on further program-
ming, acts as a bridge to more specialised texts, for those who wish to pursue
programming more deeply.
Chapter 12 deals with univariate and multivariate optimisation, and Chapter
13 with systems of ordinary differential equations. These chapters assume a ba-
sic familiarity with vector and differential calculus. This material is largely self-
contained, though there are some exercises and examples elsewhere in the book
that incorporate optimisation. In particular, the curve fitting Example 18.1.2
uses the optim function, and curve fitting also appears in Exercise 19.13.13
and student project 24.2. However, if you are prepared to use optimise and
optim as black boxes, then these curve fitting examples/exercises are quite
accessible without reading the optimisation chapter.
We also mention student project 24.5 (the pipe spiders of Brunswick), which
guides students through a stochastic optimisation problem using an evolution-
ary algorithm. This project is self-contained and does not rely on Chapter 12
(and is always very popular with our own students).

Chapter outlines

1: Setting up. Here we describe how to obtain and install R, and the package
spuRs, which complements the book.
2: R as a calculating environment. This chapter shows you how to use R to
do arithmetic calculations; create and manipulate variables, vectors, and ma-
trices; work with logical expressions; call and get help on built-in R functions;
and to understand the workspace.
3: Basic programming. This chapter introduces a set of basic programming
structures that are the building blocks of many programs. Some structures are
common to numerous programming languages, for example if, for and while
statements. Others, such as vector-based programming, are more specialised,
but are arguably just as important for efficient R coding.
4: Input and output. This chapter describes some of the infrastructure that R
provides for importing data for subsequent analysis, and for displaying and
saving results of that analysis. More details on the construction of graphics
are available in Chapter 7, and we provide more information about importing
data in Chapter 6.
5: Programming with functions. This chapter extends Chapter 3 to include
user-defined functions. We cover the creation of functions, the rules that they
must follow, and how they relate to the environments from which they are
called. We also present some tips on the construction of efficient functions,
with especial reference to how they are treated in R.
HOW TO USE THIS BOOK xxi
6: Sophisticated data structures. In this chapter we study R’s more sophisti-
cated data structures—lists and dataframes—which simplify data representa-
tion, manipulation, and analysis. The dataframe is like a matrix but extended
to allow for different data modes in different columns, and the list is a general
data storage object that can house pretty much any other kind of R object.
We also introduce the factor, which is used to represent categorical objects.
7: Better graphics. This chapter provides a deeper exposition of the graphical
capabilities of R, building on Chapter 4. We explain the individual pieces that
make up the default plot. We discuss the graphics parameters that are used
to fine-tune individual graphs and multiple graphics on a page. We show how
to save graphical objects in various formats. Finally, we demonstrate some
graphical tools for the presentation of multivariate data (lattice graphs), and
3D-graphics.
8: Further programming. This chapter briefly mentions some more advanced
aspects of programming in R. We introduce the management of and interac-
tion with packages. We present details about how R arranges the objects that
we create within the workspace, and within functions that we are running.
We provide further suggestions for debugging your own functions. Finally, we
present some of the infrastructure that R provides for object-oriented program-
ming, and for executing code that has been compiled from another computer
language, for example, C.
9: Numerical accuracy and program efficiency. In this chapter we consider
technical details about how computers operate, and their ramifications for
programming practice, particularly within R. We look at how computers rep-
resent numbers, and the effect that this has on the accuracy of computation
results. We also discuss the time it takes to perform a computation, and pro-
gramming techniques for speeding things up. Finally we consider the effects
of memory limitations on computation efficiency.
10: Root-finding. This chapter presents a suite of different techniques for find-
ing roots. We cover fixed-point iteration, the Newton–Raphson method, the
secant method, and the bisection method.
11: Numerical integration. This chapter introduces numerical integration. The
problem with integration is that often a closed form of the antiderivative is not
available. Under such circumstances we can try to approximate the integral
using computational methods. We cover the trapezoidal rule, Simpson’s rule,
and adaptive quadrature.
12: Optimisation. This chapter covers the problem of finding the maximum
or minimum of a possibly multivariate function. We introduce the Newton
method and the golden-section method in the context of a univariate function,
and steepest ascent/descent and Newton’s method for multivariate functions.
We then provide some further information about the optimisation tools that
are available in R.
xxii HOW TO USE THIS BOOK
13: Systems of ordinary differential equations. We cover the Euler, midpoint,
and fourth-order Runge–Kutta (RK4) schemes for solving systems of first-
order ordinary differential equations (initial value problems only). The nu-
merical efficiencies of the different schemes are compared experimentally, and
we show how to improve the RK4 scheme by using an adaptive step size,
analogous to adaptive quadrature as seen in Chapter 11.
14: Probability. In this chapter we introduce mathematical probability, which
allows us to describe and think about uncertainty in a precise fashion. We cover
the probability axioms and conditional probability. We also cover the Law of
Total Probability, which can be used to decompose complicated probabilities
into simpler ones that are easier to compute, and Bayes’ theorem, which is
used to manipulate conditional probabilities in very useful ways.
15: Random variables. In this chapter we introduce the concept of a random
variable. We define discrete and continuous random variables and consider
various ways of describing their distributions, including the distribution func-
tion, probability mass function, and probability density function. We define
expectation, variance, independence, and covariance. We also consider trans-
formations of random variables and derive the Weak Law of Large Numbers.
16: Discrete random variables. In this chapter we study some of the most
important discrete random variables, and summarise the R functions relating
to them. We cover the Bernoulli, binomial, geometric, negative binomial, and
the Poisson distribution.
17: Continuous random variables. This chapter presents the theory, applica-
tions of, and R representations of a number of continuous random variables.
We cover the uniform, exponential, Weibull, gamma, normal, χ2 , and t distri-
butions.
18: Parameter estimation. This chapter covers point and interval estimation.
We introduce the Central Limit Theorem, normal approximations, asymptotic
confidence intervals and Monte Carlo confidence intervals.
19: Markov chains. This chapter covers both discrete and continuous time
Markov chains. We cover transition and rate matrices, classification of states,
limiting behaviour (including balance equations), Kolmogorov forward and
backward equations, finite absorbing chains (including expected absorption
times and probabilities) and expected hitting times. We cover techniques for
defining the state space, including lumping states and supplementary vari-
ables, and methods for simulating both discrete and continuous time chains.
20: Simulation. In this chapter we simulate uniformly distributed random vari-
ables and discrete random variables, and describe the inversion and rejection
methods for simulating continuous random variables. We also cover several
techniques for simulating normal random variables.
21: Monte Carlo integration. This chapter covers simulation-based approaches
HOW TO USE THIS BOOK xxiii
to integration. We cover the hit-and-miss method, and the more efficient
Monte Carlo integration method. We also give some comparative results on
the convergence rate of these two techniques compared with the trapezoid and
Simpson’s rule, which we covered in Chapter 11.
22: Variance reduction. This chapter introduces several sampling-based inno-
vations to the problem of estimation. We cover antithetic sampling, control
variates, and importance sampling. These techniques can vastly increase the
efficiency of simulation exercises when judiciously applied.
23: Case studies. In this chapter we present three case studies, on epidemics,
inventory, and seed dispersal (including an application of object-oriented cod-
ing). These are extended examples intended to demonstrate some of our sim-
ulation techniques.
24: Student projects. This chapter presents a suite of problems that can be
tackled by students. They are less involved than the case studies in the pre-
ceding chapter, but more substantial than the exercises that we have included
in each chapter.

Caveat computator

R is under constant review. The core programmers schedule a major release


and a minor release every year. Releases involve many changes and additions,
most of which are small, but some of which are large. There is no guarantee
of total backward compatibility, so new releases can break code that makes
assumptions about how the environment should work.
For example, while we were writing the first edition of this book, the upgrade
from version 2.7.1 to 2.8.0. changed the default behaviour of var, to return an
NA where previously it returned an error, if any of the input were NA. Happily,
we had time to rewrite the material that presumed that an error would be
returned.
We conclude that R changes, and we note that this book was written using
version 3.0.1. The spuRs package will include a list of errata.

Bibliography/further reading

For those wishing to further their study of scientific programming and simu-
lation, here are some texts that the authors have found useful.
The R language
W.N. Venables and B.D. Ripley, S Programming. Springer, 2000.
W.N. Venables and B.D. Ripley, Modern Applied Statistics with S, Fourth
Edition. Springer, 2002.
xxiv HOW TO USE THIS BOOK
J.M. Chambers and T.J. Hastie (Eds), Statistical Models in S.
Brooks/Cole, 1992.
J. Maindonald and J. Braun, Data Analysis and Graphics Using R: An
Example-Based Approach, Second Edition. Cambridge University Press, 2006.
Scientific programming/numerical techniques
W. Cheney and D. Kincaid, Numerical Mathematics and Computing, Sixth
Edition. Brooks/Cole, 2008.
M.T. Heath, Scientific Computing: An Introductory Survey, Second Edition.
McGraw-Hill, 2002.
W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical
Recipes, 3rd Edition: The Art of Scientific Computing. Cambridge University
Press, 2007.
C.B. Moler, Numerical Computing with Matlab, Society for Industrial Mathe-
matics, 2004.
Stochastic modelling and simulation
A.M. Law and W.D. Kelton, Simulation Modeling and Analysis, Third Edi-
tion. McGraw-Hill, 1999.
M. Pidd, Computer Simulation in Management Science, Fifth Edition. Wi-
ley, 2004.
S.M. Ross, Applied Probability Models with Optimization Applications.
Dover, 1992.
D.L. Minh, Applied Probability Models. Brooks/Cole, 2001.
PART I

Programming
CHAPTER 1

Setting up

In this chapter we show you how to obtain and install R, ensure R can find
your data and program files, choose an editor to help write R scripts, and
access the extensive help resources and manuals available in R. We also tell
you how to install the spuRs package, which complements this book and gives
access to most of the code examples and functions developed in the book.
R is an open-source implementation of a functional programming language
called S. It has been developed and is maintained by a core of statistical pro-
grammers, with the support of a large community of users. Unlike S-plus, the
other currently available implementation of S, R is free. It is most widely used
for statistical computing and graphics, but is a fully functional programming
language well suited to scientific programming in general.

1.1 Installing R

Versions of R are available for a wide variety of computing platforms including


various variants of Unix, Windows, and MacOS.
You can download R from one of the many mirror sites of the Comprehensive R
Archive Network (CRAN), for example http://cran.ms.unimelb.edu.au/.
In the first instance it will be sufficient to obtain the base distribution. Advice
on downloading and installing R is available from the FAQs provided on the
CRAN site. The operations are straightforward for the major platforms.

1.2 Starting R

The Windows R implementation is called Rgui.exe (short for R graphical


user interface). The MacOS R implementation is called R.app. In UNIX you
start an R session simply by entering R at the command line interface (we are
assuming that your path includes the R binaries; installation and configuration
of R on UNIX is beyond the scope of this book).
When R starts it loads some infrastructure and provides you with a prompt:

>

3
4 SETTING UP
This prompt is the fundamental entry point for communicating with R. We
can type expressions at the prompt; R evaluates the expressions, and returns
output.

> 1 + 1

[1] 2

R is object oriented, meaning that we can create objects that persist within
an R session, and manipulate these objects by name. For example, here we
create the object x as the evaluation of the expression 1 + 1, and then print
it.

> x <- 1 + 1
> x

[1] 2

When you are finished using R, you quit with the command q(). R asks if
you would like to save your workspace, which amounts to all the objects that
you have created during the session. This is not normally necessary, but if you
choose to do so then the objects are all saved as a compressed binary object.
See Section 2.9 for more information about the workspace.

1.3 Working directory

When you run R, it nominates one of the directories on your hard drive as a
working directory, which is where it looks for user-written programs and data
files. You can determine the current working directory using the command
getwd. The first thing you should do when you start an R session is to make
sure that the working directory is the right one for your needs. You can do
this using the command setwd("dir"), where dir is the directory address.
The directory address dir can be absolute or relative to the current working
directory. Alternatively, if you are using Rgui.exe in Windows, then there is
a menu command for changing the working directory.
For example, if you had a USB drive mounted as drive E and you wanted R to
save your solutions to the Chapter 2 exercises in the directory E:\spuRs\ch2
by default, then you would type setwd("E:/spuRs/ch2"). Note that R uses
the UNIX convention of forward slashes / in directory and file addresses; .
refers to the current directory and .. refers to the parent directory.

> getwd()

[1] "/home/andrewr/spuRs/trunk/manuscript/chapters"

> setwd("../scripts")
> getwd()
WRITING SCRIPTS 5
[1] "/home/andrewr/spuRs/trunk/manuscript/scripts"

On Windows you can set R to automatically start up with your preferred


working directory by right clicking on the program shortcut, choosing Prop-
erties, and completing the ‘Start in’ field. On MacOS you can set the initial
working directory using the Preferences menu.

1.4 Writing scripts

Although we can type and evaluate all possible R expressions at the prompt,
it is much more convenient to write scripts, which simply comprise collections
of R expressions that we intend R to evaluate sequentially. We will use the
terms program and code synonymously with script.
To write programs you will need a text editor (as distinguished from a
word processor). The Windows R implementation has a built-in text ed-
itor, but many users prefer to use RStudio, which includes a number of
tools to ease code development. RStudio is free and can be obtained from
http://www.rstudio.com/. A similar alternative is Tinn-R. For more ad-
vanced users, emacs and Xemacs also work very well with R, and we par-
ticularly recommend the Emacs Speaks Statistics (ESS) package for these
applications.

1.5 Help

This book does not cover all the features of R, and even the features it does
cover are not dealt with in full generality. To find out more about an R com-
mand or function x, you can type help(x) or just ?x. If you cannot remem-
ber the exact name of the command or function you are interested in, then
help.search("x") will search the titles, names, aliases, and keyword entries
of the available help files for the phrase x.
For a useful HTML help interface, type help.start(). This will allow you to
search for help, and also provides links to a number of manuals, in particular
the highly recommended ‘An Introduction to R.’
A short glossary of commands is included at the end of the book. For fur-
ther documentation, a good place to start is the CRAN network, which gives
references and links to online resources provided by the R community. Some
references to more advanced material are given in Chapter 8.
Of course reading the help system, R manuals, and this book will start you on
the way to understanding R and its applications. But to properly understand
how things really work, there is no substitute for trying them out for yourself:
learn through play.
6 SETTING UP
1.6 Supporting material

We give examples of R usage and programs throughout the book. So that you
do not have to retype all of these yourself, we have made the longer programs
and all of datasets that we use available in an online archive, distributed
using the same CRAN network that distributes R. In fact, the archive has
the added functionality of what is called a package. This means that it can
be loaded within R, in which case some of our functions and datasets will be
directly available, in the same way that built-in functions and datasets are
available.
We describe how to obtain, install, and load the archive below. When success-
fully installed, you will have a new directory called spuRs, within which is a
subdirectory resources, which contains the material from the book. You will
see that spuRs contains a number of other subdirectories: these are required to
provide the package functionality and can be safely ignored. The resources
directory contains two subdirectories: scripts, which contains program code;
and data, which contains the datasets.
When the package is installed and then loaded in R, you get direct access to
some of our functions and datasets. To obtain a list of these, type ?spuRs once
the package has been loaded. To use a dataset called x, in addition to loading
the package you need to type data(x), at which point it becomes available as
an object called x. You can also get the code for function f just by typing f
in R.
Within the text, when giving the code for a program prog.r, if it is included
in the archive it will begin with the comment line
# spuRs/resources/scripts/prog.r

The code for a function f that is available as part of the package will begin
with the line
# loadable spuRs function

Note that the code for f will also be available as the file
spuRs/resources/scripts/f.r

within the spuRs archive.

1.6.1 Installing and loading the package when you have write privileges

In order for the following approaches to succeed, your computer needs access
to the Internet. If your computer is behind a firewall, then further steps may
be required; please consult your network manual or local support.
If your computer is appropriately configured, then you may be able to install
SUPPORTING MATERIAL 7
the archive in a single step, from within R. The key facility is that you need
to be able to write to the R application directory. That is, you need to be able
to save files in the directory that R was installed in. Start R as usual, then
try:

> install.packages("spuRs")

If installation was successful, then a compressed version of the archive will


have been downloaded to a temporary location. This location is reported in
case you wish to move the compressed version, as otherwise it will be deleted
when R quits. The decompressed archive is saved in the directory spuRs in
the library subdirectory of the R application directory. That is, within the
R application directory, you will find our program code in the subdirectory
library/spuRs/resources/scripts and datasets in the subdirectory li-
brary/spuRs/resources/data.
If the process failed, then either downloading or installation failed. If down-
loading failed, then there may be a problem with the network; try again in a
short time. If it fails again, then consult your local support.
If no errors or warnings ensue, then any time you want access to the objects
in the package, type

> library(spuRs)

This code adds the functions and objects in spuRs to the search path.

1.6.2 Installing and loading the package with limited write privileges

This section covers the necessary steps to obtain and install the archive even
if the user has limited write access to the computer.

Preparation Create a directory to download the archive to, in a convenient


area of your hard drive for which you have write permissions. You may elect to
delete this directory when you are done, so its location is not very important.
For example, we might create a directory called:
D:\temporary

Now, create a directory to house the archive, in a convenient area of your hard
drive. You will probably want to keep this directory. For example, we might
create a directory called:
D:\library

Note that our examples assume that we have write access to the D:\ drive. If
we do not have write access, then we would create the directories elsewhere.
Make a note of the locations.
8 SETTING UP
Start R normally, then check that you have created the directories successfully.
An easy way to do this is using the list.files function, to list the contents
of the directories.

> list.files("D:/library")

character(0)

> list.files("D:/temporary")

character(0)

These will give a warning if the directory cannot be found. As we have noted
earlier, within R we use the forward slash for addresses, regardless of the
operating system.

Download Having created the directories and verified that R can find them,
we proceed to downloading the archive. This is performed using the down-
load.packages function.

> info <- download.packages("spuRs", destdir = "D:/temporary")

You will be asked to select a CRAN mirror for use in your session. A closer
mirror will be slightly faster. R will provide you information about the URL
and the size of the archive. Notice that the download.packages command
gives output, which we have saved in the object called info.
The compressed archive has been saved to D:\temporary. NB: you can now
extract the scripts and datasets, which we have located in the resources direc-
tory within the archive.

Install Next we install the package to get direct access from within R to
many of the functions and datasets. Here is where the info object that we
created becomes useful.

> info

[,1] [,2]
[1,] "spuRs" "D:/temporary/spuRs_1.0.0.zip"

Note that the second element of info is the address of the archive. We can
easily install the archive now via:

> install.packages(info[1,2], repos = NULL, lib = "D:/library")

package 'spuRs' successfully unpacked and MD5 sums checked

R will have created a subdirectory named spuRs within the library directory,
containing the archive. That is, you will find our program code in the subdi-
rectory library/spuRs/resources/scripts and datasets in the subdirectory
library/spuRs/resources/data.
SUPPORTING MATERIAL 9
At this point we can use the library command to load the spuRs package
to our session. We have to include the directory to which the archive was
installed as the lib.loc argument.

> library(spuRs, lib.loc = "D:/library")

It is also useful to add this directory to the R’s list of recognised libraries, so
that the various help tools are aware of it. The second of the following three
expressions is necessary; the other two show its effect.

> .libPaths()

[1] "C:/PROGRA~1/R/R/library"

> .libPaths("D:/library")
> .libPaths()

[1] "D:/library" "C:/PROGRA~1/R/R/library"

Now when we invoke a help search, or use help.start, R knows to look in


the local library D:\library as well as in the usual places.
CHAPTER 2

R as a calculating environment

You can use R as a powerful calculator for a wide range of numerical com-
putations. Using R in this way can be useful in its own right, but can also
help you to create and test code fragments that you wish to build into your
R programs, and help you to learn about new R functions as you meet them.
This chapter shows you how to use R to do arithmetic calculations; create and
manipulate variables, vectors, and matrices; work with logical expressions; call
and get help on inbuilt R functions; and to understand the workspace that
contains all the associated objects R creates along the way.
Throughout this book examples of typed R input will appear in the Slanted
Typewriter font and R output and code in plain Typewriter. The right angle
bracket > is the R input prompt. In R you can separate commands using a
newline/return or a semicolon, though the latter usually leads to a lack of
clarity in programming and is thus discouraged. If you type return before a
command is finished then R displays the + prompt, rather than the usual >,
and waits for you to complete the command.
R provides a very rich computing environment, so to avoid overwhelming the
reader we will introduce different objects and functions as their need arises,
rather than all at once.

2.1 Arithmetic

R uses the usual symbols for addition +, subtraction -, multiplication *, di-


vision /, and exponentiation ^. Parentheses ( ) can be used to specify the
order of operations. R also provides %% for taking the modulus and %/% for
integer division.

> (1 + 1/100)^100

[1] 2.704814

> 17 %% 5

[1] 2

> 17 %/% 5

11
12 R AS A CALCULATING ENVIRONMENT
[1] 3

The [1] that prefixes the output indicates (here, somewhat redundantly) that
this is item 1 in a vector of output. R calculates to a high precision, but by
default only displays 7 significant digits. You can change the display to x
digits using options(digits = x). (Although displaying x digits does not
guarantee accuracy to x digits, as we will see in Chapter 9.)
R has a number of built-in functions, for example sin(x), cos(x), tan(x),
(all in radians), exp(x), log(x), and sqrt(x). Some special constants such
as pi are also predefined.

> exp(1)

[1] 2.718282

> options(digits = 16)


> exp(1)

[1] 2.718281828459045

> pi

[1] 3.141592653589793

> sin(pi/6)

[1] 0.4999999999999999

The functions floor(x) and ceiling(x) round down and up, respectively, to
the nearest integer.

2.2 Variables

A variable is like a folder with a name on the front. You can place something
inside the folder, look at it, replace it with something else, but the name on
the front of the folder stays the same.
To assign a value to a variable we use the assignment command <-. Variables
are created the first time you assign a value to them. You can give a variable
any name made up of letters, numbers, and . or _, provided it starts with a
letter, or . then a letter. Note that names are case sensitive.
To display the value of a variable x on the screen we just type x. This is in
fact shorthand for print(x). Later we will see that in some situations we have
to use the longer format, or its near equivalent show(x), for example when
writing scripts or printing results inside a loop.

> x <- 100


> x
FUNCTIONS 13
[1] 100
> (1 + 1/x)^x
[1] 2.704814
> x <- 200
> (1 + 1/x)^x
[1] 2.711517

We can also show the outcome of an assignment by surrounding it with paren-


theses, as follows.
> (y <- (1 + 1/x)^x)
[1] 2.711517

When assigning a value to a variable, the expression on the right-hand side is


evaluated first, then that value is placed in the variable on the left-hand side.
It is thus possible (and quite common) to have the same variable appearing
on the right- and left-hand sides.
> n <- 1
> n <- n + 1
> n
[1] 2

In common with most programming languages, R allows the use of = for vari-
able assignment, as well as <-. We prefer the latter, because there is no pos-
sibility of confusion with mathematical equality. For example, we understand
the assignment n <- n + 1 by thinking of n as the name of a data location in
the computer memory, whose contents change as the assignment is processed.
Contrast this with the usual mathematical interpretation of n = n + 1, where
the variable n is thought of as having the same value on both sides (so this
equation has no finite solution).
A good programming practice is to use informative names for your vari-
ables to improve readability. For example, the following code is relatively
self-explanatory.

2.3 Functions

In mathematics a function takes one or more arguments (or inputs) and pro-
duces one or more outputs (or return values). Functions in R work in an
analogous way.
To call or invoke a built-in (or user-defined) function in R you write the name
of the function followed by its argument values enclosed in parentheses and
separated by commas. We illustrate with the seq function, which produces
arithmetic sequences:
14 R AS A CALCULATING ENVIRONMENT
> seq(from = 1, to = 9, by = 2)

[1] 1 3 5 7 9

Some arguments are optional, and have predefined default values, for example,
if we omit by, then R assumes that by = 1:

> seq(from = 1, to = 9)

[1] 1 2 3 4 5 6 7 8 9

To find out about default values and alternative usages of the built-in function
fname, you can access the built-in help by typing help(fname) or ?fname.
Every function has a default order for the arguments. If you provide arguments
in this order, then they do not need to be named, but you can choose to
give the arguments out of order provided you give them names in the format
argument_name = expression.

> seq(1, 9, 2)

[1] 1 3 5 7 9

> seq(to = 9, from = 1)

[1] 1 2 3 4 5 6 7 8 9

> seq(by = -2, 9, 1)

[1] 9 7 5 3 1

Each argument value is given by an expression, which can be a constant,


variable, another function call, or an algebraic combination of these.

> x <- 9
> seq(1, x, x/3)

[1] 1 4 7

In R, functions can have a variable number of arguments, including no argu-


ments at all. A function call always needs the parentheses, even if no argu-
ments are required. If you just type the name of the function, then R types
out the function ‘object’, which is simply the program defining the function
itself. Try typing demo and then demo() to see the difference. (Then type
demo(graphics) to see a good demonstration of some of R’s graphics capa-
bilities.)
Generally, when we describe functions, we will only describe the most impor-
tant or commonly used options. For complete definitions you should use the
built-in help facility.
VECTORS 15
2.4 Vectors

A vector is an indexed list of variables. You can think of a vector as a drawer


in a filing cabinet: the drawer has a name on the outside and within it are files
labelled sequentially 1, 2, 3, . . . from the front. Each file is a simple variable
whose name is made up from the name of the vector and the number of the
label/index: the name of the i-th element of vector x is x[i].
Like variables, vectors are created the first time you assign values to them.
In fact, a simple variable is just a vector with length 1 (also described as
atomic). To create vectors of length greater than 1, we use functions that pro-
duce vector-valued output. There are many of these, but the three basic func-
tions for constructing vectors are c(...) (combine); seq(from, to, by)
(sequence); and rep(x, times) (repeat).

> (x <- seq(1, 20, by = 2))

[1] 1 3 5 7 9 11 13 15 17 19

> (y <- rep(3, 4))

[1] 3 3 3 3

> (z <- c(y, x))

[1] 3 3 3 3 1 3 5 7 9 11 13 15 17 19

The functions seq(from, to, by = 1) and seq(from, to, by = -1) are


used all the time and so R provides the shorthand colon, namely from:to.
Note that : takes precedence over algebraic operators *, +, /, and -, so to get
the sequence from 1 to n + 1, you need to use 1:(n+1) and not 1:n+1, which
produces the sequence 2, 3, . . . , n, n + 1.
To refer to element i of vector x, we use x[i]. If i is a vector of positive
integers, then x[i] is the corresponding subvector of x. If the elements of i
are negative, then the corresponding values are omitted. We can use the square
brackets in this way to set or get the value.

> (x <- 100:110)

[1] 100 101 102 103 104 105 106 107 108 109 110

> i <- c(1, 3, 2)


> x[i]

[1] 100 102 101

> j <- c(-1, -2, -3)


> x[j]

[1] 103 104 105 106 107 108 109 110


16 R AS A CALCULATING ENVIRONMENT
> x[1] <- 1000
> x

[1] 1000 101 102 103 104 105 106 107 108 109 110

The function length(x) gives the number of elements of x. It is possible to


have a vector with no elements.

> x <- c()


> length(x)

[1] 0

Algebraic operations on vectors act on each element separately, that is, ele-
mentwise.

> x <- c(1, 2, 3)


> y<-c(4, 5, 6)
> x * y

[1] 4 10 18

> x + y

[1] 5 7 9

> y^x

[1] 4 25 216

When you apply an algebraic expression to two vectors of unequal length,


R automatically repeats the shorter vector until it has something the same
length as the longer vector.

> c(1, 2, 3, 4) + c(1, 2)

[1] 2 4 4 6

> (1:10) ^ c(1, 2)

[1] 1 4 3 16 5 36 7 64 9 100

This happens even when the shorter vector is of length 1, allowing the short-
hand notation:

> 2 + c(1, 2, 3)

[1] 3 4 5

> 2 * c(1, 2, 3)

[1] 2 4 6
VECTORS 17
> (1:10)^2

[1] 1 4 9 16 25 36 49 64 81 100

R will still duplicate the shorter vector even if it cannot match the longer
vector with a whole number of multiples, but in this case it will produce a
warning.

> c(1,2,3) + c(1,2)

[1] 2 4 4
Warning message:
In c(1,2,3) + c(1, 2) :
longer object length is not a multiple of shorter object length

A useful set of functions that take vector arguments are sum(...), prod(...),
max(...), min(...), sqrt(...), sort(x), mean(x), and var(x). Note that
functions applied to a vector may be defined to act elementwise or may act
on the whole vector input to return a result:

> sqrt(1:6)

[1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490

> mean(1:6)

[1] 3.5

> sort(c(5,1,3,4,2))

[1] 1 2 3 4 5

2.4.1 Example: mean and variance

> x <- c(1.2, 0.9, 0.8, 1.0, 1.2)


> x.mean <- sum(x)/length(x)
> x.mean - mean(x)

[1] 0

> x.var <- sum((x - x.mean)^2)/(length(x) - 1)


> x.var - var(x)

[1] 0
18 R AS A CALCULATING ENVIRONMENT
2.4.2 Example: simple numerical integration

> dt <- 0.005


> t <- seq(0, pi/6, by = dt)
> ft <- cos(t)
> (I <- sum(ft)*dt)

[1] 0.5015487

> I - sin(pi/6)

[1] 0.001548651

In this example note that t is a vector, so ft is also a vector, where ft[i]


equals cos(t[i]).
To plot one vector against another, we use the function plot(x, y, type).
When using plot, x and y must be vectors of the same length. The optional
argument type is a graphical parameter used to control the appearance of the
plot: "p" for points (the default); "l" for lines; "o" for points over lines; etc.

2.4.3 Example: exponential limit

> x <- seq(10, 200, by = 10)


> y <- (1 + 1/x)^x
> exp(1) - y

[1] 0.124539368 0.064984123 0.043963053 0.033217990 0.026693799


[6] 0.022311689 0.019165457 0.016796888 0.014949367 0.013467999
[11] 0.012253747 0.011240338 0.010381747 0.009645015 0.009005917
[16] 0.008446252 0.007952077 0.007512533 0.007119034 0.006764706

> plot(x, y)

The output is given in Figure 2.1.

2.5 Missing data: NA

In real experiments it is often the case, for one reason or another, that cer-
tain observations are missing. Depending on the statistical analysis involved,
missing data can be ignored or invented (a process called imputation).
R represents missing observations through the data value NA. They can be
mixed in with all other kinds of data. It is easiest to think of NA values as
place holders for data that should have been there, but, for some reason, are
not. We can detect whether variables are missing values using is.na.
MISSING DATA: NA 19

2.70
2.68
2.66
y

2.64
2.62
2.60

50 100 150 200

Figure 2.1 y = (1 + 1/x)x ; output for Example 2.4.3.

> a <- NA # assign NA to variable A


> is.na(a) # is it missing?
[1] TRUE
> a <- c(11,NA,13) # now try a vector
> is.na(a) # identify missing elements
[1] FALSE TRUE FALSE
> any(is.na(a)) # are any missing?
[1] TRUE
> mean(a) # NAs can propagate
[1] NA
> mean(a, na.rm = TRUE) # NAs can be removed
[1] 12

We also mention the null object, called NULL, which is returned by some func-
tions and expressions. Note that NA and NULL are not equivalent. NA is a place-
holder for something that exists but is missing. NULL stands for something that
never existed at all.
20 R AS A CALCULATING ENVIRONMENT
2.6 Expressions and assignments

So far we have been using simple R commands without being very precise
about what is going on. In this section we cover some useful vocabulary.
In R, the term expression is used to denote a phrase of code that can be
executed. The following are examples of expressions.

> seq(10, 20, by = 3)

[1] 10 13 16 19

> 4

[1] 4

> mean(c(1,2,3))

[1] 2

> 1 > 2

[1] FALSE

If the evaluation of an expression is saved, using the <- operator, then the com-
bination is called an assignment. The following are examples of assignments.

> x1 <- seq(10, 20, by = 3)


> x2 <- 4
> x3 <- mean(c(1,2,3))
> x4 <- 1 > 2

2.7 Logical expressions

A logical expression is formed using the comparison operators <, >, <=, >=, ==
(equal to), and != (not equal to); and the logical operators & (and), | (or),
and ! (not). The order of operations can be controlled using parentheses ( ).
Two other comparison operators, && and ||, are introduced in Section 2.7.2.
The value of a logical expression is either TRUE or FALSE. The integers 1 and
0 can also be used to represent TRUE and FALSE, respectively (which is an
example of what is called coercion).
Note that A|B is TRUE if A or B or both are TRUE. If you want exclusive dis-
junction, that is either A or B is TRUE but not both, then use xor(A,B):
> c(0,0,1,1)|c(0,1,0,1)

[1] FALSE TRUE TRUE TRUE


LOGICAL EXPRESSIONS 21
> xor(c(0,0,1,1),c(0,1,0,1))
[1] FALSE TRUE TRUE FALSE

The example above also shows that logical expressions can be applied to vec-
tors to produce vectors of TRUE/FALSE values. This is particularly useful for
selecting a subvector using the indexing operation, x[subset].
One way of extracting a subvector is to provide subset as a vector of
TRUE/FALSE values, the same length as x. The result of the x[subset] com-
mand is that subvector of x for which the corresponding elements of subset
are TRUE. Importantly, the argument subset can be generated using x.
For example, suppose we wished to find all those integers between 1 and 20
that are divisible by 4.
> x <- 1:20
> x %% 4 == 0
[1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE
[12] TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE
> (y <- x[x %% 4 == 0])
[1] 4 8 12 16 20

R also provides the subset function, for choosing a subvector of x. One differ-
ence between the function subset and using the index operator is how they
handle missing values (NA). The subset function will ignore the missing index
values, whereas the x[subset] command preserves them, for example:
> x <- c(1, NA, 3, 4)
> x > 2
[1] FALSE NA TRUE TRUE
> x[x > 2]
[1] NA 3 4
> subset(x, subset = x > 2)
[1] 3 4

The preservation of missing values by the square bracket subsetting can


lead to objects being unexpectedly large. Another difference between
subset(x, subset = ?) and x[?] is that the latter accepts expressions that
resolve to integer or logical objects, whereas the former only works with logical
objects.
If you wish to know the index positions of TRUE elements of a logical vector
x, then use which(x).
> x <- c(1, 1, 2, 3, 5, 8, 13)
> which(x %% 2 == 0)
[1] 3 6
22 R AS A CALCULATING ENVIRONMENT
2.7.1 Example: rounding error

Only integers and fractions whose denominator is a power of 2 can be repre-


sented exactly with the floating point representation used for storing numbers
in digital computers (see Section 9.1 for more detail). All other numbers are
subject to rounding error. This necessary limitation has caused many heart-
aches.

> 2 * 2 == 4

[1] TRUE

> sqrt(2) * sqrt(2) == 2

[1] FALSE

The problem here is that sqrt(2) has rounding error, which is magnified
when we square it. The solution is to use the function all.equal(x, y),
which returns TRUE if the difference between x and y is smaller than some set
tolerance, based on R’s operational level of accuracy.

> all.equal(sqrt(2) * sqrt(2), 2)

[1] TRUE

We return to the issue of accuracy in Section 9.2.

2.7.2 Sequential && and ||

The logical operators && and || are sequentially evaluated versions of & and
|, respectively.
Suppose that x and y are logical expressions. To evaluate x & y, R first eval-
uates x and y, then returns TRUE if x and y are both TRUE, FALSE otherwise.
To evaluate x && y, R first evaluates x. If x is FALSE then R returns FALSE
without evaluating y. If x is TRUE then R evaluates y and returns TRUE if y is
TRUE, FALSE otherwise.
Similarly, to evaluate x || y, R only evaluates y if it has to, that is, if x is
FALSE.
Sequential evaluation of x and y is useful when y is not always well defined,
or when y takes a long time to compute. As an example of the first instance,
suppose we wish to know if x sin(1/x) = 0.

> x <- 0
> x * sin(1/x) == 0
MATRICES 23
[1] NA
Warning message:
In sin(1/x) : NaNs produced

> (x == 0) | (sin(1/x) == 0)

[1] TRUE
Warning message:
In sin(1/x) : NaNs produced

> (x == 0) || (sin(1/x) == 0)
[1] TRUE

Note that && and || only work on scalars, whereas & and | work on vectors
on an element-by-element basis.

2.8 Matrices

A matrix is created from a vector using the function matrix, which has the
form
matrix(data, nrow = 1, ncol = 1, byrow = FALSE).

Here data is a vector of length at most nrow*ncol, nrow and ncol are the
number of rows and columns, respectively (with default values of 1), and byrow
can be either TRUE or FALSE (defaults to FALSE) and indicates whether you
would like to fill the matrix up row-by-row or column-by-column, using the
elements of data. If length(data) is less than nrow*ncol (for example, the
length is 1), then data is reused as many times as is needed. This provides a
compact way of making a matrix of zeros or ones.

> (A <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE))

[,1] [,2] [,3]


[1,] 1 2 3
[2,] 4 5 6

To retrieve the dimension of a matrix use dim:

> dim(A)

[1] 2 3

To create a diagonal matrix we use diag(x). To join matrices with rows of


the same length (stacking vertically) use rbind(...). To join matrices with
columns of the same length (stacking horizontally) use cbind(...).
We refer to the elements of a matrix using two indices.
24 R AS A CALCULATING ENVIRONMENT
> A[1, 3] <- 0
> A[, 2:3]

[,1] [,2]
[1,] 2 0
[2,] 5 6

> (B <- diag(c(1, 2, 3)))

[,1] [,2] [,3]


[1,] 1 0 0
[2,] 0 2 0
[3,] 0 0 3

The usual algebraic operations, including *, act elementwise on matrices. To


perform matrix multiplication we use the operator %*%. We also have a number
of functions for using with matrices, for example nrow(x), ncol(x), det(x)
(the determinant), t(x) (the transpose), and solve(A, B), which returns x
such that A %*% x == B. If A is invertible then solve(A) returns the matrix
inverse of A.

> (A <- matrix(c(3, 5, 2, 3), nrow = 2, ncol = 2))

[,1] [,2]
[1,] 3 2
[2,] 5 3

> (B <- matrix(c(1, 1, 0, 1), nrow = 2, ncol = 2))

[,1] [,2]
[1,] 1 0
[2,] 1 1

> A %*% B

[,1] [,2]
[1,] 5 2
[2,] 8 3

> A * B

[,1] [,2]
[1,] 3 0
[2,] 5 3

> (A.inv <- solve(A))

[,1] [,2]
[1,] -3 2
[2,] 5 -3

> A %*% A.inv


MATRICES 25
[,1] [,2]
[1,] 1 -8.881784e-16
[2,] 0 1.000000e+00

> A^(-1)

[,1] [,2]
[1,] 0.3333333 0.5000000
[2,] 0.2000000 0.3333333

Observe the small error in A %*% A.inv. Numerical errors like this are the
result of having to store real numbers in a binary format, with a finite number
of bits, and are often called rounding errors (see Chapter 9).
Note that, in R, a matrix is stored as a vector with an added dimension
attribute, which gives the number of rows and columns. The matrix elements
are stored columnwise in the vector. Therefore it is possible to access the
matrix elements using a single index, as follows.

> A[2]

[1] 5

Whilst R prints out a vector x (which has no dimension attribute) as a row


vector, in matrix operations it will treat x as either a row or column vector in
an attempt to make the components conformable. Thus:

> A <- matrix(c(3, 5, 2, 3), nrow = 2, ncol = 2)


> (x <- c(1,2))

[1] 1 2

> x %*% A

[,1] [,2]
[1,] 13 8

> A %*% x

[,1]
[1,] 7
[2,] 11

However the command t(x) treats x as a column vector by default, hence


producing an array with the fixed dimension attributes of a row vector:

> A %*% t(x)

Error in A %*% t(x) : non-conformable arguments


Exploring the Variety of Random
Documents with Different Content
interests of trade, and so oppressive against the rights of the poor
man, must be a gross and flagrant violation of the law, and when the
guilt is established, must be visited by a proper measure of
punishment.” But the masters also may now be made to feel the
restraining power of the law; and at this moment one of our highest
tribunals, a Court of Error, is occupied with a question of no small
importance and difficulty, arising from an attempt of eighteen
Lancashire mill-owners to enter into a counter-combination. Their
men having combined to support each other in forcing their masters
to yield to their terms, the masters entered into a bond to each other
not to open their mills for twelve months, except on terms agreed to
by a majority; and the question was brought before the Court of
Queen’s Bench, whether such an agreement was or was not one in
restraint of trade, and consequently consistent or inconsistent with
the public good. “The Court differed,” says Mr Warren; “but the
majority held that the agreement was illegal, as unduly restraining
the freedom of trade, holding ‘that if particular masters might thus
combine, so might all the masters in the kingdom:’ and, on the other
hand, all the men in the kingdom might combine themselves into a
sort of Labour Parliament.” The case, it is understood, will not be
held settled on either side until it has been taken to the House of
Lords, and decided by the Court of last appeal in the kingdom.
The principle or object kept in view by the Legislature in framing
the present statutes seems to have been, as Chief-Justice Tindal once
observed, “that if the workmen, on the one hand, refused to work, or
the master, on the other, refused to employ, as such a state of things
could not continue long, it might fairly be expected that the party
must ultimately give way whose pretensions were not founded on
reason or justice—the masters if they offered too little, the workmen
if they demanded too much.” But, says Mr Warren, “this leaves each
party to decide on the reason and justice of its pretensions, and the
unreasonableness and injustice of those of its opponent. And it is
more likely that the Legislature said to itself,—‘It will always be a
question of time; the weakest will go to the wall first, though not till
after it has greatly hurt the stronger.’” They just left each side to do
its worst, and worry or be worried to death by its opponent, without
the State interfering so long as this work of social murder went on
peaceably!
Truly, this is sad work! And yet legislation, we fear, though it may
in some degree curb, will never reach the root of the evil. The only
cure, we feel persuaded, will be found in social, not legislative
reform. Better information on the part of the working-classes will do
something to the attainment of this most desirable end; and Mr
Warren, while paying a just tribute to the “keen mother-wit and right
honest heart” of the English working-classes, says,—

“If many years’ observation and reflection entitle me to make a


recommendation, it would be, that the working-classes would find it of the highest
value to acquire, in a general way, as they could with a little effort,—as by plain and
good lectures in this very place,—some knowledge of the circumstances which
determine the rate of wages. That is a question, in its higher and remoter branches,
of extreme difficulty; but its elementary principles are pretty well agreed upon
now, and directly touch the only capital of the poor man—his labour, and teach
him how to set a true and not a chimerical and exaggerated value on it, at times
when the keenest dispute has arisen on that very subject. Oh, what incalculable
benefits might arise from a knowledge, by the acute working-classes, of the leading
principles agreed upon by great thinkers, statesmen, and economists of every hue
of opinion, as those regulating the relation between employers and employed, and
establishing, not a conflict of interest, but an absolute identity!”

Yet it is not Ignorance, but Selfishness—that passion the most


abiding of our nature—that is the prime mover in these dire contests
between the employers and employed; and along with every effort for
the education of our working-classes, we should strive also still more
assiduously to cultivate their moral nature and make mutual charity
and forbearance more prevalent both among high and low. Very
beautifully, and no less wisely and earnestly, does Mr Warren speak
on this subject. Inculcating forbearance between master and man in
hard-times, he says:—

“Each ought honestly to place himself, for a moment, in the other’s situation—
when each might see causes in operation which he might not otherwise have seen—
trials and difficulties of which he had not dreamed. Let the master look steadily at
the position of the working man, especially in hard times, pressed down to the
earth with exhausting labour, anxiety, and galling privations endured by himself
and his family, often almost maddening him, as he feels that it is in vain for him to
rise up early, to sit up late, to eat the bread of sorrow: in moments of
despondency and despair, he feels as though the appalling language of the prophet
were sounding in his ears—Son of man, eat thy bread with quaking, and drink thy
water with trembling and with carefulness! He cannot keep himself and those
towards whom his harassed heart yearns so tenderly from the jaws of starvation,
with all his patience, economy, and sobriety; and yet he sees out of the fruit of his
labours, his employers apparently rolling in riches, and revelling in luxury and
splendour! But let that workman, on the other hand, do as he would be done by: let
his master deal with his capital, which happens to be money, as the workman with
his, which happens to be labour—‘freely.’ Let him reflect on the anxieties and
dangers to which his employer is often exposed, but dare not explain, or make
them public, lest it should injure or ruin his credit: his capital may be locked up in
machinery, or he may be otherwise unable to realise it, however desperate his
emergency, without a destructive sacrifice: great but perfectly legitimate
speculation may have failed from causes he could not foresee or control—from
accident, from fraud, or misfortune of others—from a capricious change in public
taste: he may have been running desperately, but with an honest spirit, along the
black line of bankruptcy for many months, without his workmen dreaming of it,
and yet has punctually paid their weekly wages to perhaps several or many
hundreds of them, often borrowing at heavy interest to do so, while these workmen
supposed him always the master of untold thousands! Now I say, let each party try
to think of all these things, and pause before he commits himself to a rash and
ruinous line of hostility. A strike too often partakes of the nature of a social suicide.
Capital—that is, labour and money—at war with itself, may be compared to the
madman who, in a sudden phrenzy, dashes each of his fists against the other, till
both are bleeding and disabled—perhaps for ever.... Let each party sincerely try to
respect the other; to find out and dwell on those qualities really, and to so large an
extent, entitling each to the other’s respect and sympathy. Let the master reflect on
the patience, ay the truly heroic patience, self-denial, fortitude, and energy with
which the workman endures severe trials and privations; and let the workman
reflect on the fairness and moderation, often under circumstances of serious
difficulty,—on the generosity and munificence of his master, as could be testified
by tens of thousands of grateful workmen, in seasons of sickness, suffering, and
bereavement.”

Towards the close of his elaborate lecture, Mr Warren discourses


nobly and cheerfully on the Dignity and Consolations of labour, and
glances at the monster evils of Improvidence and Intemperance by
which the daily life of the working-classes is robbed alike of its
honour and its comfort. In this part occurs a passage so striking and
so eloquent that we cannot but transfer it to our pages, and we trust
the warning and appeal which it conveys will animate all who have
the privilege of influencing the working-classes, with an enduring
desire to banish the debasing and all-abstracting passion of
intemperance from their ranks.

“I hope and believe that I must go out of this hall, to find a victim of
Intemperance! Such a man, or rather wreck of a man, is not to be found here! I
know, however, where to find him; there is another hall in which I took my seat
this morning, have sate all day, and shall be at my gloomy post again in the
morning, to see,—possibly,—standing trembling, or sullen and desperate at the bar
of justice, one whom the untiring and remorseless fiend Intemperance has dragged
thither, and stands grim but unseen beside his victim. He had been a man, might
we say, well to do in the world, and getting respected by all his neighbours, till he
took to drink, and then it was all up with him—and there he stands! disgraced, and
in despair. I need not draw on my imagination for illustrations, especially before
an audience which numbers so many men whose painful duty as jurymen it is to sit
every sessions, with myself, engaged in the administration of justice. You have seen
how often, in a moment of voluntary madness occasioned by drink, a life’s
character has been sacrificed, the brand of felon impressed on the brow, and free
labour exchanged for that which is profitless, compulsory, and ignominious to the
workman, within the walls of your prison! It would be unjust, however, not to say
that exhausting labour, and the companionship of those who are together so
exhausted, supply but too many temptations to seek the refreshment and
exhilaration afforded by liquor, and which soon degenerates, from an occasional
enjoyment, into an accursed habit. Home soon ceases to be home, to him who
returns to it under the guilty delirium of intoxication: there, weeping and starving
wife and children appear like dismal spectres flitting before his bloodshot eye and
reeling brain. As the husband frequents the dramshop, so he drives his wretched
wife the oftener to the pawn-shop, and her and his children at length to the
workhouse; or perhaps in her desperation—but I dare not proceed! The coroner
can tell the rest.
“Look at yonder desolate little room, at the end of a dreary court; a funeral goes
out from it in the morning! Enter this evening. All is silent, and a single candle on
the mantel-piece sheds a dull flickering light on a coffin, not yet screwed down.
Beside it sits morally a murderer; his bloated face is hid in his shaking hands; he
has not yet ventured to move aside the coffin lid, but at length he dares to look at
his poor victim—his broken-hearted wife! Poor, poor soul! thou art gone at last!
Gone, where the wicked cease from troubling, and the weary are at rest! ’Tis a
happy release, say the friendly neighbours, who have contributed their little means
to lay her decently in her coffin. Ay, besotted husband! let your bloodshot eyes look
on that white face, that wreck of a face so sweet and pretty when you married her!
Never fear! the eyes are closed, and will weep and look mournfully at you no more!
Touch, if you dare, those limbs, which the woman who laid them out said, with a
sigh, were mere skin and bone! Dare you take hold of her cold hand and look at her
wedding-ring? Do you see how her finger is worn with the needle? During the day,
during the night, this poor creature was your willing slave, mending your linen,
and that of your wronged children, and what was left of her own, and which are
nearly rags. Do you hear those children sobbing in the next room? Do you see the
scar on that cheek? Look and tremble. Have you forgotten the blow that caused it,
given by your hand of drunken and ruffian violence? Yet she never reproached you!
And when at length, worn away with misery, starvation, and ill-usage, she was
forced to give up the struggle for life, her last—her very last act was gently and in
silence to squeeze your unworthy hand! Perhaps remorse is now shaking your
heart, and you inwardly groan—

‘Oh, if she would but come again,


I think I’d grieve her so no more!’

She will come no more on earth, but you will have to meet her again! So, man,
close the coffin lid! Go to bed, and sleep if you can! The funeral is in the morning,
and you must follow the poor emaciated body close past your favourite dramshop!”

As befitted the audience, it is manual or mechanical labour that Mr


Warren in his essay chiefly concerns himself with. But so eminent an
author cannot be insensible to the still nobler labour of the Mind, or
to the grand and touching lives of so many of its votaries. Manual
labour may appear harder than some kinds of intellectual pursuits,
but it cannot be carried to the same excess. It is less fatal, because
less alluring. The labour of the hands does not kill like the labour of
the head. It is not the lower classes alone that work. Mr Warren well
says:—

“The working-classes! Are those not worthy of the name, and in its very highest
sense, few in number, comparatively, though they be, who by their prodigious
powers of thought make those discoveries in science which have given tenfold
efficacy and value to labour, turned it suddenly into a thousand new channels, and
conferred on all classes of society new conveniences and enjoyments? Are we to
overlook those great intellects which have devoted themselves to statesmanship, to
jurisprudence, to morals, to the science of medicine—securing and advancing the
best interests of mankind, and relieving them from physical anguish and misery;
the noble genius devoted to literature, refining, expanding, and elevating the
minds of all capable of it, and whose immortal works are glittering like stars of the
first magnitude in the hemisphere of thought and imagination? No, my friends; let
us not be so unjust, ungrateful, or unthinking; let us rather be thankful to God for
giving us men of such powers, and opportunity and inclination to use them, not for
their own reputation’s sake alone, but for our advantage; and let us not enhance
the claims of manual, by forgetting or depreciating intellectual labour. I could at
this moment give you a dozen instances within my personal knowledge, of men
whom God has given very little physical strength, but great mental endowments,
and who cheerfully undergo an amount of exhausting labour of which you have no
idea, in conducting public affairs, political and legal, and prosecuting scientific
researches, immortalising the age in which they live.”

Genius in all ages commands the spontaneous homage of


mankind. And it is only just that it should be so. “Tell me,” said an
acute observer of human affairs, “what a few leading minds are
thinking in their closets, and I will tell you what their countrymen
will be thinking in the next generation.” It is the great minds of a
country that most deeply influence its fortunes,—it is the great minds
of the world that mould the progress of our race. These men may live
a life of toil and sacrifices in the cause to which their high powers are
devoted, and may die ere the precious seed sown by them has begun
to germinate. But they do not lose their reward. The fruit comes at
last. Their words enlighten the world, hastening its progress to a
happy goal; while their example of high powers and glorious self-
devotion reaps a rich recompense by inspiriting others through
future ages to follow in their steps. As saith Longfellow,—
“Lives of great men all remind us
We can make our lives sublime,
And, departing, leave behind us,
Footprints on the sands of time:
Footprints that perchance another,
Sailing o’er life’s solemn main,
A forlorn and shipwreck’d brother,
Seeing, shall take heart again!”
TOUCHING OXFORD.
A LETTER TO PROFESSOR NEBEL.

My dear Professor!—You see that I have not forgotten the note of


admiration which your countrymen use at the beginning of letters
when they address each other. It is an easy way of giving emphasis to
the greeting, or of expressing the admiration of the writer for the
character of the person written to. When I last saw you at
Dummerjungenberg, I recollect I promised to write you down the
impressions which an intended visit to my old University might
make upon me, and I hasten to fulfil that promise now. It is
superfluous for me to tell you that the two English universities are
essentially different in their constitution from a German university,
as you are well acquainted theoretically with the constitutions of
both. I maintain that each kind is good, and answers its own end.
The German university fully answers its purpose of making men
learned, but the stamp of character which it affixes to the man is
evanescent, and does not follow him through life. According to the
language of the Bursch or German student, as soon as a man has
ceased to be a student, he falls back again, as a matter of course, into
the Philisterium, or limbo of the Philistines, which is the student’s
term to designate the uncovenanted class, which comprises all
mankind excepting the student. On the other hand, we speak of men
for the whole of life as Oxford or Cambridge men much more than
we do of them as Göttingen or Leipzig men, inferring by this mode of
expression that they have been, as it were, fed on the milk of Alma
Mater, which continues through the whole of life to affect their
constitutions in a peculiar manner. So highly do some of our men
think of this influence, that they dread too much infusion of the
Germanic element, as dangerous to this peculiar quality of our
universities of forming and stamping the whole man, instead of
merely the logical part of him. I recollect well that at a meeting of
Convocation at Oxford, when some material changes were brought
under consideration, no sentiment was more highly applauded than
one which concluded the Latin speech of a talented polemical
churchman, when he said, “Hanc Universitatem Germanizari non
volo”—“I protest against this university being Germanised;”—by
which he plainly meant, not that he objected to the widening of its
scope of teaching, but that he feared that mere instruction would
usurp too much prominence in the scheme of education, and throw
into the shade that general moral training which is now a most
essential part of the system. One of the feelings, to speak
individually, that I should be sorry to lose is that which this very
name of Alma Mater implies. The word “Almus” is one of the most
beautiful in the Latin language; it means that whose nature is to
cherish, nourish, inspire with life. Thus, Venus is called “Alma” by
the ancients, as representing the principle of life in nature; Ceres is
also called “Alma,” as being the goddess that supplies the staff of life.
If it be true, as Mr Carlyle says, that our word “lady” is derived from
two old words, meaning a giver of loaves, it would be a good
translation of the word “Alma.” And desirable it certainly is, that the
word “lady” should bear this fulness of meaning; the function of
woman, in her beautiful ideal, being to give life, to support life, and
to make life worth living. And the poet saw the matter truly, as poets
generally do the most truly, when he said—
“Woman, dear woman, in whose name,
Wife, sister, mother meet,
Thine is the heart by earliest claim,
And thine its latest beat.”

Now, to every Oxford man, his Lady Mother, or Alma Mater, in the
transcendental sense, is his university, occupying nearly as high a
place in his heart as Our Lady occupies in that of the devout Catholic.
And this much I can say from experience. As Hercules could do
nothing in wrestling against the giant Antæus, the son of the Earth,
as long as he persisted in throwing him, seeing that whenever he fell
in his mother’s lap he gained new strength, so is it with myself; the
world never throws me,—I never am cast down by circumstances, but
a thrill from the warm bosom of Alma Mater, as powerful but more
enduring than galvanism, inspires me with a new life, and I rise with
fresh courage and fresh heart to the wrestling-match of life.
I have lately visited my old University after a long absence, and
found its outward aspect fair as ever—nay, rather fairer and fresher
than ever. Changed it is undoubtedly, but changed for the better.
Much that is new and tasteful, at the same time—a rare accident in
our times—has been added, and the hand of Time has been arrested,
and that which was decayed or destroyed has been restored with
affectionate fidelity. One of the greatest improvements, to my mind,
has been effected by the railroad, which was at first greatly feared as
a revolutionary agent. It has diverted from the main thoroughfares
that brawling stream of traffic which formerly flowed through them
in the shape of stage-coaches, stage-waggons, and other properties
and accessories of the stage, and left the town to its genuine
academical character of a dignified repose. Although this change
gives to the town, in the eyes of commercial travellers, a somewhat
dead-alive appearance, and although a similar change in other places
seems to take away truly the only life they possessed, it seems, on the
contrary, to have withdrawn an unpleasant intrusion from Oxford,
and left her to the dignified retirement from the world of bustle and
action, in which she most delights.
Oxford is a town which, for its medieval beauty, deserves to be
kept under a glass-case; and nothing can be more advantageous to its
academical character, than diverting from its walls the turbid current
of commerce which belongs to this much-bepraised nineteenth
century. This the railroad has achieved most effectually. There is still
abundance of life in the streets, but life in unison with the history of
the place; and suddenly whirled as one is by the express train from
the turmoil of London to the repose of Oxford, with its lines of
venerable colleges, and troops of sombre but graceful gowned
figures, one experiences a feeling as of having been transported in a
trance on the carpet of the Arabian Nights from one place to another.
Never did the High Street appear so broad or so beautiful as now that
its area is uninvaded by the rattle of vulgar vehicles. The time to see
it to perfection is when the sun happens to set behind the opening at
Carfax Church, dazzling the eye at its focus, and forcing shafts of
amber light out along the fronts of St Mary’s and All Saint’s
churches, and the fantastic façade of Queen’s College. This is a
condition which presents one of the finest town-views in the world
that can be seen where there are no mountains in the case. There is
much similarity between Oxford and the grand old Flemish towns;
and the railway has been a boon to them, as it has been to her, in
preserving their quiet character. Unlike other English towns, the
inhabitants of which point with an ignorant pride to the substitution
of stucco-fronted houses, and cockney plate-glass, for the cross-
beamed gables and lattices, all the architectural changes which have
taken place of late years in Oxford appear to have been for the better.
One is certainly sorry to see the time-corroded and weather-beaten
stone disappearing from the faces of the colleges, and new freestone
appearing in its place; but this change, though one that we may sigh
over as even over the seasonal changes of nature, is, in reality, of a
conservative character, and its absolute necessity is an unanswerable
plea. The nature of the stone of which most of the colleges are built
being such as to peculiarly expose it to wear and tear of weather, we
are not sorry to see it replaced by a material which looks durable in
its novelty, and to many generations yet to come will become more
beautiful with age. No expense has been spared in these reparations;
and the stranger will be peculiarly struck with the manner in which
they have been carried out in many of the principal buildings. In
Oxford alone, of all the towns in England, domestic architecture
appears properly subordinate to that devoted to public purposes; and
as she grows in beauty with each addition, her inhabitants may be
one day allowed to boast as the Romans of the olden time,
“Privatus illis census erat brevis,
Commune magnum,”

for the splendour of her public buildings will quickly dwarf the most
ambitious attempts of private proprietors; and one good result of the
communal, or, as a Cantab would rather say, combinational life of
Oxford, is the prospect that things will be achieved there by bodies of
men imbued with the “genius loci,” which would surpass the
aspiration, taste, or indeed ability of most individuals to accomplish
elsewhere. So should it ever be. What can the use be of any
individual, whose establishment does not assume palatial
proportions, pluming himself on the possession of architectural
decorations, or masterpieces of painting or sculpture, which, added
to a public gallery, would give delight and instruction to thousands,
instead of administering to the pleasures of a few? I do not know
whether you have ever visited Oxford. If you have, I may remind you,
though unnecessarily, that, besides the world-renowned High Street,
there are two other streets in it not less characteristic—one the Broad
Street, parallel with it for a part of its length; and the other St Giles’s,
a continuation of the Corn Market, running at right angles to the
High Street from Oxford Cross. The Broad Street is one of those
areas reminding us of Continental cities, where the population might
be mustered in arms if necessary. It was in the middle of this that
Cranmer, Ridley, and Latimer were martyred; and at its junction
with St Giles’s is now set up an elegant Gothic monument, something
in the manner of Sir Walter Scott’s at Edinburgh, to perpetuate the
memory of that event. St Giles’s is a most remarkable street. It has a
church at its commencement and near its end, where it branches into
two roads. It is so spacious that the houses on each side, irregularly
built as they are, and ought to be, appear diminutive; and between
the houses and the central road, on each side, is a row of trees, which
gives it the appearance of a boulevard. On entering it, you have on
the right the new buildings of Baliol, and farther on, the more
ancient face of St John’s College; facing which are the new Taylor
Buildings—a structure with which much fault has been found, as a
weak centre on the side towards Beaumont Street appears to carry
two heavy wings, but which must be allowed on all hands to conduce
greatly to the adorning of its site, and indeed of the town generally. It
is in this street that fountains, judiciously placed, would add much to
the general effect; but many may doubt whether fountains would
ever have other than an unnatural and artificial aspect in England,
where the wetness of the atmosphere renders drier objects
pleasanter to look upon. There are two seasons of the year when
fountains are especially agreeable—in the summer heats, when it is
delightful to be within reach of their spray; and in frost, when they
are draped with pendulous icicles of the most fantastic beauty—a
phenomenon I have indeed seen on the little fountain in the Botanic
Garden at Oxford. Both these seasons are generally with us of short
duration, and during all the rest, fountains to many would be
somewhat of an eyesore, and create a shivering sensation. Those in
Trafalgar Square count as nothing. As for the Crystal Palace and
Versailles fountains, and all of the same description, people delight
in them more for their mechanical cleverness than their artistic
effect, and they are things got up for holiday occasions, not meant to
form parts of the scenes of everyday life, like the fountains of Italy, or
the gossip-haunted Brunnen of Germany. I fear then that, for the
present, Oxford must be contented with her rivers, and not babble of
fountains. She is one of the few large towns singularly blest with the
presence of ever-flowing and ever-living water. The Isis runs beside
her, covered with a fleet of pleasure-boats, probably as large as that
of Athens during the Peloponnesian war, to which it has been wittily
compared, and in the summer days, swarming in and out amongst
each other like the gondolas of Venice. The Cherwell, which is a river
as large as the famed Cam, or nearly so, encircles the meadows of
Christchurch and Magdalen, and, with its sinuous course, and banks
overshadowed with trees, presents numberless nooks of beauty, and
spots of refuge from the heats of summer. The avenue in
Christchurch meadow is second to none in the world, perhaps
superior to all, though there are many like it; for instance, the avenue
at Cambridge, which was compared by Porson to a college fellowship,
as a long dreary vista with a church at the end of it; the avenue by the
Severn, in the Quarries at Shrewsbury: that of the University of
Bonn, and others at royal residences, and near places of academic
retirement. In connection with this avenue, it is well to mention that
there is a time-honoured custom prevalent in the University, of
making it a general promenade on the Sunday in Commemoration-
week, which generally occurs towards the end of the leafy month of
June. On that day, most of the members of the University are to be
seen in their distinctive dresses; and those are considered happy who
are accompanied with friends, called, from their object in visiting the
University, “lions and lionesses;” nor is the wealth and beauty of the
city unrepresented. From this custom arises the name of “Show
Sunday.”
The rivers afford an inexhaustible source of amusement, at a cheap
and easy rate, to the gownsmen, who luxuriate in all sorts of boats,
according to their activity or laziness—the energetic eight-oar, the
social four-oar, the friendly pair-oar, the fantastic canoe, the
adventurous outrigger-skiff, the dreamy sailing-boat, and the sleepy
punt, the latter having come into fashion chiefly of late years, and in
the hot season, and being a method of amusement which, at the price
of the violent exertion of one of the party, purchases the perfect
repose of the rest, who lie on their backs in boating-dresses, cigar in
mouth, and the last work of Dickens or Thackeray, chosen for its
lightness, in hand, and watch over the sides the swimmings of their
Skye terriers. This peculiar dog, distinguished from all others by its
sagacity, fidelity, and an ugliness which has worn into beauty, is now
quite a part of the University system; yet I remember when the first
was introduced into Oxford, and considered so remarkable that he
gave his master the name among the townsmen of the “gentleman
what belongs to the dog.” The poor little fellow had to suffer much
for his resemblance to a door-mat, before his position was fully
recognised.
Next in importance to the colleges and rivers of Oxford are the
gardens. With the latter we must include the college-meadows, which
are composed of a real meadow in the centre, surrounded by a
planted gravel-walk, bounded generally, on the outer side, by one of
the rivers. These gardens, though private, are liberally opened by the
college authorities to the public, and, occupying a large part of the
area of the town, they invite the residents to a number of short walks
and lounges, the temptation to which in other towns is generally
wanting, but which must be most conducive to health. In some of
them—as in St John’s—the members of the college amuse themselves
with archery, in others with bowls—a truly after-dinner recreation;
while in the park that is attached to the grounds of Magdalen College
the eye is gladdened by the sight of a number of browsing deer, who
become singularly tame in consequence of the attentions of the
Fellows. Well might Macaulay call it “their pleasant abode” of
Magdalen! Magdalen is now rendered even more pleasant to some
minds by the choral service of the Church of England having been
brought to perfection in its chapel, so that its members can never
attend Divine service without their ears being charmed by the most
exquisite music. Others may be of opinion that the service solemnly
read produces an effect which is appreciable by all rather than by a
few of peculiar temperament. I do not take upon myself to strike the
balance. In two other colleges is the service sung instead of being
said—namely, in St John’s and New Colleges, and these three
colleges are naturally a source of great attraction to strangers—so
much so, that the chapels being of limited dimensions, admission to
them has of necessity been made a favour. In the chapels at Oxford,
customs have been perpetuated from time immemorial, which would
shock rigid Protestantism, unless inured to them by habitual contact
—such as the lighting of candles on the altar, and painted altar-
pieces, instead of the Commandments-table which is usual in
Anglican churches. Be this as it may, the attendance at morning
chapel, which is enforced on the junior members, and sometimes
considered by them a grievance, becomes in time so much a habit
that they feel the want of it when they become parochial clergymen,
and in many cases endeavour to perpetuate it by daily services
(having certainly the letter of the law of their Church on their side),
with considerable success indeed in some town parishes, and among
the richer classes; but with doubtful result in the rural districts,
where the peculiar habits of the labouring poor scarcely seem to
allow them to fall in with it to any great extent.
While on the subject of Oxford, you naturally wish me to say what
I think generally of the system of education of the place. I will tell
you, then, in short, that I consider it the best possible system of
education to form the character of a man and a gentleman. Do you
ask me why? I answer that it is so for this simple reason—that it
tends to develop in the fairest manner all the various energies of that
many-sided creature, Man. There are two sorts of education at
Oxford, as at our public schools—one enforced by law, the other
dependent on social customs: both have their full sway at Oxford.
Thus we have a practical illustration of the strongest kind of the
Platonic theory of education. Plato very properly thought that the
development of the bodily powers was almost of as much
consequence as that of the mental, and accordingly enjoined that
education in his Utopia should consist of music and gymnastics. By
music he understood all that falls into the province of either of the
nine Muses. By gymnastics he understood not a dreary tugging at
ropes, and hugging of bars, and climbing ladders with hands, but a
simultaneous exercise of mind and body in pastimes where the body
is deceived by the mind into activity, and cheated into wholesome
weariness—such as contests of strength and passages of arms,
hunting, fowling, and the like. Even so at Oxford physical education
is complete; and although it does not form a subject of examination
in the schools under the new system, it is carried perhaps to greater
perfection than any other kind, and therefore we may conclude that
the Royal Commission does well to leave it where it stands. These
Oxford gymnastics (using the word always in its special and Platonic
sense) are for the greater part perfectly consistent with the “musical”
part of the system which emanates from authority. Occasionally,
however, those sports, which, as a Catholic founder of one of the
colleges said, “miram atque incredibilem delectationem afferunt”
(showing that the old boy himself, though he wished to see his
seminary like a bee-hive, thoroughly appreciated them), interfere
with the hours devoted to study; and therefore fox-hunting, which I
especially allude to, is generally discouraged by the Dons even in the
case of those students who are able to afford it. The delicious
languor, so unlike the rude and partial fatigue resulting from any
other exercise, which pervades the whole system after a good day’s
riding, and gives a Parisian savour to the plainest dinner, is of course
fatal for the rest of the day to any other intellectual work; for who
shall deny that hunting is intellectual work?—intellectual for the
hounds, who have the sagest of beasts to outwit—intellectual for the
horses, who have the safest footing to choose in a moment of time,
and the exactest distances to measure; intellectual for the rider, who
requires the eye of an eagle and the judgment of a Solon to know
where he ought to be, not to mention the huntsman and M. H.,
whose whole lives, if they take deep interest in the matter, as they
generally do, must be spent in intense thought? An excellent exercise
it is of mind, undoubtedly, but fatal to other exercises of a less
absorbing character, and therefore consistently discouraged by the
Dons. The same may be said of driving. Driving is at best but a lazy
exercise; and though it requires skill, it is not sufficiently gymnastic;
besides, it is expensive, and presents no advantage corresponding to
the expense. But we cannot help thinking that if the thunders of each
university Zeus had been less lavishly launched against tandem-
driving in particular, this antiquated practice, very good in peculiar
countries, but generally merely a puppyish display, would have died
out of itself. There is always a peculiar sweetness to young minds in
forbidden pleasures.
But boating and cricket and football, tennis, rackets, fives, and
billiards, still please, although there is nothing illegitimate about
them, and are perfectly consistent with the earnest pursuits of the
place. With regard to billiards, I must just observe that this
fascinating game has in a great measure lost its reputation, from the
fact that the billiard-room is in most English towns the rendezvous of
all the blackguardism of the place; but in Oxford the billiard-rooms
are private, and engaged by each party of players; they are an
especial refuge on wet days, nor can I see any exception that can be
taken to the pastime, save when it degenerates into the public pool,
becomes a species of gambling, and loses its real character, which is
that of a game of skill, quite as much as that of chess, combined with
gentle exercise. As there is not the slightest danger of the studies I
have mentioned falling into desuetude, so have they been with good
judgment overlooked by the University authorities, and as they
present in every phase an examination of themselves, it has not been
found necessary to create any special honours as a reward for
proficiency in them. The universal existence of this gymnastic
education in Oxford, superadded to a peculiar keenness and
dampness in the air, induces an appetite which can only be satisfied
by what appears to strangers an unusual amount of eating and
drinking. In the latter particular there is indeed a great
improvement. Excess in quantity is extremely rare even among
extravagant students; but the fiery wines of Portugal and Spain still
hold their ground against all comers, and public opinion is decidedly
in their favour—so much so, that others are treated with a sort of
contempt. It is said that on the occasion of the visit of a great
personage to the sister University, whose habits bear a strong
resemblance to those of Oxford, when the servants of that personage
sent a complaint to the entertainer,—a Head of a House,—that they
were only supplied with port when they were used to claret, he sent
back a message to them that the college port, with a due admixture of
pump-water, would make the best claret in the world. The
substantial nature of an Oxford breakfast, enough of itself to convert
Bishop Berkeley to a belief in the existence of Matter, is in itself an
evidence that the potations of the preceding night have seldom been
immoderate. With regard to that part of the education of the place, to
the furtherance of which its gymnastics and good fare are supposed
only to administer, it is truly “musical” in the Greek sense of the
word. Of music, as we understand it, there is certainly little as yet
enjoined; but every encouragement is given to its culture by chanted
services in certain chapels, by a liberal allowance of concerts
sanctioned by authority, by doctor’s degrees conferred in it, with a
most splendid gown worthy of Apollo himself if he ever wore one; by
especially the Grand Commemoration festival, at which the first
public singers are often engaged. On the whole, there is a great taste
in Oxford for this beautiful art, which requires little forcing, for it
grows of itself in the climate of the place. This taste is especially
shown by the liberality with which brass-bands playing your national
airs are remunerated; but important as it is, it is sometimes found to
interfere with the soundless but sounder elements of education, and
therefore it becomes necessary in certain cases to check it. The rooms
of the men have in general such thin partitions, that the noise of one
seriously interferes with the silence of another. I once knew a reading
man in —— College, who was placed between two pianofortes, one
overhead, and the other underfoot: he especially complained of the
interruption on Sundays, as on that day his more celestial neighbour
played sacred tunes, while his neighbour of the nether world played
profane, producing a discord in mid-air as ludicrous as painful to an
ear of taste. But I take it that the sense in which music is used in old
scholastic Latin, is in general the Platonic sense, and thus the Music
school at Oxford means one not especially devoted to exercises in
what we call music, but to exercises on examination in belles lettres.
That this term has acquired a broader significance by the recent
changes in the Oxford University system, I cannot but think a subject
for congratulation. When the University departed as a general
principle from the practice of making verse-writing in the dead
languages the mainspring of erudition in them—a practice still far
from obsolete in the public schools of England—it became necessary,
if only to take up the time of the students, and prevent them from
lapsing into intellectual inanition, to supply them with other food
congenial to the spirit of the place. The germ of these new studies
had existed before, and only required development. There could be
no better foundation for culture in modern history and jurisprudence
than the exact study of the ancient historians of Greece and Rome
pursued under the old system. Even so with mathematics. The
modern examinations are, for the most part, mere distributions of
the former work, and by getting part of it over sooner, the student is
less puzzled as to the disposal of his time. But the paucity of
candidates for mathematical honours, in comparison with those who
cling to belles lettres, is a sign that the exact sciences are still exotics
in the atmosphere of Oxford; and as long as the spirit of the place
remains what it is, they are scarcely likely to become otherwise. Nor
are the physical sciences apparently likely to acquire soon a hold on
the popular feeling of the University. Still, as before, the pivot around
which Oxford studies revolve is formed by the solid metal of the
ancient classical authors, whose words are picturesque and
statuesque, and fraught with the same eternal beauty, the same
adaptability as models for all time, as the things that the hands of
their contemporaries produced. Although as yet no school of modern
languages has been formed in which examination in them forms a
part of the University system, yet every encouragement has been
given to the study of them by the foundation of a professorship
supported by public teacherships; and even if nothing more is done,
there is every reason to think that, supported as it is by the
cosmopolitan position which our country has taken of late years, this
important branch of literature will sufficiently nourish in Oxford.
So far it appears that the changes which have been made in the
constitution of Oxford have been of a conservative character—the
reforms have destroyed nothing, but developed a great deal that
formerly lay dormant in the University system. They will continue to
be of this character if the University is allowed abundance of light
and air and space to put forth its own energies, and not damaged by
injudicious meddling from without. There have been rumours of
further changes, some of which are apparently called for by the
necessities of the time, while others have merely been engendered by
the inventiveness of the spirit of innovation. One peculiarly delicate
subject has been brought on the tapis, which, although I hold an
opinion of my own respecting it, I should prefer stating in the
position of one balancing two conflicting views, as far as my
prejudice admits. I mean the celibacy of the Fellows. In the first
place, if it is true that women are like a church, because there is no
living without them, a proposition I heard the other day in the form
of a riddle, the business is settled at once, because it is cruelty to
condemn any body of men to a living grave; but, on the other hand, if
the men themselves acquiesce in this social burial, and refuse to be
delivered from it, they have undeniably a voice in the matter, even
though it be from the catacombs, and ought to be heard in a manner
so nearly and dearly affecting their own interests. The defenders of
the present system have a great advantage in being able to raise a
laugh against those who from within advocate a change, alleging that
they have some gentle reasons for doing so. We are a nation
peculiarly sensitive to being placed in a ridiculous position, and it
requires no small amount of moral courage for any man who is a
member of a body to start opinions which the rest, though they may
in their hearts sympathise with, are not immediately prepared to fall
in with. It must be allowed that the outcry against collegiate celibacy
has been louder outside than inside the walls of common rooms. It
may be said, on the other side, that the voices of those without are
not stifled by the fear of snubbing and ridicule as those within are,
and that those who see the effect of a system on others are better
qualified to judge than those whose own minds are biassed by its
pressure. Those who work in mines and live in unwholesome air only
feel by diminished energy the evil effects of the miasma they have to
breathe, while those who live apart from them see it in their pale and
haggard looks. It is not the bondsman in general who calls for
emancipation so loudly as the spectator who has tasted the sweets of
freedom. To come to a practical aspect of the question; it is urged by
the advocates of emancipation that celibacy was part of the religious
system under which the colleges were founded, and that as that
religious system has ceased to exist in reference to them, there is no
object in keeping up a restriction which can have no such motive;
and to those who would urge that the intentions of the founders
ought to be consulted as that of any testator ought to be, it is
answered that it is hypocrisy to pretend to consult the wills of
founders in a matter which is merely a corollary to a rule which has
been essentially broken through, and that the wills of founders are
even in this instance nullified by the marriage of heads of colleges,
who being of necessity priests by the statutes under the papal regime,
would render such a prohibition in their cases superfluous. Again,
those who are for continuing the celibacy system urge that a
fellowship is intended only as a stepping-stone to a permanent
provision in the view of the world, and that to allow the marriage of
Fellows would render the succession so slow as to destroy the
practical value of the foundations. To this is opposed the statement
that in fact men are well content to settle down on a fellowship,
which is indeed a premium on indolence, and that they acquire, even
if industrious, habits of expense, which make them loth to part with a
large proportion of their incomes without grave cause, so that in fact
many men do continue Fellows until late in life, when they care
naturally less about marriage; and moreover, that the slowness of
succession might equally be urged in the case of livings which only
become vacant by death, and that for the same reason it would be
equally reasonable to enforce the celibacy of bishops were they not
expressly commanded to be husbands, as some interpret Scripture;
yet more, the fellowship might be made tenable for a certain number
of years only, and superannuation might not entail, as it does now,
the loss of the chance of college patronage to livings. Some satirical
writers have drawn a humorous picture of the condition of colleges
with sets of rooms inhabited by family Fellows, the quadrangles
turned into play-grounds, and the sacred grass-plots invaded by
nursemaids with their charges, still further presuming to imagine
intestine feuds between jealous fellowinnen (as you Germans would
call them), which they think would be incompatible with the feeling
of collegiate brotherhood or sisterhood. To this it may be answered,
that, as it is, the majority of Fellows reside in the country, and are
otherwise occupied than with collegiate duties, and there would be
less inducement than formerly for the plural Fellow to content
himself with the limited accommodation of a college; and it would be
easy to make a rule that a certain number of the Fellows,—that is to
say, of the younger, should reside to undertake the offices; and even
if they were married, those offices should only continue so long as to
incur no danger of their inundating the quadrangles with urchins.
The worst of it is, that the Oxford education has a peculiar tendency
to develop the poetical and artistic temperament; and to men of this
temperament, who are, in all countries, in a much larger proportion
to others than is generally thought, the long vista of celibacy is little
else than a long perspective of purgatory. To all who love the
beautiful, whether saints or sinners, there is one central point round
which all their thoughts revolve—one standard by which all their
comparisons are made,—and that is none other than woman. The
musical mind is drawn to her through the symphonies of Mozart or
Handel—through the complicated opera strain, and the simple
national air—
“The soul of love and bravery;”

for even the hero-songs of war, by arousing the manliness of man,


suggest the loveliness of woman. The artistic mind is drawn to her
through all the schools of painting—through even the sumptuous
Madonnas which the sacred painters have imagined, as through the
sun-warm but less heavenly creations of Titian or Correggio. It is
impossible for the artistic eye to look at the symmetry of a tree or the

You might also like