100% found this document useful (2 votes)
61 views73 pages

R and Python For Oceanographers: A Practical Guide With Applications Hakan Alyurukinstant Download

The document provides information on downloading and exploring various ebooks and textbooks related to R and Python, specifically for oceanographers. It includes links to recommended products and details about the book 'R and Python for Oceanographers: A Practical Guide with Applications' by Hakan Alyuruk. Additionally, it covers the installation and usage of R, its environment, and integrated development environments for programming in R.

Uploaded by

sisabresci
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
61 views73 pages

R and Python For Oceanographers: A Practical Guide With Applications Hakan Alyurukinstant Download

The document provides information on downloading and exploring various ebooks and textbooks related to R and Python, specifically for oceanographers. It includes links to recommended products and details about the book 'R and Python for Oceanographers: A Practical Guide with Applications' by Hakan Alyuruk. Additionally, it covers the installation and usage of R, its environment, and integrated development environments for programming in R.

Uploaded by

sisabresci
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Download the full version and explore a variety of ebooks

or textbooks at https://ebookmass.com

R and Python for Oceanographers: A Practical Guide


with Applications Hakan Alyuruk

_____ Tap the link below to start your download _____

https://ebookmass.com/product/r-and-python-for-
oceanographers-a-practical-guide-with-applications-hakan-
alyuruk/

Find ebooks or textbooks at ebookmass.com today!


Here are some recommended products for you. Click the link to
download, or explore more at ebookmass.com

Applied Statistics with R: A Practical Guide for the Life


Sciences Justin C. Touchon

https://ebookmass.com/product/applied-statistics-with-r-a-practical-
guide-for-the-life-sciences-justin-c-touchon/

Practical Business Analytics Using R and Python 2nd


Edition Umesh R. Hodeghatta

https://ebookmass.com/product/practical-business-analytics-using-r-
and-python-2nd-edition-umesh-r-hodeghatta/

Synthetic Data for Deep Learning: Generate Synthetic Data


for Decision Making and Applications with Python and R 1st
Edition Necmi Gürsakal
https://ebookmass.com/product/synthetic-data-for-deep-learning-
generate-synthetic-data-for-decision-making-and-applications-with-
python-and-r-1st-edition-necmi-gursakal-2/

Synthetic Data for Deep Learning: Generate Synthetic Data


for Decision Making and Applications with Python and R 1st
Edition Necmi Gürsakal
https://ebookmass.com/product/synthetic-data-for-deep-learning-
generate-synthetic-data-for-decision-making-and-applications-with-
python-and-r-1st-edition-necmi-gursakal/
Health Analytics with Python: A Comprehensive Guide for
2024 Van Der Post

https://ebookmass.com/product/health-analytics-with-python-a-
comprehensive-guide-for-2024-van-der-post/

Python Programming for Beginners: 2 Books in 1 - the


Ultimate Step-By-Step Guide to Learn Python Programming
Quickly With Practical Exercises Mark Reed
https://ebookmass.com/product/python-programming-for-
beginners-2-books-in-1-the-ultimate-step-by-step-guide-to-learn-
python-programming-quickly-with-practical-exercises-mark-reed/

Financial Architect: Algorithmic Trading with Python: A


comprehensive Guide for 2024 Van Der Post

https://ebookmass.com/product/financial-architect-algorithmic-trading-
with-python-a-comprehensive-guide-for-2024-van-der-post/

Beginner's Guide to Streamlit with Python: Build Web-Based


Data and Machine Learning Applications 1st Edition Sujay
Raghavendra
https://ebookmass.com/product/beginners-guide-to-streamlit-with-
python-build-web-based-data-and-machine-learning-applications-1st-
edition-sujay-raghavendra/

Practical Business Analytics Using R and Python: Solve


Business Problems Using a Data-driven Approach 2nd Edition
Umesh R. Hodeghatta
https://ebookmass.com/product/practical-business-analytics-using-r-
and-python-solve-business-problems-using-a-data-driven-approach-2nd-
edition-umesh-r-hodeghatta/
R AND PYTHON
FOR OCEANOGRAPHERS
R AND PYTHON
FOR OCEANOGRAPHERS
A Practical Guide with Applications

HAKAN ALYURUK
Institute of Marine Sciences and Technology,
Dokuz Eylul University, Turkey
Elsevier
Radarweg 29, PO Box 211, 1000 AE Amsterdam, Netherlands
The Boulevard, Langford Lane, Kidlington, Oxford OX5 1GB, United Kingdom
50 Hampshire Street, 5th Floor, Cambridge, MA 02139, United States
© 2019 Elsevier Inc. All rights reserved.
No part of this publication may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, recording, or any information storage and retrieval system,
without permission in writing from the publisher. Details on how to seek permission, further
information about the Publisher’s permissions policies and our arrangements with organizations such
as the Copyright Clearance Center and the Copyright Licensing Agency, can be found at our website:
www.elsevier.com/permissions.
This book and the individual contributions contained in it are protected under copyright by the
Publisher (other than as may be noted herein).
Notices
Knowledge and best practice in this field are constantly changing. As new research and experience
broaden our understanding, changes in research methods, professional practices, or medical
treatment may become necessary.
Practitioners and researchers must always rely on their own experience and knowledge in evaluating
and using any information, methods, compounds, or experiments described herein. In using such
information or methods they should be mindful of their own safety and the safety of others, including
parties for whom they have a professional responsibility.
To the fullest extent of the law, neither the Publisher nor the authors, contributors, or editors, assume
any liability for any injury and/or damage to persons or property as a matter of products liability,
negligence or otherwise, or from any use or operation of any methods, products, instructions, or ideas
contained in the material herein.
Library of Congress Cataloging-in-Publication Data
A catalog record for this book is available from the Library of Congress
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library
ISBN: 978-0-12-813491-7

For information on all Elsevier publications visit our


website at https://www.elsevier.com/books-and-journals

Publisher: Candice Janco


Acquisition Editor: Louisa Munro
Editorial Project Manager: Hilary Carr
Production Project Manager:
Prem Kumar Kaliamoorthi
Cover Designer: Miles Hitchen

Typeset by SPi Global, India


CHAPTER 1

Introduction to R and Python

1.1 Introduction to R
R is a language and package-based software environment that provides a
wide variety of functions for statistical computing and graphics. R is a project
of GNU, and its root depends on S language with some differences.
S language and environment was developed by John Chambers and his col-
leagues at Bell Laboratories (formerly AT&T and now Lucent Technolo-
gies). While S language provides programmable research tools for
statistical analysis, R has evolved as an Open Source alternative of the
S language. R was initially developed by Robert Gentleman and Ross Ihaka
at the statistics department of the University of Auckland. Its name “R”
comes from the first letters of its developers. Besides its statistical capabilities
(such as linear and nonlinear modelling, classical statistical tests, time-series
analysis, classification, clustering, etc.), high-resolution publication-quality
plots can be produced with full control of the users. R is distributed under
the terms of Free Software Foundation’s GNU GPL license. Thanks to
terms of this license, source codes of both base distribution and external
packages with GPL license can be accessed, modified, and re-distributed
by the user. Therefore, data analysts can view and contribute to source codes
of these packages by accessing the running algorithms and adding their spe-
cific functions. As a result, scientists and students at universities can
use R freely and without a license fee. The use of free software in
science encourages and improves worldwide collaboration on data-analysis
approaches. Also, R is used in teaching statistics at undergraduate and grad-
uate levels at universities since students can freely use these statistical
tools [1, 2].
The base distribution of R is maintained by the R Development Core
Team since 1997. In addition, a huge group of volunteer developers con-
tribute to the project by developing new packages or upgrading existing
add-on packages to improve their functionalities. The project’s website is
the main official information source and can be reached from Fig. 1.1:
https://www.r-project.org

R and Python for Oceanographers © 2019 Elsevier Inc.


https://doi.org/10.1016/B978-0-12-813491-7.00001-4 All rights reserved. 1
2 R and Python for Oceanographers

Fig. 1.1 A view of official R-Project website.

1.2 R environment
R statistical environment system is composed of two main parts: base-
distribution system and add-on packages.

1.2.1 Base system of R


The base system consists of core functions required to run R language. Also,
core statistical functions (stats package) and graphical tools (graphics pack-
age) are included as dependencies of other add-on packages. Core packages
included in the installation media of base system cover standard statistical
functions, such as statistical tests, linear models, non-linear models, data-
handling functions, clustering functions, and survival-test functions. A list
of packages within the base system (included in R version 3.4.0) is
given below.
A list of base distribution packages:

base methods tools


compiler parallel translations
datasets splines utils
graphics stats
grDevices stats4
grid tcltk
Introduction to R and Python 3

1.2.2 Add-on packages


Add-on packages are developed and maintained by the user community.
These packages contain many advanced statistical, computational, and
graphical functions. Some of the packages have dependencies on other
packages.
Examples of add-on packages:

agricolae maps
car plyr
ggplot2 psych
lattice

1.3 Installation of R
1.3.1 Installation of R base software
R is an open source software, and it can be downloaded and installed freely.
Latest/older versions of R software for Windows, Linux, or Mac OSX oper-
ating systems could be downloaded and installed from http://cran.r-project.
org/ (Fig. 1.2).
In Linux systems, like Ubuntu, the latest version of R base (r-base) envi-
ronment can be installed from Software Center by adding official reposito-
ries of R-CRAN (Comprehensive R Archive Network) to the repository
list. In Debian systems, latest R version can be installed from Package Man-
ager after adding appropriate CRAN repositories. In Mac OSX systems, the
latest version of R can be downloaded from its official website and installed
according to the instructions.

1.3.2 Installation of add-on packages


You can install add-on packages from the internet into the package library
folder under R installation directory or any user-defined library folder as
below:
# install into default package library folder

install.packages("package_name")

# install into user defined library folder

install.packages("package_name", lib='C:\Program Files\R\R-


version\library')
4
R and Python for Oceanographers
Fig. 1.2 A view of R-Project download page.
Introduction to R and Python 5

Or you can install packages from the R console application under the Pack-
ages menu by clicking the install packages option. Then, you can select the
desired package to install from the drop-down list of add-on packages.
Alternatively, you can install a previously downloaded package from a
local file by following these instructions:
1. First download the latest versions of packages with their dependencies
from CRAN
2. Create PACKAGE and PACKAGE.gz logs for packages in the directory
with these codes:

library(tools)

write_PACKAGES("C:/Users/username/r_packages")

3. Delete PACKAGE.gz file


4. Run this code to install the package:

install.packages("package_name", contriburl="file:
C:/Users/username/r_packages ")

Optionally, the latest or test versions of some packages can be installed


directly from its Github page maintained by its user:
1. First install devtools package that allows the installation of packages from
Github repository as well as it provides many useful tools:

install.packages("devtools",
lib="file:C:/Users/username/r_packages")

2. Install desired package from its Github repository:

devtools::install_github("Github_username/package_name")

You can test the installation of add-on packages by loading them from
R console with this code:

library(package_name)

If the code runs without any errors, this means the installation of the package
was successful.
6 R and Python for Oceanographers

1.4 Integrated development environments (IDEs)


and editors for R
Commands, functions, and scripts of R language can be edited and saved
with lightweight and user-friendly code editors like Notepad++, RKWard,
Rgedit, Atom, Vim with Nvim-R plugin, Emacs with ESS plugin as well as
with other text editors. Some of these editors provide code highlighting,
autocompletion, and syntax error-checking functions. Behind these editors,
IDEs like Official R Console and Editor, R Studio, and Tinn-R have addi-
tional code execution and plotting capabilities. These IDEs have multi-panel
systems within a single application window, allowing the user to manage
scripts easier and faster.

1.4.1 Official R console and editor


R base software installation comes with an R editor for writing of com-
mands/scripts and an R console for execution of commands (Fig. 1.3).
The console is an interpreter of R language and works like a command line
interface such as CMD in Windows and Terminal in Linux systems. It is
possible to run saved scripts from a file and to load and save workspace
and history of commands. It is also possible to manage packages and to open
help files from the main menu bar.

1.4.2 RStudio
RStudio is a free and open source IDE for R language (Fig. 1.4). Compared
to official R console, it provides many advantages for editing and running of
scripts. RStudio is available for Windows, Linux, and Mac OSX systems.
More information about RStudio can be found at its official website:
https://www.rstudio.com/

1.5 Useful R commands


# show version number of R and installed OS

sessionInfo()

# show R version

getRversion()
Introduction to R and Python
Fig. 1.3 A screenshot of R editor and console.

7
8
R and Python for Oceanographers
Fig. 1.4 A screenshot of RStudio.
Introduction to R and Python 9

# show current working directory

getwd()

# change working directory to a user defined location

setwd("C:/...")

# list all packages in the R package library

library()

# open download mirrors list for package installation

available.packages()

# download R packages from CRAN repository to a local folder

download.packages("package_name", "download_directory")

# update all packages

update.packages(checkBuilt=TRUE)

# show version numbers of R packages, dependencies of packages, recom-


mended packages, license info and builded R version number

installed.packages()

# parses and returns the description file of a package

packageDescription("package_name")

# remove packages

remove.packages("package_name", "installed_directory")

# show license info

license()
10 R and Python for Oceanographers

# display citation

citation()

# attach packages

library(package_name)

# detach packages

detach("package:package_name")

# list all packages in the default library

library(lib.loc = .Library)

# list loaded packages

search()

# running time of R

proc.time()

# current memory usage

memory.size()

# total available memory

memory.limit()

# terminate an R session

q()

# display warning messages

warnings()
Introduction to R and Python 11

# display the commands history

history()

# load the commands history

loadhistory(file = ".Rhistory")

# save the commands history

savehistory(file = ".Rhistory")

# Save R image

sys.save.image("C:\\Users\\username\\...\\filename.RData")

sys.load.image("C:\\Users\\user\\...\\filename.RData")

1.6 Getting help for R


Both online and offline help documentations and manuals for R are avail-
able. You can start help while using R with help.start() function from the
console. For more help, you can use online documentations from the official
R website by using these links:
• Help page: https://www.r-project.org/help.html
• Manuals page: https://cran.r-project.org/manuals.html
• Frequently Asked Questions (FAQs) Page: https://cran.r-project.org/
faqs.html

1.7 Introduction to Python


Python is an interpreted, general-purpose, object-oriented and high-level
programming language. It was conceived by Guido van Rossum in the late
1980s, and its first implementation started in 1989. Python is developed as a
successor of ABC language at Centrum Wiskunde & Informatica (CWI) in
the Netherlands. In the development of Python, van Rossum also influ-
enced from Modula-3. As a result, Python has been evolved as a new
language that includes improvements over ABC and Modula-3 [3, 4].
12 R and Python for Oceanographers

Currently, the development of Python language is organized and supported


by Python Software Foundation (PSF).
Some advantages of Python as a data science tool are:
– It is simple, readable, and easy to learn.
– Python interpreter can run on multiple platforms: Windows, Linux, and
Mac OSX.
– It is possible to express functions with fewer codes compared to other
languages.
– It is an open source language and can be freely used and distributed.
– There are many libraries for scientific computing.
– It is possible to use Python in combination with other languages such as
C or C++.

1.8 Modules and packages in Python


The power of Python language depends on the availability of modules and
packages for wide ranges of applications. A module is a file that contains
functions and definitions [5]. Modules include pre-defined and special func-
tions, and they are imported at the start of Python scripts when needed.
Modules are created to keep functions modular and separate.
A package is a collection of related modules in a single hierarchical struc-
ture [6]. Packages can be very complex to include hundreds of individual
modules. Some examples of widely used and fundamental scientific Python
packages are: NumPy, SciPy, Matplotlib, Pandas, Sympy, IPython, scikit-
learn, seaborn, and SciTools.
These packages provide the following functionalities:
– NumPy is a base package for N-dimensional arrays, linear algebra, inte-
gration of C/C++, and Fortran codes, etc.
– SciPy is a fundamental library for scientific computing, such as numerical
integration and optimization.
– Matplotlib is a 2D plotting library for high quality and publication-ready
figures.
– Pandas provides high-performance data structure and data analysis tools.
– Sympy is a symbolic mathematics library.
– IPython is an enhanced interactive console for Python.
– scikit-learn is a machine learning library.
– seaborn is a matplotlib based visualization library for statistical graphics.
– SciTools is a scientific computing library built on top of other widely used
packages such as NumPy, SciPy, Gnuplot, etc.
Introduction to R and Python 13

1.9 Python IDEs


There are many IDEs for editing and running python scripts. This multi-
purpose software provides ease of writing, highlighting and formatting codes
as well as finding syntax errors. They also provide autocompletion function
and file/path browser for easy handling of script files. Some examples of
IDEs for scientific computing are: Python IDLE (Python’s Official Inte-
grated Development and Learning Environment), Eclipse, Eric and Spyder.
Application previews of Python IDLE and Spyder are given at Figs. 1.5 and
1.6, respectively.

1.10 Installing Python and scientific Python distributions


Python comes pre-installed in Linux and Mac OSX systems. In Windows,
Python interpreter could be installed from https://www.python.org/
downloads/windows/. In Linux and Mac OSX systems, individual scientific
python packages could be added to local python libraries.
In Linux and Mac OSX systems, standalone python packages (installation
of SciPy stack given as an example) could be installed by using one of the
below options:

1.10.1 Using pip package


To use this option, Python and pip should be already installed on your
system.
First, upgrade the pip package:

python -m pip install –upgrade pip

Then, install the latest version of a module and its dependencies from the
Python Packaging Index (PyPI):

python -m pip install package_name

For example, install SciPy stack using user option:

pip install –user numpy scipy matplotlib ipython jupyter


pandas sympy nose

Add user installation directory to system’s PATH by,


14
R and Python for Oceanographers
Fig. 1.5 A screenshot of Python IDLE.
Introduction to R and Python
Fig. 1.6 A screenshot of Spyder IDE.

15
16 R and Python for Oceanographers

For Linux:
# Add below command to the end of your /.bashrc file

export PATH="$PATH:/home/your_user/.local/bin"

For Mac OSX,


# Add below command to the end of your /.bash_profile file

export PATH="$PATH:/Users/your_user/Library/Python/3.5/bin"

Change “your_user” with your username and “3.5” with Python version
installed on your system.

1.10.2 Using package managers


Depending on the availability of packages and their update status on the
repositories of your operating system, this option might install latest/previ-
ous versions of packages.
In Linux, you can choose from these options, depending on your
distribution:
For Ubuntu or Debian systems,

sudo apt-get install package_name

For example, to install SciPy stack using this option:

sudo apt-get install python-numpy python-scipy python-


matplotlib ipython ipython-notebook python-pandas python-
sympy python-nose

For Fedora:

sudo dnf install package_name

For example, to install SciPy stack using this option,

sudo dnf install numpy scipy python-matplotlib ipython


python-pandas sympy python-nose atlas-devel
Introduction to R and Python 17

1.10.3 Using source files of packages


If package files are not found at PyPI and at repositories of your operating
system, you can use this option. First, download the latest source code of the
package to a local directory. Uncompress the installation files from the
downloaded source file (usually compressed as tar.gz or zip files). Then,
run these codes to install the package:
For Linux systems

python setup.py install

For Windows

setup.py install

Detailed instructions for installation of SciPy stack could be found at https://


www.scipy.org/install.html. Depending on their availabilities at your sys-
tem’s repositories, other python packages could also be installed by using
package managers or by installing from their source files.
For windows systems, scientific python distributions are the easiest solu-
tion to use scientific python packages. They provide a great number of pack-
ages with a single software installation. Canopy (by Enthought), Anaconda
(by Continuum Analytics), and Python(x,y) are among several scientific
python distributions that are free to use for educational and academic pur-
poses. Canopy and Anaconda are multi-platform (Windows, Linux, and
Mac OS-X versions are available) distributions with the support of the latest
package updates, whereas Python(X,Y) is only available for Windows sys-
tems with update schedules at longer intervals. An application preview of
Canopy Editor is given at Fig. 1.7 as an example.
Some advantages of using these scientific python distributions are as
follows:
– Python packages are automatically installed along with Python
environment.
– It is possible to manage packages from GUI package managers.
– Python code editor and interpreter are provided in the same application
window.
Download links for the latest and older versions of Canopy, Anaconda,
Miniconda and Python(x,y). Distributions are given below:
– Canopy: https://store.enthought.com/downloads
– Anaconda: https://www.continuum.io/downloads
18
R and Python for Oceanographers
Fig. 1.7 A screenshot of Canopy Editor.
Introduction to R and Python 19

– Miniconda: https://conda.io/miniconda.html
– Python(x,y): https://python-xy.github.io/downloads.html
To test the Python installation:
– Open terminal (in Linux/Mac OSX)/command prompt (in Windows),
type python and press enter or click Python icon from the start menu.
– Then, run the following code at the Python shell:

import sys
print sys.version_info

– If you get the below output, it means that Python (version 2) works with-
out any problem on your system.

sys.version_info(major=2, minor=..., micro=..., ...)

1.11 Getting help for Python


Python has online and offline help documentations. You can start help while
using Python with help() function from the console. For more help, you can
use online documentations from the official Python website by using the
following links.
• Documentation page: https://www.python.org/doc/
• Help page: https://www.python.org/about/help/
• FAQs page: https://docs.python.org/2.7/faq/ or https://docs.python.
org/3/faq/

1.12 Some useful packages and libraries in R


and Python for oceanography
In R and Python, some packages useful for oceanographic and geographical
purposes are as follows:

R packages Python libraries


• OceanView • numpy
• marelac • matplotlib
• oce • pandas
• ocedata • basemap
• oceanmap • scipy
• maps • netcdf4
Continued
20 R and Python for Oceanographers

R packages Python libraries


• mapdata • iris
• mapproj • cartopy
• rworldmap • gsw
• rworldxtra • seawater
• ggmap • oceans
• rgdal • rgdal
• geosphere • geos
• OpenStreetMap • shapely
• rgeos • ctd
• maptools • proj4
• marmap • pyproj
• GISTools • pyshp
• PBSmapping • geopandas
• spatialkernel • geoplot
• geoR • GeoRasters
• automap • gridded
• RNetCDF • seabird

In this book, R examples were prepared with R version > 3 and tested
with latest R 3.5.1 version.
Python examples were prepared and tested with package versions in
Miniconda Python Environment.
A simple conda environment can be created, and necessary packages can
be installed from command line/terminal by typing:
# Create python environment

conda create -n env_name python=2

# Activate new environment

conda activate env_name

# Install packages

conda install -n env_name numpy=1.11.3 matplotlib=1.5.3


pandas=0.17.0 basemap=1.0.7 scipy=0.19.1 netcdf4=1.2.4
cartopy=0.14.3 gsw=3.0.6 seawater=3.3.4 oceans=0.4.0
netcdftime iris=1.9.2 geopy=1.11.0 cmocean

# Install seabird package with pip

pip install seabird


Introduction to R and Python 21

References
[1] B.S. Everitt, T. Hothorn, A Handbook of Statistical Analyses Using R, second ed., CRC
Press, Florida, 2010.
[2] R-Project Website, About R, n.d. https://www.r-project.org/about.html. Accessed
01 September 2017.
[3] A. Boschetti, L. Massaron, Python Data Science Essentials, first ed., Pack Publishing,
Birmingham, 2015.
[4] Python Documentation, Foreword for “Programming Python” n.d. (1st ed.), http://
legacy.python.org/doc/essays/foreword/. Accessed 01 September 2017.
[5] Python Documentation, n.d. Modules, https://docs.python.org/2.7/tutorial/modules.
html. Accessed 01 September 2017.
[6] Python Documentation, n.d. Packages, https://docs.python.org/2.7/tutorial/modules.
html#packages. Accessed 01 September 2017.
CHAPTER 2

Data import and export


in R and Python

2.1 Object types in R


Vectors, matrices, arrays, data frames, lists, factors, and functions are object
types used to store data in R [1]. Their uses are explained in the following
examples.

2.1.1 Vectors
c is a generic function that combines its arguments as a vector.
For details run:

?c

Examples:
# Numeric vector

vector1 <- c(-1.5,-1,0,1,1.5)

vector1
[1] -1.5 -1.0 0.0 1.0 1.5

class(vector1)
[1] "numeric"

# Character vector

vector2 <- c("Train","Bus","Taxi","Subway","Tramway")

vector2
[1] "Train" "Bus" "Taxi" "Subway" "Tramway"

class(vector2)
[1] "character"

R and Python for Oceanographers © 2019 Elsevier Inc.


https://doi.org/10.1016/B978-0-12-813491-7.00002-6 All rights reserved. 23
24 R and Python for Oceanographers

# Logical vector

vector3 <- c(TRUE,FALSE,TRUE)

vector3
[1] TRUE FALSE TRUE

class(vector3)
[1] "logical"

# Date vector (defined as character vector and transformed to date)

vector4 <- as.Date(c("2003-10-05","2003-10-10","2003-10-15",


"2003-10-20","2003-10-25"))

vector4
[1] "2003-10-05" "2003-10-10" "2003-10-15" "2003-10-20" "2003-10-25"

class(vector4)
[1] "Date"

2.1.2 Matrices
Matrix is a function that creates a matrix from the given set of values.
In R, a matrix is the special case of a two-dimensional array.
In a matrix, all columns must have the same class (numeric, character, or
logical) and the same length.
Usage of a matrix function:

matrix(vector, nrow=r, ncol=c, byrow=FALSE, dimnames=list(char_


vector_rownames, char_vector_colnames))

For details, run:

?matrix

Examples:
# create a 2 x 2 numeric matrix

mat1 <-matrix(1:4, nrow=2,ncol=2)

# create a 2 x 2 numeric matrix with row and column names, data is filled by
rows.
Data import and export in R and Python 25

data_vector <- c(1:4)


row_names <- c("R1","R2")
col_names <- c("C1","C2")
mat2 <- matrix(data_vector, nrow=2, ncol=2, byrow=TRUE,
dimnames=list(row_names, col_names))

2.1.3 Arrays
Array function creates an array with n dimensions (dim) and their names
(dimnames).
An array could have one, two, or more dimensions. A two-dimensional
array is the same as a matrix.
Usage of an array function:

array(data = NA, dim = length(data), dimnames = NULL)

For details, run:

?array

Examples:

vector1 <- c(1,2,3,4)


vector2 <- c(5,6,7,8)
vector3 <- c(9,10,11,12)

matrix_name <- c("Matrix")


matrix_names <- c("Matrix 1","Matrix 2")
row_names <- c("R1","R2","R3","R4")
col_names1 <- c("C1")
col_names2 <- c("C1","C2")
col_names3 <- c("C1","C2","C3")

array1 <- array(vector1, dim=c(4,1,1),


dimnames=list(row_names,col_names1,matrix_name))

array2 <- array(c(vector1,vector2), dim=c(4,2,1),


dimnames=list(row_names,col_names2,matrix_name))

array3 <- array(c(vector1,vector2,vector3), dim=c(4,3,1),


dimnames=list(row_names,col_names3,matrix_name))

array4 <- array(c(vector1,vector2,vector3), dim=c(4,3,2),


dimnames=list(row_names,col_names3,matrix_names))
26 R and Python for Oceanographers

2.1.4 Data frames


In a data frame, different types of vectors (numeric, character, logical, or
date) could be defined.
Lengths of the vectors should be the same, and the vectors are stored in
columns.
Usage of data frames:

data.frame(..., row.names = NULL, check.rows = FALSE,


check.names = TRUE, fix.empty.names = TRUE,
stringsAsFactors = default.stringsAsFactors())

For details, run:

?data.frame

Example:

vector1 <- c(-1.5,-1,0,1,1.5)


vector2 <- c("Train","Bus","Taxi","Subway","Tramway")
vector3 <- c(TRUE,FALSE,TRUE,TRUE,FALSE)
vector4 <- as.Date(c("2003-10-05","2003-10-10","2003-10-
15","2003-10-20","2003-10-25"))

data_frame <- data.frame(num=vector1, char=vector2,


log=vector3,date=vector4,stringsAsFactors=FALSE)

names(data_frame) <-
c("numeric","character","logical","date")

2.1.5 Lists
In lists, objects are stored in the order they are given. Different types of
objects can be stored in lists.
For details, run:

?list

Examples:

vector1 <- c(-1.5,-1,0,1,1.5)


vector2 <- c("Train","Bus","Taxi","Subway","Tramway")
Data import and export in R and Python 27

vector3 <- c(TRUE,FALSE,TRUE)


vector4 <- as.Date(c("2003-10-05","2003-10-10","2003-10-15"))

matrix1 <-matrix(1:4, nrow=2,ncol=2)

list1 <- list(vec1=vector1, vec2=vector2, vec3=vector3,


vec4=vector4, mat=matrix1)

list2 <- list(vec2=vector2, vec4=vector4)

list3 <- c(list1,list2)

2.1.6 Factors
Factor is a function used to define a vector as a factor. The orders of variables
in a factor can be controlled by levels.
For details, run:

?factor

Examples:

vector1 <- c(5,10,15,20)


factor1 <- factor(vector1)
factor1

factor2 <- factor(vector1, levels=c(20,10,5,15))


factor2

factor3 <- factor(vector1, levels=c(10,5,20,15),


labels=c("august","february","may","november"))
factor3

2.1.7 Functions
R has many built-in functions, but in some cases, it is more useful to create
user-defined functions for a specific task.
A sample function to find roots of a quadratic equation:

quad_root <- function(a, b, c){

delta <- (b^2) - 4*a*c


if (delta>0) {

Continued
28 R and Python for Oceanographers

pos_root <- format(((-b) + sqrt(delta)) / (2*a),


digits=2, nsmall=2)

neg_root <- format(((-b) - sqrt(delta)) / (2*a),


digits=2, nsmall=2)
print(paste("Positive root: ",pos_root))
print(paste("Negative root: ",neg_root))
} else if (delta==0) {
root <- format((-b) / (2*a), digits=2, nsmall=2)
print(paste("Root: ",root))

} else {
root_real <- format((-b) / (2*a), digits=2,
nsmall=2)
root_imag <- format(sqrt(abs(delta)) / (2*a),
digits=2, nsmall=2)
print(paste("For quadratic equation of ",a,"x^2 +",b,
"x +",c,":"))

print(paste("Roots are complex numbers: ",


root_real, "\U00B1", root_imag,"i"))
}
}

# define coefficients of the 2nd order polynomial

a <- 5; b <- 4; c <- 3

quad_root(a,b,c)
[1] "For quadratic equation of 5 x^2 + 4 x + 3 :"
[1] "Roots are complex numbers: -0.40 ± 0.66 i"

You can also use built-in polyroot function to find roots.

polyroot(c(3,4,5))
[1] -0.4+0.663325i -0.4-0.663325i

2.2 Data import in R


Data can be imported from many file types such as txt, dat, csv, xls, xlsx, nc
(netCDF4), mat (Matlab), and cnv (Seabird). These are some of the file types
mostly used in storage of oceanographic data. In the following data import-
ing examples, data files exported in Section 2.3 can be used.
Data import and export in R and Python 29

2.2.1 Import from txt, dat, csv and Excel xls, xlsx files

data <- read.table("/path/data.txt", header=TRUE, sep="/t")

data <- read.table("/path/data.dat", header=TRUE, sep=";")

data <- read.table("/path/data.csv", header=TRUE, sep=",")

library(xlsx)

data <- read.xlsx("/path/data.xls", sheetIndex=1, header=TRUE)

data <- read.xlsx("/path/data.xlsx", sheetIndex=1, header=TRUE)

data <- read.xlsx("/path/data.xlsx", sheetName="Sheet1",


header=TRUE)

2.2.2 Import from netCDF4 file

library(ncdf4)
ncin <- nc_open("/path/seasurf_ts.nc")
ncin

lon <- ncvar_get(ncin, "lon")

lat <- ncvar_get(ncin, "lat")

t1 <- ncvar_get(ncin, "temp_val")

s1 <- ncvar_get(ncin, "sal_val")

2.2.3 Import from mat files

setwd('/path_to_working_directory/')
library(R.matlab)

data <- readMat('data_m5.mat')


str(data)
30 R and Python for Oceanographers

2.2.4 Import from SeaBird cnv files

library(oce)

f <- read.ctd("/path/ctd.cnv")
f

summary(f )

plot(f )

f[['temperature']]

Data in this example was retrieved from GitHub page of oce package:
“https://github.com/dankelley/oce/blob/develop/tests/testthat/
local_data/ctd.cnv”

2.2.5 Import data from online databases


Import tab delimited text data from LOBO-0010 Northwest Arm,
Halifax, Canada
This example demonstrates reading data in text format from online database
of Land/Ocean Biogeochemical Observatory (LOBO) system measuring
biogeochemical parameters with chemical and physical sensors at Northwest
Arm, Halifax, and Canada (URL: http://lobo.satlantic.com/).

url <- 'http://lobo.satlantic.com/cgi-data/nph-data.cgi?


min_date=20101225&max_date=20101230&y=temperature,salinity'

colnames <- c('DATE_TIME','TEMPERATURE','SALINITY')

tmpFile <- tempfile()

download.file(url, destfile = tmpFile, method = "auto")

url.data <- read.table(tmpFile, header=FALSE, sep='\t',


col.names=colnames, skip=1)

print(url.data)

2.2.6 Import csv.gz file from WOA13 V2


This example demonstrates reading data in compressed csv format from the
online database of World Ocean Atlas 2013 V2 (WOA13 V2) maintained by
NOAA (URL: https://www.nodc.noaa.gov/OC5/woa13/). WOA13 V2
is a set of climatological data with 1° grid resolution and provides annual,
Data import and export in R and Python 31

seasonal, and monthly in situ temperature, salinity, dissolved oxygen, Appar-


ent Oxygen Utilization (AOU), percent oxygen saturation, phosphate,
silicate, and nitrate data at standard depth levels for the World Ocean.

url <-
'http://data.nodc.noaa.gov/woa/WOA13/DATAv2/temperature/
csv/decav/1.00/woa13_decav_t07mn01v2.csv.gz'

colnames <-
c('LATITUDE','LONGITUDE','0','5','10','15','20','25','30','35',
'40','45','50','55','60','65','70','75','80','85','90','95',
'100','125','150','175','200','225','250','275','300','325',
'350','375','400','425','450','475','500','550','600','650',
'700','750','800','850','900','950','1000','1050','1100',
'1150','1200','1250','1300','1350','1400','1450','1500')

tmpFile <- tempfile()

download.file(url, destfile = tmpFile, method = "auto")

url.data <- read.csv(tmpFile, header=FALSE, sep=',',


col.names=colnames, skip=2)

datasub <- subset(url.data, LATITUDE=="36.5" & LONGITUDE > 0


& LONGITUDE < 30, select=c(LATITUDE,LONGITUDE,X0,X5,X10))

print(datasub)

2.3 Data export in R


Raw or processed data in R can be exported as file types, such as txt, dat, csv,
xls, xlsx, nc (netCDF4), and mat (Matlab).

2.3.1 Export as txt, dat, csv and Excel xls, xlsx files
# Import data

data <- read.table("/path/data.txt ", header=TRUE, sep="\t")

# Export data

write.table(data, "/path/data.txt", sep="\t", quote=FALSE,


dec=".", row.names=FALSE, col.names=TRUE)

write.table(data, "/path/data.dat", sep=";", quote=FALSE,


dec=".", row.names=FALSE, col.names=TRUE)

Continued
32 R and Python for Oceanographers

write.table(data, "/path/data.csv", sep=",", quote=FALSE,


dec=".", row.names=FALSE, col.names=TRUE)

library(xlsx)

write.xlsx(data, "/path/data.xls", sheetName="Sheet1",


col.names=TRUE, row.names=FALSE, append=FALSE, showNA=TRUE,
password=NULL)

write.xlsx(data, "/path/data.xlsx", sheetName="Sheet1",


col.names=TRUE, row.names=FALSE, append=FALSE, showNA=TRUE,
password=NULL)

2.3.2 Export as netCDF4 file

library(ncdf4)

setwd("/path_to_working_directory/")

# generate lons, lats and set time

lon <- as.array(seq(26.59,26.72,0.0005))


nlon <- dim(lon)

lat <- as.array(seq(38.57,38.67,0.0005))


nlat <- dim(lat)

temp <- as.array(rnorm(nlon*nlat, mean=18, sd=2.5))


ntemp <- dim(temp)
tunit <- "Celcius"

sal <- as.array(rnorm(nlon*nlat, mean=38, sd=1.2))


nsal <- dim(sal)
sunit <- "psu"

# nlon * nlat * nt array

temp_array <- array(temp, dim=c(nlon,nlat))


sal_array <- array(sal, dim=c(nlon,nlat))
Data import and export in R and Python 33

# define dimensions

londim <- ncdim_def("lon","degrees_east",as.double(lon))


latdim <- ncdim_def("lat","degrees_north",as.double(lat))
tempdim <- ncdim_def("temp",tunit,as.double(temp))
saldim <- ncdim_def("sal",sunit,as.double(sal))

# define variables

fillvalue <- 1e32

dlname <- "sea surface temperature"

temp_def <-
ncvar_def("temp_val","deg_C",list(londim,latdim),fillvalue,
dlname,prec="single")

dlname <- "sea surface salinity"

sal_def <-
ncvar_def("sal_val","psu",list(londim,latdim), fillvalue,
dlname,prec="single")

# create netCDF file and add arrays

ncfname <- "seasurf_ts.nc"


ncout <-
nc_create(ncfname,list(temp_def,sal_def ),force_v4=T)

# add variables

ncvar_put(ncout,temp_def,temp_array)
ncvar_put(ncout,sal_def,sal_array)

# add additional attributes into dimension and data variables

ncatt_put(ncout,"lon","axis","X") #,verbose=FALSE)
#,definemode=FALSE)
ncatt_put(ncout,"lat","axis","Y")

# add global attributes

title <- paste("Sea Surface Temperature and Salinity")


institution <- paste("DEU, IMST")
source <- paste("Project 1, Survey 1")

Continued
34 R and Python for Oceanographers

history <- paste("H.A.", date(), sep=",")


references <- paste("")
conventions <- paste("")

ncatt_put(ncout,0,"title",title)
ncatt_put(ncout,0,"institution",institution)
ncatt_put(ncout,0,"source",source)
ncatt_put(ncout,0,"references",references)
ncatt_put(ncout,0,"history",history)
ncatt_put(ncout,0,"Conventions",conventions)

# save and close the file

nc_close(ncout)

2.3.3 Export as Matlab mat files

setwd(/path_to_working_directory/')

library(R.matlab)

lon <- as.array(seq(26.59,26.72,0.0005))


lat <- as.array(seq(38.57,38.67,0.0005))
temp <- as.array(rnorm(dim(lon)*dim(lat), mean=18, sd=2.5))
sal <- as.array(rnorm(dim(lon)*dim(lat), mean=38, sd=1.2))

A <- matrix(1:30, ncol=3)


B <- as.matrix(1:20)
C <- array(1:15, dim=c(2,2,3))

writeMat("data_m5.mat", lon=lon, lat=lat, temp=temp, sal=sal,


A=A, B=B, C=C)

2.4 Object types in Python


In Python, numeric and character data are stored as lists, tuples, dictionaries,
sets, and functions. It is also possible to store numeric data as NumPy arrays,
Pandas series, and Pandas data frames (Table 2.1) [2,3].
Data import and export in R and Python 35

Table 2.1 Standard data and object types in Python


Object type Example Properties
Lists [1, 12, 2.46] Mutable sequences, used with square
brackets.
Tuples (3, 4.5, ‘unit’, ‘D’), Immutable sequences, used with
tuple(‘extra’) parenthesis.
Dictionaries {‘Jack’: ‘train’, ‘Sally’: Data stored as key: value pair. Used
‘subway’} with curly braces.
Sets {‘r’, ‘u’, ’n’}, set(’run’) Collections of unique elements.

2.4.1 Arrays in Numpy package


Create an array
Usage of array function:

numpy.array(object, dtype = None, copy = True, order = None,


subok = False, ndmin = 0)

For more details, run:

help(np.array)

Example:

array1 = np.array([1,2,3])

print array1

array2 = np.array([1,2,3],[4,5,6])

print array2

Create array from existing data


Usage of asarray function:

numpy.asarray(a, dtype = None, order = None)

For more details, run:

help(np.asarray)
36 R and Python for Oceanographers

Example:

import numpy as np

list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]

array1 = np.asarray([list1, list2, list3])

print array1

array2 = np.transpose(array1)

print array2

2.4.2 Series and data frame objects in Pandas package


Pandas Series
Pandas Series is a one-dimensional array with axis labels, and it can store dif-
ferent types of data (integer, string, other python objects, etc.) [2].
Usage of Series function:

pd.Series(data, index, dtype, copy)

For more details, run:

help(pd.Series)

Example:

import numpy as np
import pandas as pd

array = np.array([1,2,3])

print array

series = pd.Series(array)

print series

data = [1,2,3]

series2 = pd.Series(data)

print series2
Data import and export in R and Python 37

Pandas Data Frames


Pandas Data Frame has a two-dimensional data structure and stores data in a
table-like format within rows and columns. Different data types can be
stored in different columns; mutable object, rows, and columns can be
labeled, and arithmetic operations can be performed on rows and columns.
Pandas Data Frames can be created from objects like lists, sets, dictionaries,
and NumPy arrays.
Usage of DataFrame function:

pd.DataFrame(data, index, columns, dtype, copy)

import numpy as np
import pandas as pd

list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]

array1 = np.asarray([list1, list2, list3])


array2 = np.transpose(array1)

data_frame = pd.DataFrame(array2,columns=['Col1','Col2','Col3'])

data = [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]

data_frame2 = pd.DataFrame(data,columns=['Col1','Col2','Col3'])

2.4.3 User-defined functions in Python


Python has many built-in functions, but in some cases, it is useful to create
user-defined functions for a specific task.
A sample function to find roots of a quadratic equation:

import math

def quad_root(a,b,c):

delta = b**2 - 4*a*c


if delta > 0:
pos_root = ((-1.*b)+math.sqrt(delta))/(2*a)
neg_root = ((-1.*b)-math.sqrt(delta))/(2*a)
print "Positive root: %.2f" % (pos_root)
print "Negative root: %.2f" % (neg_root)

Continued
38 R and Python for Oceanographers

elif delta == 0:
root = (-1.*b) / (2*a)
print "Root: %.2f" % (root)
else:
root_real = (-1.*b) / (2*a)
root_imag = math.sqrt(math.fabs(delta)) / (2*a)
print "For quadratic equation of %d x^2 + %d x + %d
:" % (a,b,c)
print "Roots are complex numbers: %.2f +- %.2f i" %
(root_real,root_imag)

# define coefficients of the 2nd order polynomial

a = 5
b = 4
c = 3

quad_root(a,b,c)

You can also use built-in numpy.roots function to find roots:

import numpy as np

coeffs = [a,b,c]

roots = np.roots(coeffs)

2.5 Data import in Python


In Python, data can be imported from many file types, such as txt, dat, csv,
xls, xlsx, nc (netCDF4), mat (Matlab), and cnv (Seabird). In the following
data importing examples, data files in Section 2.6 can be used.

2.5.1 Import from txt, dat, csv, and Excel xls, xlsx files
with Numpy loadtxt

import numpy as np
import os
os.chdir(/path_to_working_directory/')

depth,do,phos,tnox,si = np.loadtxt('data.csv', unpack=True,


usecols=None, skiprows=1, delimiter=',')
Data import and export in R and Python 39

depth,do,phos,tnox,si = np.loadtxt('data.txt', unpack=True,


usecols=None, skiprows=1, delimiter='\t')

depth,do,phos,tnox,si = np.loadtxt('data.dat', unpack=True,


usecols=None, skiprows=1, delimiter=';')

2.5.2 Import from Excel xls files with Pandas read_excel

import pandas as pd
import numpy as np
import os
os.chdir(/path_to_working_directory/')
np.set_printoptions(precision=4)
pdata = pd.read_excel('data.xls')
ndata = np.array(pdata, 'g')
ndata

depth = np.take(ndata, 0, axis=1)


do = np.take(ndata, 1, axis=1)
phos = np.take(ndata, 2, axis=1)
tnox = np.take(ndata, 3, axis=1)
si = np.take(ndata, 4, axis=1)

2.5.3 Import from Excel xlsx files with Pandas read_excel

import pandas as pd
import numpy as np
import os
os.chdir(/path_to_working_directory/')
np.set_printoptions(precision=4)
pdata = pd.read_excel('data.xlsx')
ndata = np.array(pdata, 'g')
ndata

depth = np.take(ndata, 0, axis=1)


do = np.take(ndata, 1, axis=1)
phos = np.take(ndata, 2, axis=1)
tnox = np.take(ndata, 3, axis=1)
si = np.take(ndata, 4, axis=1)
40 R and Python for Oceanographers

2.5.4 Import from netCDF4 file

import netCDF4 as nc

# open a local NetCDF file or remote data URL

file = '/path/py_ss_ts.nc'
ncd = nc.Dataset(file, 'r')

# Print variables, dimensions, units and general descriptions

print ncd

# Print attributes for all variables

print ncd.variables

# Print all variable names

print ncd.variables.keys()

# Print all attributes of a specific variable

print ncd.variables['Temperature']

tvar = ncd.variables['Temperature']

# Print attribute names of a specific variable

print tvar.ncattrs()

# Print units of a variable

print tvar.getncattr('units')

# Copy values from a specific variable to a newly defined variable

tempv = ncd.variables['Temperature'][:]
Data import and export in R and Python 41

2.5.5 Import from Matlab mat files

import scipy.io

file 1 = '/path/data_m5.mat'

mat1 = scipy.io.loadmat(file1, mat_dtype=True)

vars1 = scipy.io.whosmat(file1)

mat1.keys()

temp = mat1['temp']

type(temp)

2.5.6 Import from Seabird cnv file

import os
os.chdir('/path_to_working_directory/')

from seabird.cnv import fCNV

profile = fCNV('dPIRX003.cnv')
profile.attributes

print "The profile coordinates is latitude: %.4f, and


longitude: %.4f" % \
(profile.attributes['LATITUDE'],
profile.attributes['LONGITUDE'])
print profile.keys()
print profile['TEMP'].mean(), profile['TEMP'].std()

from matplotlib import pyplot as plt

plt.plot(profile['TEMP'], profile['PRES'],'b')
plt.plot(profile['TEMP2'], profile['PRES'],'g')
plt.gca().invert_yaxis()
plt.xlabel('temperature')
plt.ylabel('pressure')
plt.title(profile.attributes['filename'])
plt.show()
42 R and Python for Oceanographers

2.5.7 Import data from online databases


Import tab delimited text data from LOBO-0010 Northwest Arm,
Halifax, Canada

import pandas as pd

url = 'http://lobo.satlantic.com/cgi-data/nph-data.cgi?
min_date=20101225&max_date=20101230&y=temperature,salinity'

colnames = ['DATE_TIME','TEMPERATURE','SALINITY']

data = pd.read_csv(url, delimiter='\t', compression=None,


error_bad_lines=False, warn_bad_lines=False, skiprows=[0],
names=colnames)

print data

Import all data in a csv file

import pandas as pd

url =
'https://data.nodc.noaa.gov/woa/WOA13/DATAv2/temperature/csv/
decav/1.00/woa13_decav_t07mn01v2.csv.gz'

colnames =
['LATITUDE','LONGITUDE','0','5','10','15','20','25','30','35',
'40','45','50','55','60','65','70','75','80', '85','90','95','
100','125','150','175','200','225','250','275','300','325',
'350','375','400','425','450','475','500','550','600','650',
'700','750','800','850','900','950','1000', '1050','1100',
'1150','1200','1250','1300','1350','1400','1450','1500']

data = pd.read_csv(url, delimiter=',', compression='gzip',


error_bad_lines=False, warn_bad_lines=False, skiprows=[0,1],
names=colnames)

print data

Import block of data at defined ranges of rows and columns


It is possible to import data as a block of rows and columns by defining use-
cols and nrows parameters in read_csv function.
Other documents randomly have
different content
proper to bestow the fragments in support, and the tithes in tuition, of the
poor.

But, without even such small cost, they might have taught the poor many
beneficial things. In some places they have taught them manners, which is
already much. They might have cheaply taught them merriment also:—
dancing and singing, for instance. The young English ladies who sit nightly
to be instructed, themselves, at some cost, in melodies illustrative of the
consumption of La Traviata, and the damnation of Don Juan, might have
taught every girl peasant in England to join in costless choirs of innocent
song. Here and there, perhaps, a gentleman might have been found able to
teach his peasantry some science and art. Science and fine art don’t pay; but
they cost little. Tithes—not of the income of the country, but of the income,
say, of its brewers—nay, probably the sum devoted annually by England to
provide drugs for the adulteration of its own beer,—would have founded
lovely little museums, and perfect libraries, in every village. And if here and
there an English churchman had been found (such as Dean Stanley) willing
to explain to peasants the sculpture of his and their own cathedral, and to
read its black-letter inscriptions for them; and, on warm Sundays, when
they were too sleepy to attend to anything more proper—to tell them a story
about some of the people who had built it, or lay buried in it—we perhaps
might have been quite as religious as we are, and yet need not now have
been offering prizes for competition in art schools, nor lecturing with tender
sentiment on the inimitableness of the works of Fra Angelico.

These things the great Picnic Party might have taught without cost, and with
amusement to themselves. One thing, at least, they were bound to teach,
whether it amused them or not;—how, day by day, the daily bread they
expected their village children to pray to God for, might be earned in
accordance with the laws of God. This they might have taught, not only
without cost, but with great gain. One thing only they have taught, and at
considerable cost.

They have spent four hundred millions4 of pounds here in England within
the last twenty years!—how much in France and Germany, I will take some
pains to ascertain for you,—and with this initial outlay of capital, have
taught the peasants of Europe—to pull each other’s hair.

With this result, 17th January, 1871, at and around the chief palace of their
own pleasures, and the chief city of their delights:

“Each demolished house has its own legend of sorrow, of pain, and horror; each
vacant doorway speaks to the eye, and almost to the ear, of hasty flight, as armies
or fire came—of weeping women and trembling children running away in awful
fear, abandoning the home that saw their birth, the old house they loved—of
startled men seizing quickly under each arm their most valued goods, and rushing,
heavily laden, after their wives and babes, leaving to hostile hands the task of
burning all the rest. When evening falls, the wretched outcasts, worn with fatigue
and tears, reach Versailles, St. Germain, or some other place outside the range of
fire, and there they beg for bread and shelter, homeless, foodless, broken with
despair. And this, remember, has been the fate of something like a hundred
thousand people during the last four months. Versailles alone has about fifteen
thousand such fugitives to keep alive, all ruined, all hopeless, all vaguely asking
the grim future what still worse fate it may have in store for them.”—Daily
Telegraph, Jan. 17th, 1871.

That is the result round their pleasant city, and this within their industrious
and practical one: let us keep, for the reference of future ages, a picture of
domestic life, out of the streets of London in her commercial prosperity,
founded on the eternal laws of Supply and Demand, as applied by the
modern Capitalist:

“A father in the last stage of consumption—two daughters nearly marriageable


with hardly sufficient rotting clothing to ‘cover their shame.’ The rags that hang
around their attenuated frames flutter in strips against their naked legs. They have
no stool or chair upon which they can sit. Their father occupies the only stool in
the room. They have no employment by which they can earn even a pittance.
They are at home starving on a half-chance meal a day, and hiding their
raggedness from the world. The walls are bare, there is one bed in the room, and a
bundle of dirty rags are upon it. The dying father will shortly follow the dead
mother; and when the parish coffin encloses his wasted form, and a pauper’s
grave closes above him, what shall be his daughters’ lot? This is but a type of
many other homes in the district: dirt, misery, and disease alone flourish in that
wretched neighbourhood. ‘Fever and smallpox rage,’ as the inhabitants say, ‘next
door, and next door, and over the way, and next door to that, and further down.’
The living, dying, and dead are all huddled together. The houses have no
ventilation, the back yards are receptacles for all sorts of filth and rubbish, the old
barrels or vessels that contain the supply of water are thickly coated on the sides
with slime, and there is an undisturbed deposit of mud at the bottom. There is no
mortuary house—the dead lie in the dogholes where they breathed their last, and
add to the contagion which spreads through the neighbourhood.”—Pall Mall
Gazette, January 7th, 1871, quoting the Builder.

As I was revising this sheet,—on the evening of the 20th of last month,—
two slips of paper were brought to me. One contained, in consecutive
paragraphs, an extract from the speech of one of the best and kindest of our
public men, to the ‘Liberal Association’ at Portsmouth; and an account of
the performances of the 35-ton gun called the ‘Woolwich infant’ which is
fed with 700-pound shot, and 130 pounds of gunpowder at one mouthful;
not at all like the Wapping infants, starving on a half-chance meal a day.
“The gun was fired with the most satisfactory result,” nobody being hurt,
and nothing damaged but the platform, while the shot passed through the
screens in front at the rate of 1,303 feet per second: and it seems, also, that
the Woolwich infant has not seen the light too soon. For Mr. Cowper-
Temple, in the preceding paragraph, informs the Liberals of Portsmouth,
that in consequence of our amiable neutrality “we must contemplate the
contingency of a combined fleet coming from the ports of Prussia, Russia,
and America, and making an attack on England.”

Contemplating myself these relations of Russia, Prussia, Woolwich, and


Wapping, it seems to my uncommercial mind merely like another case of
iron railings—thieves outside, and nothing to steal within. But the second
slip of paper announced approaching help in a peaceful direction. It was the
prospectus of the Boardmen’s and General Advertising Co-operative
Society, which invites, from the “generosity of the public, a necessary small
preliminary sum,” and, “in addition to the above, a small sum of money by
way of capital,” to set the members of the society up in the profitable
business of walking about London between two boards. Here is at last
found for us, then, it appears, a line of life! At the West End, lounging about
the streets, with a well-made back to one’s coat, and front to one’s shirt, is
usually thought of as not much in the way of business; but, doubtless, to
lounge at the East End about the streets, with one Lie pinned to the front of
you, and another to the back of you, will pay, in time, only with proper
preliminary expenditure of capital. My friends, I repeat my question: Do
you not think you could contrive some little method of employing—
yourselves? for truly I think the Seraphic Doctors are nearly at their wits’
end (if ever their wits had a beginning). Tradesmen are beginning to find it
difficult to live by lies of their own; and workmen will not find it much
easier to live, by walking about, flattened between other people’s.

Think over it. On the first of March, I hope to ask you to read a little history
with me; perhaps also, because the world’s time, seen truly, is but one long
and fitful April, in which every day is All Fools’ day,—we may continue
our studies in that month; but on the first of May, you shall consider with
me what you can do, or let me, if still living, tell you what I know you can
do—those of you, at least, who will promise—(with the help of the three
strong Fates), these three things:

1. To do your own work well, whether it be for life or death.

2. To help other people at theirs, when you can, and seek to avenge no
injury.

3. To be sure you can obey good laws before you seek to alter bad ones.

Believe me,
Your faithful friend,

JOHN RUSKIN.

1 See Carey’s translation of the ninth book of Dante’s ‘Purgatory,’ line 105. ↑
2 I assume the Cambridge quotation to be correct: in my old edition (1848), the
distinction is between ‘weavers and lace-makers’ and ‘journeymen bricklayers;’ and
making velvet is considered to be the production of a ‘commodity,’ but building a house
only doing a ‘service.’ ↑
3 I do not mean that there are no other kinds, nor that well-paid labour must necessarily
be unproductive. I hope to see much done, some day, for just pay, and wholly productive.
But these, named in the text, are the two opposite extremes; and, in actual life, hitherto, the
largest means have been usually spent in mischief, and the most useful work done for the
worst pay. ↑
4 £992,740,328, in seventeen years, say the working men of Burnley, in their address
just issued—an excellent address in its way, and full of very fair arithmetic—if its facts are
all right; only I don’t see, myself, how, “from fifteen to twenty-five millions per annum,”
make nine hundred and ninety-two millions in seventeen years. ↑
FORS CLAVIGERA.
LETTER III.

Denmark Hill,
1st March, 1871.

My Friends,

We are to read—with your leave—some history to-day; the leave, however,


will perhaps not willingly be given, for you may think that of late you have
read enough history, or too much, in Gazettes of morning and evening. No;
you have read, and can read, no history in these. Reports of daily events,
yes;—and if any journal would limit itself to statements of well-sifted fact,
making itself not a “news”paper, but an “olds”paper, and giving its
statements tested and true, like old wine, as soon as things could be known
accurately; choosing also, of the many things that might be known, those
which it was most vital to know, and summing them in few words of pure
English,—I cannot say whether it would ever pay well to sell it; but I am
sure it would pay well to read it, and to read no other.

But even so, to know only what was happening day by day, would not be to
read history. What happens now is but the momentary scene of a great play,
of which you can understand nothing without some knowledge of the
former action. And of that, so great a play is it, you can at best understand
little; yet of history, as of science, a little, well known, will serve you much,
and a little, ill known, will do you fatally the contrary of service.

For instance, all your journals will be full of talk, for months to come, about
whose fault the war was; and you yourselves, as you begin to feel its deadly
recoil on your own interests, or as you comprehend better the misery it has
brought on others, will be looking about more and more restlessly for some
one to accuse of it. That is because you don’t know the law of Fate, nor the
course of history. It is the law of Fate that we shall live, in part, by our own
efforts, but in the greater part, by the help of others; and that we shall also
die, in part, for our own faults; but in the greater part for the faults of others.
Do you suppose (to take the thing on the small scale in which you can test
it) that those seven children torn into pieces out of their sleep, in the last
night of the siege of Paris,1 had sinned above all the children in Paris, or
above yours? or that their parents had sinned more than you? Do you think
the thousands of soldiers, German and French, who have died in agony, and
of women who have died of grief, had sinned above all other soldiers, or
mothers, or girls, there and here?

It was not their fault, but their Fate. The thing appointed to them by the
Third Fors. But you think it was at least the Emperor Napoleon’s fault, if
not theirs? Or Count Bismarck’s? No; not at all. The Emperor Napoleon had
no more to do with it than a cork on the top of a wave has with the toss of
the sea. Count Bismarck had very little to do with it. When the Count sent
for my waiter, last July, in the village of Lauterbrunnen, among the Alps,—
that the waiter then and there packed his knapsack and departed, to be shot,
if need were, leaving my dinner unserved (as has been the case with many
other people’s dinners since)—depended on things much anterior to Count
Bismarck. The two men who had most to answer for in the mischief of the
matter were St. Louis and his brother, who lived in the middle of the
thirteenth century. One, among the very best of men; and the other, of all
that I ever read of, the worst. The good man, living in mistaken effort, and
dying miserably, to the ruin of his country; the bad man living in triumphant
good fortune, and dying peaceably, to the ruin of many countries. Such
were their Fates, and ours. I am not going to tell you of them, nor anything
about the French war to-day; and you have been told, long ago, (only you
would not listen, nor believe,) the root of the modern German power—in
that rough father of Frederick, who “yearly made his country richer, and
this not in money alone (which is of very uncertain value, and sometimes
has no value at all, and even less), but in frugality, diligence, punctuality,
veracity,—the grand fountains from which money, and all real values and
valours, spring for men. As a Nation’s Husband, he seeks his fellow among
Kings, ancient and modern. Happy the nation which gets such a Husband,
once in the half thousand years. The Nation, as foolish wives and Nations
do, repines and grudges a good deal, its weak whims and will being
thwarted very often; but it advances steadily, with consciousness or not, in
the way of well-doing; and, after long times, the harvest of this diligent
sowing becomes manifest to the Nation, and to all Nations.”2

No such harvest is sowing for you,—Freemen and Independent Electors of


Parliamentary representatives, as you think yourselves.

Freemen, indeed! You are slaves, not to masters of any strength or honour;
but to the idlest talkers at that floral end of Westminster bridge. Nay, to
countless meaner masters than they. For though, indeed, as early as the year
1102, it was decreed in a council at St. Peter’s, Westminster, “that no man
for the future should presume to carry on the wicked trade of selling men in
the markets, like brute beasts, which hitherto hath been the common custom
of England,” the no less wicked trade of under-selling men in markets has
lasted to this day; producing conditions of slavery differing from the ancient
ones only in being starved instead of full-fed: and besides this, a state of
slavery unheard of among the nations till now, has arisen with us. In all
former slaveries, Egyptian, Algerine, Saxon, and American, the slave’s
complaint has been of compulsory work. But the modern Politico-Economic
slave is a new and far more injured species, condemned to Compulsory
Idleness, for fear he should spoil other people’s trade; the beautifully logical
condition of the national Theory of Economy in this matter being that, if
you are a shoemaker, it is a law of Heaven that you must sell your goods
under their price, in order to destroy the trade of other shoemakers; but if
you are not a shoemaker, and are going shoeless and lame, it is a law of
Heaven that you must not cut yourself a bit of cowhide, to put between your
foot and the stones, because that would interfere with the total trade of
shoemaking.

Which theory, of all the wonderful—!

We will wait till April to consider of it; meantime, here is a note I have
received from Mr. Alsager A. Hill, who having been unfortunately active in
organizing that new effort in the advertising business, designed, as it seems,
on this loveliest principle of doing nothing that will be perilously
productive—was hurt by my manner of mention of it in the last number of
Fors. I offered accordingly to print any form of remonstrance he would
furnish me with, if laconic enough; and he writes to me, “The intention of
the Boardmen’s Society is not, as the writer of Fors Clavigera suggests, to
‘find a line of life’ for able-bodied labourers, but simply, by means of co-
operation, to give them the fullest benefit of their labour whilst they
continue a very humble but still remunerative calling. See Rule 12. The
capital asked for to start the organization is essential in all industrial
partnerships, and in so poor a class of labour as that of street board-carrying
could not be supplied by the men themselves. With respect to the ‘lies’
alleged to be carried in front and behind, it is rather hard measure to say
that mere announcements of public meetings or places of entertainments (of
which street notices chiefly consist) are necessarily falsehoods.”

To which, I have only to reply that I never said the newly-found line of life
was meant for able-bodied persons. The distinction between able and
unable-bodied men is entirely indefinite. There are all degrees of ability for
all things; and a man who can do anything, however little, should be made
to do that little usefully. If you can carry about a board with a bill on it, you
can carry, not about, but where it is wanted, a board without a bill on it;
which is a much more useful exercise of your ability. Respecting the
general probity, and historical or descriptive accuracy, of advertisements,
and their function in modern economy, I will inquire in another place. You
see I use none for this book, and shall in future use none for any of my
books; having grave objection even to the very small minority of
advertisements which are approximately true. I am correcting this sheet in
the “Crown and Thistle” inn at Abingdon, and under my window is a shrill-
voiced person, slowly progressive, crying, “Soles, three pair for a shillin’.”
In a market regulated by reason and order, instead of demand and supply,
the soles would neither have been kept long enough to render such
advertisement of them necessary, nor permitted, after their inexpedient
preservation, to be advertised.

Of all attainable liberties, then, be sure first to strive for leave to be useful.
Independence you had better cease to talk of, for you are dependent not
only on every act of people whom you never heard of, who are living round
you, but on every past act of what has been dust for a thousand years. So
also, does the course of a thousand years to come, depend upon the little
perishing strength that is in you.

Little enough, and perishing, often without reward, however well spent.
Understand that. Virtue does not consist in doing what will be presently
paid, or even paid at all, to you, the virtuous person. It may so chance; or
may not. It will be paid, some day; but the vital condition of it, as virtue, is
that it shall be content in its own deed, and desirous rather that the pay of it,
if any, should be for others; just as it is also the vital condition of vice to be
content in its own deed, and desirous that the pay thereof, if any, should be
to others.

You have probably heard of St. Louis before now: and perhaps also that he
built the Sainte Chapelle of Paris, of which you may have seen that I wrote
the other day to the Telegraph, as being the most precious piece of Gothic
in Northern Europe; but you are not likely to have known that the spire of it
was Tenterden steeple over again, and the cause of fatal sands many, quick,
and slow, and above all, of the running of these in the last hour-glass of
France; for that spire, and others like it, subordinate, have acted ever since
as lightning-rods, in a reverse manner; carrying, not the fire of heaven
innocently to earth, but electric fire of earth innocently to heaven, leaving
us all, down here, cold. The best virtue and heart-fire of France (not to say
of England, who building her towers for the most part with four pinnacles
instead of one, in a somewhat quadrumanous type, finds them less apt as
conductors), have spent themselves for these past six centuries in running
up those steeples and off them, nobody knows where, leaving a “holy
Republic” as residue at the bottom; helpless, clay-cold, and croaking, a
habitation of frogs, which poor Garibaldi fights for, vainly raging against
the ghost of St. Louis.

It is of English ghosts, however, that I would fain tell you somewhat to-day;
of them, and of the land they haunt, and know still for theirs. For hear this
to begin with:—
“While a map of France or Germany in the eleventh century is useless for
modern purposes, and looks like the picture of another region, a map of
England proper in the reign of Victoria hardly differs at all from a map of
England proper in the reign of William” (the Conqueror). So says, very
truly, Mr. Freeman in his History of the Conquest. Are there any of you who
care for this old England, of which the map has remained unchanged for so
long? I believe you would care more for her, and less for yourselves, except
as her faithful children, if you knew a little more about her; and especially
more of what she has been. The difficulty, indeed, at any time, is in finding
out what she has been; for that which people usually call her history is not
hers at all; but that of her Kings, or the tax-gatherers employed by them,
which is as if people were to call Mr. Gladstone’s history, or Mr. Lowe’s,
yours and mine.

But the history even of her Kings is worth reading. You remember, I said,
that sometimes in church it might keep you awake to be told a little of it.
For a simple instance, you have heard probably of Absalom’s rebellion
against his father, and of David’s agony at his death, until from very
weariness you have ceased to feel the power of the story. You would not
feel it less vividly if you knew that a far more fearful sorrow, of the like
kind, had happened to one of your own Kings, perhaps the best we have
had, take him for all in all. Not one only, but three of his sons, rebelled
against him, and were urged into rebellion by their mother. The Prince, who
should have been King after him, was pardoned, not once, but many times
—pardoned wholly, with rejoicing over him as over the dead alive, and set
at his father’s right hand in the kingdom; but all in vain. Hard and
treacherous to the heart’s core, nothing wins him, nothing warns, nothing
binds. He flies to France, and wars at last alike against father and brother,
till, falling sick through mingled guilt, and shame, and rage, he repents idly
as the fever-fire withers him. His father sends him the signet ring from his
finger in token of one more forgiveness. The Prince lies down upon a heap
of ashes with a halter round his neck, and so dies. When his father heard it
he fainted away three times, and then broke out into bitterest crying and
tears. This, you would have thought enough for the Third dark Fate to have
appointed for a man’s sorrows. It was little to that which was to come. His
second son, who was now his Prince of England, conspired against him, and
pursued his father from city to city, in Norman France. At last, even his
youngest son, best beloved of all, abandoned him, and went over to his
enemies.

This was enough. Between him and his children Heaven commanded its
own peace. He sickened and died of grief on the 6th of July, 1189.

The son who had killed him, “repented” now; but there could be no signet
ring sent to him. Perhaps the dead do not forgive. Men say, as he stood by
his father’s corpse, that the blood burst from his nostrils. One child only had
been faithful to him, but he was the son of a girl whom he had loved much,
and as he should not; his Queen, therefore, being a much older person, and
strict upon proprieties, poisoned her; nevertheless poor Rosamond’s son
never failed him; won a battle for him in England, which, in all human
probability, saved his kingdom; and was made a bishop, and turned out a
bishop of the best.

You know already a little about the Prince who stood unforgiven (as it
seemed) by his father’s body. He, also, had to forgive, in his time; but only
a stranger’s arrow shot—not those reversed “arrows in the hand of the
giant,” by which his father died. Men called him “Lion-heart,” not untruly;
and the English as a people, have prided themselves somewhat ever since
on having, every man of them, the heart of a lion; without inquiring
particularly either what sort of heart a lion has, or whether to have the heart
of a lamb might not sometimes be more to the purpose. But it so happens
that the name was very justly given to this prince; and I want you to study
his character somewhat, with me, because in all our history there is no truer
representative of one great species of the British squire, under all the three
significances of the name; for this Richard of ours was beyond most of his
fellows, a Rider and a Shieldbearer; and beyond all men of his day, a
Carver; and in disposition and unreasonable exercise of intellectual power,
typically a Squire altogether.

Note of him first, then, that he verily desired the good of his people
(provided it could be contrived without any check of his own humour), and
that he saw his way to it a great deal clearer than any of your squires do
now. Here are some of his laws for you:—

“Having set forth the great inconveniences arising from the diversity of
weights and measures in different parts of the kingdom, he, by a law,
commanded all measures of corn, and other dry goods, as also of liquors, to
be exactly the same in all his dominions; and that the rim of each of these
measures should be a circle of iron. By another law, he commanded all
cloth to be woven two yards in breadth within the lists, and of equal
goodness in all parts; and that all cloth which did not answer this
description should be seized and burnt. He enacted, further, that all the coin
of the kingdom should be exactly of the same weight and fineness;—that no
Christian should take any interest for money lent; and, to prevent the
extortions of the Jews, he commanded that all compacts between Christians
and Jews should be made in the presence of witnesses, and the conditions of
them put in writing.” So, you see, in Cœur-de-Lion’s day, it was not
esteemed of absolute necessity to put agreements between Christians in
writing! Which if it were not now, you know we might save a great deal of
money, and discharge some of our workmen round Temple Bar, as well as
from Woolwich Dockyards. Note also that bit about interest of money also
for future reference. In the next place observe that this King had great
objection to thieves—at least to any person whom he clearly comprehended
to be a thief. He was the inventor of a mode of treatment which I believe the
Americans—among whom it has not fallen altogether into disuse—do not
gratefully enough recognize as a Monarchical institution. By the last of the
laws for the government of his fleet in his expedition to Palestine, it is
decreed,—“That whosoever is convicted of theft shall have his head
shaved, melted pitch poured upon it, and the feathers from a pillow shaken
over it, that he may be known; and shall be put on shore on the first land
which the ship touches.” And not only so; he even objected to any theft by
misrepresentation or deception,—for being evidently particularly interested,
like Mr. Mill, in that cloth manufacture, and having made the above law
about the breadth of the web, which has caused it to be spoken of ever since
as “Broad Cloth,” and besides, for better preservation of its breadth, enacted
that the Ell shall be of the same length all over the kingdom, and that it shall
be made of iron—(so that Mr. Tennyson’s provision for National defences
—that every shop-boy should strike with his cheating yard-wand home,
would be mended much by the substitution of King Richard’s honest ell-
wand, and for once with advisable encouragement to the iron trade)—King
Richard finally declares—“That it shall be of the same goodness in the
middle as at the sides, and that no merchant in any part of the kingdom of
England shall stretch before his shop or booth a red or black cloth, or any
other thing by which the sight of buyers is frequently deceived in the choice
of good cloth.”

These being Richard’s rough and unreasonable, chancing nevertheless,


being wholly honest, to be wholly right, notions of business, the next point
you are to note in him is his unreasonable good humour; an eminent
character of English Squires; a very loveable one; and available to himself
and others in many ways, but not altogether so exemplary as many think it.
If you are unscrupulously resolved, whenever you can get your own way, to
take it; if you are in a position of life wherein you can get a good deal of it,
and if you have pugnacity enough to enjoy fighting with anybody who will
not give it to you, there is little reason why you should ever be out of
humour, unless indeed your way is a broad one, wherein you are like to be
opposed in force. Richard’s way was a very narrow one. To be first in
battle, (generally obtaining that main piece of his will without question;
once only worsted, by a French knight, and then, not at all good-
humouredly,) to be first in recognized command—therefore contending
with his father, who was both in wisdom and acknowledged place superior;
but scarcely contending at all with his brother John, who was as definitely
and deeply beneath him; good-humoured unreasonably, while he was
killing his father, the best of kings, and letting his brother rule unresisted,
who was among the worst; and only proposing for his object in life to enjoy
himself everywhere in a chivalrous, poetical, and pleasantly animal manner,
as a strong man always may. What should he have been out of humour for?
That he brightly and bravely lived through his captivity is much indeed to
his honour; but it was his point of honour to be bright and brave; not at all
to take care of his kingdom. A king who cared for that, would have got
thinner and sadder in prison.
And it remains true of the English squire to this day, that, for the most part,
he thinks that his kingdom is given him that he may be bright and brave;
and not at all that the sunshine or valour in him is meant to be of use to his
kingdom.

But the next point you have to note in Richard is indeed a very noble
quality, and true English; he always does as much of his work as he can
with his own hands. He was not in any wise a king who would sit by a
windmill to watch his son and his men at work, though brave kings have
done so. As much as might be, of whatever had to be done, he would
stedfastly do from his own shoulder; his main tool being an old Greek one,
and the working God Vulcan’s—the clearing axe. When that was no longer
needful, and nothing would serve but spade and trowel, still the king was
foremost; and after the weary retreat to Ascalon, when he found the place
“so completely ruined and deserted, that it afforded neither food, lodging,
nor protection,” nor any other sort of capital,—forthwith, 20th January,
1192—his army and he set to work to repair it; a three months’ business, of
incessant toil, “from which the king himself was not exempted, but wrought
with greater ardour than any common labourer.”

The next point of his character is very English also, but less honourably so.
I said but now that he had a great objection to anybody whom he clearly
comprehended to be a thief. But he had great difficulty in reaching anything
like an abstract definition of thieving, such as would include every method
of it, and every culprit, which is an incapacity very common to many of us
to this day. For instance, he carried off a great deal of treasure which
belonged to his father, from Chinon (the royal treasury-town in France), and
fortified his own castles in Poitou with it; and when he wanted money to go
crusading with, sold the royal castles, manors, woods, and forests, and even
the superiority of the Crown of England over the kingdom of Scotland,
which his father had wrought hard for, for about a hundred thousand
pounds. Nay, the highest honours and most important offices become venal
under him; and from a Princess’s dowry to a Saracen caravan, nothing
comes much amiss; not but that he gives generously also; whole ships at a
time when he is in the humour; but his main practice is getting and
spending, never saving; which covetousness is at last the death of him. For
hearing that a considerable treasure of ancient coins and medals has been
found in the lands of Vidomar, Viscount of Limoges, King Richard sends
forthwith to claim this waif for himself. The Viscount offers him part only,
presumably having an antiquarian turn of mind. Whereupon Richard loses
his temper, and marches forthwith with some Brabant men, mercenaries, to
besiege the Viscount in his castle of Chalus; proposing, first, to possess
himself of the antique and otherwise interesting coin in the castle, and then,
on his general principle of objection to thieves, to hang the garrison. The
garrison, on this, offer to give up the antiquities if they may march off
themselves; but Richard declares that nothing will serve but they must all
be hanged. Whereon the siege proceeding by rule. and Richard looking, as
usual, into matters with his own eyes, and going too near the walls, an
arrow well meant, though half spent, pierces the strong, white shoulder; the
shield-bearing one, carelessly forward above instead of under shield; or
perhaps, rather, when he was afoot, shieldless, engineering. He finishes his
work, however, though the scratch teases him; plans his assault, carries his
castle, and duly hangs his garrison, all but the archer, whom in his royal,
unreasoning way he thinks better of, for the well-spent arrow. But he pulls it
out impatiently, and the head of it stays in the fair flesh; a little surgery
follows; not so skilful as the archery of those days, and the lion heart is
appeased—

Sixth April, 1199.

We will pursue our historical studies, if you please, in that month of the
present year. But I wish, in the meantime, you would observe, and meditate
on, the quite Anglican character of Richard, to his death.

It might have been remarked to him, on his projecting the expedition to


Chalus, that there were not a few Roman coins, and other antiquities, to be
found in his own kingdom of England, without fighting for them, but by
mere spade labour and other innocuous means;—that even the brightest
new money was obtainable from his loyal people in almost any quantity for
civil asking; and that the same loyal people, encouraged and protected, and
above all, kept clean-handed, in the arts, by their king, might produce
treasures more covetable than any antiquities.
“No;” Richard would have answered,—“that is all hypothetical and
visionary; here is a pot of coin presently to be had—no doubt about it—
inside the walls here:—let me once get hold of that, and then,”—

That is what we English call being “Practical.”

Believe me,
Faithfully yours,

JOHN RUSKIN.

1 Daily Telegraph, 30th January, 1871. ↑


2 Carlyle’s Frederick, Book IV., chap. iii. ↑
FORS CLAVIGERA.
LETTER IV.

Denmark Hill,
1st April, 1871.

My Friends,

It cannot but be pleasing to us to reflect, this day, that if we are often foolish
enough to talk English without understanding it, we are often wise enough
to talk Latin without knowing it. For this month retains its pretty Roman
name, and means the month of Opening; of the light in the days, and the life
in the leaves, and of the voices of birds, and of the hearts of men.

And being the month of Manifestation, it is pre-eminently the month of


Fools;—for under the beatific influences of moral sunshine, or Education,
the Fools always come out first.

But what is less pleasing to reflect upon, this spring morning, is, that there
are some kinds of education which may be described, not as moral
sunshine, but as moral moonshine; and that, under these, Fools come out
both First—and Last.

We have, it seems, now set our opening hearts much on this one point, that
we will have education for all men and women now, and for all boys and
girls that are to be. Nothing, indeed, can be more desirable, if only we
determine also what kind of education we are to have. It is taken for granted
that any education must be good;—that the more of it we get, the better;
that bad education only means little education; and that the worst thing we
have to fear is getting none. Alas, that is not at all so. Getting no education
is by no means the worst thing that can happen to us. One of the pleasantest
friends I ever had in my life was a Savoyard guide, who could only read
with difficulty, and write scarcely intelligibly, and by great effort. He knew
no language but his own—no science, except as much practical agriculture
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like