Full Download Introduction to Scientific Programming and Simulation Using R 2nd Edition Owen Jones PDF DOCX
Full Download Introduction to Scientific Programming and Simulation Using R 2nd Edition Owen Jones PDF DOCX
com
https://ebookfinal.com/download/introduction-to-scientific-
programming-and-simulation-using-r-2nd-edition-owen-jones/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookfinal.com/download/introduction-to-the-simulation-of-
dynamics-using-simulink-1st-edition-michael-a-gray/
ebookfinal.com
https://ebookfinal.com/download/an-introduction-to-programming-with-
mathematica-3rd-edition-paul-r-wellin/
ebookfinal.com
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
https://ebookfinal.com/download/analyzing-linguistic-data-a-practical-
introduction-to-statistics-using-r-1st-edition-r-h-baayen/
ebookfinal.com
https://ebookfinal.com/download/an-introduction-to-stata-
programming-2nd-edition-christopher-f-baum/
ebookfinal.com
https://ebookfinal.com/download/engineering-materials-2-third-edition-
an-introduction-to-microstructures-processing-and-design-d-r-h-jones/
ebookfinal.com
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
Series Editors
John M. Chambers Torsten Hothorn
Department of Statistics Division of Biostatistics
Stanford University University of Zurich
Stanford, California, USA Switzerland
Customer and Business Analytics: Applied Data Mining for Business Decision
Making Using R, Daniel S. Putler and Robert E. Krider
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
Robert Maillardet
Andrew Robinson
Contents
Preface xvii
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
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
14 Probability 271
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
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 II: Thinking about mathematics from a numerical point of view: applying
Part I concepts to root finding and numerical integration. Chapters 9–11.
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
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
1.2 Starting R
>
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.
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"
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
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")
> 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.
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.
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:
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.
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()
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
> (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
[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.
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
[1] 1 2 3 4 5 6 7 8 9
[1] 9 7 5 3 1
> x <- 9
> seq(1, x, x/3)
[1] 1 4 7
[1] 1 3 5 7 9 11 13 15 17 19
[1] 3 3 3 3
[1] 3 3 3 3 1 3 5 7 9 11 13 15 17 19
[1] 100 101 102 103 104 105 106 107 108 109 110
[1] 1000 101 102 103 104 105 106 107 108 109 110
[1] 0
Algebraic operations on vectors act on each element separately, that is, ele-
mentwise.
[1] 4 10 18
> x + y
[1] 5 7 9
> y^x
[1] 4 25 216
[1] 2 4 4 6
[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.
[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)
> mean(1:6)
[1] 3.5
> sort(c(5,1,3,4,2))
[1] 1 2 3 4 5
[1] 0
[1] 0
18 R AS A CALCULATING ENVIRONMENT
2.4.2 Example: simple numerical integration
[1] 0.5015487
> I - sin(pi/6)
[1] 0.001548651
> plot(x, y)
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
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.
[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.
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)
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
> 2 * 2 == 4
[1] TRUE
[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.
[1] TRUE
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.
> dim(A)
[1] 2 3
[,1] [,2]
[1,] 2 0
[2,] 5 6
[,1] [,2]
[1,] 3 2
[2,] 5 3
[,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
[,1] [,2]
[1,] -3 2
[2,] 5 -3
> 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
[1] 1 2
> x %*% A
[,1] [,2]
[1,] 13 8
> A %*% x
[,1]
[1,] 7
[2,] 11
“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.”
“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—
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!”
“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.”
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;”