Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

R Programming and Its Applications in

Financial Mathematics 1st Edition


Shuichi Ohsaki
Visit to download the full and correct content document:
https://textbookfull.com/product/r-programming-and-its-applications-in-financial-mathe
matics-1st-edition-shuichi-ohsaki/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Mixed Integer Nonlinear Programming the Ima Volumes In


Mathematics And Its Applications 2012th Edition
Leyffer

https://textbookfull.com/product/mixed-integer-nonlinear-
programming-the-ima-volumes-in-mathematics-and-its-
applications-2012th-edition-leyffer/

Discrete Mathematics and Its Applications 8th Edition


Rosen

https://textbookfull.com/product/discrete-mathematics-and-its-
applications-8th-edition-rosen/

Proof Complexity Encyclopedia of Mathematics and its


Applications 1st Edition Jan Krají■ek

https://textbookfull.com/product/proof-complexity-encyclopedia-
of-mathematics-and-its-applications-1st-edition-jan-krajicek/

Bubbles and Contagion in Financial Markets, Volume 2:


Models and Mathematics 1st Edition Eva R. Porras
(Auth.)

https://textbookfull.com/product/bubbles-and-contagion-in-
financial-markets-volume-2-models-and-mathematics-1st-edition-
eva-r-porras-auth/
Fractional Calculus in Medical and Health Science
(Mathematics and its Applications) 1st Edition Devendra
Kumar (Editor)

https://textbookfull.com/product/fractional-calculus-in-medical-
and-health-science-mathematics-and-its-applications-1st-edition-
devendra-kumar-editor/

Mathematical Methods in Engineering and Applied


Sciences (Mathematics and its Applications) 1st Edition
Hemen Dutta (Editor)

https://textbookfull.com/product/mathematical-methods-in-
engineering-and-applied-sciences-mathematics-and-its-
applications-1st-edition-hemen-dutta-editor/

Crossing Numbers of Graphs (Discrete Mathematics and


Its Applications) 1st Edition Marcus Schaefer

https://textbookfull.com/product/crossing-numbers-of-graphs-
discrete-mathematics-and-its-applications-1st-edition-marcus-
schaefer/

Solid State Chemistry and its Applications Student


Edition Anthony R. West

https://textbookfull.com/product/solid-state-chemistry-and-its-
applications-student-edition-anthony-r-west/

Linear Programming Using MATLAB Springer Optimization


and Its Applications 127 Ploskas

https://textbookfull.com/product/linear-programming-using-matlab-
springer-optimization-and-its-applications-127-ploskas/
R Programming and Its
Applications in Financial
Mathematics
R Programming and Its
Applications in Financial
Mathematics

Shuichi Ohsaki
Chief Japan Rates Strategist, American Investment Bank, Tokyo, Japan

Jori Ruppert-Felsot
Equity Derivatives Trader, Tokyo, Japan

Daisuke Yoshikawa
Hokkai-Gakuen University, Sapporo, Hokkaido, Japan

p,
p,
A SCIENCE PUBLISHERS BOOK
A SCIENCE PUBLISHERS BOOK
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742

© 2017 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

Printed on acid-free paper


Version Date: 20170119

International Standard Book Number-13: 978-1-4987-4799-8 (Hardback)

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
CRC so we may rectify in any future reprint.
Press
Taylor & Francis Group
Except as
6000 Broken permitted under U.S.
Sound Parkway NW, Copyright
Suite 300Law, no part of this book may be reprinted, reproduced, transmitted,
or
Bocautilized
Raton,inFLany form by any electronic, mechanical, or other means, now known or hereafter invented, includ-
33487-2742
ing photocopying, microfilming, and recording, or in any information storage or retrieval system, without written
permission
© 2017 from the
2018 by Taylor publishers.
& Francis Group, LLC
CRC Press is an imprint of Taylor & Francis Group, an Informa business
For permission to photocopy or use material electronically from this work, please access www.copyright.com
(http://www.copyright.com/)
No or contactworks
claim to original U.S. Government the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers,
MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety
Printed
of users.on acid-free
For paper that have been granted a photocopy license by the CCC, a separate system of payment
organizations
Version
has beenDate: 20170119
20180104
arranged.

Trademark Notice:
International Standard Book Number-13:
Product or corporate 978-1-4987-6609-8
978-1-4987-4799-8 (Hardback)
names may be trademarks or registered trademarks, and are used only for
identification and explanation without intent to infringe.
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
Library of Congress Cataloging‑in‑Publication Data
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
Names: Liu, Jian (Chemical engineer), editor. | Jiang, San Ping, editor.
publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let
Title: Mesoporous materials for advanced energy storage and conversion
us know so we may rectify in any future reprint.
technologies / editors, Jian Liu, Department of Chemical Engineering,
Faculty of Science and Engineering, Curtin University, Perth, WA,
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted,
Australia, San Ping Jiang, Fuels and Energy Technology Institute &
or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, includ-
Department of Chemical Engineering, Curtin University, Perth, WA,
ing photocopying, microfilming, and recording, or in any information storage or retrieval system, without written
Australia.
permission from the publishers.
Description: Boca Raton, FL : CRC Press, Taylor & Francis Group, 2017. |
Series: A
For permission toscience publishers
photocopy or usebook | Includes
material bibliographical
electronically references
from this work, please access www.copyright.com
and index.
(http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers,
Identifiers: LCCN 2016042509| ISBN 9781498747998 (hardback
MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides : alk.licenses
paper) and
| registration for a variety
ISBN
of users. For 9781498748018
organizations that(e-book)
have been granted a photocopy license by the CCC, a separate system of payment
Subjects:
has been arranged. LCSH: Electric batteries--Materials. | Fuel cells--Materials. |
Solar cells--Materials. | Mesoporous materials.
Trademark Classification: LCC or
Notice: Product TK2901 .M47
corporate 2017 may
names | DDCbe 621.31/24240284--dc23
trademarks or registered trademarks, and are used only for
LC record
identification available atwithout
and explanation https://lccn.loc.gov/2016042509
intent to infringe.

Visit the Taylor & Francis Web Library


site atof Congress Cataloging‑in‑Publication Data
http://www.taylorandfrancis.com
Names: Liu, Jian (Chemical engineer), editor. | Jiang, San Ping, editor.
and the CRC
Title:Press Web sitematerials
Mesoporous at for advanced energy storage and conversion
http://www.crcpress.com
technologies / editors, Jian Liu, Department of Chemical Engineering,
Faculty of Science and Engineering, Curtin University, Perth, WA,
Australia, San Ping Jiang, Fuels and Energy Technology Institute &
Department of Chemical Engineering, Curtin University, Perth, WA,
Australia.
Description: Boca Raton, FL : CRC Press, Taylor & Francis Group, 2017. |
Series: A science publishers book | Includes bibliographical references
and index.
Identifiers: LCCN 2016042509| ISBN 9781498747998 (hardback : alk. paper) |
ISBN 9781498748018 (e-book)
Subjects: LCSH: Electric batteries--Materials. | Fuel cells--Materials. |
Solar cells--Materials. | Mesoporous materials.
Classification: LCC TK2901 .M47 2017 | DDC 621.31/24240284--dc23
LC record available at https://lccn.loc.gov/2016042509
Preface

The importance of having basic knowledge of computational methods continues


to increase for those working in the financial services industry. Computational
finance theory has developed along with advancements in computing technology.
The objective of this book is therefore to present an introduction to the various
computing methods used in the financial service industry, via the R programming
language. This book is intended for graduate students who are interested in
computational finance, junior bankers, economists and traders working in the
finance industry.
We have several reasons why R has been used, rather than other available
languages; e.g., C++, C#, Java, Python, EXCEL VBA, and MatLab, etc. First, R
is available free and is an open source programming language. As such it is easily
extensible through the addition of packages and has a large and active community
of R users. And as a high-level scripting language, it is very easy to set up and to
use. Second, R was developed for statistical computation and thus comes equipped
with various packages which enable us to do regression analysis and statistical
tests, etc. This reduces the time and effort required for implementation of many
statistical methods and allows us to execute numerical experiments easily. Third,
R comes equipped with a graphic capability to visualize large sets of data and the
results of analysis. This is an attractive feature, particularly if we want to produce
high-quality graphics for publication. Further, the basics that we learn here with
R, are easily applicable to other languages, because many languages, like C# and
Python have similar coding logic, albeit different syntax.
We expect readers to write and execute the sample code introduced in this
book. Following the sample code will help the readers’ understanding of the
theory and improve their facility with R. Of course, incomplete understanding
of theory may lead to codes which do not work well. However, the process of
correcting an incomplete code is an important step in understanding the theory
and improving one’s coding technique.
We focus on two major aspects of computational finance theory: (1) statistical
analysis of financial data, and (2) the valuation of financial instruments. We have
vi < R Programming and Its Applications in Financial Mathematics

divided the book into some parts. Section I of this book is devoted to statistical
and time-series analysis, Section II covers the finance theory for the valuation of
financial instruments and we focus on numerical methods for derivative pricing
in Section III.
This book was first published in Japanese, derived from sets of lectures given
by the authors Ohsaki and Yoshikawa at the Graduate School of Management,
Kyoto University in the Spring terms of 2008, 2009 and 2010. The lectures formed
the basis of Section II and III, while Chapter 1 and Section I were written for the
publication of the Japanese version of the book. Section 3.4.3 and Appendix B
were added for the current English version of the book.
We would like to thank the publishers, especially, the editor Vijay Primlani for
his understanding and patience and Tetsuya Ishii who is the editor of the Japanese
version for his understanding regarding the publication of the English version.
We also thank Toshifumi Ikemori, Hideki Iwaki, Yoshihiko Uchida, and Zensho
Yoshida for their helpful advice and support in completing this manuscript.
Shuichi Ohsaki
Jori Ruppert-Felsot
Daisuke Yoshikawa
Contents

Preface v

1 Introduction to R Programming 1
1.1 Installation of R 2
1.2 Operators 6
1.3 Data structure 7
1.3.1 Scalar 9
1.3.2 Vector 11
1.3.3 Matrix 14
1.3.4 List 17
1.3.5 Data frame 20
1.3.6 Factor 21
1.3.7 Investigation of types and structures of data 22
1.4 Functions 22
1.5 Control statements 24
1.5.1 if statement 25
1.5.2 Iterative processing: for statement, while statement 27
1.6 Graphics 29
1.7 Reading and writing data 33
1.8 Reading program 34
1.9 Packages 36

SECTION I: STATISTICS IN FINANCE

2 Statistical Analysis with R 41


2.1 Basic statistics 41
2.2 Probability distribution and random numbers 46
2.3 Hypothesis testing 47
2.3.1 What is hypothesis testing? 47
2.3.2 t-Test of population mean 49
viii < R Programming and Its Applications in Financial Mathematics

2.4 Regression Analysis 54


2.5 Yield curve analysis using principal component analysis 59
2.5.1 Yield curve 59
2.5.2 What is principal component analysis? 61
2.5.3 Example of principal component analysis using JGB 64
2.5.4 How to calculate the principal component analysis? 70

3 Time Series Analysis with R 73


3.1 Preparation of time series data 74
3.2 Before applying for models 77
3.3 The application of the AR model 80
3.3.1 Residual analysis 83
3.3.2 Forecasting 84
3.4 Models extended from AR 87
3.4.1 ARMA and ARIMA model 87
3.4.2 Vector autoregressive 91
3.4.3 GARCH model 97
3.4.4 Co-integration 103
3.5 Application of the time series analysis to finance: Pairs trading 107

SECTION II: BASIC THEORY OF FINANCE

4 Modern Portfolio Theory and CAPM 111


4.1 Mean-variance portfolio 113
4.2 Market portfolio 117
4.3 Derivation of CAPM 120
4.4 The extension of CAPM: Multi-factor model 121
4.4.1 Arbitrage Pricing Theory 121
4.4.2 Fama-French’s 3 factor model 125
4.5 The form of the efficient frontier 125

5 Interest Rate Swap and Discount Factor 129


5.1 Interest rate swap 129
5.2 Pricing of interest rate swaps and the derivation of 131
discount factors
5.3 Valuation of interest rate swaps and their risk 135

6 Discrete Time Model: Tree Model 139


6.1 Single period binomial model 140
6.1.1 Derivative pricing 141
6.1.2 Pricing by risk neutral measure 146
6.2 Multi period binomial model 149
6.2.1 Generalization to the multi period model 149
6.2.2 Pricing call options 152
6.3 Trinomial model 156
Contents n ix

7 Continuous Time Model and the Black-Scholes Formula 161


7.1 Continuous rate of return 162
7.2 Itô’s lemma 165
7.3 The Black-Scholes formula 167
7.4 Implied volatility 170

SECTION III: NUMERICAL METHODS IN FINANCE

8 Monte Carlo Simulation 175


8.1 The basic concept of Monte Carlo simulation 176
8.2 Variance reduction method 179
8.2.1 Antithetic variates method 180
8.2.2 Moment matching method 182
8.3 Exotic options 184
8.4 Multi asset options 188
8.5 Control variates method 191

9 Derivative Pricing with Partial Differential Equations 199


9.1 The explicit method 202
9.2 The implicit method 205

APPENDIX

A Optimization with R 213


A.1 Multi variate optimization problem 213
A.2 The efficient frontier by optimization problem 216

B Noise Reduction via Kalman Filter 221


B.1 Introduction to Kalman filter 222
B.2 Nonlinear Kalman filter 227

C The Other References on R 233


C.1 Information sources on R 233
C.2 R package on finance 234
References 235
Index 245
Chapter 1

Introduction to R
Programming

CONTENTS
1.1 Installation of R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.1 Scalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.2 Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.3 Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.3.4 List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.3.5 Data frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.3.6 Factor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.3.7 Investigation of types and structures of data . . . . . . . . . . . . . . . . 22
1.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.5 Control statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.5.1 if-statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.5.2 Iterative processing: for-statement, while-statement . . . . . . . . . 27
1.6 Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.7 Reading and writing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.8 Reading program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.9 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

The objective of this book is to learn the theory of finance using the R
language, which is a programming language developed specifically for numerical

1
2  R Programming and Its Applications in Financial Mathematics

calculation. Before the introduction of finance theory, we need to build the cases
for using R. Thus, the first chapter is devoted to introducing R, its installation,
and the basic usage of R. Readers already familiar with R programming can skip
this chapter.

1.1 Installation of R
Let us start with the installation of R.1 We can get the basic files for installation
and packages from the website of the CRAN project (see Figure 1.1)

http://www.r-project.org/index.html

To get an exe file for installation of R, click download R (as of July 2017).
Then, the screen transits to the following one like Figure 1.2. Choose a mirror site
close to your location. Thus, for Japan we choose https://cran.ism.ac.jp/.
Then the screen transits to that like Figure 1.3. For Windows users, click
“Download R for Windows” on the screen “The Comprehensive R Archive Net-
work”. If you are not a Windows user, then choose the appropriate option.

Figure 1.1: Click “download R” on the page “The R Project for Statistical Computing”

1 This section covers the installation of R from a windows-based executable file. For installation on

Mac choose “Download R for (Mac) OS X”, and on Linux choose “Download R for Linux” (Figure 1.3).
Compilation from source code depends on the operation system. Here, we just show the example based
on windows-based executable file.
Introduction to R Programming  3

Figure 1.2: Choose a mirror site

Figure 1.3: Click “Download R for Windows” on the screen “The Comprehensive R Archive
Network”
4  R Programming and Its Applications in Financial Mathematics

Figure 1.4: Click “base” or “install R for the first time”

Then, the screen like 1.4 appears. Click “base” or “install R for the first time”.
On the next screen Figure 1.5, by clicking “Download R 3.4.1 for Windows”,
we can get “R-3.4.1-win.exe” (3.4.1 is the version name).
You can skip this procedure and go directly to the following site, if you use
Windows.
https://cran.ism.ac.jp/bin/windows/base/
The last step is just to expand the exe file so that you can easily install R.
Now let’s start R. You should be able to start R from the shortcut on your
desktop or via the start menu. If your installation was successful, you should see
the R console appear like Figure 1.6.
You can close the window and exit R by running the command q() from the
console view (Figure 1.7). You can also quit R by selecting “Exit” in the “File”
menu.
Introduction to R Programming  5

Figure 1.5: On the screen “R-3.4.1 for Windows (32/64 bit)”, click “Download R 3.4.1 for
Windows”. Then, we can get “R-3.4.1-win.exe”

Figure 1.6: Start screen of R


6  R Programming and Its Applications in Financial Mathematics

Figure 1.7: Screen for quitting R

Now let’s start to learn R programming by example. First, note a few things
about R:

 It may be better to specify explicitly the directory to read data or scripts


or write results to files in the designated directory. Later, we introduce
how to read and write files in the directory. To specify the directory, click
“Change directory” from the “File” menu, and choose the directory you
like.
 Comment statement: Any line that starts with the # character is inter-
preted as a comment statement, not regarded as the programming state-
ment. If we put # in the middle of the line, any following text is regarded
as a comment.

1.2 Operators
Firstly we introduce important operators of R, i.e., arithmetic, comparative and
logical operators.
The arithmetic operators includes + for addition of two scalars or vectors, -
for subtraction of second scalar or vector from the first ones, * for multiplication,
both scalars or vectors, / for division of the first scalar or vector by the second
ones, %% for the reminder of the division, %/% for the quotient of the first scalar
or vector by the second one and ^ for the exponent.
> 1+2
[1] 3
> 3-5
[1] -2
> 3*2
[1] 6
> 5/2
[1] 2.5
> 5%%2
[1] 1
Introduction to R Programming  7

> 5%/%2
[1] 2
> 2^3
[1] 8
R is also equipped with comparative operators. To test whether variables are
equal to each other, we use the comparative operator ==. To test if it is not equal,
we use the operator !=. For comparisons of magnitude (inequalities), we use >,
>=, <, or <=.
Further, R has logical operators like && for “AND” and || for “OR”. Compar-
ative and logical operators are often used in the conditional statement described
in section 1.5.1.
In addition to these operators, the most basic operator is assignment opera-
tors; e.g., <-, <<- and =.

1.3 Data structure


R is equipped with the following types of variables:
 numeric
 complex
 logical
 character
In other programming languages, e.g., C, we need to declare the type of variable
like integer or double. However, in R we can declare a variable by name only
without explicitly declaring a type. In general, we should avoid giving variable
names, which conflict with variables, constants, or functions defined in R by
default, such as pi, sin, log.
R has several useful functions that we can use to interrogate the type of vari-
ables and data.

> x <- 1
> is.numeric(x) # check whether the data x is numeric
[1] TRUE
> mode(x) # output the type of x
[1] "numeric"
> x <- "foo"
> is.numeric(x)
[1] FALSE
8  R Programming and Its Applications in Financial Mathematics

> # since it is not numeric but character, the output is FALSE


> mode(x)
[1] "character" # we can confirm it is character
> # by using the function mode()
> x <- 2+4i
> is.complex(x) # check whether x is complex number or not
[1] TRUE
> is.numeric(x)
[1] FALSE
> mode(x)
[1] "complex"
> x <- c(T,F) # generate a vector of logical values
> mode(x)
[1] "logical"
> # generate a vector of characters and numeric values,
> x <- c("foo",3)
> mode(x) # and to check the type
[1] "character"

The above example shows the priority of type assignment to variables in R. The
assignment hierarchy is given as follows:
character > complex > numeric > logical
Let’s check this order of priority.
> # generate a vector of a complex number and a character
> x <- c(3+4i,"foo")
> mode(x) # check the type of x
[1] "character"
> # generate a vector of a complex number and numeric number
> x <- c(3+4i,3)
> mode(x) # check the type of x again
[1] "complex"
> # generate a vector of a numeric number and logical number
> x <- c(3.0,TRUE)
> mode(x) # check the type of x again
[1] "numeric"
This hierarchy gives a criterion for R to decide data type. Indeed, if TRUE is
substituted into a variable, it is regarded as logical. However, if the same "TRUE"
has quotation signs, it is regarded as character. Similarly, "3+4i" is substituted
into a variable, it is regarded as character, although it is regarded as complex
without quotation.
Introduction to R Programming  9

For types of variables stated above, R is equipped with the following data
structure.
 scalar
 vector
 matrix
 list
 data frame
 factor

1.3.1 Scalar
Scalars in R can be of the following types: numeric number, complex number,
characters, and logical values. We do not need to be concerned with the differ-
ence between them. Let us describe the following in console view and assign the
number 4 to the variable x:
>x <- 4
>x # display the value of the variable x
[1] 4
We can also use the operator = for variable assignment. However, the common
usage in R is the operator <- which we follow in this book.
Basic arithmetic calculations such as addition, subtraction, multiplication and
division are straightforward in R.

>y <- -3.2 # substitute -3.2 into y


>x+y # sum x and y
[1] 0.8

>x^10 # calculate the tenth power of x


[1] 1048576
> x^100
[1] 1.606938e+60
> x^1000
[1] Inf

Inf means infinity. This implies that the result exceeds the limit of the order that
R can calculate.
10  R Programming and Its Applications in Financial Mathematics

To specify a complex number, we add the suffix i.

> 1i
[1] 0+1i
> 0i
[1] 0+0i
> i
Error: object ‘i’ not found
> 1+2i
[1] 1+2i
> (1+2i)*(2+1i)
[1] 0+5i

The above error message implies that i by itself is not interpreted as a complex
number.
Characters between single quotation mark’ or double quotation marks” are
interpreted as a character sequence.

> # substitute the character sequence "character" into y


> y <- "character"
> y
[1] "character"
> # substitute the character sequence "pasted" into z
> z <- "pasted"
> y+z
Error in y + z : non-numeric argument to binary operator

The addition operator is not defined for two character sequences. To combine
(concatenate) character sequences, we use the function paste().

> paste(y,z)
[1] "character pasted"
> paste(z,y)
[1] "pasted character"

If you do not want a blank space between the two character sequences, you
need to specify a third input as follows:

> paste(y,z,sep="")
[1] "characterpasted"
Introduction to R Programming  11

Here, sep means the character separator between the input strings, which is
a blank character by default. If we denote the inside of sep=",", it works as
follows:
> paste(y,z,sep=",")
[1] "character,pasted"
We can use logical numbers. Logical numbers consists of the value of True
and False. The logical value true, is denoted in R by T, or TRUE, and the logical
value false by F or FALSE. These are case sensitive in R.

> T
[1] TRUE
> FALSE
[1] FALSE
> false
Error: object ‘false’ not found
> TRUE
[1] TRUE

Let’s try the following simple calculations.

Exercise
1. (3 × 4 + 3.5)/3.3
2. (1 + 3i) × (3 + 3i)
3. ‘My’+‘name’+‘is’+‘(Daisuke)’

1.3.2 Vector
Vectors consist of a set of scalars and can be generated by the function c().

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


> x
[1] 0 1 2 3 4
> y <- c("tokyo","kyoto")
> y
[1] "tokyo" "kyoto"
> x[2] # extract second element of the vector
[1] 1
> y[1] # extract first element of the vector
[1] "tokyo"
> x[c(1,3,5)] # extract 1st, 3rd and 5th elements together
[1] 0 2 4
12  R Programming and Its Applications in Financial Mathematics

The multiplication of vectors is defined as an element-wise product, rather


than as an inner product of vectors.

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


> y <- c(3,4,1)
> x*y
[1] 3 8 3

The example below is an artificial calculation to derive an error; to multiply


vectors which are defined as different dimensions.
> y <- c(3,4,1,1)
> x*y
[1] 0 4 2 3 12
Warning message:
In x * y : longer object length is not a multiple of shorter
object length
This example shows us that we need to make sure that the dimensions of vectors
are equal.
> y <- c(3,4,1) # redefine y as 3-dimensional vector
> x*y
[1] 3 8 3
To calculate the inner product of two vectors, we use %*%. Alternatively, we can
use sum(x*y) which returns the same result.
> x%*%y
[,1]
[1,] 14
The function seq() allows us to generate a vector with a sequence of num-
bers.

> # generate a sequence from 0 to 3 by increments of 0.5


> x <- seq(0,3,by=0.5)
> x
[1] 0.0 0.5 1.0 1.5 2.0 2.5 3.0
> # generate a sequence from 0 to 3 with length (the number
> # of elements) 5
> y <- seq(0,3,length=5)
> y
[1] 0.00 0.75 1.50 2.25 3.00
Introduction to R Programming  13

> z <- 1:10 # generate a sequence from 1 to 10


by increments of 1
> z
[1] 1 2 3 4 5 6 7 8 9 10
> z <- 10:1 # generate a sequence from 10 to 1
by decrements of 1
> z
[1] 10 9 8 7 6 5 4 3 2 1
> z[3:8]# extract the 3rd to the 8th elements of z
[1] 8 7 6 5 4 3
The function rep() generates a repeated sequence as follows:
> z <- rep(1,8) # repeat the scalar value 1, 8 times
> z
[1] 1 1 1 1 1 1 1 1
> y <- rep(c(1,2,3),3) # repeat the vector (1,2,3), 3 times
> y
[1] 1 2 3 1 2 3 1 2 3
> # repeat each element in (1,2,3) by 3 times
> z <- rep(c(1,2,3),each=3)
> z
[1] 1 1 1 2 2 2 3 3 3
We make some more manipulations of vectors
> # generate a sequence from 0 to 2 by the increment 0.3
> x <- seq(0,2,by=0.3)
> x
[1] 0.0 0.3 0.6 0.9 1.2 1.5 1.8
> length(x) # the length (number of dimension) of vector x
[1] 7
> y <- 2:5 # a sequence of integer from 2 to 5
> y
[1] 2 3 4 5
> z <- c(x,y)# combine vectors x and y
> z
[1] 0.0 0.3 0.6 0.9 1.2 1.5 1.8 2.0 3.0 4.0 5.0
> rev(z) # the reverse vector
[1] 5.0 4.0 3.0 2.0 1.8 1.5 1.2 0.9 0.6 0.3 0.0
> str(z) # structure of the vector
num [1:11] 0 0.3 0.6 0.9 1.2 1.5 1.8 2 3 4 ...

The authors consider functions rep(), seq() and length() are very convenient
and are often used.
14  R Programming and Its Applications in Financial Mathematics

1.3.3 Matrix
There are two methods to generate a matrix in R. One is to use the function
matrix(). The other is to combine several vectors or several matrix.
Let us generate a matrix from arbitrary elements by using the function
matrix().
> # generate a sequence x from 1 to 8.
> x <- 1:8
> x
[1] 1 2 3 4 5 6 7 8
> y <- matrix(x,2,4) # generate a (2,4)-matrix
> # from the element x
> y
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
> y <- matrix(x,4,2) # generate a (4,2)-matrix
> # from the element x
> y
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8
> # example where the number of rows and columns
> # are not consistent with the number
> # of elements in x
> y <- matrix(x,3,2)
Warning message:
In matrix(x, 3, 2) :
data length [8] is not a sub-multiple or multiple
of the number of rows [3]
> y <- matrix(x,2,5)
Warning message:
In matrix(x, 2, 5) :
data length [8] is not a sub-multiple or multiple
of the number of columns [5]
The above example shows that we need to define the number of rows and
columns to be consistent with the number of elements: The number of rows mul-
tiplied by the number of columns should be the number of elements.
Introduction to R Programming  15

Next, we combine vectors to generate a matrix.


> x <- 1:4
> y <- 5:8
> cbind(x,y) # combine column vectors
x y
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8
> rbind(x,y) # combine row vectors
[,1] [,2] [,3] [,4]
x 1 2 3 4
y 5 6 7 8
> rbind(x,y,x) # combine 3 row vectors
[,1] [,2] [,3] [,4]
x 1 2 3 4
y 5 6 7 8
x 1 2 3 4
>
> cbind(matrix(x,2,2),matrix(y,2,2)) # combine two matrices
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
> rbind(matrix(x,2,2),matrix(y,2,2))
[,1] [,2]
[1,] 1 3
[2,] 2 4
[3,] 5 7
[4,] 6 8
We can generate a diagonal matrix by using the function diag().
> diag(c(1,2,3)) # generate a diagonal matrix
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 2 0
[3,] 0 0 3
> diag(rep(1,3)) # generate the identity matrix
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
16  R Programming and Its Applications in Financial Mathematics

Next, we extract elements, rows and columns from the matrix and check the
number of rows and columns of the matrix.
> x <- matrix(seq(1,15,by=2),2,4)
> x
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 3 7 11 15
> x[2,3] # output the element from the 2nd row and 3rd column
[1] 11
> x[2,] # output the 2nd row
[1] 3 7 11 15
> x[,3] # output the 3rd column
[1] 9 11
> dim(x) # output the number of rows and columns
> # of the matrix
[1] 2 4
> nrow(x) # output the number of rows
[1] 2
> ncol(x) # output the number of columns
[1] 4
We can also perform multiplication of matrices and vectors.

> # generate a 3-by-3 matrix


> mat <- rbind(c(1,0.2,0.3),c(0.2,1,0.5),c(0.3,0.5,1))
> mat
[,1] [,2] [,3]
[1,] 1.0 0.2 0.3
[2,] 0.2 1.0 0.5
[3,] 0.3 0.5 1.0

> x <- c(1,0.4,0.3) # generate 1-by-3 vector


> x
[1] 1.0 0.4 0.3

In the following example, we apply the operator * which can be used for
multiplication of matrices and vectors such as we have above. However, this
operator does not generate the inner product as follows:
Introduction to R Programming  17

> # calculate the product of the elements in each row


> # of the matrix with each column of the vector
> mat*x
[,1] [,2] [,3]
[1,] 1.00 0.20 0.3
[2,] 0.08 0.40 0.2
[3,] 0.09 0.15 0.3

To calculate the inner product, we need to use the operator %*%.


> mat %*% x # calculate the inner product
[,1]
[1,] 1.17
[2,] 0.75
[3,] 0.80

> # generate two vectors y and z.


> # note that ; separates calculations on a line.
> y <- c(2,0.5,1.3);z<-c(1,5,0.2)
> # combine the vectors (x,y,z) as columns of a new matrix.
> # note that using rbind(x,y,z) would combine the vectors
> # as rows of a new matrix
> xyz<-cbind(x,y,z)
> xyz
x y z
[1,] 1.0 2.0 1.0
[2,] 0.4 0.5 5.0
[3,] 0.3 1.3 0.2
> # calculate the inner product of the matrix ‘mat’ and ‘xyz’
> mat%*%xyz
x y z
[1,] 1.17 2.49 2.06
[2,] 0.75 1.55 5.30
[3,] 0.80 2.15 3.00

1.3.4 List
A list is a set of vectors or matrices combined in a single object. We can generate
a list in R by using the function list(). It is not necessary to specify the types
of the factors in a list; a list can simultaneously include different data types (i.e.
numeric and characters) and items of different lengths and sizes.
18  R Programming and Its Applications in Financial Mathematics

> # generate a list including month,price,brand


> equity <- list(month=c(1,2,3),price=c(100,300,240),
+ brand="muji")
> equity # display the contents of equity
$month
[1] 1 2 3

$price
[1] 100 300 240

$brand
[1] "muji"

> # the structure of the equity object in more compact format


> str(equity)
List of 3
$ month: num [1:3] 1 2 3
$ price: num [1:3] 100 300 240
$ brand: chr "muji"

> equity$month # extract month from equity


[1] 1 2 3
> equity$price # extract price from equity
[1] 100 300 240
> equity$price[3] # extract the 3rd item of price from equity
[1] 240
> equity[[3]] # extract 3rd item of equity
[1] "muji"
> equity[[2]] # to extract 2nd item of equity
[1] 100 300 240

We can redefine the name of items included in a list.


> # generate a list
> equity <- list(c(1,2,3),c(300,200,400),"muji")
> equity
[[1]]
[1] 1 2 3

[[2]]
[1] 300 200 400

[[3]]
[1] "muji"
Another random document with
no related content on Scribd:
“Indeed, one so young as you appear to be! But yours, young
man, are the sorrows, perhaps, of a youthful lover. Yours are not so
deeply rooted as mine.”
These words led to an explanation which told the two strangers
that their concerns were more nearly allied than they had been
aware. Our readers of course need not be informed that the elder of
the two was Mr Primrose, and the younger Mr Robert Darnley. They
were happy, however, in the midst of their sorrows, to have become
thus acquainted at a distance from home. They only regretted that
the distance between their respective situations in India had formed
an insuperable barrier against an acquaintance and intimacy there.
The fact is that, so long as Dr Greendale considered the return of Mr
Primrose as a matter of uncertainty, he had been very cautious of
exciting his daughter’s expectations. He had ventured to consider his
own approbation quite sufficient to allow of the correspondence
between his niece and Mr Robert Darnley, and had in his letters to
Mr Primrose simply mentioned the fact without stating particulars,
thinking that it would be time enough hereafter, should the mutual
affection of the young persons for each other continue and
strengthen. Mr Primrose had, in reply to that information, left Dr
Greendale quite at liberty to make such disposal of Penelope as he
might think proper; for the father was well aware that the uncle was,
both by discretion and affection, well qualified for the guardianship of
his child.
The vessels in which the two gentlemen sailed soon weighed
anchor and put to sea again. So the friends were parted for a time;
nor did they hold any farther communication on the course of their
voyage, for they had not left St Helena many days before the ship
parted company in a gale of wind. That vessel in which Mr Primrose
sailed first arrived in England, as we have already intimated.
CHAPTER XIV.
England appeared to Mr Primrose quite a new world. He had
sixteen years ago sailed down the river Thames, which presented on
its banks at that time quite as much picturesque beauty as now. But
he did not then observe these beauties. His heart was full of other
thoughts, and his mind was moved by widely different feelings. There
had not been in his soul the sentiment of moral beauty, nor was
there in his heart that repose of pleasure which could admit of
enjoying the external world in its manifestations of beauty or
sublimity. But on his return homewards his thoughts were far
different. He had left England in forlorn hope, but he was returning
under brighter auspices. He had sailed from his native land, bearing
a deeply felt burden of self-reproach; and though he could not forget
or forgive his former self, and though still there were painful scenes
to be witnessed, and melancholy information to be received, yet the
aspect of things was widely different from what it had been at his
departure. And he expressed himself delighted with all that he saw.
The little boats and the lighter craft upon the river spoke of bustle
and activity, and of human interest; and in them he saw the
flutterings of business and prosperity. Though it was winter, and the
trees on the rising grounds were leafless, and the fields had lost their
greenness, yet the very pattern and outline of what the scene had
been in summer, and of what it would be again in spring, were all
very charming to his eye, then active with imagination. His own
bright thoughts gave verdure to the trees and greenness to the
fields; and he thought that England indeed was a blessed land. And
as the vessel made her way up the river, and as at a distance a
dense black cloud was seen, he knew that that was a manifestation
of their vicinity to the great city, and that dark mass of floating
smoke, which rustic eloquence so glibly reprobates, was to his soul a
great refreshment and a most pleasing sight.
As soon as he disembarked, he first directed his steps to the office
of his agent in the city, to make enquiry respecting the speediest
mode of arriving at Smatterton: for he knew not that his daughter’s
residence was now in London. There is a great contrast between the
appearance of the banks of the Thames and the inside of a city
counting-house; but they are both very pleasant sights to those who
are glad to see them. Mr Primrose was indeed very glad to see his
native land, and to walk the streets of its busy metropolis; and with
very great cordiality did he shake hands with the principal in the
office, and very politely did the principal congratulate him on his
return to England. Mr Primrose did not notice the great contrast
between his own joy-expanded face and the business-looking aspect
of the agent; but he thought that all London looked as glad to see
him as he was to see London. After transacting at the office of his
agent such business as was immediately important, and without
waiting to observe what changes and improvements had taken place
in the great city since he had left it sixteen years ago, he made
enquiry after the readiest and quickest mode of reaching Smatterton,
and finding that the stage-coach was the most rapid conveyance, he
immediately directed his steps thitherward.
There are in the course of human life many strange and singular
coincidences. Now it happened that the very day on which Mr
Primrose was preparing to start for Smatterton, Mr Kipperson also
was going to travel the same road, and by the same conveyance.
Little did the former imagine that he was going away from his
daughter; little did he think that, in his way to the White Horse cellar
in Piccadilly, he had actually passed the house in which his beloved
child and only hope lay sick and ill. The days in December are very
short; and it was nearly dark when, at four o’clock in the afternoon,
Mr Primrose and Mr Kipperson, unknown to each other, took their
seats in the coach. They had the inside of the coach to themselves.
Mr Primrose, as we have said, was in good spirits. He certainly
had some cause for grief, and some source of concern; but the
feeling of satisfaction was most prominent. He had shed tears to the
memory of Dr Greendale, and he hoped that the worthy man had so
instructed the dependent one committed to his care, that no
permanent cause of uneasiness would be found in her. The
intelligence which he had received respecting her alleged and
supposed fickleness came from Mr Darnley, and the father,
therefore, knowing Mr Darnley to be a very severe and rigid kind of
man, and withal mighty positive, hoped that a premature judgment
had been formed, and trusted that, when all was explained, all would
be right. We must indeed do the father of Penelope the justice to say
that, with all his failings, he was sincere, candid, and downright. He
never suffered any misunderstanding to exist where it could possibly
be cleared up. He was plain and direct in all his conduct.
We need not say that Mr Kipperson was in good spirits. He always
was so. He was so very happy that by this last journey to London he
had saved the nation from being starved to death by a
superabundance of corn. What a fine thing it is to be the cleverest
man in the kingdom! What would become of us all were it not for
such men as Mr Kipperson starting up about once in a century, or
twice a-week, to rectify all the errors of all the rest of the world? And
what is the use of all the world beside, but to admire the wisdom of
such men as Mr Kipperson? Our only fear is that we may have too
many such profoundly wise men; and the consequence of an over
supply of wisdom would be to ruin the nation by folly.
Whether Mr Kipperson addressed Mr Primrose, or Mr Primrose
addressed Mr Kipperson, we know not; but in a very short time they
became mighty good friends. To some observation of Mr Primrose,
his fellow traveller replied:
“You have been abroad I suppose, sir?”
“I have, sir,” said Mr Primrose; “and that for a long while: it is now
upwards of sixteen years since I left England, and I am most happy
to return to it. Many changes have taken place since I went abroad,
and some, I hope, for the better.”
“Many improvements have indeed been made in the course of that
time. We have improved, for instance, in the rapidity with which we
travel; our roads are as smooth as a bowling-green. But our greatest
improvements of all are our intellectual improvements. We have
made wonderful strides in the march of intellect. England is now the
first country in the world for all that relates to science and art. The
cultivation of the understanding has advanced most astonishingly.
“I remember noticing when I was in India,” said Mr Primrose, “that
the number of publications seemed much increased. But many of
them appeared to be merely light reading.”
“Very likely, sir; but we have not merely light reading; we have a
most abundant supply of scientific publications: and these are read
with the utmost avidity by all classes of people, especially by the
lower classes. You have no doubt heard of the formation of the
mechanics’ institutes?”
“I have, sir,” replied Mr Primrose; “but I am not quite aware of the
precise nature of their constitution, or the object at which they aim.
Perhaps you can inform me?”
“That I can, sir,” said Mr Kipperson; “and I shall have great
pleasure in so doing; for to tell you the truth I am a very zealous
promoter of these institutions. The object of these institutions is to
give an opportunity to artisans, who are employed all day in manual
labour, to acquire a scientific knowledge, not only of the art by which
he lives and at which he works, but of everything else which can
possibly be known or become a subject of human inquiry or interest.”
“But surely,” interrupted Mr Primrose, “it is not designed to convert
mechanical into scientific men. That seems to my view rather a
contradiction to the general order of things.”
“I beg your pardon,” replied the other; “you are repeating, I
perceive, exploded objections. Is it possible, do you think, that a man
should do his work worse for understanding something of the
philosophy of it? Is it not far better, where it is practicable, that a man
should act as a rational reflecting creature, than as a piece of mere
machinery?”
“Very true, certainly, sir; you are right. Ay, ay, now I see: you
instruct all artisans in the philosophy of their several employments.
Most excellent. Then, I suppose, you teach architecture and read
lectures on Vitruvius to journey-men bricklayers?”
“Nay, nay, sir,” replied Mr Kipperson, “we do not carry it quite so far
as that.”
“Oh, I beg your pardon,” replied Mr Primrose, “I had not the
slightest idea that this was carrying your system too far. It might,
perhaps, be a little refinement on the scheme to suppose that you
would teach tailors anatomy; but after all I do not see why you
should start at carrying a matter of this kind too far. The poet says, ‘a
little knowledge is a dangerous thing;’ and, for my own part, I can
see no great liberality in this parsimonious and stinted mode of
dealing out knowledge; for unless you teach the lower classes all
that is to be taught, you make, or more properly speaking keep up,
the distinction.”
Mr Kipperson was not best pleased with these remarks; he saw
that his fellow-traveller was one of those narrow-minded aristocratic
people, who are desirous of keeping the mass of the people in gross
ignorance, in order that they may be the more easily governed and
imposed upon. Though in good truth it has been said, that the
ignorant are not so easily governed as the enlightened. The
ingenious and learned Mr Kipperson then replied:
“You may say what you please, sir, in disparagement of the system
of enlightening the public mind; but surely you must allow that it is far
better for a poor industrious mechanic to attend some lecture on a
subject of science or philosophy, than to spend his evenings in
drunkenness and intemperance.”
“Indeed, sir, I have no wish to disparage the system of
enlightening the public mind; and I am quite of your opinion, that it is
much more desirable that a labouring man”——
“Operative, if you please,” said Mr Kipperson; “we have no
labouring men.”
“Well,” pursued Mr Primrose, “operative; the term used to be
labouring or working when I was last in England: I will agree with
you, sir, that it is really better that an operative should study
philosophy, than that he should drink an inordinate quantity of beer.
But do you find, sir, that your system does absolutely and actually
produce such effects?”
“Do we?” exclaimed Mr Kipperson triumphantly: “That we certainly
and clearly do: it is clear to demonstration; for, since the
establishment of mechanics’ institutes, the excise has fallen off very
considerably. And what can that deficiency be owing to, if it be not to
the fact which I have stated, that the operatives find philosophy a far
more agreeable recreation after labour than drinking strong beer?”
“You may be right, sir, and I have no doubt you are; but, as I have
been so long out of England, it is not to be wondered at that my
ideas have not been able to keep pace with the rapid strides which
education has made in England during that time. I am very far from
wishing to throw any objection or obstacle in the way of human
improvement. You call these establishments ‘mechanics’ institutions:’
but pray, sir, do you not allow any but mechanics to enjoy the benefit
of them? Now there is a very numerous class of men, and women
too—for I should think that so enlightened an age would not exclude
women from the acquisition of knowledge;—there is, I say, a very
numerous class of men and women who have much leisure and little
learning—I mean the servants of the nobility and gentry at the west
end of the town. It would be charitable to instruct them also in the
sciences. How pleasant it must be now for the coachman and
footman, who are waiting at the door of a house for their master and
mistress, at or after midnight, instead of sleeping on the carriage, or
swearing and blaspheming as they too frequently do, to have a
knowledge of astronomy, and study the movements of the planets. Is
there no provision made for these poor people?”
“Certainly there is,” said Mr Kipperson. “There are cheap
publications which treat of all the arts and sciences, so that for the
small charge of sixpence, a gentleman’s coachman may, in the
course of a fortnight, become acquainted with all the Newtonian
theory.”
Mr Primrose was delighted and astonished at what Mr Kipperson
told him; he could hardly believe his senses; he began to imagine
that he must himself be the most ignorant and uninformed person in
his majesty’s dominions.
“But tell me, sir,” continued he, “if those persons, whose time and
attention is of necessity so much occupied, are become so well
informed; do others, who have greater leisure, keep pace with them;
or, I should say, do they keep as much in the advance as their
leisure and opportunity allow them? For, according to your account,
the very poorest of the community are better instructed now than
were the gentry when I lived in England.”
“Education, sir,” answered Mr Kipperson, with the tone of an
oracle, “is altogether upon the advance. The science of instruction
has reached a point of perfection, which was never anticipated; nay,
I may say, we are astonished at ourselves. The time is now arrived
when the only ignorant and uninformed persons are those who have
had the misfortune to be educated at our public schools and
universities: for in them there is no improvement. I have myself been
witness of the most shocking and egregious ignorance in those men
who call themselves masters of arts. They know nothing in the world
about agriculture, architecture, botany, ship building, navigation,
ornithology, political economy, icthyology, zoology, or any of the ten
thousand sciences with which all the rest of the world is intimate. I
have actually heard an Oxford student, as he called himself, when
looking over a manufactory at Birmingham, ask such questions as
shewed that he was totally ignorant even of the very first rudiments
of button-making.”
“Astonishing ignorance,” exclaimed Mr Primrose, who was rather
sleepy; “I dare say they make it a rule to teach nothing but ignorance
at the two universities.”
“I believe you are right, sir,” said Mr Kipperson, rubbing his hands
with cold and extacy; “those universities have been a dead weight on
the country for centuries, but their inanity and weakness will be
exposed, and the whole system exploded. There is not a common
boys’ school in the kingdom which does not teach ten times more
useful knowledge than both the universities put together, and all the
public schools into the bargain. Why, sir, if you send a boy to school
now, he does not spend, as he did formerly, ten or twelve years in
learning the Latin grammar, but now he learns Latin and Greek, and
French, German, Spanish, Italian, dancing, drawing, music,
mapping, the use of the globes, chemistry, history, botany,
mechanics, hydrostatics, hydraulics, hydrodynamics, astronomy,
geology, gymnastics, architecture, engineering, ballooning, and
many more useful and indispensable arts and sciences, so that he is
fitted for any station in life, from a prime minister down to a shoe-
black.”
Before this speech was finished, Mr Primrose was fast asleep; but
short is the sleep in a coach that travels by night. The coach stopped
and woke our foreigner from a frightful dream. We do not wish to
terrify our readers, but we must relate the dream in consequence of
its singularity. He dreamed then, that he was in the island of Laputa,
and that having provoked the indignation of some of the learned
professors by expressing a doubt as to the practicability of some of
their schemes, he was sentenced to be buried alive under a pyramid
of encyclopedias. Just as the cruel people were putting the sentence
into execution, he woke and found his coat-collar almost in his
mouth, and heard the word ‘ology’ from the lips of his fellow traveller.
He was very glad to find that matters were no worse.
CHAPTER XV.
Few indeed are the adventures now to be met with in travelling by
a stage coach, and few also, comparatively speaking, the accidents.
But our travellers were destined to meet both with accident and
adventure. The coach, as our observant readers have noticed, must
necessarily have travelled all night. The nights in December are long
and dark; and not unfrequently, during the long cold silence of a
December night, there gently falls upon the dank surface of the earth
a protecting and embellishing fleece of flaky snow. And the morning
snow as yet untrodden has a brilliant and even cheerful look beneath
a blue and brightly frosty sky; and when a wide expanse of country
variegated with venerably-aged trees, and new enclosures and old
open meadow lands, and adorned with here and there a mansion
surrounded with its appurtenances of larch, pine, and poplar, and
divided into unequal but gracefully undulating sections by means of a
quiet stream—when a scene like this bursts upon the morning eye of
a winter traveller, and shows itself set off and adorned with a mantle
of virgin snow, it is indeed a sight well worth looking at. Mr Primrose
had not seen snow for sixteen years, and the very sight of it warmed
his heart; for it was so much like home. It was one of those natural
peculiarities which distinguished the land of his birth from the land of
his exile. He expressed to his fellow traveller the delight which he felt
at the sight. Mr Kipperson coincided with him that the view was fine,
and proposed that, as they were both well clad, and as the scenery
was very magnificent, they should by way of a little variety seat
themselves on the outside of the coach. The proposal was readily
embraced, and they mounted the roof.
The carriage was proceeding at a tolerably rapid pace on high but
level ground; and the travellers enjoyed the brightness of the
morning, and the beauty of the valley which lay on their left hand.
Shortly they arrived at a steep descent which led into the valley
beneath, and there was no slacking of pace or locking of wheels,
which had been customary in going down hill when Mr Primrose was
last in England. He expressed, therefore, his surprise at the
boldness or carelessness of the coachman, and hinted that he was
fearful lest some accident might happen. But Mr Kipperson
immediately dissipated his fears, by telling him that this was the
usual practice now, and that the construction of stage-coaches, and
the art of driving, were so much improved, that it was now
considered a far safer and better plan to proceed in the usual pace
down hill as well as upon level ground. Mr Kipperson, in short, had
just proved to a demonstration that it was impossible that any
accident could happen, when down fell one of the horses, and
presently after down fell coach and all its company together.
Happily no lives were lost by the accident. But if Mr Kipperson’s
neck was not broken by the fall, his heart was almost broken by the
flat contradiction which the prostrate carriage gave to his theory, and
he lay as one bereft of life. Equally still and silent lay Mr Primrose;
for he was under the awkward difficulty of either denying his fellow
traveller’s correctness or doubting the testimony of his own senses.
The catastrophe took place near to a turnpike house; so that those of
the passengers, who had experienced any injury from the
overturning of the coach, could be speedily accommodated with all
needful assistance. All the passengers, however, except Mr
Primrose, were perfectly able, when the coach was put to rights
again, to resume their journey. Mr Primrose, as soon as he
recovered from the first shock of his fall, was very glad to take refuge
in the turnpike house, and he soon became sensible that it would not
be prudent for him then to pursue his journey. He had indeed
received a severe shock from the accident, and though he had no
bones broken he had suffered a violent concussion which might be
doctored into an illness.
As soon as possible medical assistance was procured. The
surgeon examined and interrogated the overturned gentleman with
great diligence and sagacity. From the examination, it appeared not
unlikely that the patient might promise himself the pleasure of a
speedy removal. The truth of the matter was, that the poor
gentleman was more frightened than hurt. Some cases there are,
and this was one of them, in which no time should be lost in sending
for the doctor, seeing that, if the doctor be not sent for immediately,
he may not be wanted at all. This is one of the reasons why
physicians keep carriages, and have their horses always in
readiness; for by using great expedition they frequently manage to
arrive before the patient recovers.
The surgeon who attended Mr Primrose thought proper to take
some blood from his patient, and to supply the place of the same by
as many draughts as could be conveniently taken, or be reasonably
given in the time. It was also recommended that the gentleman
should be put to bed.
The dwellings attached to turnpike gates are seldom so roomy and
so abundantly provided with accommodation as to admit of an
accidental visitor: but in the present case it so happened that there
was an apartment unoccupied and not unfurnished. The
gatekeeper’s wife, who was a notable and motherly kind of woman,
said, that if the gentleman could put up with a very small apartment,
and a coarse but clean bed, he might be accommodated, and he
need not fear that the bed was damp, for it had been occupied for
the last month, and had only been vacated the day before. Mr
Primrose readily accepted the offer, not being very particular as to
appearance.
“I suppose,” said he, “you keep a spare bed for the
accommodation of those who may be overturned in coming down
this hill? Your surgeon, I find, does not live far off. That is a good
contrivance. Pray can you tell me, within a dozen or two, how many
broken bones the stage coach supplies him with in the course of the
year?”
At this speech the good woman laughed, for it was uttered in such
a tone as intimated that the gentleman wished it to be laughed at;
and as he was a respectable looking man, and carried in his aspect
a promise to pay, the worthy wife of the gate-keeper laughed with
right good will.
“Oh dear no, sir,” said she, “there is not an accident happens here
hardly ever. The coachman what overturned you this morning, is one
of the most carefullest men in the world, only he had a new horse as
didn’t know the road.”
“A very great comfort is that,” said Mr Primrose, and he smiled,
and the gate-keeper’s wife smiled, and she thought Mr Primrose a
very funny man, that he should be able to joke when under the
doctor’s hands. There are some people who are very facetious when
they are sick, provided the sickness be not very acute; for it looks
like heroism to laugh amidst pain and trouble.
Mr Primrose then proceeded; “So you will assure me that the
person who occupied your spare bed last, was not an overturned
coach passenger?”
The poor woman did not smile at this observation, but on the
contrary looked very grave, and her eyes seemed to be filling with
tears, when she compressed her lips and shook her head mournfully.
With some effort, after a momentary silence, she said:
“No, sir, it was not any one that was overturned; but it was a coach
passenger. It was a young lady, poor dear soul! that seemed almost
dying of a broken heart. But had not you better go to bed, sir? The
doctor said you wanted rest.”
Mr Primrose was a nervous man, and tales of sorrow inartificially
told frequently depressed him, and excited his sympathy with greater
force than was consistent with poetical enjoyment. He therefore took
the considerate advice which the good woman gave him, and retired
to rest. To a person of such temperament as Mr Primrose, the very
mention of a young lady almost dying of a broken heart was quite
sufficient to set his imagination most painfully at work. Rapidly did
his thoughts run over the various causes of broken hearts. Very
angry did he become with those hardened ones, by whose follies
and vices so many of the gentler sex suffer the acutest pangs of the
spirit. He thought of his own dear and only child, and he almost
wrought himself up to a fever by the imagination that some villanous
coxcomb might have trifled with her affections, and have left her to
the mockery of the world. He then thought of the mother of his
Penelope, and that she had died of a broken heart, and that his
follies had brought her to an untimely grave. Then came there into
his mind thoughts of retributive justice, and there was an
indescribable apprehension in his soul that the sorrows which he had
occasioned to another might fall also to his own lot. He wondered
that there should be in the world so much cruelty, and such a wanton
sporting with each others’ sufferings. The powerful emotions which
had been raised in his mind from the first hour that he embarked for
England, were of a nature so mingled, and in their movements so
rapid, that he hardly knew whether they were pleasurable or painful.
There was so much pleasure in the pain, and so much pain in the
pleasure, that his mind was rendered quite unsteady by a constant
whirl and vortex of emotions. He felt a kind of childish vivacity and
womanly sensibility. His tears and his smiles were equally
involuntary; he had no power over them, and he had scarcely notice
of their approach. Something of this was natural to him; but present
circumstances more strongly and powerfully developed this
characteristic. The accident, from which he had received so sudden
a shock, tended still farther to increase the excitability of his mind.
When therefore he retired for the purpose of gaining a little rest, his
solitude opened a wider door to imagination and recollection; and
thereupon a confused multitude of images of the past, and of fancies
for the future, came rushing in upon him, and his mind was like a
feather in a storm.
The surgeon was very attentive to his patient, for he made a
second visit not above four hours after the first. The people at the
turnpike-house told him that the gentleman had, in pursuance of the
advice given him, retired to take a little rest. The medical man
commended that movement; but being desirous to see how his
patient rested, he opened the door of the apartment very gently, and
Mr Primrose, who was wide awake, and happy to see any one to
whom he could talk, called aloud to the surgeon to walk in.
“I am not asleep, sir; you may come in; I am very glad to see you; I
have felt very much relieved by the bleeding. I think I shall be quite
well enough to proceed to-morrow. Pray, sir, can you inform me how
far it is to Smatterton from this place?”
“About sixty miles,” replied the surgeon.
“Sixty miles!” echoed Mr Primrose; “at what a prodigious rate then
we must have travelled.” Thereupon the patient raised himself up in
the bed, and began, or attempted to begin, a long conversation with
his doctor. “Why, sir, when I was in England last, the coach used to
be nearly twice as long on the road. Is this the usual rate of
travelling?”
The medical man smiled, and said, “The coach by which you
travelled, is by no means a quick one, some coaches on this road
travel much faster.”
“And pray, sir, do these coaches ever arrive safely at their
journey’s end?”
The surgeon smiled again and said, “Oh yes, sir, accidents are
very rare.”
“Then I wish,” replied Mr Primrose; “that they had not indulged me
with so great a rarity just on my arrival in England. I have been in the
East Indies for the last sixteen or seventeen years, and during that
time—”
Few medical men whose business is worth following, have time to
listen to the history of a man’s life and adventures for sixteen or
seventeen years. Hindoostan is certainly a very interesting country,
but there is no country on the face of the earth so interesting as a
man’s own cupboard. The doctor therefore cut off his patient’s
speech, not in the midst, but at the very beginning; saying unto him,
with a smile, for there is much meaning in a smile; “Yes sir, certainly
sir, there is no doubt of it—very true; but, sir, I think it will be better
for you at present to be kept quiet; and if you can get a little sleep it
will be better for you. I think, sir, to-morrow, or the next day, you may
venture to proceed on your journey. I will send you a composing
draught as soon as I return home, and will see you again to-morrow,
early in the morning. But I would not recommend you to travel by the
stage coach.”
“Ay, ay, thank you for that recommendation, and you may take my
word I will follow it.”
The doctor very quickly took his leave, and Mr Primrose thought
him a very unmannerly cub, because he would not stop to talk. “A
composing draught!” thus soliloquized the patient; “a composing
draught! a composing fiddlestick! What does the fellow mean by
keeping me thus in bed and sending me in his villanous compounds.
Why, I think I am almost able to walk to Smatterton. I won’t take his
composing draught; I’ll leave it here for the next coach passenger
that may be overturned at the foot of this hill. I dare to say it will not
spoil with keeping.”
The word “coach-passenger” brought to Mr Primrose’s recollection
the melancholy look and sorrowful tone of the poor woman who
mentioned the young lady who seemed almost dying of a broken
heart. His curiosity was roused, his nerves were agitated. He kept
thinking of his poor Penelope. He recollected with an almost painful
vividness the features and voice of the pretty little innocent he had
left behind him when he quitted England. He recollected and painted
with imagination’s strongest lines and most glowing colours that
distracting and heart-rending scene, when after listening with tearful
silence to the kind admonitions of his brother-in-law, he snatched up
in his arms his dear little laughing Penelope, and he saw again as
pungently as in reality, the little arms that clasped him with an
eagerness of joy, and he recollected how his poor dear child in the
simplicity of her heart mistook the agitations and tremblings of grief
for the frolicsome wantonness of joy, and he saw again that
indescribably exquisite expression with which she first caught sight
of his tears; and then there came over his mind the impression
produced by the artless manner in which the poor thing said, “Good
night, papa, perhaps you won’t cry to-morrow.”
Now he thought of that Penelope as grown up to woman’s estate,
and he felt that he should be proud of his daughter: but oh what
fears and misgivings came upon him, and he kept muttering to
himself the words of the woman who had talked of the young lady
almost dying of a broken heart. It was well for the patient that the
doctor soon fulfilled his word and sent a composing draught. But the
very moment that his attentive nurse gently tapped at the door of his
room, he called out:
“Come in, come in, I am not asleep. Oh, what you have brought
me a composing draught! Nonsense, nonsense, keep it for the next
coach-passenger that is overturned, and give it to him with my
compliments. Well, but I say, good woman, you were telling me
something about a poor young lady who was almost dying with a
broken heart. Who is she? Where is she? What is her name? Where
is she gone to? Where did she come from? Who broke her heart?
Was she married, or was she single? Now tell me all about her.”
“Oh dear, sir, I am sure you had better take this physic what the
doctor has sent you, that will do you more good than a mallancolly
story. Indeed you’d better, sir; shall I pour it out into a cup?”
“Ay, ay, pour it out. But I say, good woman, tell me where did this
poor young lady come from?”
“Lord, sir, I never saw such a curious gentleman in my life. Why,
then if you must know, she came from a long way off, from a village
of the name of Smatterton, a little village where my Lord Smatterton
has a fine castle.”
While the good woman was speaking she kept her eyes fixed
upon the cup into which she was slowly pouring the medicine, and
therefore she did not perceive the effect produced upon the patient
by the mention of Smatterton; for, as soon as he heard the name he
started, turned pale, and was breathless and speechless for a
moment; and then recovering the use of his speech, he exclaimed,
“Smatterton! Smatterton! Good woman, are you in your senses?
What do you mean?”
Now it was very well for Mr Primrose and his composing draught
that the wife of the gate-keeper was not nervous; for had she been
nervous, that sudden and almost ridiculous exclamation, uttered as it
was, in a very high key, and with a very loud voice, would certainly
have upset the cup together with its contents. If ever a composing
draught was necessary, it clearly was so on this occasion. The good
woman however did not let the cup fall, but with the utmost
composure looked at the patient and said:
“Lawk-a-mercy, sir, don’t be in such a taking. I durst to say the
poor cretter wasn’t nobody as you know. She was a kind of a poor
young lady like. There now, sir, pray do take your physic, ’cause
you’ll never get well if you don’t.”
Mr Primrose was still in great agitation, and that more from
imagination than apprehension. His nervous sensibility had been
excited, and everything that at all touched his feelings did most
deeply move him. He therefore answered the poor woman in a
hurried manner:
“Come, come, good woman, I will swallow the medicine, if you will
have the goodness to tell me all you know about this poor young
lady.”
Now, as it was very little that the good woman did know, she
thought it might be for the patient’s advantage if he would take the
medicine even upon those terms. For she had so much respect for
the skill of the doctor, that it was her firm opinion that the draught
would have more power in composing, than her slender narrative in
disturbing, the gentleman’s mind. She very calmly then handed the
cup and said: “Well, sir, then if you will but take the physic, I will tell
you all I know about the matter.”
Mr Primrose complied with the condition, and took the medicine
with so much eagerness, that he seemed as if he were about to
swallow cup and all.
“There, sir,” said the good woman, mightily pleased at her own
management; “now I hope you will soon get better.”
“Well, now I have taken my medicine; so tell me all you know
about this young lady.”
“Why, sir, ’tisn’t much as I know: only, about two months ago, that
coach what you came by was going up to town, and it stopped, as it
always does, at our gate, and the coachman says to my husband,
says he, ‘Here’s a poor young lady in the coach so ill that she cannot
travel any farther; can you take her in for a day or two?’ And so I
went and handed the poor thing out of the coach, and I put her to
bed; and sure enough, poor thing, she was very ill. Then, sir, I sent
for the doctor; but, dear me, he could do her no good: and so then I
used to go and talk to the poor cretter, and all she would say to me
was, ‘Pray, let me die.’ But in a few days she grew a little better, and
began to talk about continuing her journey, and I found out, sir, that
the poor dear lady was broken-hearted.”
Here the narrator paused. But hitherto no definite information had
been conveyed to Mr Primrose, and he almost repented that he had
taken the trouble to swallow the medicine for such a meagre
narrative.
“And is that all you know, good woman? Did not you learn her
name?”
“Yes,” replied the informant: “her name was Fitzpatrick: and after
she was gone, I asked the coachman who brought her, and he told
me that that wicked young nobleman, Lord Spoonbill, had taken the
poor thing away from her friends, and had promised to make a fine
lady of her, but afterwards deserted her and sent her about her
business. And all because my lord was mighty sweet upon another
young lady what lives at Smatterton.”
Now came the truth into Mr Primrose’s mind, and he readily knew
that this other young lady was his Penelope. This corroborated the
letter which Mr Darnley had written to him on the decease of Dr
Greendale. Happy was it for the father of Penelope that he had no
suspicion of unworthy intentions towards his daughter on the part of
Lord Spoonbill; and well was it for the traveller that he had
swallowed the composing draught. He received the information with
tolerable calmness, and thanking the poor woman for indulging his
curiosity, he very quietly dismissed her. And as soon as she was
gone he muttered to himself:
“My child shall never marry a villain, though he may be a
nobleman.”
CHAPTER XVI.
Whether it was that the medicine which Mr Primrose had taken
possessed extraordinary composing powers, or whether his mind
had been quieted by its own outrageous agitations, we cannot say;
but to whatever cause it might be owing, it is a fact that, on the
following morning he was much more composed, and the medical
attendant pronounced that he might without any danger proceed on
his journey.
He was not slow in availing himself of this permission, and he also
followed the suggestion of his medical attendant in not travelling by
the stage-coach. After astonishing the gate-keeper and his wife, and
also the doctor, by his liberality for their attention to him, he started in
a post-chaise for Smatterton. No accident or interruption impeded his
progress, and at a late hour he arrived at Neverden, intending to pay
his first visit to Mr Darnley, and designing through him to
communicate to Penelope the knowledge of his arrival, and prepare
her for the meeting.
It was necessary for Mr Primrose to introduce himself to Mr
Darnley. The stately rector of Neverden was in his study. He was not
much of a reading man, he never had been; but still it was necessary
that he should keep up appearances, and therefore he occasionally
shut himself up in that room which he called his study; and there he
would read for an hour or two some papers of the Spectator, or some
old numbers of the Gentleman’s Magazine, or Blackstone’s
Commentaries, or any other book of equal reputation for sound
principles. There is a great advantage in reading those books that
everybody talks about and nobody reads. It was also very proper
that, if any of the parishioners called on the rector, it might be
necessary to send for him “out of the study.” Sometimes also Mr
Darnley gave audiences in his study, and then the unlearned
agriculturists thought him a most wonderful man to have so many
books, and so many large books too; some of them looking as big as

You might also like