Professional Documents
Culture Documents
Ebook The R Book 3Rd Edition Elinor Jones Online PDF All Chapter
Ebook The R Book 3Rd Edition Elinor Jones Online PDF All Chapter
https://ebookmeta.com/product/the-r-book-3rd-edition-elinor-
jones-simon-harden-michael-j-crawley/
https://ebookmeta.com/product/the-quick-python-book-3rd-edition-
naomi-r-ceder/
https://ebookmeta.com/product/composites-science-technology-and-
engineering-frank-r-jones/
https://ebookmeta.com/product/contemporary-management-12th-
ed-12th-edition-gareth-r-jones/
Contemporary Management, 10th ed. 10th Edition Gareth
R. Jones
https://ebookmeta.com/product/contemporary-management-10th-
ed-10th-edition-gareth-r-jones/
https://ebookmeta.com/product/murder-at-the-museum-agatha-oddly-
book-2-2nd-edition-lena-jones/
https://ebookmeta.com/product/the-human-rights-reader-3rd-
edition-micheline-r-ishay/
https://ebookmeta.com/product/cambridge-igcse-and-o-level-
history-workbook-2c-depth-study-the-united-states-1919-41-2nd-
edition-benjamin-harrison/
https://ebookmeta.com/product/media-distortions-understanding-
the-power-behind-spam-noise-and-other-deviant-media-1st-edition-
elinor-carmi/
The R Book
The R Book
Third Edition
Elinor Jones
University College London, UK
Simon Harden
University College London, UK
Michael J. Crawley
Imperial College London, UK
This third edition first published 2023
© 2023 John Wiley & Sons Ltd
Edition History: John Wiley & Sons Ltd (1e, 2007; 2e, 2013)
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any
means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by law. Advice on how to obtain
permission to reuse material from this title is available at http://www.wiley.com/go/permissions.
The right of Elinor Jones, Simon Harden and Michael J. Crawley to be identified as the authors of this work has been asserted in
accordance with law.
Registered Offices
John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, USA
John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, UK
Editorial Office
9600 Garsington Road, Oxford, OX4 2DQ, UK
For details of our global editorial offices, customer services, and more information about Wiley products visit us at www.wiley.com.
Wiley also publishes its books in a variety of electronic formats and by print-on-demand. Some content that appears in standard
print versions of this book may not be available in other formats.
1 Getting Started 1
2 Technical Background 17
3 Essentials of the R Language 55
4 Data Input and Dataframes 207
5 Graphics 249
6 Graphics in More Detail 297
7 Tables 359
8 Probability Distributions in R 373
9 Testing 405
10 Regression 439
11 Generalised Linear Models 499
12 Generalised Additive Models 579
13 Mixed-Effect Models 601
14 Non-linear Regression 627
15 Survival Analysis 649
16 Designed Experiments 667
17 Meta-Analysis 699
18 Time Series 715
19 Multivariate Statistics 741
vi CONTENTS
Index 839
Detailed Contents
1 Getting Started 1
1.1 Navigating the book 1
1.1.1 How to use this book 1
1.2 R vs. RStudio 3
1.3 Installing R and RStudio 3
1.4 Using RStudio 4
1.4.1 Using R directly via the console 5
1.4.2 Using text editors 5
1.5 The Comprehensive R Archive Network 7
1.5.1 Manuals 7
1.5.2 Frequently asked questions 8
1.5.3 Contributed documentation 8
1.6 Packages in R 8
1.6.1 Contents of packages 9
1.6.2 Finding packages 9
1.6.3 Installing packages 9
1.7 Getting help in R 11
1.7.1 Worked examples of functions 12
1.7.2 Demonstrations of R functions 13
1.8 Good housekeeping 13
1.8.1 Variable types 13
1.8.2 What’s loaded or defined in the current session 14
1.8.3 Attaching and detaching objects 14
1.8.4 Projects 15
1.9 Linking to other computer languages 15
References 15
viii DETAILED CONTENTS
2 Technical Background 17
2.1 Mathematical functions 17
2.1.1 Logarithms and exponentials 18
2.1.2 Trigonometric functions 19
2.1.3 Power laws 20
2.1.4 Polynomial functions 22
2.1.5 Gamma function 24
2.1.6 Asymptotic functions 25
2.1.7 Sigmoid (S-shaped) functions 27
2.1.8 Biexponential function 28
2.1.9 Transformations of model variables 29
2.2 Matrices 30
2.2.1 Matrix multiplication 31
2.2.2 Diagonals of matrices 32
2.2.3 Determinants 33
2.2.4 Inverse of a matrix 35
2.2.5 Eigenvalues and eigenvectors 36
2.2.6 Solving systems of linear equations using matrices 39
2.3 Calculus 40
2.3.1 Differentiation 40
2.3.2 Integration 41
2.3.3 Differential equations 42
2.4 Probability 45
2.4.1 The central limit theorem 45
2.4.2 Conditional probability 49
2.5 Statistics 50
2.5.1 Least squares 51
2.5.2 Maximum likelihood 51
Reference 53
5 Graphics 249
5.1 Plotting principles 249
5.1.1 Axes labels and titles 251
5.1.2 Plotting symbols and colours 251
5.1.3 Saving graphics 254
5.2 Plots for single variables 255
5.2.1 Histograms vs. bar charts 255
5.2.2 Histograms 256
5.2.3 Density plots 260
5.2.4 Boxplots 261
5.2.5 Dotplots 262
5.2.6 Bar charts 263
5.2.7 Pie charts 264
5.3 Plots for showing two numeric variables 265
5.3.1 Scatterplot 265
5.3.2 Plots with many identical values 270
5.4 Plots for numeric variables by group 272
5.4.1 Boxplots by group 272
5.4.2 Dotplots by group 274
5.4.3 An inferior (but popular) option 275
5.5 Plots showing two categorical variables 277
5.5.1 Grouped bar charts 277
5.5.2 Mosaic plots 277
5.6 Plots for three (or more) variables 279
5.6.1 Plots of all pairs of variables 279
5.6.2 Incorporating a third variable on a scatterplot 280
5.6.3 Basic 3D plots 281
5.7 Trellis graphics 283
5.7.1 Panel boxplots 285
5.7.2 Panel scatterplots 286
5.7.3 Panel barplots 289
5.7.4 Panels for conditioning plots 290
5.7.5 Panel histograms 291
5.7.6 More panel functions 292
5.8 Plotting functions 293
5.8.1 Two-dimensional plots 293
5.8.2 Three-dimensional plots 295
References 295
xii DETAILED CONTENTS
7 Tables 359
7.1 Tabulating categorical or discrete data 359
7.1.1 Tables of counts 359
7.1.2 Tables of proportions 360
7.2 Tabulating summaries of numeric data 362
7.2.1 General summaries by group 362
7.2.2 Bespoke summaries by group 364
7.3 Converting between tables and dataframes 367
7.3.1 From a table to a dataframe 367
7.3.2 From a dataframe to a table 370
Reference 371
9 Testing 405
9.1 Principles 406
9.1.1 Defining the question to be tested 406
9.1.2 Assumptions 408
9.1.3 Interpreting results 408
9.2 Continuous data 410
9.2.1 Single population average 410
9.2.2 Two population averages 412
9.2.3 Multiple population averages 414
9.2.4 Population distribution 415
9.2.5 Checking and testing for normality 417
9.2.6 Comparing variances 419
9.3 Discrete and categorical data 421
9.3.1 Sign test 421
9.3.2 Test to compare proportions 423
9.3.3 Contingency tables 427
9.3.4 Testing contingency tables 429
9.4 Bootstrapping 431
9.5 Multiple tests 433
9.6 Power and sample size calculations 434
9.7 A table of tests 436
References 437
10 Regression 439
10.1 The simple linear regression model 440
10.1.1 Model format and assumptions 440
10.1.2 Building a simple linear regression model 443
10.2 The multiple linear regression model 446
10.2.1 Model format and assumptions 446
10.2.2 Building a multiple linear regression model 447
10.2.3 Categorical covariates 449
10.2.4 Interactions between covariates 454
10.3 Understanding the output 458
10.3.1 Residuals 458
10.3.2 Estimates of coefficients 459
10.3.3 Testing individual coefficients 459
10.3.4 Residual standard error 460
10.3.5 R2 and its variants 460
10.3.6 The regression F-test 460
10.3.7 ANOVA: Same model, different output 461
10.3.8 Extracting model information 464
10.4 Fitting models 465
10.4.1 The principle of parsimony 465
10.4.2 First plot the data 467
10.4.3 Comparing nested models 468
10.4.4 Comparing non-nested models 470
10.4.5 Dealing with large numbers of covariates 471
10.5 Checking model assumptions 473
10.5.1 Residuals and standardised residuals 473
10.5.2 Checking for linearity 474
DETAILED CONTENTS xv
Index 839
List of Tables
Table 1.1 Libraries used in this book that come supplied as part of the base package of R 8
Table 1.2 Task Views on CRAN 10
Table 3.1 Mathematical functions 61
Table 3.2 Common operators 62
Table 3.3 Logical and relational operations 67
Table 3.4 Data types 80
Table 3.5 Vector functions 94
Table 3.6 Format codes for dates and times 167
Table 3.7 Escape sequences for use with cat () 199
Table 4.1 Correctly set out dataset for importing into a dataframe 216
Table 4.2 Dataset that will not form a dataframe correctly 217
Table 4.3 Dataset that will form a dataframe correctly 217
Table 4.4 Selecting parts of a dataframe called df_dummy 223
Table 5.1 Plotting single variables 255
Table 6.1 Orientation and sizes of labels 310
Table 6.2 Drawing mathematical expressions in text 323
Table 6.3 Graphical parameters and their default values 354
Table 8.1 Some commonly used probability distributions supported by R 376
Table 9.1 Tests used in Chapter 9 436
Table 10.1 Functions for various regression models 497
Table 10.2 Frequently used functions to extract information about regression models 498
Table 11.1 Common members of the exponential family 501
xxii LIST OF TABLES
R is the most powerful tool in the known universe for carrying out statistical analysis, and it’s free!
This book is aimed at those who wish to carry out such work – exploring, plotting, and modelling
data – but who do not have much experience in R and/or statistics. R is described from scratch
with instructions for loading and getting going with the software in Chapter 1 and a description of its
essential elements in Chapter 3. Later chapters discuss statistical methods and are written so that
they can be used either as a beginner’s guide or as a reference manual on particular procedures in
R. The theory behind the analyses is covered in enough depth, we hope, to make it comprehensible
but without overburdening the reader with too much mathematics. The datasets used to illustrate
various analyses are available at https://www.wiley.com/go/jones/therbook3e.
Using R has become far simpler with the introduction of RStudio, which is also free (other editors
are available). RStudio provides a friendly front end and easy access to tools, all of which seem
a long way from R’s original rather forbidding command prompt. This book assumes the use of
RStudio rather than using R directly, but the code presented will work using the latter setup too.
While there is still the usual hurdle of getting to know powerful software, the benefits, particularly
in graphics and modelling, far outweigh the effort. Academic papers in many disciplines routinely
use and report results using R. In addition, the open-source nature of the software means that users
have added extra functionality by writing packages to broaden R’s capabilities. There are currently
over 18,000 packages that, together with useful links and information, can be found at the official
R distribution site, CRAN: https://cran.r-project.org/.
This book is contingent upon the existence of R. Those involved are too numerous to mention,
but we are hugely grateful to all involved in its creation and continuing evolution. When you use R,
R packages (e.g. spatstat), and RStudio, please cite them. Up-to-date citation details for each
of these can be found by typing the following in R, respectively:
citation ()
citation ("spatstat")
RStudio.Version ()
Elinor Jones
Simon Harden
Michael J. Crawley
August 2022
Acknowledgments
This book would not exist without its previous editions so thanks, firstly, to the originating author,
Michael J. Crawley.
It has been a pleasure to revise The R Book to create this third edition. We are very grateful to
Professor Crawley for allowing us to use materials from previous versions, including his fantastic
array of datasets that make a welcome return in this edition.
Finally, we would like to thank the Department of Statistical Science at University College London
for giving us time and space to complete the book during a difficult period for everybody.
Elinor Jones
Simon Harden
August 2022
About the Companion Website
www.wiley.com/go/jones/therbook3e
1+3
[1] 4
• Datasets, variable names, model names, and so on, are written in typewriter font;
• R packages (see Section 1.6) are highlighted in blue, for example MASS.
The R Book, Third Edition. Elinor Jones, Simon Harden and Michael J. Crawley.
© 2023 John Wiley & Sons Ltd. Published 2023 by John Wiley & Sons Ltd.
Companion website: www.wiley.com/go/jones/therbook3e
2 THE R BOOK
Done some R and some statistics, but keen to learn more of both
The best plan is to skim quickly through the introductory material in case there is anything new to
be learned. It is a good idea to read Chapter 3 on the fundamentals of the R language and Chapters
5 and 6 on graphics. Much of the rest of the book is organised by analysis type making it easy to
jump to the relevant chapter.
?rnbinom
Recognizing mathematical functions is quite straightforward because of their names and the fact
that their arguments are enclosed in round brackets ( ). Subscripts on objects have square brackets
[ ]. Multi-line blocks of R code are enclosed within curly brackets { }. The idea of lists might be new,
or applying functions to lists; elements within lists have double square brackets [[ ]].
Look at the sections at the start of Chapter 3 as a starting point. The index is probably the most
sensible entry point for queries about specifics.
Familiar with statistics and computing, but need a friendly reference manual
For information about a topic, use the chapter list and the Detailed Contents to find the most
appropriate section. For aspects of the R language, look at the sections mentioned at the start of
Chapter 3. Spending time browsing the contents of general material such as Chapters 5 and 6 on
graphics is a good idea.
Get used to R’s help pages. Each R function has a help page which can be accessed by typing a
question mark followed directly by the function name. To find out what all the graphics parameters
mean, for instance, just type:
?par
R is a powerful open-source software for statistical computing (R Core Team, 2021). It can be used
directly, or for a more pleasing user experience, can be used via the RStudio interface which is freely
available (RStudio Team, 2020). We strongly recommend using RStudio rather than R directly as
it makes managing workspace easy and avoids some of R’s rather cumbersome features. The rest
of the book will assume the use of RStudio, but all code presented will work – and provide identical
results – if used in ‘native’ R instead.
We will generally write ‘R’ instead of ‘RStudio’ throughout this book.
You will need to install both R and RStudio. Both will run under Windows, a number of flavours of
Linux (more for R than for RStudio so check the links below) and even Apple’s Mac OS X.
4 THE R BOOK
First download and install R. Note that this needs to be done first before attempting to download
RStudio.
Rather than downloading R and RStudio, there is the option of accessing the software online via
RStudio Cloud (https://www.rstudio.com/products/cloud/). There are some advantages to using
RStudio online, for example when working on a group project. However, for individual use, it is
likely that downloading R and RStudio is the best way forward.
Once installed, open RStudio. The screen is divided into three parts as in Figure 1.1.
On the left is the console, numbered 1 in Figure 1.1. This is R. All code will be passed to the
console where it will be executed, and numerical output will also be displayed here. The console
displays the version number of R, its date, and version name (always comedic).
In the top right-hand corner is the workspace, numbered 2 in Figure 1.1. This is the control centre
and gives an at-a-glance overview of what has been done so far in the session.
The bottom right corner, numbered 3 in Figure 1.1, hosts a number of things. Switch between
them by clicking on the relevant tabs:
• Files: Shows the accessible file directories (more on this in Section 1.8.4);
• Plots: This is where plots and other graphics will be displayed;
• Packages: Lists packages that have been installed and provides functionality for installing others
(more on this in Section 1.6);
• Help: As the name might suggest, help with various functions or procedures can be found here
(more on this in Section 1.7);
• Viewer: Used for viewing local web content.
2 + 3
[1] 5
When working, a + is sometimes displayed at the left-hand side of the screen instead of >. This
means that the last command typed is incomplete. The most common cause of this is forgetting
one or more brackets. If what’s missing is clear (e.g. a final right-hand bracket), then just type the
missing character and press enter, at which point the command will execute. If a mistake has been
made, then press the Esc key and the command line prompt > will reappear. Use the Up arrow key
to scroll through previous commands, then use the Left and Right arrow keys to navigate to the
mistake and correct it.
A failsafe way of opening a blank text editor, which doesn’t depend on the operating system of
your machine, is to go to File, then New File, then R Script. It will appear in the top left hand corner
as in Figure 1.2.
The text editor is where we write commands, using a new line for each one. Click the text editor
to activate it, before writing the following:
2 + 3
3 * 6
exp (2)
To run commands, highlight the relevant lines and click ‘Run’ (top right corner of the text editor)
or press Ctrl and Enter, simultaneously. Output will be displayed in the console (bottom left). For
readability, output will be shown directly beneath each of the relevant command throughout this
book like this:
2 + 3
[1] 5
3 * 6
[1] 18
exp (2)
[1] 7.389056
GETTING STARTED 7
The commands so far request calculations to be performed, but we can also define objects (see
Chapter 3 for details), for example a is assigned (<-) the value 5 while we define b to be ln(10):
a <- 5
b <- log (10)
• there is no output in the console (because all we’ve done is define two objects);
• the Environment tab in the workspace has been populated with the definitions of a and b.
1.5.1 Manuals
There are several manuals available on CRAN, for example (descriptions are taken from the
webpage):
• An Introduction to R gives an introduction to the language and how to use R for doing statistical
analysis and graphics.
• A draft of the R Language Definition, which documents the language per se – that is, the objects
that it works on, and the details of the expression evaluation process, which are useful to know
when programming R functions. This is perhaps the most important of all the manuals.
8 THE R BOOK
• Writing R Extensions covers how to create your own packages, write R help files, and use the
foreign language (C, C + +, Fortran, … ) interfaces.
• Data Import/Export describes the import and export facilities available either in R itself or via
packages which are available from CRAN.
• R Installation and Administration, which is self-explanatory.
These manuals are also available in RStudio by going to the Help tab in the bottom right-hand
corner and clicking the ‘home’ icon.
The most useful part of the site, however, is the Search facility. This is a good starting point for
investigating the contents of most of the R documents, functions, and searchable mail archives.
• the R FAQ, which contains useful information for users on all platforms (Linux, Mac, Unix,
Windows);
• the R Mac OS X FAQ for all users of Apple operating systems;
• the R Windows FAQ for all users of Microsoft operating systems.
Read the first of these, plus the appropriate one for your platform.
1.6 Packages in R
A lot can be done with R or RStudio ‘straight out of the box’, also known as base-R. Table 1.1 lists
some of the packages that come supplied as part of the base-R installation.
Table 1.1 Libraries used in this book that come supplied as part of the base package of R.
However, there is a huge community of R users who contribute to its functionality via packages.
A package contains additional functionality for R that can be loaded during a session. Navigating
contributed packages can be tricky simply because there are so many of them, and the name of
the package is not always as indicative of its function as one might hope.
Viewing existing packages can be done in RStudio by clicking on the Packages tab. Clicking the
box next to a package loads it. A far better way of loading a package is to do so via the library ()
function, which also means we have it as part of our code. For example, to load the MASS package
(Venables and Ripley, 2002), which has a wide range of useful functions and datasets, type:
library (MASS)
This brings up general information about the package in a new tab of the text editor in RStudio,
including a list of all the functions and data sets.
To find out how to use, say, Ripley’s K (kfn ()) from spatial, we load the package and then
use ? to query the function:
library (spatial)
?Kfn
install.packages ("akima")
install.packages ("boot")
10 THE R BOOK
install.packages ("BSDA")
install.packages ("car")
install.packages ("coda")
install.packages ("DescTools")
install.packages ("deSolve")
install.packages ("EMT")
GETTING STARTED 11
install.packages ("geoR")
install.packages ("ggplot2")
install.packages ("lme4")
install.packages ("metafor")
install.packages ("nlstools")
install.packages ("PerformanceAnalytics")
install.packages ("plotly")
install.packages ("predictmeans")
install.packages ("psych")
install.packages ("R2jags")
install.packages ("RColorBrewer")
install.packages ("rpart")
install.packages ("SemiPar")
install.packages ("spatstat")
install.packages ("spdep")
install.packages ("stringr")
install.packages ("tree")
Installing a package doesn’t load it! The library () function needs to be used to load an installed
package.
?read.table
The help page can then be viewed in the bottom right corner in RStudio.
Sometimes the precise name of the function isn’t known, but general subject area is (e.g. data
input in this case). Use the help.search () function (without a question mark) with the query in
double quotes like this:
and (with any luck) the names of the R functions associated with this query will be displayed. Then
use, for example ?read.table to get detailed help.
Other useful functions are find () and apropos (). The find () function indicates what
package something is in
find ("lowess")
[1] "package:stats"
12 THE R BOOK
while apropos () returns a character vector giving the names of all objects in the search list that
match a (potentially partial) enquiry:
apropos ("lm")
There is a huge world-wide R user network. An Internet search of a problem is likely to point to a
solution if the above approaches don’t help.
example (lm)
which provides an example of the printed and graphical output produced by the lm () function.
GETTING STARTED 13
demo (persp)
demo (graphics)
demo (Hershey)
demo (plotmath)
Most of the examples given are straightforward, but a few deserve special attention. Take the num-
ber of daily cases of a virus, for example. It is clear that this should be a discrete variable because
it can only take whole numbers 0, 1, 2, … (we can’t have, say, 10.462 cases!). Though this is
undeniably discrete, we could face difficulty if daily cases varies considerably from no cases to
many thousands. With such a vast range of possible values, we might consider treating this variable
as continuous instead. This could potentially make an analysis simpler, which is not a bad thing.
It may seem surprising that a patient’s pain rating from 0 to 10 is classified as an ordinal (categor-
ical) variable. The possible values are numbers so why isn’t this a discrete variable? The numbers
here are merely labels for underlying categories, and not meaningful in themselves. Though it would
be slightly odd to do so, we could equivalently ask a patient to classify their pain from 100 to 110
instead, or ask them to identify the pain using labels such as ‘no pain’, ‘very mild pain’, all the way up
to ‘worst possible pain’. This would extract the same information from the patients and reveals that
14 THE R BOOK
there is nothing special about the numeric labels we initially applied to the categories. The moral of
the story here is don’t jump to the conclusion that any variable with quantitative values is actually
numeric.
Once we have a good hold of the variable types in our dataset, we can start thinking about how
to approach any analysis.
objects ()
The Environment tab in RStudio also lists everything that has been imported or created. To see
which packages and dataframes are currently attached (see Section 1.8.3):
search ()
mean (mydata$myvar)
where, of course, the function mean () computes the arithmetic mean. This can get quite cumber-
some.
We could attach () mydata so that we don’t have to do this. By attaching the dataset, its
contents become visible to R so that we don’t have to specify that myvar is located inside mydata:
attach (mydata)
mean (myvar)
detach (mydata)
Attaching objects comes with a serious health warning. It can get very messy and easily lead to
mistakes. Once an object is attached, it should be detached as soon as possible using detach
(mydata) in our example. The detach () command does not make the dataset disappear; it
just means that the variables within it are no longer accessible directly by name.
It may also be necessary to remove particular objects created using rm (). That way, the Envi-
ronment in RStudio doesn’t get unnecessarily cluttered:
x <- 5
y <- exp(4)
objects ()
rm (x, y)
objects ()
GETTING STARTED 15
rm (list = ls ())
but be absolutely sure that you really want to be as draconian as this before executing the command.
There is no going back.
1.8.4 Projects
It is a good idea to keep files relating to a particular piece of work together. An RStudio project is a
good way of doing this. A project is just a folder containing relevant files which are not necessarily
all R-related (e.g. code, data, files, notes), together with an .RProj file.
Opening the .RProj file automatically sets the working directory to the project folder, which
is more efficient than setting it manually each time RStudio is loaded. The working directory is the
folder that R searches to find files (see Section 4.1). A list of files in the project can be seen under
the Files tab in the bottom right corner in RStudio.
Creating a basic RStudio project is very simple. In RStudio, go to File, then New Project … then
choose New Directory followed by New Project. Now choose to create a new directory from scratch
or use an existing folder. The (new) project folder contains an .RProj file. Alternatively, use the
Project menu in the top right corner of RStudio to do the same.
The project can be opened by double clicking on the .RProj file within the newly created project
folder, or by using File then Open Project in RStudio.
Advanced users can employ the functions .C and .Fortran to provide a standard interface to
compiled code that has been linked into R, either at build time or via dyn.load. They are primarily
intended for compiled C and Fortran code, respectively, but the .C function can be used with other
languages which can generate C interfaces, for example C++. The .Internal and .Primitive
interfaces are used to call C code compiled into R at build time. Functions .Call and .External
provide interfaces which allow compiled code (primarily compiled C code) to manipulate R objects.
It can be very time-consuming to get these links to work. A particular problem to bear in mind
is that if variables are specified as integers in the lower-level language, then they will need to be
specified as such in R before being passed to the C or Fortran code.
References
R Core Team. (2021). R: A language and environment for statistical computing. R Foundation for Statistical
Computing. Vienna, Austria. https://www.R-project.org/.
RStudio Team. (2020). Rstudio: Integrated development environment for R. RStudio, PBC. Boston, MA.
http://www.rstudio.com/.
Venables, W. N., & Ripley, B. D. (2002). Modern applied statistics with S (Fourth) [ISBN 0-387-95457-0].
Springer. https://www.stats.ox.ac.uk/pub/MASS4/.
Another random document with
no related content on Scribd:
Spraying Yellow Paint through the Wing-Bone of an Eagle
For burial they dressed him in his best clothes—a suit of soft-tanned
deerskin, with leggings and moccasins to match. They wrapped the
body in a robe and placed it on the summit of a high ridge—his favorite
place to sit and dream.
The Blackfoot believed that the spirit went eastward to the Sand Hills,
a barren country on the plains. It was inhabited by the ghosts of people
and animals, which exist together as in this life.
They placed their dead upon scaffolds in trees, on the summit of a hill,
or in a death lodge hidden away among the trees. The dead were
clothed according to their station in life, believing they went to the Sand
Hills in their burial clothes. Often the things a person valued most were
left beside the grave. Sometimes the best horses of a chief were killed,
that they might go with him to the Spirit Land. [273]
It was customary for a man and his wife to give their sacred bundles
into the care of another couple who were expected to make new
clothes and give ceremonies for the couple in mourning. Finally friends
of the mourners came and tried to make them forget their sorrow, and
to persuade them to return to their ordinary life. [274]
[Contents]
CHAPTER XXXIX
DANCE OF THE HAIR-PARTERS (GRASS DANCE)
One morning Elk Horn, the herald, galloped through the camp, holding
aloft a standard with eagle feathers along its staff. He called in a loud
voice that the Grass Dancers would hold their ceremony, and invited
every one to come. He wore a deerskin suit, a beaded breast ornament
of many strands, and a blanket draped about his waist. His horse was
painted, and decorated with clusters of feathers and sleigh bells; and
there were coyote tails hanging from his stirrups.
Soon the dancers began to assemble. Some were naked, except for
loin-cloths and beaded dance moccasins, and had their faces and
bodies variously painted. Others wore fine costumes, with war shirts of
soft-tanned buckskin, which were decorated with colored beads and
trimmed over the shoulders and legs with black-tipped ermine tails.
They had breast ornaments and necklaces of beads, of elk teeth and
grizzly bear claws. They carried tomahawks, bows and arrows, and
rattles made of bunches of deer and elk hoofs; [275]and wore war
bonnets of eagle feathers and headdresses made of colored horsehair
and porcupine-skins, caps of otter and mink skins, which were wound
about their heads and had the tails hanging down behind. They had
skin ankle-bands with small bells attached, and strings of sleigh bells
strapped about their legs and hanging from their waists.
The dancers sat in a circle, with the drummers in the center, having
large cowhide drums of different colors. They used single drumsticks
with which they beat with spirit; they sang rhythmically and in perfect
unison. In the dance the drumming was a continued booming that did
not break, growing faster and faster, until it ended suddenly with a
crash and in a chorus of shrill war-whoops. Such was the music the
Hair-Parters had for their ceremony.
They had one dance figure, in which only warriors took part; those who
had escaped after being surrounded in battle. Another dance was for
men who had never turned away from a fight; and another in which
only generous men took part—those who were known to give freely of
their possessions.
When an eagle feather fell in the dance from the war bonnet of Night
Gun, he did not try to recover it himself; this might bring him bad luck.
He chose Bear Chief, a famous [276]warrior, to pick it up. Then, led by
Bear Chief, the dancers circled three times round the feather; the
fourth time, Bear Chief took the feather; and, after recounting four of
his brave deeds in battle, he gave it back to the owner.
There was a special dance for those who had been wounded in battle.
Wolf Eagle, a warrior with only one arm, danced with spirit and
abandon, carrying in his single hand the decorated bone of his missing
arm. Another dancer, “Behind-the-Ears” by name, held his rifle ready to
shoot. In battle he had once made a good shot and hit an enemy
behind the ear; in this dance, he went through similar motions to recall
that deed.
The leader of the Hair-Parters was Black Weasel. His seat in the dance
circle was marked by a wand decorated with eagle feathers and driven
into the ground. He wore a war bonnet of selected eagle feathers and a
soft-tanned suit of deerskin trimmed with ermine tails. Across his
shoulders and along arms and legs were broad strips of quill work.
Black Weasel opened the dance by moving about the circle, striking
the seated warriors with his feathered wand to make them join in and
whipping any who lagged behind. It was also his duty to look out for
strangers, and to see that women and children had seats.
Among the spectators was Nokoa, a small boy with his mother. He
wore a fringed buckskin suit and a beaded necklace of many strands.
During one of the figures his father, Wolverine, took him into the dance.
At first he was abashed before so many people, but soon forgot himself
and danced fearlessly, his moccasined feet keeping time with the
rhythmic beating of drums, swaying his small body like the warriors and
aiming a stick for a gun.
The Grass Dance lasted throughout the day and ended after sunset
with a feast. During intermissions, they had speeches and stories of
brave deeds in war. Mountain Chief [277]stood up and told how he used
to dance in former days. He urged the Hair-Parters to be generous and
to give many horses to visitors, especially those who came from a
distance. In his hand he held a stick which represented a horse. He
crossed the circle and handed the stick to a visiting Sioux Indian. Then
from the spectators came shouts of approval; and an aged chief sang:
“Good man, to give away your horse so generously.”
During the feast, the venerable chief, Running Crane, stood up and
spoke, saying:
On this same day, and in a different part of the camp, were sham
battles of former fights with hostile Indian tribes—dances by warriors
on foot and mounted on horses. Their functions were to excite the
people, both old and young, and to stir up enthusiasm for war and
make young men eager to fight.
One of these sham battles on foot enacted a fight between Crows and
Blackfoot. The warriors, representing the Crow Indians, were led by
Flat Tail; and the Blackfoot by Little Dog, their war chief. They
advanced in line with rifles, beating drums and singing war songs.
When the waiting warriors fired their guns, some of the enemy fell and
the rest retreated. Then the visitors scalped the dead amid cheers and
war-whoops from the spectators.
[MP3 | MuseScore]
Just outside the circle camp was the race track, a level stretch along a
low range of hills. The head of the course lay towards the snow-capped
Rockies and extended eastward toward the open plains. On one side
were grass-covered prairies, decked with lovely wild flowers; and on
the other the outskirts of the big camp with its smoke-colored tepees.
For the most exciting race of that day, a large crowd of Indians
gathered at the finish; they wagered horses, robes, and blankets. The
young riders were naked, wearing only loin-cloths and moccasins.
They rode wild broncos without saddles, using rawhide ropes for
bridles. At the start I heard shouts, and saw a cloud of dust moving
swiftly. The riders came, lying low along the backs of their broncos and
beating them with rawhide whips. A famous race horse named “Bull
Shoe” won, amid shouts from the throng of spectators.
Then Elk Horn, the herald, rode through the camp and announced that
White Grass, the medicine man, would take out his Dancing Pipe; he
invited every one to come to the ceremony.
Now the Dancing Pipe was the oldest and most powerful of the
medicine pipes. Many came to follow it, both men and women, dressed
in their best, each carrying some sacred object to which they prayed. A
throng soon filled the lodge of White Grass and crowded about the
outside. They watched him remove the wrappings from the pipe, one
by one, each with a different song, until at last he held up the long
stem. It was wrapped with fur and decorated with eagle feathers and
bright-colored plumes.
White Grass lifted the Pipe reverently, holding it to the north, south,
east, and west; and prayed to the Sun for all the people. Two chiefs
arose and recounted their brave deeds in war; and, after that, four men
sounded their drums. [280]
Then White Grass stood up and held the Pipe in front of him. He
danced slowly from the lodge, men and women and even children
following in single file, until there was a long line of dancing Indians
moving in and out among the tepees. White Grass and the four
drummers led the dancers, beating their drums and singing the songs
of the Dancing Pipe. They moved once around the big camp circle and
then back to the lodge of White Grass.
[MP3 | MuseScore]
But a tragedy put an end to the Kissing Dance. There was a married
woman who liked the dance so much she neglected home and
children. When her husband found out that she kept choosing a former
lover, he came to the dance lodge and killed her.
ELK HORN, HERALD OF THE BRAVE DOG SOCIETY
[MP3 | MuseScore]
That same night, I was wakened by a dog fight close to our lodge.
Quickly other dogs came and joined in a mass fight, with barking, yelps
and snarls. Then hundreds of dogs in all parts of the circle camp,
roused by the noise of the fight, united in a deep-throated and mournful
howl—a weird sound, like the wailing of a great wolf-pack.
[MP3 | MuseScore]
When their dismal chorus died away, I went outside the lodge. It was a
glorious night; the sky was clear and a full moon rising over the prairie.
All about me were white tepees with their picturesque clusters of
tapering poles. In the west a brilliant planet was sinking behind the dim
outlines of the Rocky Mountains. The camp was throbbing with life. On
all sides I heard singing and drumming. The Sioux warriors were again
making their rounds, singing a Traveling Song. Then Red Fox and his
sweetheart passed, singing in unison a Riding Song. The girl sat in
front of her lover, wearing his [283]war bonnet. His robe of soft-tanned
elkskin flowed gracefully back as they rode. Some of the night-singers
were riding, mounted two on a horse, singing and marking time with
clusters of sleigh bells, in perfect time with the slow jog-trot of their
horses.
It was an old custom for young people to ride all night and sing, while
guarding camp and protecting the horse herds. Then it became a
social custom with special songs, sung in unison by different groups
riding two on a horse. [284]
[Contents]
CHAPTER XL
SOCIETY OF BRAVE DOGS
My tepee was near the three dance lodges of the Brave Dog Society, which
were somewhat apart from the others, near the center of the circle camp. There
they kept their costumes and weapons and dressed for parades and dances.
Day after day I watched them in their interesting customs.
As a society they had power, because of their reputation for bravery. Every one
feared to oppose them. They did not maltreat people, but sometimes punished
severely offenders against the public welfare. Their function in the tribal camp
was primarily to preserve order.
The first evening of the camp, they rode round the circle shouting their orders to
the people, saying:
“Let every one be quiet to-night. Young people must not act thoughtlessly or play
pranks. The sacred woman has important ceremonies and should not be
disturbed.”
For parades and dances out of doors, the Brave Dogs went forth in their best
costumes. They marched by twos. Short Robe, their leader, wore a beaded suit
of deerskin trimmed over shoulders and arms with black-tipped weasel-skins;
also a large coyote-skin, with his head thrust through a slit in the middle of the
skin and the tail hanging down his back. According to their society custom, he
carried a rattle in his right hand and a blanket over his left arm. Sometimes in
their parades, Short Robe’s youngest son, a boy of twelve, walked by his
father’s side, wearing a miniature costume like the chief.
SOCIETY OF BRAVE DOGS MARCHING THROUGH THE CAMP
In front is Short Robe, the head man, with his small son