Rprogramming PDF
Rprogramming PDF
Roger D. Peng
This book is for sale at http://leanpub.com/rprogramming
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.
1. Stay in Touch! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2. Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
5.15 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
13.8 rename() . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
13.9 mutate() . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
13.10 group_by() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
13.11 %>% . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
13.12 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
15. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
15.1 Functions in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
15.2 Your First Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
15.3 Argument Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
15.4 Lazy Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
15.5 The ... Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
15.6 Arguments Coming After the ... Argument . . . . . . . . . . . . . . . . . . . . 81
15.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
23. Data Analysis Case Study: Changes in Fine Particle Air Pollution in the U.S. . . . . . 149
23.1 Synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
23.2 Loading and Processing the Raw Data . . . . . . . . . . . . . . . . . . . . . . . . 149
23.3 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
First, I encourage you to join my mailing list of Leanpub Readers. On this list I send out
updates of my own activities as well as occasional comments on data science current events.
Ill also let you know what my co-conspirators Jeff Leek and Brian Caffo are up to because
sometimes they do really cool stuff.
Second, I have a regular podcast called Not So Standard Deviations that I co-host with Dr.
Hilary Parker, a Data Scientist at Stitch Fix. On this podcast, Hilary and I talk about the craft of
data science and discuss common issues and problems in analyzing data. Well also compare
how data science is approached in both academia and industry contexts and discuss the latest
industry trends. You can listen to recent episodes on our SoundCloud page or you can subscribe
to it in iTunes or your favorite podcasting app.
For those of you who purchased a printed copy of this book, I encourage you to go to the Leanpub
web site and obtain the e-book version, which is available for free. The reason is that I will
occasionally update the book with new material and readers who purchase the e-book version are
entitled to free updates (this is unfortunately not yet possible with printed books).
Thanks again for purchasing this book and please do stay in touch!
http://eepurl.com/bAJ3zj
https://soundcloud.com/nssd-podcast
https://itunes.apple.com/us/podcast/not-so-standard-deviations/id1040614570
https://leanpub.com/rprogramming
2. Preface
I started using R in 1998 when I was a college undergraduate working on my senior thesis.
The version was 0.63. I was an applied mathematics major with a statistics concentration and
I was working with Dr. Nicolas Hengartner on an analysis of word frequencies in classic texts
(Shakespeare, Milton, etc.). The idea was to see if we could identify the authorship of each of the
texts based on how frequently they used certain words. We downloaded the data from Project
Gutenberg and used some basic linear discriminant analysis for the modeling. The work was
eventually published and was my first ever peer-reviewed publication. I guess you could argue
it was my first real data science experience.
Back then, no one was using R. Most of my classes were taught with Minitab, SPSS, Stata, or
Microsoft Excel. The cool people on the cutting edge of statistical methodology used S-PLUS. I
was working on my thesis late one night and I had a problem. I didnt have a copy of any of those
software packages because they were expensive and I was a student. I didnt feel like trekking over
to the computer lab to use the software because it was late at night.
But I had the Internet! After a couple of Yahoo! searches I found a web page for something called R,
which I figured was just a play on the name of the S-PLUS package. From what I could tell, R was a
clone of S-PLUS that was free. I had already written some S-PLUS code for my thesis so I figured
I would try to download R and see if I could just run the S-PLUS code.
It didnt work. At least not at first. It turns out that R is not exactly a clone of S-PLUS and quite a few
modifications needed to be made before the code would run in R. In particular, R was missing a lot of
statistical functionality that had existed in S-PLUS for a long time already. Luckily, Rs programming
language was pretty much there and I was able to more or less re-implement the features that were
missing in R.
After college, I enrolled in a PhD program in statistics at the University of California, Los Angeles.
At the time the department was brand new and they didnt have a lot of policies or rules (or classes,
for that matter!). So you could kind of do what you wanted, which was good for some students and
not so good for others. The Chair of the department, Jan de Leeuw, was a big fan of XLisp-Stat and
so all of the departments classes were taught using XLisp-Stat. I diligently bought my copy of Luke
Tierneys book and learned to really love XLisp-Stat. It had a number of features that R didnt have
at all, most notably dynamic graphics.
But ultimately, there were only so many parentheses that I could type, and still all of the research-
level statistics was being done in S-PLUS. The department didnt really have a lot of copies of S-PLUS
lying around so I turned back to R. When I looked around at my fellow students, I realized that I
was basically the only one who had any experience using R. Since there was a budding interest in R
http://amstat.tandfonline.com/doi/abs/10.1198/000313002100#.VQGiSELpagE
http://www.amazon.com/LISP-STAT-Object-Oriented-Environment-Statistical-Probability/dp/0471509167/
Preface 3
around the department, I decided to start a brown bag series where every week for about an hour
I would talk about something you could do in R (which wasnt much, really). People seemed to like
it, if only because there wasnt really anyone to turn to if you wanted to learn about R.
By the time I left grad school in 2003, the department had essentially switched over from XLisp-
Stat to R for all its work (although there were a few hold outs). Jan discusses the rationale for the
transition in a paper in the Journal of Statistical Software.
In the next step of my career, I went to the Department of Biostatistics at the Johns Hopkins
Bloomberg School of Public Health, where I have been for the past 12 years. When I got to Johns
Hopkins people already seemed into R. Most people had abandoned S-PLUS a while ago and were
committed to using R for their research. Of all the available statistical packages, R had the most
powerful and expressive programming language, which was perfect for someone developing new
statistical methods.
However, we didnt really have a class that taught students how to use R. This was a problem because
most of our grad students were coming into the program having never heard of R. Most likely in
their undergraduate programs, they used some other software package. So along with Rafael Irizarry,
Brian Caffo, Ingo Ruczinski, and Karl Broman, I started a new class to teach our graduate students
R and a number of other skills theyd need in grad school.
The class was basically a weekly seminar where one of us talked about a computing topic of interest.
I gave some of the R lectures in that class and when I asked people who had heard of R before, almost
no one raised their hand. And no one had actually used it before. The main selling point at the time
was Its just like S-PLUS but its free! A lot of people had experience with SAS or Stata or SPSS. A
number of people had used something like Java or C/C++ before and so I often used that a reference
frame. No one had ever used a functional-style of programming language like Scheme or Lisp.
To this day, I still teach the class, known a Biostatistics 140.776 (Statistical Computing). However,
the nature of the class has changed quite a bit over the past 10 years. The population of students
(mostly first-year graduate students) has shifted to the point where many of them have been
introduced to R as undergraduates. This trend mirrors the overall trend with statistics where we
are seeing more and more students do undergraduate majors in statistics (as opposed to, say,
mathematics). Eventually, by 20082009, when Id asked how many people had heard of or used
R before, everyone raised their hand. However, even at that late date, I still felt the need to convince
people that R was a real language that could be used for real tasks.
R has grown a lot in recent years, and is being used in so many places now, that I think its
essentially impossible for a person to keep track of everything that is going on. Thats fine, but
it makes introducing people to R an interesting experience. Nowadays in class, students are often
teaching me something new about R that Ive never seen or heard of before (they are quite good
at Googling around for themselves). I feel no need to bring people over to R. In fact its quite the
oppositepeople might start asking questions if I werent teaching R.
http://www.jstatsoft.org/v13/i07
http://www.biostat.jhsph.edu
Preface 4
This book comes from my experience teaching R in a variety of settings and through different stages
of its (and my) development. Much of the material has been taken from by Statistical Computing
class as well as the R Programming class I teach through Coursera.
Im looking forward to teaching R to people as long as people will let me, and Im interested in
seeing how the next generation of students will approach it (and how my approach to them will
change). Overall, its been just an amazing experience to see the widespread adoption of R over the
past decade. Im sure the next decade will be just as amazing.
https://www.coursera.org/course/rprog
3. History and Overview of R
There are only two kinds of languages: the ones people complain about and the ones
nobody uses Bjarne Stroustrup
3.1 What is R?
This is an easy question to answer. R is a dialect of S.
3.2 What is S?
S is a language that was developed by John Chambers and others at the old Bell Telephone
Laboratories, originally part of AT&T Corp. S was initiated in 1976 as an internal statistical analysis
environmentoriginally implemented as Fortran libraries. Early versions of the language did not
even contain functions for statistical modeling.
In 1988 the system was rewritten in C and began to resemble the system that we have today (this
was Version 3 of the language). The book Statistical Models in S by Chambers and Hastie (the white
book) documents the statistical analysis functionality. Version 4 of the S language was released in
1998 and is the version we use today. The book Programming with Data by John Chambers (the
green book) documents this version of the language.
Since the early 90s the life of the S language has gone down a rather winding path. In 1993 Bell Labs
gave StatSci (later Insightful Corp.) an exclusive license to develop and sell the S language. In 2004
Insightful purchased the S language from Lucent for $2 million. In 2006, Alcatel purchased Lucent
Technologies and is now called Alcatel-Lucent.
Insightful sold its implementation of the S language under the product name S-PLUS and built a
number of fancy features (GUIs, mostly) on top of ithence the PLUS. In 2008 Insightful was
acquired by TIBCO for $25 million. As of this writing TIBCO is the current owner of the S language
and is its exclusive developer.
The fundamentals of the S language itself has not changed dramatically since the publication of the
Green Book by John Chambers in 1998. In 1998, S won the Association for Computing Machinerys
Software System Award, a highly prestigious award in the computer science field.
https://youtu.be/STihTnVSZnI
http://cm.bell-labs.com/stat/doc/94.11.ps
History and Overview of R 6
The key part here was the transition from user to developer. They wanted to build a language that
could easily service both people. More technically, they needed to build language that would
be suitable for interactive data analysis (more command-line based) as well as for writing longer
programs (more traditional programming language-like).
3.4 Back to R
The R language came to use quite a bit after S had been developed. One key limitation of the S
language was that it was only available in a commericial package, S-PLUS. In 1991, R was created
by Ross Ihaka and Robert Gentleman in the Department of Statistics at the University of Auckland. In
1993 the first announcement of R was made to the public. Rosss and Roberts experience developing
R is documented in a 1996 paper in the Journal of Computational and Graphical Statistics:
Ross Ihaka and Robert Gentleman. R: A language for data analysis and graphics. Journal
of Computational and Graphical Statistics, 5(3):299314, 1996
In 1995, Martin Mchler made an important contribution by convincing Ross and Robert to use the
GNU General Public License to make R free software. This was critical because it allowed for the
source code for the entire R system to be accessible to anyone who wanted to tinker with it (more
on free software later).
In 1996, a public mailing list was created (the R-help and R-devel lists) and in 1997 the R Core
Group was formed, containing some people associated with S and S-PLUS. Currently, the core group
controls the source code for R and is solely able to check in changes to the main R source tree. Finally,
in 2000 R version 1.0.0 was released to the public.
http://www.stat.bell-labs.com/S/history.html
http://www.gnu.org/licenses/gpl-2.0.html
History and Overview of R 7
2.0.
According to the Free Software Foundation, with free software, you are granted the following four
freedoms
The freedom to run the program, for any purpose (freedom 0).
The freedom to study how the program works, and adapt it to your needs (freedom 1). Access
to the source code is a precondition for this.
The freedom to redistribute copies so you can help your neighbor (freedom 2).
The freedom to improve the program, and release your improvements to the public, so that
the whole community benefits (freedom 3). Access to the source code is a precondition for
this.
You can visit the Free Software Foundations web site to learn a lot more about free software. The
Free Software Foundation was founded by Richard Stallman in 1985 and Stallmans personal web
site is an interesting read if you happen to have some spare time.
1. The base R system that you download from CRAN: Linux Windows Mac Source Code
2. Everything else.
The base R system contains, among other things, the base package which is required to run
R and contains the most fundamental functions.
The other packages contained in the base system include utils, stats, datasets, graphics,
grDevices, grid, methods, tools, parallel, compiler, splines, tcltk, stats4.
http://www.gnu.org/licenses/gpl-2.0.html
http://www.gnu.org/philosophy/free-sw.html
http://www.fsf.org
https://stallman.org
http://cran.r-project.org
http://cran.r-project.org/bin/linux/
http://cran.r-project.org/bin/windows/
http://cran.r-project.org/bin/macosx/
http://cran.r-project.org/src/base/R-3/R-3.1.3.tar.gz
History and Overview of R 9
There are also Recommended packages: boot, class, cluster, codetools, foreign, KernS-
mooth, lattice, mgcv, nlme, rpart, survival, MASS, spatial, nnet, Matrix.
When you download a fresh installation of R from CRAN, you get all of the above, which represents
a substantial amount of functionality. However, there are many other packages available:
There are over 4000 packages on CRAN that have been developed by users and programmers
around the world.
There are also many packages associated with the Bioconductor project.
People often make packages available on their personal websites; there is no reliable way to
keep track of how many packages are available in this fashion.
There are a number of packages being developed on repositories like GitHub and BitBucket
but there is no reliable listing of all these packages.
3.8 Limitations of R
No programming language or statistical analysis system is perfect. R certainly has a number of
drawbacks. For starters, R is essentially based on almost 50 year old technology, going back to the
original S system developed at Bell Labs. There was originally little built in support for dynamic or
3-D graphics (but things have improved greatly since the old days).
Another commonly cited limitation of R is that objects must generally be stored in physical memory.
This is in part due to the scoping rules of the language, but R generally is more of a memory hog
than other statistical packages. However, there have been a number of advancements to deal with
this, both in the R core and also in a number of packages developed by contributors. Also, computing
power and capacity has continued to grow over time and amount of physical memory that can be
installed on even a consumer-level laptop is substantial. While we will likely never have enough
physical memory on a computer to handle the increasingly large datasets that are being generated,
the situation has gotten quite a bit easier over time.
At a higher level one limitation of R is that its functionality is based on consumer demand and
(voluntary) user contributions. If no one feels like implementing your favorite method, then its your
job to implement it (or you need to pay someone to do it). The capabilities of the R system generally
reflect the interests of the R user community. As the community has ballooned in size over the past
10 years, the capabilities have similarly increased. When I first started using R, there was very little
in the way of functionality for the physical sciences (physics, astronomy, etc.). However, now some
of those communities have adopted R and we are seeing more code being written for those kinds of
applications.
If you want to know my general views on the usefulness of R, you can see them here in the following
exchange on the R-help mailing list with Douglas Bates and Brian Ripley in June 2004:
http://bioconductor.org
History and Overview of R 10
Roger D. Peng: I dont think anyone actually believes that R is designed to make
everyone happy. For me, R does about 99% of the things I need to do, but sadly, when I
need to order a pizza, I still have to pick up the telephone.
Douglas Bates: There are several chains of pizzerias in the U.S. that provide for Internet-
based ordering (e.g. www.papajohnsonline.com) so, with the Internet modules in R, its
only a matter of time before you will have a pizza-ordering function available.
Brian D. Ripley: Indeed, the GraphApp toolkit (used for the RGui interface under R for
Windows, but Guido forgot to include it) provides one (for use in Sydney, Australia, we
presume as that is where the GraphApp author hails from). Alternatively, a Padovian
has no need of ordering pizzas with both home and neighbourhood restaurants .
At this point in time, I think it would be fairly straightforward to build a pizza ordering R package
using something like the RCurl or httr packages. Any takers?
3.9 R Resources
Official Manuals
As far as getting started with R by reading stuff, there is of course this book. Also, available from
CRAN are
An Introduction to R
R Data Import/Export
Writing R Extensions: Discusses how to write and organize R packages
R Installation and Administration: This is mostly for building R from the source code)
R Internals: This manual describes the low level structure of R and is primarily for developers
and R core members
R Language Definition: This documents the R language and, again, is primarily for develop-
ers
http://cran.r-project.org
http://cran.r-project.org/doc/manuals/r-release/R-intro.html
http://cran.r-project.org/doc/manuals/r-release/R-data.html
http://cran.r-project.org/doc/manuals/r-release/R-exts.html
http://cran.r-project.org/doc/manuals/r-release/R-admin.html
http://cran.r-project.org/doc/manuals/r-release/R-ints.html
http://cran.r-project.org/doc/manuals/r-release/R-lang.html
History and Overview of R 11
Other Resources
Major technical publishers like Springer, Chapman & Hall/CRC have entire series of books
dedicated to using R in various applications. For example, Springer has a series of books called
Use R!.
A longer list of books can be found on the CRAN web site.
http://www.r-project.org/doc/bib/R-books.html
4. Getting Started with R
4.1 Installation
The first thing you need to do to get started with R is to install it on your computer. R works on
pretty much every platform available, including the widely available Windows, Mac OS X, and Linux
systems. If you want to watch a step-by-step tutorial on how to install R for Mac or Windows, you
can watch these videos:
Installing R on Windows
Installing R on the Mac
There is also an integrated development environment available for R that is built by RStudio. I really
like this IDEit has a nice editor with syntax highlighting, there is an R object viewer, and there are
a number of other nice features that are integrated. You can see how to install RStudio here
Installing RStudio
http://youtu.be/Ohnk9hcxf9M
https://youtu.be/uxuuWXU-7UQ
https://youtu.be/bM7Sfz-LADM
http://rstudio.com
https://youtu.be/8xT3hmJQskU
https://youtu.be/XBcvH1BpIBo
5. R Nuts and Bolts
5.1 Entering Input
Watch a video of this section
At the R prompt we type expressions. The <- symbol is the assignment operator.
> x <- 1
> print(x)
[1] 1
> x
[1] 1
> msg <- "hello"
The # character indicates a comment. Anything to the right of the # (including the # itself) is ignored.
This is the only comment character in R. Unlike some other languages, R does not support multi-line
comments or comment blocks.
5.2 Evaluation
When a complete expression is entered at the prompt, it is evaluated and the result of the evaluated
expression is returned. The result may be auto-printed.
https://youtu.be/vGY5i_J2c-c?t=4m43s
R Nuts and Bolts 14
The [1] shown in the output indicates that x is a vector and 5 is its first element.
Typically with interactive work, we do not explicitly print objects with the print function; it is much
easier to just auto-print them by typing the name of the object and hitting return/enter. However,
when writing scripts, functions, or longer programs, there is sometimes a need to explicitly print
objects because auto-printing does not work in those settings.
When an R vector is printed you will notice that an index for the vector is printed in square brackets
[] on the side. For example, see this integer sequence of length 20.
The numbers in the square brackets are not part of the vector itself, they are merely part of the
printed output.
With R, its important that one understand that there is a difference between the actual R object
and the manner in which that R object is printed to the console. Often, the printed output may have
additional bells and whistles to make the output more friendly to the users. However, these bells and
whistles are not inherently part of the object.
Note that the : operator is used to create integer sequences.
5.3 R Objects
Watch a video of this section
R has five basic or atomic classes of objects:
character
numeric (real numbers)
integer
complex
logical (True/False)
The most basic type of R object is a vector. Empty vectors can be created with the vector() function.
There is really only one rule about vectors in R, which is that A vector can only contain objects
of the same class.
But of course, like any good rule, there is an exception, which is a list, which we will get to a bit later.
A list is represented as a vector but can contain objects of different classes. Indeed, thats usually
why we use them.
There is also a class for raw objects, but they are not commonly used directly in data analysis and
I wont cover them here.
https://youtu.be/vGY5i_J2c-c
R Nuts and Bolts 15
5.4 Numbers
Numbers in R are generally treated as numeric objects (i.e. double precision real numbers). This
means that even if you see a number like 1 or 2 in R, which you might think of as integers, they
are likely represented behind the scenes as numeric objects (so something like 1.00 or 2.00). This
isnt important most of the timeexcept when it is.
If you explicitly want an integer, you need to specify the L suffix. So entering 1 in R gives you a
numeric object; entering 1L explicitly gives you an integer object.
There is also a special number Inf which represents infinity. This allows us to represent entities like
1 / 0. This way, Inf can be used in ordinary calculations; e.g. 1 / Inf is 0.
The value NaN represents an undefined value (not a number); e.g. 0 / 0; NaN can also be thought of
as a missing value (more on that later)
5.5 Attributes
R objects can have attributes, which are like metadata for the object. These metadata can be very
useful in that they help to describe the object. For example, column names on a data frame help to
tell us what data are contained in each of the columns. Some examples of R object attributes are
names, dimnames
dimensions (e.g. matrices, arrays)
class (e.g. integer, numeric)
length
other user-defined attributes/metadata
Attributes of an object (if any) can be accessed using the attributes() function. Not all R objects
contain attributes, in which case the attributes() function returns NULL.
https://youtu.be/w8_XdYI3reU
R Nuts and Bolts 16
Note that in the above example, T and F are short-hand ways to specify TRUE and FALSE. However,
in general one should try to use the explicit TRUE and FALSE values when indicating logical values.
The T and F values are primarily there for when youre feeling lazy.
You can also use the vector() function to initialize vectors.
In each case above, we are mixing objects of two different classes in a vector. But remember that
the only rule about vectors says this is not allowed. When different objects are mixed in a vector,
coercion occurs so that every element in the vector is of the same class.
In the example above, we see the effect of implicit coercion. What R tries to do is find a way to
represent all of the objects in the vector in a reasonable fashion. Sometimes this does exactly what
you want andsometimes not. For example, combining a numeric object with a character object
will create a character vector, because numbers can usually be easily represented as strings.
Sometimes, R cant figure out how to coerce an object and this can result in NAs being produced.
When nonsensical coercion takes place, you will usually get a warning from R.
5.9 Matrices
Matrices are vectors with a dimension attribute. The dimension attribute is itself an integer vector
of length 2 (number of rows, number of columns)
Matrices are constructed column-wise, so entries can be thought of starting in the upper left corner
and running down the columns.
R Nuts and Bolts 18
Matrices can also be created directly from vectors by adding a dimension attribute.
Matrices can be created by column-binding or row-binding with the cbind() and rbind() functions.
5.10 Lists
Lists are a special type of vector that can contain elements of different classes. Lists are a very
important data type in R and you should get to know them well. Lists, in combination with the
various apply functions discussed later, make for a powerful combination.
Lists can be explicitly created using the list() function, which takes an arbitrary number of
arguments.
R Nuts and Bolts 19
[[2]]
[1] "a"
[[3]]
[1] TRUE
[[4]]
[1] 1+4i
We can also create an empty list of a prespecified length with the vector() function
[[2]]
NULL
[[3]]
NULL
[[4]]
NULL
[[5]]
NULL
5.11 Factors
Watch a video of this section
Factors are used to represent categorical data and can be unordered or ordered. One can think of
a factor as an integer vector where each integer has a label. Factors are important in statistical
modeling and are treated specially by modelling functions like lm() and glm().
Using factors with labels is better than using integers because factors are self-describing. Having a
variable that has values Male and Female is better than a variable that has values 1 and 2.
Factor objects can be created with the factor() function.
https://youtu.be/NuY6jY4qE7I
R Nuts and Bolts 20
Often factors will be automatically created for you when you read a dataset in using a function like
read.table(). Those functions often default to creating factors when they encounter data that look
like characters or strings.
The order of the levels of a factor can be set using the levels argument to factor(). This can be
important in linear modelling because the first level is used as the baseline level.
https://github.com/hadley/dplyr
R Nuts and Bolts 22
5.14 Names
R objects can have names, which is very useful for writing readable code and self-describing objects.
Here is an example of assigning names to an integer vector.
$Boston
[1] 2
$London
[1] 3
> names(x)
[1] "Los Angeles" "Boston" "London"
Column names and row names can be set separately using the colnames() and rownames()
functions.
Note that for data frames, there is a separate function for setting the row names, the row.names()
function. Also, data frames do not have column names, they just have names (like lists). So to set
the column names of a data frame just use the names() function. Yes, I know its confusing. Heres a
quick summary:
5.15 Summary
There are a variety of different builtin-data types in R. In this chapter we have reviewed the following
All R objects can have attributes that help to describe what is in the object. Perhaps the most useful
attribute is names, such as column and row names in a data frame, or simply names in a vector or
list. Attributes like dimensions are also important as they can modify the behavior of objects, like
turning a vector into a matrix.
6. Getting Data In and Out of R
6.1 Reading and Writing Data
Watch a video of this section
There are a few principal functions reading data into R.
There are of course, many R packages that have been developed to read in all kinds of other datasets,
and you may need to resort to one of these packages if you are working in a specific area.
There are analogous functions for writing data to files
write.table, for writing tabular data to text files (i.e. CSV) or connections
writeLines, for writing character data line-by-line to a file or connection
dump, for dumping a textual representation of multiple R objects
dput, for outputting a textual representation of an R object
save, for saving an arbitrary number of R objects in binary format (possibly compressed) to
a file.
serialize, for converting an R object into a binary format for outputting to a connection (or
file).
For small to moderately sized datasets, you can usually call read.table without specifying any other
arguments
Telling R all these things directly makes R run faster and more efficiently. The read.csv() function
is identical to read.table except that some of the defaults are set differently (like the sep argument).
Read the help page for read.table, which contains many hints
https://youtu.be/BJYYIJO3UFI
Getting Data In and Out of R 26
Make a rough calculation of the memory required to store your dataset (see the next section
for an example of how to do this). If the dataset is larger than the amount of RAM on your
computer, you can probably stop right here.
Set comment.char = "" if there are no commented lines in your file.
Use the colClasses argument. Specifying this option instead of using the default can make
read.table run MUCH faster, often twice as fast. In order to use this option, you have to know
the class of each column in your data frame. If all of the columns are numeric, for example,
then you can just set colClasses = "numeric". A quick an dirty way to figure out the classes
of each column is the following:
Set nrows. This doesnt make R run faster but it helps with memory usage. A mild overestimate
is okay. You can use the Unix tool wc to calculate the number of lines in a file.
In general, when using R with larger datasets, its also useful to know a few things about your
system.
http://en.wikipedia.org/wiki/Double-precision_floating-point_format
Getting Data In and Out of R 27
So the dataset would require about 1.34 GB of RAM. Most computers these days have at least that
much RAM. However, you need to be aware of
Reading in a large dataset for which you do not have enough RAM is one easy way to freeze up your
computer (or at least your R session). This is usually an unpleasant experience that usually requires
you to kill the R process, in the best case scenario, or reboot your computer, in the worst case. So
make sure to do a rough calculation of memeory requirements before reading in a large dataset.
Youll thank me later.
7. Using the readr Package
The readr package is recently developed by Hadley Wickham to deal with reading in large flat files
quickly. The package provides replacements for functions like read.table() and read.csv(). The
analogous functions in readr are read_table() and read_csv(). These functions are often much
faster than their base R analogues and provide a few other nice features such as progress meters.
For the most part, you can read use read_table() and read_csv() pretty much anywhere you might
use read.table() and read.csv(). In addition, if there are non-fatal problems that occur while
reading in the data, you will get a warning and the returned data frame will have some information
about which rows/observations triggered the warning. This can be very helpful for debugging
problems with your data before you get neck deep in data analysis.
The importance of the read_csv function is perhaps better understood from an historical perspective.
Rs built in read.csv function similarly reads CSV files, but the read_csv function in readr builds on
that by removing some of the quirks and gotchas of read.csv as well as dramatically optimizing
the speed with which it can read data into R. The read_csv function also adds some nice user-
oriented features like a progress meter and a compact method for specifying column types.
A typical call to read_csv will look as follows.
> library(readr)
> teams <- read_csv("data/team_standings.csv")
Parsed with column specification:
cols(
Standing = col_integer(),
Team = col_character()
)
> teams
# A tibble: 32 2
Standing Team
<int> <chr>
1 1 Spain
2 2 Netherlands
3 3 Germany
4 4 Uruguay
5 5 Argentina
6 6 Brazil
7 7 Ghana
8 8 Paraguay
9 9 Japan
10 10 Chile
# ... with 22 more rows
Using the readr Package 29
By default, read_csv will open a CSV file and read it in line-by-line. It will also (by default), read in
the first few rows of the table in order to figure out the type of each column (i.e. integer, character,
etc.). From the read_csv help page:
If NULL, all column types will be imputed from the first 1000 rows on the input. This
is convenient (and fast), but not robust. If the imputation fails, youll need to supply the
correct types yourself.
You can specify the type of each column with the col_types argument.
In general, its a good idea to specify the column types explicitly. This rules out any possible guessing
errors on the part of read_csv. Also, specifying the column types explicitly provides a useful safety
check in case anything about the dataset should change without you knowing about it.
Note that the col_types argument accepts a compact representation. Here "cc" indicates that the
first column is character and the second column is character (there are only two columns). Using
the col_types argument is useful because often it is not easy to automatically figure out the type of
a column by looking at a few rows (especially if a column has many missing values).
The read_csv function will also read compressed files automatically. There is no need to decompress
the file first or use the gzfile connection function. The following call reads a gzip-compressed CSV
file containing download logs from the RStudio CRAN mirror.
Note that the warnings indicate that read_csv may have had some difficulty identifying the type of
each column. This can be solved by using the col_types argument.
Using the readr Package 30
You can specify the column type in a more detailed fashion by using the various col_* functions.
For example, in the log data above, the first column is actually a date, so it might make more sense
to read it in as a Date variable. If we wanted to just read in that first column, we could do
Now the date column is stored as a Date object which can be used for relevant date-related
computations (for example, see the lubridate package).
Using the readr Package 31
The read_csv function has a progress option that defaults to TRUE. This options provides a nice
progress meter while the CSV file is being read. However, if you are using read_csv in a function,
or perhaps embedding it in a loop, its probably best to set progress = FALSE.
8. Using Textual and Binary Formats
for Storing Data
Watch a video of this chapter
There are a variety of ways that data can be stored, including structured text files like CSV or tab-
delimited, or more complex binary formats. However, there is an intermediate format that is textual,
but not as simple as something like CSV. The format is native to R and is somewhat readable because
of its textual nature.
One can create a more descriptive representation of an R object by using the dput() or dump()
functions. The dump() and dput() functions are useful because the resulting textual format is edit-
able, and in the case of corruption, potentially recoverable. Unlike writing out a table or CSV file,
dump() and dput() preserve the metadata (sacrificing some readability), so that another user doesnt
have to specify it all over again. For example, we can preserve the class of each column of a table or
the levels of a factor variable.
Textual formats can work much better with version control programs like subversion or git which
can only track changes meaningfully in text files. In addition, textual formats can be longer-lived;
if there is corruption somewhere in the file, it can be easier to fix the problem because one can just
open the file in an editor and look at it (although this would probably only be done in a worst case
scenario!). Finally, textual formats adhere to the Unix philosophy, if that means anything to you.
There are a few downsides to using these intermediate textual formats. The format is not very space-
efficient, because all of the metadata is specified. Also, it is really only partially readable. In some
instances it might be preferable to have data stored in a CSV file and then have a separate code file
that specifies the metadata.
https://youtu.be/5mIPigbNDfk
http://www.catb.org/esr/writings/taoup/
Using Textual and Binary Formats for Storing Data 33
Notice that the dput() output is in the form of R code and that it preserves metadata like the class
of the object, the row names, and the column names.
The output of dput() can also be saved directly to a file.
Multiple objects can be deparsed at once using the dump function and read back in using source.
> source("data.R")
> str(y)
'data.frame': 1 obs. of 2 variables:
$ a: int 1
$ b: Factor w/ 1 level "a": 1
> x
[1] "foo"
Using Textual and Binary Formats for Storing Data 34
If you have a lot of objects that you want to save to a file, you can save all objects in your workspace
using the save.image() function.
Notice that Ive used the .rda extension when using save() and the .RData extension when using
save.image(). This is just my personal preference; you can use whatever file extension you want.
The save() and save.image() functions do not care. However, .rda and .RData are fairly common
extensions and you may want to use them because they are recognized by other software.
The serialize() function is used to convert individual R objects into a binary format that can be
communicated across an arbitrary connection. This may get sent to a file, but it could get sent over
a network or other connection.
When you call serialize() on an R object, the output will be a raw vector coded in hexadecimal
format.
Using Textual and Binary Formats for Storing Data 35
If you want, this can be sent to a file, but in that case you are better off using something like save().
The benefit of the serialize() function is that it is the only way to perfectly represent an R object
in an exportable format, without losing precision or any metadata. If that is what you need, then
serialize() is the function for you.
9. Interfaces to the Outside World
Watch a video of this chapter
Data are read in using connection interfaces. Connections can be made to files (most common) or to
other more exotic things.
In general, connections are powerful tools that let you navigate files or other external objects.
Connections can be thought of as a translator that lets you talk to objects that are outside of R.
Those outside objects could be anything from a data base, a simple text file, or a a web service API.
Connections allow R functions to talk to all these different external objects without you having to
write custom code for each object.
> str(file)
function (description = "", open = "", blocking = TRUE, encoding = getOption("encoding"),
raw = FALSE, method = getOption("url.method", "default"))
The file() function has a number of arguments that are common to many other connection
functions so its worth going into a little detail here.
In practice, we often dont need to deal with the connection interface directly as many functions for
reading and writing data just deal with it in the background.
For example, if one were to explicitly use connections to read a CSV file in to R, it might look like
this,
In the background, read.csv() opens a connection to the file foo.txt, reads from it, and closes the
connection when its done.
The above example shows the basic approach to using connections. Connections must be opened,
then the are read from or written to, and then they are closed.
For more structured text data like CSV files or tab-delimited files, there are other functions like
read.csv() or read.table().
The above example used the gzfile() function which is used to create a connection to files
compressed using the gzip algorithm. This approach is useful because it allows you to read from
a file without having to uncompress the file first, which would be a waste of space and time.
There is a complementary function writeLines() that takes a character vector and writes each
element of the vector one line at a time to a text file.
While reading in a simple web page is sometimes useful, particularly if data are embedded in the
web page somewhere. However, more commonly we can use URL connection to read in specific
data files that are stored on web servers.
Interfaces to the Outside World 39
Using URL connections can be useful for producing a reproducible analysis, because the code
essentially documents where the data came from and how they were obtained. This is approach
is preferable to opening a web browser and downloading a dataset by hand. Of course, the code you
write with connections may not be executable at a later date if things on the server side are changed
or reorganized.
10. Subsetting R Objects
Watch a video of this section
There are three operators that can be used to extract subsets of R objects.
The [ operator always returns an object of the same class as the original. It can be used to
select multiple elements of an object
The [[ operator is used to extract elements of a list or a data frame. It can only be used to
extract a single element and the class of the returned object will not necessarily be a list or
data frame.
The $ operator is used to extract elements of a list or data frame by literal name. Its semantics
are similar to that of [[.
The [ operator can be used to extract multiple elements of a vector by passing the operator an integer
sequence. Here we extract the first four elements of the vector.
> x[1:4]
[1] "a" "b" "c" "c"
The sequence does not have to be in order; you can specify any arbitrary integer vector.
We can also pass a logical sequence to the [ operator to extract elements of a vector that satisfy a
given condition. For example, here we want the elements of x that come lexicographically after the
letter a.
https://youtu.be/VfZUZGUgHqg
Subsetting R Objects 41
Another, more compact, way to do this would be to skip the creation of a logical vector and just
subset the vector directly with the logical expression.
We can access the (1, 2) or the (2, 1) element of this matrix using the appropriate indices.
> x[1, 2]
[1] 3
> x[2, 1]
[1] 2
Indices can also be missing. This behavior is used to access entire rows or columns of a matrix.
Similarly, when we extract a single row or column of a matrix, R by default drops the dimension of
length 1, so instead of getting a 1 3 matrix after extracting the first row, we get a vector of length
3. This behavior can similarly be turned off with the drop = FALSE option.
Be careful of Rs automatic dropping of dimensions. This is a feature that is often quite useful
during interactive work, but can later come back to bite you when you are writing longer programs
or functions.
$bar
[1] 0.6
The [[ operator can be used to extract single elements from a list. Here we extract the first element
of the list.
https://youtu.be/DStKguVpuDI
Subsetting R Objects 43
> x[[1]]
[1] 1 2 3 4
The [[ operator can also use named indices so that you dont have to remember the exact ordering
of every element of the list. You can also use the $ operator to extract elements by name.
> x[["bar"]]
[1] 0.6
> x$bar
[1] 0.6
Notice you dont need the quotes when you use the $ operator.
One thing that differentiates the [[ operator from the $ is that the [[ operator can be used with
computed indices. The $ operator can only be used with literal names.
$baz
[1] "hello"
https://youtu.be/q3BNhHHVCu4
Subsetting R Objects 45
In general, this is fine for interactive work, but you shouldnt resort to partial matching if you are
writing longer scripts, functions, or programs. In those cases, you should refer to the full element
name if possible. That way theres no ambiguity in your code.
What if there are multiple R objects and you want to take the subset with no missing values in any
of those objects?
https://youtu.be/TtJxmwXbwo0
Subsetting R Objects 46
> head(airquality)
Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
5 NA NA 14.3 56 5 5
6 28 NA 14.9 66 5 6
> good <- complete.cases(airquality)
> head(airquality[good, ])
Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
7 23 299 8.6 65 5 7
8 19 99 13.8 59 5 8
11. Vectorized Operations
Watch a video of this chapter
Many operations in R are vectorized, meaning that operations occur in parallel in certain R objects.
This allows you to write code that is efficient, concise, and easier to read than in non-vectorized
languages.
The simplest example is when adding two vectors together.
z <- numeric(length(x))
for(i in seq_along(x)) {
z[i] <- x[i] + y[i]
}
z
[1] 7 9 11 13
If you had to do that every time you wanted to add two vectors, your hands would get very tired
from all the typing.
Another operation you can do in a vectorized manner is logical comparisons. So suppose you wanted
to know which elements of a vector were greater than 2. You could do he following.
> x
[1] 1 2 3 4
> x > 2
[1] FALSE FALSE TRUE TRUE
https://youtu.be/YH3qtw7mTyA
Vectorized Operations 48
> x >= 2
[1] FALSE TRUE TRUE TRUE
> x < 3
[1] TRUE TRUE FALSE FALSE
> y == 8
[1] FALSE FALSE TRUE FALSE
Notice that these logical operations return a logical vector of TRUE and FALSE.
Of course, subtraction, multiplication and division are also vectorized.
> x - y
[1] -5 -5 -5 -5
> x * y
[1] 6 14 24 36
> x / y
[1] 0.1666667 0.2857143 0.3750000 0.4444444
12.1 Dates in R
Watch a video of this section
Dates are represented by the Date class and can be coerced from a character string using the
as.Date() function. This is a common way to end up with a Date object in R.
You can see the internal representation of a Date object by using the unclass() function.
> unclass(x)
[1] 0
> unclass(as.Date("1970-01-02"))
[1] 1
12.2 Times in R
Watch a video of this section
Times are represented by the POSIXct or the POSIXlt class. POSIXct is just a very large integer under
the hood. It use a useful class when you want to store times in something like a data frame. POSIXlt
is a list underneath and it stores a bunch of other useful information like the day of the week, day
of the year, month, day of the month. This is useful when you need that kind of information.
There are a number of generic functions that work on dates and times to help you extract pieces of
dates and/or times.
https://youtu.be/opYexVgjwkE
https://youtu.be/8HENCYXwZoU
Dates and Times 50
Times can be coerced from a character string using the as.POSIXlt or as.POSIXct function.
Finally, there is the strptime() function in case your dates are written in a different format.
strptime() takes a character vector that has dates and times and converts them into to a POSIXlt
object.
Dates and Times 51
> datestring <- c("January 10, 2012 10:40", "December 9, 2011 9:10")
> x <- strptime(datestring, "%B %d, %Y %H:%M")
> x
[1] "2012-01-10 10:40:00 EST" "2011-12-09 09:10:00 EST"
> class(x)
[1] "POSIXlt" "POSIXt"
The weird-looking symbols that start with the % symbol are the formatting strings for dates and
times. I can never remember the formatting strings. Check ?strptime for details. Its probably not
worth memorizing this stuff.
The nice thing about the date/time classes is that they keep track of all the annoying things about
dates and times, like leap years, leap seconds, daylight savings, and time zones.
Heres an example where a leap year gets involved.
Heres an example where two different time zones are in play (unless you live in GMT timezone, in
which case they will be the same!).
https://youtu.be/vEmWJrpP1KM
Dates and Times 52
12.4 Summary
Dates and times have special classes in R that allow for numerical and statistical calculations
Dates use the Date class
Times use the POSIXct and POSIXlt class
Character strings can be coerced to Date/Time classes using the strptime function or the
as.Date, as.POSIXlt, or as.POSIXct
13. Managing Data Frames with the
dplyr package
Watch a video of this chapter
select: return a subset of the columns of a data frame, using a flexible notation
filter: extract a subset of rows from a data frame based on logical conditions
arrange: reorder rows of a data frame
rename: rename variables in a data frame
mutate: add new variables/columns or transform existing variables
summarise / summarize: generate summary statistics of different variables in the data frame,
possibly within strata
%>%: the pipe operator is used to connect multiple verb actions together into a pipeline
The dplyr package as a number of its own data types that it takes advantage of. For example, there
is a handy print method that prevents you from printing a lot of data to the console. Most of the
time, these additional data types are transparent to the user and do not need to be worried about.
http://www.jstatsoft.org/v59/i10/paper
Managing Data Frames with the dplyr package 55
> install.packages("dplyr")
> install_github("hadley/dplyr")
After installing the package it is important that you load it into your R session with the library()
function.
> library(dplyr)
filter, lag
The following objects are masked from 'package:base':
You may get some warnings when the package is loaded because there are functions in the dplyr
package that have the same name as functions in other packages. For now you can ignore the
warnings.
13.5 select()
For the examples in this chapter we will be using a dataset containing air pollution and temperature
data for the city of Chicago in the U.S. The dataset is available from my web site.
After unzipping the archive, you can load the data into R using the readRDS() function.
You can see some basic characteristics of the dataset with the dim() and str() functions.
http://www.biostat.jhsph.edu/~rpeng/leanpub/rprog/chicago_data.zip
Managing Data Frames with the dplyr package 56
> dim(chicago)
[1] 6940 8
> str(chicago)
'data.frame': 6940 obs. of 8 variables:
$ city : chr "chic" "chic" "chic" "chic" ...
$ tmpd : num 31.5 33 33 29 32 40 34.5 29 26.5 32.5 ...
$ dptp : num 31.5 29.9 27.4 28.6 28.9 ...
$ date : Date, format: "1987-01-01" "1987-01-02" ...
$ pm25tmean2: num NA NA NA NA NA NA NA NA NA NA ...
$ pm10tmean2: num 34 NA 34.2 47 NA ...
$ o3tmean2 : num 4.25 3.3 3.33 4.38 4.75 ...
$ no2tmean2 : num 20 23.2 23.8 30.4 30.3 ...
The select() function can be used to select columns of a data frame that you want to focus on.
Often youll have a large data frame containing all of the data, but any given analysis might only
use a subset of variables or observations. The select() function allows you to get the few columns
you might need.
Suppose we wanted to take the first 3 columns only. There are a few ways to do this. We could for
example use numerical indices. But we can also use the names directly.
> names(chicago)[1:3]
[1] "city" "tmpd" "dptp"
> subset <- select(chicago, city:dptp)
> head(subset)
city tmpd dptp
1 chic 31.5 31.500
2 chic 33.0 29.875
3 chic 33.0 27.375
4 chic 29.0 28.625
5 chic 32.0 28.875
6 chic 40.0 35.125
Note that the : normally cannot be used with names or strings, but inside the select() function
you can use it to specify a range of variable names.
You can also omit variables using the select() function by using the negative sign. With select()
you can do
which indicates that we should include every variable except the variables city through dptp. The
equivalent code in base R would be
Managing Data Frames with the dplyr package 57
You can also use more general regular expressions if necessary. See the help page (?select) for more
details.
13.6 filter()
The filter() function is used to extract subsets of rows from a data frame. This function is similar
to the existing subset() function in R but is quite a bit faster in my experience.
Suppose we wanted to extract the rows of the chicago data frame where the levels of PM2.5 are
greater than 30 (which is a reasonably high level), we could do
Managing Data Frames with the dplyr package 58
You can see that there are now only 194 rows in the data frame and the distribution of the pm25tmean2
values is.
> summary(chic.f$pm25tmean2)
Min. 1st Qu. Median Mean 3rd Qu. Max.
30.05 32.12 35.04 36.63 39.53 61.50
We can place an arbitrarily complex logical sequence inside of filter(), so we could for example
extract the rows where PM2.5 is greater than 30 and temperature is greater than 80 degrees
Fahrenheit.
> chic.f <- filter(chicago, pm25tmean2 > 30 & tmpd > 80)
> select(chic.f, date, tmpd, pm25tmean2)
date tmpd pm25tmean2
1 1998-08-23 81 39.60000
2 1998-09-06 81 31.50000
3 2001-07-20 82 32.30000
4 2001-08-01 84 43.70000
5 2001-08-08 85 38.83750
6 2001-08-09 84 38.20000
7 2002-06-20 82 33.00000
8 2002-06-23 82 42.50000
9 2002-07-08 81 33.10000
10 2002-07-18 82 38.85000
11 2003-06-25 82 33.90000
12 2003-07-04 84 32.90000
13 2005-06-24 86 31.85714
14 2005-06-27 82 51.53750
15 2005-06-28 85 31.20000
16 2005-07-17 84 32.70000
17 2005-08-03 84 37.90000
Now there are only 17 observations where both of those conditions are met.
Managing Data Frames with the dplyr package 59
13.7 arrange()
The arrange() function is used to reorder rows of a data frame according to one of the variables/-
columns. Reordering rows of a data frame (while preserving corresponding order of other columns)
is normally a pain to do in R. The arrange() function simplifies the process quite a bit.
Here we can order the rows of the data frame by date, so that the first row is the earliest (oldest)
observation and the last row is the latest (most recent) observation.
Columns can be arranged in descending order too by useing the special desc() operator.
Looking at the first three and last three rows shows the dates in descending order.
Managing Data Frames with the dplyr package 60
13.8 rename()
Renaming a variable in a data frame in R is surprisingly hard to do! The rename() function is
designed to make this process easier.
Here you can see the names of the first five variables in the chicago data frame.
The dptp column is supposed to represent the dew point temperature adn the pm25tmean2 column
provides the PM2.5 data. However, these names are pretty obscure or awkward and probably be
renamed to something more sensible.
The syntax inside the rename() function is to have the new name on the left-hand side of the = sign
and the old name on the right-hand side.
I leave it as an exercise for the reader to figure how you do this in base R without dplyr.
Managing Data Frames with the dplyr package 61
13.9 mutate()
The mutate() function exists to compute transformations of variables in a data frame. Often, you
want to create new variables that are derived from existing variables and mutate() provides a clean
interface for doing that.
For example, with air pollution data, we often want to detrend the data by subtracting the mean
from the data. That way we can look at whether a given days air pollution level is higher than or
less than average (as opposed to looking at its absolute level).
Here we create a pm25detrend variable that subtracts the mean from the pm25 variable.
There is also the related transmute() function, which does the same thing as mutate() but then
drops all non-transformed variables.
Here we detrend the PM10 and ozone (O3) variables.
> head(transmute(chicago,
+ pm10detrend = pm10tmean2 - mean(pm10tmean2, na.rm = TRUE),
+ o3detrend = o3tmean2 - mean(o3tmean2, na.rm = TRUE)))
pm10detrend o3detrend
1 -10.395206 -16.904263
2 -14.695206 -16.401093
3 -10.395206 -12.640676
4 -6.395206 -16.175096
5 -6.895206 -14.966763
6 -25.395206 -5.393846
Note that there are only two columns in the transmuted data frame.
Managing Data Frames with the dplyr package 62
13.10 group_by()
The group_by() function is used to generate summary statistics from the data frame within strata
defined by a variable. For example, in this air pollution dataset, you might want to know what the
average annual level of PM2.5 is. So the stratum is the year, and that is something we can derive
from the date variable. In conjunction with the group_by() function we often use the summarize()
function (or summarise() for some parts of the world).
The general operation here is a combination of splitting a data frame into separate pieces defined by
a variable or group of variables (group_by()), and then applying a summary function across those
subsets (summarize()).
First, we can create a year varible using as.POSIXlt().
Now we can create a separate data frame that splits the original data frame by year.
Finally, we compute summary statistics for each year in the data frame with the summarize()
function.
summarize() returns a data frame with year as the first column, and then the annual averages of
pm25, o3, and no2.
In a slightly more complicated example, we might want to know what are the average levels of
ozone (o3) and nitrogen dioxide (no2) within quintiles of pm25. A slicker way to do this would be
through a regression model, but we can actually do this quickly with group_by() and summarize().
First, we can create a categorical variable of pm25 divided into quintiles.
Finally, we can compute the mean of o3 and no2 within quintiles of pm25.
From the table, it seems there isnt a strong relationship between pm25 and o3, but there appears to
be a positive correlation between pm25 and no2. More sophisticated statistical modeling can help to
provide precise answers to these questions, but a simple application of dplyr functions can often
get you most of the way there.
13.11 %>%
The pipeline operater %>% is very handy for stringing together multiple dplyr functions in a sequence
of operations. Notice above that every time we wanted to apply more than one function, the sequence
gets buried in a sequence of nested function calls that is difficult to read, i.e.
Managing Data Frames with the dplyr package 64
> third(second(first(x)))
This nesting is not a natural way to think about a sequence of operations. The %>% operator allows
you to string operations in a left-to-right fashion, i.e.
Take the example that we just did in the last section where we computed the mean of o3 and no2
within quintiles of pm25. There we had to
This way we dont have to create a set of temporary variables along the way or create a massive
nested sequence of function calls.
Notice in the above code that I pass the chicago data frame to the first call to mutate(), but then
afterwards I do not have to pass the first argument to group_by() or summarize(). Once you travel
down the pipeline with %>%, the first argument is taken to be the output of the previous element in
the pipeline.
Another example might be computing the average pollutant level by month. This could be useful to
see if there are any seasonal trends in the data.
Managing Data Frames with the dplyr package 65
Here we can see that o3 tends to be low in the winter months and high in the summer while no2 is
higher in the winter and lower in the summer.
13.12 Summary
The dplyr package provides a concise set of operations for managing data frames. With these
functions we can do a number of complex operations in just a few lines of code. In particular,
we can often conduct the beginnings of an exploratory analysis with the powerful combination of
group_by() and summarize().
Once you learn the dplyr grammar there are a few additional benefits
dplyr can work with other data frame backends such as SQL databases. There is an SQL
interface for relational databases via the DBI package
dplyr can be integrated with the data.table package for large fast tables
The dplyr package is handy way to both simplify and speed up your data frame management code.
Its rare that you get such a combination at the same time!
14. Control Structures
Watch a video of this section
Control structures in R allow you to control the flow of execution of a series of R expressions.
Basically, control structures allow you to put some logic into your R code, rather than just always
executing the same R code every time. Control structures allow you to respond to inputs or to features
of the data and execute different R expressions accordingly.
Commonly used control structures are
Most control structures are not used in interactive sessions, but rather when writing functions or
longer expresisons. However, these constructs do not have to be used in functions and its a good
idea to become familiar with them before we delve into functions.
14.1 if-else
Watch a video of this section
The if-else combination is probably the most commonly used control structure in R (or perhaps
any language). This structure allows you to test a condition and act on it depending on whether its
true or false.
For starters, you can just use the if statement.
https://youtu.be/BPNLjUDZ8_o
https://youtu.be/ZaBtJPYYGwg
Control Structures 67
if(<condition>) {
## do something
}
## Continue with rest of code
The above code does nothing if the condition is false. If you have an action you want to execute
when the condition is false, then you need an else clause.
if(<condition>) {
## do something
}
else {
## do something else
}
You can have a series of tests by following the initial if with any number of else ifs.
if(<condition1>) {
## do something
} else if(<condition2>) {
## do something different
} else {
## do something different
}
The value of y is set depending on whether x > 3 or not. This expression can also be written a
different, but equivalent, way in R.
Control Structures 68
Neither way of writing this expression is more correct than the other. Which one you use will depend
on your preference and perhaps those of the team you may be working with.
Of course, the else clause is not necessary. You could have a series of if clauses that always get
executed if their respective conditions are true.
if(<condition1>) {
if(<condition2>) {
https://youtu.be/FbT1dGXCCxU
Control Structures 69
This loop takes the i variable and in each iteration of the loop gives it values 1, 2, 3, , 10, executes
the code within the curly braces, and then the loop exits.
The following three loops all have the same behavior.
The seq_along() function is commonly used in conjunction with for loops in order to generate an
integer sequence based on the length of an object (in this case, the object x).
> for(letter in x) {
+ print(letter)
+ }
[1] "a"
[1] "b"
[1] "c"
[1] "d"
For one line loops, the curly braces are not strictly necessary.
Control Structures 70
However, I like to use curly braces even for one-line loops, because that way if you decide to expand
the loop to multiple lines, you wont be burned because you forgot to add curly braces (and you will
be burned by this).
x <- matrix(1:6, 2, 3)
for(i in seq_len(nrow(x))) {
for(j in seq_len(ncol(x))) {
print(x[i, j])
}
}
Nested loops are commonly needed for multidimensional or hierarchical data structures (e.g.
matrices, lists). Be careful with nesting though. Nesting beyond 2 to 3 levels often makes it difficult
to read/understand the code. If you find yourself in need of a large number of nested loops, you may
want to break up the loops by using functions (discussed later).
https://youtu.be/VqrS1Wghq1c
Control Structures 71
While loops can potentially result in infinite loops if not written properly. Use with care!
Sometimes there will be more than one condition in the test.
> z <- 5
> set.seed(1)
>
> while(z >= 3 && z <= 10) {
+ coin <- rbinom(1, 1, 0.5)
+
+ if(coin == 1) { ## random walk
+ z <- z + 1
+ } else {
+ z <- z - 1
+ }
+ }
> print(z)
[1] 2
Conditions are always evaluated from left to right. For example, in the above code, if z were less
than 3, the second test would not have been evaluated.
repeat initiates an infinite loop right from the start. These are not commonly used in statistical or
data analysis applications but they do have their uses. The only way to exit a repeat loop is to call
break.
One possible paradigm might be in an iterative algorith where you may be searching for a solution
and you dont want to stop until youre close enough to the solution. In this kind of situation, you
often dont know in advance how many iterations its going to take to get close enough to the
solution.
x0 <- 1
tol <- 1e-8
repeat {
x1 <- computeEstimate()
Note that the above code will not run if the computeEstimate() function is not defined (I just made
it up for the purposes of this demonstration).
The loop above is a bit dangerous because theres no guarantee it will stop. You could get in a
situation where the values of x0 and x1 oscillate back and forth and never converge. Better to set
a hard limit on the number of iterations by using a for loop and then report whether convergence
was achieved or not.
for(i in 1:100) {
if(i <= 20) {
## Skip the first 20 iterations
next
}
## Do something here
}
break is used to exit a loop immediately, regardless of what iteration the loop may be on.
Control Structures 73
for(i in 1:100) {
print(i)
14.7 Summary
Control structures like if, while, and for allow you to control the flow of an R program
Infinite loops should generally be avoided, even if (you believe) they are theoretically correct.
Control structures mentioned here are primarily useful for writing programs; for command-
line interactive work, the apply functions are more useful.
15. Functions
Writing functions is a core activity of an R programmer. It represents the key step of the transition
from a mere user to a developer who creates new functionality for R. Functions are often used
to encapsulate a sequence of expressions that need to be executed numerous times, perhaps under
slightly different conditions. Functions are also often written when code must be shared with others
or the public.
The writing of a function allows a developer to create an interface to the code, that is explicitly
specified with a set of parameters. This interface provides an abstraction of the code to potential
users. This abstraction simplifies the users lives because it relieves them from having to know every
detail of how the code operates. In addition, the creation of an interface allows the developer to
communicate to the user the aspects of the code that are important or are most relevant.
15.1 Functions in R
Functions in R are first class objects, which means that they can be treated much like any other R
object. Importantly,
Functions can be passed as arguments to other functions. This is very handy for the various
apply functions, like lapply() and sapply().
Functions can be nested, so that you can define a function inside of another function
If youre familiar with common language like C, these features might appear a bit strange. However,
they are really important in R and can be useful for data analysis.
Not very interesting, but its a start. The next thing we can do is create a function that actually has
a non-trivial function body.
The last aspect of a basic function is the function arguments. These are the options that you can
specify to the user that the user may explicity set. For this basic function, we can add an argument
that determines how many times Hello, world! is printed to the console.
Obviously, we could have just cut-and-pasted the cat("Hello, world!\n") code three times to
achieve the same effect, but then we wouldnt be programming, would we? Also, it would be un-
neighborly of you to give your code to someone else and force them to cut-and-paste the code
however many times the need to see Hello, world!.
In general, if you find yourself doing a lot of cutting and pasting, thats usually a good
sign that you might need to write a function.
Finally, the function above doesnt return anything. It just prints Hello, world! to the console num
number of times and then exits. But often it is useful if a function returns something that perhaps
can be fed into another section of code.
This next function returns the total number of characters printed to the console.
Functions 76
In the above function, we didnt have to indicate anything special in order for the function to return
the number of characters. In R, the return value of a function is always the very last expression that
is evaluated. Because the chars variable is the last expression that is evaluated in this function, that
becomes the return value of the function.
Note that there is a return() function that can be used to return an explicity value from a function,
but it is rarely used in R (we will discuss it a bit later in this chapter).
Finally, in the above function, the user must specify the value of the argument num. If it is not
specified by the user, R will throw an error.
> f()
Error in f(): argument "num" is missing, with no default
We can modify this behavior by setting a default value for the argument num. Any function argument
can have a default value, if you wish to specify it. Sometimes, argument values are rarely modified
(except in special cases) and it makes sense to set a default value for that argument. This relieves the
user from having to specify the value of that argument every single time the function is called.
Here, for example, we could set the default value for num to be 1, so that if the function is called
without the num argument being explicitly specified, then it will print Hello, world! to the console
once.
Functions 77
Remember that the function still returns the number of characters printed to the console.
At this point, we have written a function that
has one formal argument named num with a default value of 1. The formal arguments are the
arguments included in the function definition. The formals() function returns a list of all the
formal arguments of a function
prints the message Hello, world! to the console a number of times indicated by the argument
num
returns the number of characters printed to the console
Functions have named arguments which can optionally have default values. Because all function
arguments have names, they can be specified using their name.
> f(num = 2)
Hello, world!
Hello, world!
[1] 28
Specifying an argument by its name is sometimes useful if a function has many arguments and it may
not always be clear which argument is being specified. Here, our function only has one argument
so theres no confusion.
> str(rnorm)
function (n, mean = 0, sd = 1)
> mydata <- rnorm(100, 2, 1) ## Generate some data
100 is assigned to the n argument, 2 is assigned to the mean argument, and 1 is assigned to the sd
argument, all by positional matching.
The following calls to the sd() function (which computes the empirical standard deviation of a
vector of numbers) are all equivalent. Note that sd() has two arguments: x indicates the vector of
numbers and na.rm is a logical indicating whether missing values should be removed or not.
When specifying the function arguments by name, it doesnt matter in what order you specify them.
In the example below, we specify the na.rm argument first, followed by x, even though x is the first
argument defined in the function definition.
You can mix positional matching with matching by name. When an argument is matched by name,
it is taken out of the argument list and the remaining unnamed arguments are matched in the
order that they are listed in the function definition.
Here, the mydata object is assigned to the x argument, because its the only argument not yet
specified.
Below is the argument list for the lm() function, which fits linear models to a dataset.
Functions 79
> args(lm)
function (formula, data, subset, weights, na.action, method = "qr",
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE,
contrasts = NULL, offset, ...)
NULL
Even though its legal, I dont recommend messing around with the order of the arguments too
much, since it can lead to some confusion.
Most of the time, named arguments are useful on the command line when you have a long argument
list and you want to use the defaults for everything except for an argument near the end of the list.
Named arguments also help if you can remember the name of the argument and not its position
on the argument list. For example, plotting functions often have a lot of options to allow for
customization, but this makes it difficult to remember exactly the position of every argument on
the argument list.
Function arguments can also be partially matched, which is useful for interactive work. The order
of operations when given an argument is
Partial matching should be avoided when writing longer code or programs, because it may lead to
confusion if someone is reading the code. However, partial matching is very useful when calling
functions interactively that have very long argument names.
In addition to not specifying a default value, you can also set an argument value to NULL.
You can check to see whether an R object is NULL with the is.null() function. It is sometimes
useful to allow an argument to take the NULL value, which might indicate that the function should
take some specific action.
Functions 80
This function never actually uses the argument b, so calling f(2) will not produce an error because
the 2 gets positionally matched to a. This behavior can be good or bad. Its common to write a
function that doesnt use an argument and not notice it simply because R never throws an error.
This example also shows lazy evaluation at work, but does eventually result in an error.
Notice that 45 got printed first before the error was triggered. This is because b did not have to
be evaluated until after print(a). Once the function tried to evaluate print(b) the function had to
throw an error.
Generic functions use ... so that extra arguments can be passed to methods.
> mean
function (x, ...)
UseMethod("mean")
<bytecode: 0x7fac46cdbe38>
<environment: namespace:base>
The ... argument is necessary when the number of arguments passed to the function cannot be
known in advance. This is clear in functions like paste() and cat().
> args(paste)
function (..., sep = " ", collapse = NULL)
NULL
> args(cat)
function (..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE)
NULL
Because both paste() and cat() print out text to the console by combining multiple character
vectors together, it is impossible for those functions to know in advance how many character vectors
will be passed to the function by the user. So the first argument to either function is ....
> args(paste)
function (..., sep = " ", collapse = NULL)
NULL
With the paste() function, the arguments sep and collapse must be named explicitly and in full
if the default values are not going to be used.
Here I specify that I want a and b to be pasted together and separated by a colon.
Functions 82
If I dont specify the sep argument in full and attempt to rely on partial matching, I dont get the
expected result.
15.7 Summary
Functions can be defined using the function() directive and are assigned to R objects just
like any other R object
Functions have can be defined with named arguments; these function arguments can have
default values
Functions arguments can be specified by name or by position in the argument list
Functions always return the last expression evaluated in the function body
A variable number of arguments can be specified using the special ... argument in a function
definition.
16. Scoping Rules of R
16.1 A Diversion on Binding Values to Symbol
Watch a video of this section
How does R know which value to assign to which symbol? When I type
how does R know what value to assign to the symbol lm? Why doesnt it give it the value of lm that
is in the stats package?
When R tries to bind a value to a symbol, it searches through a series of environments to find the
appropriate value. When you are working on the command line and need to retrieve the value of an
R object, the order in which things occur is roughly
1. Search the global environment (i.e. your workspace) for a symbol name matching the one
requested.
2. Search the namespaces of each of the packages on the search list
> search()
[1] ".GlobalEnv" "package:knitr" "package:stats"
[4] "package:graphics" "package:grDevices" "package:utils"
[7] "package:datasets" "Autoloads" "package:base"
The global environment or the users workspace is always the first element of the search list and the
base package is always the last. For better or for worse, the order of the packages on the search list
matters, particularly if there are multiple objects with the same name in different packages.
Users can configure which packages get loaded on startup so if you are writing a function (or a
package), you cannot assume that there will be a set list of packages available in a given order.
When a user loads a package with library() the namespace of that package gets put in position 2
of the search list (by default) and everything else gets shifted down the list.
Note that R has separate namespaces for functions and non-functions so its possible to have an
object named c and a function named c().
https://youtu.be/ujdm01Vsrmo
Scoping Rules of R 84
This function has 2 formal arguments x and y. In the body of the function there is another symbol
z. In this case z is called a free variable.
The scoping rules of a language determine how values are assigned to free variables. Free variables
are not formal arguments and are not local variables (assigned insided the function body).
Lexical scoping in R means that
the values of free variables are searched for in the environment in which the function
was defined.
If the value of a symbol is not found in the environment in which a function was defined,
then the search is continued in the parent environment.
The search continues down the sequence of parent environments until we hit the top-level
environment; this usually the global environment (workspace) or the namespace of a package.
After the top-level environment, the search continues down the search list until we hit the
empty environment.
If a value for a given symbol cannot be found once the empty environment is arrived at, then an
error is thrown.
One implication of this search process is that it can be affected by the number of packages you have
attached to the search list. The more packages you have attached, the more symbols R has to sort
through in order to assign a value. That said, youd have to have a pretty large number of packages
attached in order to notice a real difference in performance.
The make.power() function is a kind of constructor function that can be used to construct other
functions.
https://youtu.be/yYzPhtF6--A
Scoping Rules of R 86
> cube
function(x) {
x^n
}
<environment: 0x7ff460527478>
Notice that cube() has a free variable n. What is the value of n here? Well, its value is taken from
the environment where the function was defined. When I defined the cube() function it was when
I called make.power(3), so the value of n at that time was 3.
We can explore the environment of a function to see what objects are there and their values.
> ls(environment(cube))
[1] "n" "pow"
> get("n", environment(cube))
[1] 3
> ls(environment(square))
[1] "n" "pow"
> get("n", environment(square))
[1] 2
> y <- 10
>
> f <- function(x) {
+ y <- 2
+ y^2 + g(x)
+ }
>
> g <- function(x) {
+ x*y
+ }
f(3)
With lexical scoping the value of y in the function g is looked up in the environment in which the
function was defined, in this case the global environment, so the value of y is 10. With dynamic
scoping, the value of y is looked up in the environment from which the function was called
(sometimes referred to as the calling environment). In R the calling environment is known as the
parent frame. In this case, the value of y would be 2.
When a function is defined in the global environment and is subsequently called from the global
environment, then the defining environment and the calling environment are the same. This can
sometimes give the appearance of dynamic scoping.
Consider this example.
Here, y is defined in the global environment, which also happens to be where the function g() is
defined.
There are numerous other languages that support lexical scoping, including
Scheme
Scoping Rules of R 88
Perl
Python
Common Lisp (all languages converge to Lisp, right?)
Lexical scoping in R has consequences beyond how free variables are looked up. In particular, its
the reason that all objects must be stored in memory in R. This is because all functions must carry
a pointer to their respective defining environments, which could be anywhere. In the S language
(Rs close cousin), free variables are always looked up in the global workspace, so everything can be
stored on the disk because the defining environment of all functions is the same.
https://youtu.be/GCNZrffYLFI
Scoping Rules of R 89
Note: Optimization functions in R minimize functions, so you need to use the negative log-
likelihood.
Now we can generate some data and then construct our negative log-likelihood.
> set.seed(1)
> normals <- rnorm(100, 1, 2)
> nLL <- make.NegLogLik(normals)
> nLL
function(p) {
params[!fixed] <- p
mu <- params[1]
sigma <- params[2]
Now that we have our nLL() function, we can try to minimize it with optim() to estimate the
parameters.
You can see that the algorithm converged and obtained an estimate of mu and sigma.
We can also try to estimate one parameter while holding another parameter fixed. Here we fix sigma
to be equal to 2.
Because we now have a one-dimensional problem, we can use the simpler optimize() function
rather than optim().
We can also try to estimate sigma while holding mu fixed at 1.
Scoping Rules of R 90
16.7 Summary
Objective functions can be built which contain all of the necessary data for evaluating the
function
No need to carry around long argument lists useful for interactive and exploratory work.
Code can be simplified and cleaned up
Reference: Robert Gentleman and Ross Ihaka (2000). Lexical Scope and Statistical Comput-
ing, JCGS, 9, 491508.
17. Coding Standards for R
Watch a video of this chapter
Coding standards are by no means universal and are often the subject of irrational flame wars on
various language- or project-specfiic mailing lists. Nevertheless, I will just give you the standards
that I use and the rationale behind them.
Always use text files / text editor. I think we can all agree on this one. Using text files and a text
editor is fundamental to coding. If youre writing your code in an editor like Microsoft Word, you
need to stop. Interactive development environments like RStudio have nice text editors built in, but
there are many others out there.
Indent your code. Indenting is very important for the readability of your code. Some programming
languages actually require it as part of their syntax, but R does not. Nevertheless, indenting is very
important. How much you should indent is up for debate, but I think each indent should be a
minimum of 4 spaces, and ideally it should be 8 spaces.
Limit the width of your code. I like to limit the width of my text editor so that the code I write
doesnt fly off into the wilderness on the right hand side. This limitation, along with the 8 space
indentation, forces you to write code that is clean, readable, and naturally broken down into modular
units. In particular, this combination limits your ability to write very long functions with many
different levels of nesting.
Limit the length of individual functions. If you are writing functions, its usually a good idea to
not let your functions run for pages and pages. Typically, purpose of a function is to execute one
activity or idea. If your function is doing lots of things, it probably needs to be broken into multiple
functions. My rule of thumb is that a function should not take up more than one page of your editor
(of course, this depends on the size of your monitor).
http://youtu.be/MSPKE1y3cyQ
18. Loop Functions
18.1 Looping on the Command Line
Writing for and while loops is useful when programming but not particularly easy when working
interactively on the command line. Multi-line expressions with curly braces are just not that easy to
sort through when working on the command line. R has some functions which implement looping
in a compact form to make your life easier.
18.2 lapply()
Watch a video of this section
The lapply() function does the following simple series of operations:
This function takes three arguments: (1) a list X; (2) a function (or the name of a function) FUN; (3)
other arguments via its ... argument. If X is not a list, it will be coerced to a list using as.list().
The body of the lapply() function can be seen here.
https://youtu.be/E1_NlFb0E4g
Loop Functions 96
> lapply
function (X, FUN, ...)
{
FUN <- match.fun(FUN)
if (!is.vector(X) || is.object(X))
X <- as.list(X)
.Internal(lapply(X, FUN))
}
<bytecode: 0x7fe63613fc00>
<environment: namespace:base>
Note that the actual looping is done internally in C code for efficiency reasons.
Its important to remember that lapply() always returns a list, regardless of the class of the input.
Heres an example of applying the mean() function to all elements of a list. If the original list has
names, the the names will be preserved in the output.
$b
[1] 0.1322028
Notice that here we are passing the mean() function as an argument to the lapply() function.
Functions in R can be used this way and can be passed back and forth as arguments just like any
other object. When you pass a function to another function, you do not need to include the open
and closed parentheses () like you do when you are calling a function.
Here is another example of using lapply().
$b
[1] 0.248845
$c
[1] 0.9935285
$d
[1] 5.051388
Loop Functions 97
You can use lapply() to evaluate a function multiple times each with a different argument. Below, is
an example where I call the runif() function (to generate uniformly distributed random variables)
four times, each time generating a different number of random numbers.
[[2]]
[1] 0.5273108 0.8803191
[[3]]
[1] 0.37306337 0.04795913 0.13862825
[[4]]
[1] 0.3214921 0.1548316 0.1322282 0.2213059
When you pass a function to lapply(), lapply() takes elements of the list and passes them as the
first argument of the function you are applying. In the above example, the first argument of runif()
is n, and so the elements of the sequence 1:4 all got passed to the n argument of runif().
Functions that you pass to lapply() may have other arguments. For example, the runif() function
has a min and max argument too. In the example above I used the default values for min and max.
How would you be able to specify different values for that in the context of lapply()?
Here is where the ... argument to lapply() comes into play. Any arguments that you place in the
... argument will get passed down to the function being applied to the elements of the list.
Here, the min = 0 and max = 10 arguments are passed down to runif() every time it gets called.
[[2]]
[1] 1.314165 9.815635
[[3]]
[1] 3.270137 5.069395 6.814425
[[4]]
[1] 0.9916910 1.1890256 0.5043966 9.2925392
Loop Functions 98
So now, instead of the random numbers being between 0 and 1 (the default), the are all between 0
and 10.
The lapply() function and its friends make heavy use of anonymous functions. Anonymous
functions are like members of Project Mayhemthey have no names. These are functions are
generated on the fly as you are using lapply(). Once the call to lapply() is finished, the function
disappears and does not appear in the workspace.
Here I am creating a list that contains two matrices.
$b
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
Suppose I wanted to extract the first column of each matrix in the list. I could write an anonymous
function for extracting the first column of each matrix.
$b
[1] 1 2 3
Notice that I put the function() definition right in the call to lapply(). This is perfectly legal and
acceptable. You can put an arbitrarily complicated function definition inside lapply(), but if its
going to be more complicated, its probably a better idea to define the function separately.
For example, I could have done the following.
http://en.wikipedia.org/wiki/Fight_Club
Loop Functions 99
$b
[1] 1 2 3
Now the function is no longer anonymous; its name is f. Whether you use an anonymous function
or you define a function first depends on your context. If you think the function f is something
youre going to need a lot in other parts of your code, you might want to define it separately. But if
youre just going to use it for this call to lapply(), then its probably simpler to use an anonymous
function.
18.3 sapply()
The sapply() function behaves similarly to lapply(); the only real difference is in the return value.
sapply() will try to simplify the result of lapply() if possible. Essentially, sapply() calls lapply()
on its input and then applies the following algorithm:
If the result is a list where every element is length 1, then a vector is returned
If the result is a list where every element is a vector of the same length (> 1), a matrix is
returned.
If it cant figure things out, a list is returned
$b
[1] -0.251483
$c
[1] 1.481246
$d
[1] 4.968715
Loop Functions 100
Notice that lapply() returns a list (as usual), but that each element of the list has length 1.
Heres the result of calling sapply() on the same list.
Because the result of lapply() was a list where each element had length 1, sapply() collapsed the
output into a numeric vector, which is often more useful than a list.
18.4 split()
Watch a video of this section
The split() function takes a vector or other objects and splits it into groups determined by a factor
or list of factors.
The arguments to split() are
> str(split)
function (x, f, drop = FALSE, ...)
where
The combination of split() and a function like lapply() or sapply() is a common paradigm in R.
The basic idea is that you can take a data structure, split it into subsets defined by another variable,
and apply a function over those subsets. The results of applying tha function over the subsets are
then collated and returned as an object. This sequence of operations is sometimes referred to as
map-reduce in other contexts.
Here we simulate some data and split it according to a factor variable. Note that we use the gl()
function to generate levels in a factor variable.
https://youtu.be/TjwE5b0fOcs
Loop Functions 101
$`2`
[1] 0.34822440 0.94893818 0.64667919 0.03527777 0.59644846 0.41531800
[7] 0.07689704 0.52804888 0.96233331 0.70874005
$`3`
[1] 1.13444766 1.76559900 1.95513668 0.94943430 0.69418458
[6] 1.89367370 -0.04729815 2.97133739 0.61636789 2.65414530
$`2`
[1] 0.5266905
$`3`
[1] 1.458703
We can split the airquality data frame by the Month variable so that we have separate sub-data
frames for each month.
Loop Functions 102
Then we can take the column means for Ozone, Solar.R, and Wind for each sub-data frame.
Loop Functions 103
$`6`
Ozone Solar.R Wind
NA 190.16667 10.26667
$`7`
Ozone Solar.R Wind
NA 216.483871 8.941935
$`8`
Ozone Solar.R Wind
NA NA 8.793548
$`9`
Ozone Solar.R Wind
NA 167.4333 10.1800
Unfortunately, there are NAs in the data so we cannot simply take the means of those variables.
However, we can tell the colMeans function to remove the NAs before computing the mean.
Loop Functions 104
Occasionally, we may want to split an R object according to levels defined in more than one variable.
We can do this by creating an interaction of the variables with the interaction() function.
With multiple factors and many levels, creating an interaction can result in many levels that are
empty.
Notice that there are 4 categories with no data. But we can drop empty levels when we call the
split() function.
Loop Functions 105
18.6 tapply
Watch a video of this section
tapply() is used to apply a function over subsets of a vector. It can be thought of as a combination
of split() and sapply() for vectors only. Ive been told that the t in tapply() refers to table,
but that is unconfirmed.
> str(tapply)
function (X, INDEX, FUN = NULL, ..., simplify = TRUE)
X is a vector
INDEX is a factor or a list of factors (or else they are coerced to factors)
FUN is a function to be applied
contains other arguments to be passed FUN
simplify, should we simplify the result?
We can also take the group means without simplifying the result, which will give us a list. For
functions that return a single value, usually, this is not what we want, but it can be done.
https://youtu.be/6YEPWjbk3GA
Loop Functions 106
$`2`
[1] 0.5336667
$`3`
[1] 0.9568236
We can also apply functions that return more than a single value. In this case, tapply() will not
simplify the result and will return a list. Heres an example of finding the range of each sub-group.
$`2`
[1] 0.09515213 0.86723879
$`3`
[1] -0.5690822 2.3644349
18.7 apply()
Watch a video of this section
The apply() function is used to a evaluate a function (often an anonymous one) over the margins
of an array. It is most often used to apply a function to the rows or columns of a matrix (which is
just a 2-dimensional array). However, it can be used with general arrays, for example, to take the
average of an array of matrices. Using apply() is not really faster than writing a loop, but it works
in one line and is highly compact.
> str(apply)
function (X, MARGIN, FUN, ...)
X is an array
MARGIN is an integer vector indicating which margins should be retained.
FUN is a function to be applied
... is for other arguments to be passed to FUN
Here I create a 20 by 10 matrix of Normal random numbers. I then compute the mean of each column.
https://youtu.be/F54ixFPq_xQ
Loop Functions 107
Note that in both calls to apply(), the return value was a vector of numbers.
Youve probably noticed that the second argument is either a 1 or a 2, depending on whether we
want row statistics or column statistics. What exactly is the second argument to apply()?
The MARGIN argument essentially indicates to apply() which dimension of the array you want to
preserve or retain. So when taking the mean of each column, I specify
because I want to collapse the first dimension (the rows) by taking the mean and I want to preserve
the number of columns. Similarly, when I want the row sums, I run
because I want to collapse the columns (the second dimension) and preserve the number of rows
(the first dimension).
The shortcut functions are heavily optimized and hence are much faster, but you probably wont
notice unless youre using a large matrix. Another nice aspect of these functions is that they are a
bit more descriptive. Its arguably more clear to write colMeans(x) in your code than apply(x, 2,
mean).
Loop Functions 108
Notice that I had to pass the probs = c(0.25, 0.75) argument to quantile() via the ... argument
to apply().
For a higher dimensional example, I can create an array of 2 2 matrices and the compute the
average of the matrices in the array.
In the call to apply() here, I indicated via the MARGIN argument that I wanted to preserve the first
and second dimensions and to collapse the third dimension by taking the mean.
There is a faster way to do this specific operation via the colMeans() function.
In this situation, I might argue that the use of rowMeans() is less readable, but it is substantially
faster with large arrays.
Loop Functions 109
18.10 mapply()
Watch a video of this section
The mapply() function is a multivariate apply of sorts which applies a function in parallel over a
set of arguments. Recall that lapply() and friends only iterate over a single R object. What if you
want to iterate over multiple R objects in parallel? This is what mapply() is for.
> str(mapply)
function (FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
The mapply() function has a different argument order from lapply() because the function to apply
comes first rather than the object to iterate over. The R objects over which we apply the function
are given in the ... argument because we can apply over an arbitrary number of R objects.
For example, the following is tedious to type
list(rep(1, 4), rep(2, 3), rep(3, 2), rep(4, 1))
With mapply(), instead we can do
[[2]]
[1] 2 2 2
[[3]]
[1] 3 3
[[4]]
[1] 4
This passes the sequence 1:4 to the first argument of rep() and the sequence 4:1 to the second
argument.
Heres another example for simulating randon Normal variables.
https://youtu.be/z8jC_h7S0VE
Loop Functions 110
Here we can use mapply() to pass the sequence 1:5 separately to the noise() function so that we
can get 5 sets of random numbers, each with a different length and mean.
[[2]]
[1] 4.764568 2.336980
[[3]]
[1] 4.6463819 2.5582108 0.9412167
[[4]]
[1] 3.978149 1.550018 -1.192223 6.338245
[[5]]
[1] 2.826182 1.347834 6.990564 4.976276 3.800743
[[2]]
[1] 1.148037 3.993318
[[3]]
[1] 4.4553214 -0.4532612 3.7067970
Loop Functions 111
[[4]]
[1] 5.4536273 5.3365220 -0.8486346 3.5292851
[[5]]
[1] 8.959267 6.593589 1.581448 1.672663 5.982219
This function takes a mean mu, a standard deviation sigma, and some data in a vector x.
In many statistical applications, we want to minimize the sum of squares to find the optimal mu and
sigma. Before we do that, we may want to evaluate or plot the function for many different values
of mu or sigma. However, passing a vector of mus or sigmas wont work with this function because
its not vectorized.
Note that the call to sumsq() only produced one value instead of 10 values.
However, we can do what we want to do by using mapply().
Theres even a function in R called Vectorize() that automatically can create a vectorized version
of your function. So we could create a vsumsq() function that is fully vectorized as follows.
Loop Functions 112
18.12 Summary
The loop functions in R are very powerful because they allow you to conduct a series of
operations on data using a compact form
The operation of a loop function involves iterating over an R object (e.g. a list or vector or
matrix), applying a function to each element of the object, and the collating the results and
returning the collated results.
Loop functions make heavy use of anonymous functions, which exist for the life of the loop
function but are not stored anywhere
The split() function can be used to divide an R object in to subsets determined by another
variable which can subsequently be looped over using loop functions.
19. Regular Expressions
Watch a video of this chapter
For this chapter, we will use a running example using data from homicides in Baltimore City. The
Baltimore Sun newspaper collects information on all homicides that occur in the city (it also reports
on many of them). That data is collected and presented in a map that is publically available. I
encourage you to go look at the web site/map to get a sense of what kinds of data are presented
there. Unfortunately, the data on the web site are not particularly amenable to analysis, so Ive
scraped the data and put it in a separate file. The data in this file contain data from January 2007 to
October 2013.
Here is an excerpt of the Baltimore City homicides dataset:
https://www.youtube.com/watch?v=q8SzNKib5-4
https://www.youtube.com/watch?v=NvHjYOilOf8
http://data.baltimoresun.com/bing-maps/homicides/
Regular Expressions 114
The data set is formatted so that each homicide is presented on a single line of text. So when we
read the data in with readLines(), each element of the character vector represents one homicide
event. Notice that the data are riddled with HTML tags because they were scraped directly from the
web site.
A few interesting features stand out: We have the latitude and longitude of where the victim was
found; then theres the street address; the age, race, and gender of the victim; the date on which the
victim was found; in which hospital the victim ultimately died; the cause of death.
19.3 grep()
Suppose we wanted to identify the records for all the victims of shootings (as opposed to other
causes)? How could we do that? From the map we know that for each cause of death there is a
different icon/flag placed on the map. In particular, they are different colors. You can see that is
indicated in the dataset for shooting deaths with a iconHomicideShooting label. Perhaps we can
use this aspect of the data to idenfity all of the shootings.
Here I use grep() to match the literal iconHomicideShooting into the character vector of homicides.
Using this approach I get 228 shooting deaths. However, I notice that for some of the entries, the
indicator for the homicide flag is noted as icon_homicide_shooting. Its not uncommon over time
Regular Expressions 115
for web site maintainers to change the names of files or update files. What happens if we now grep()
on both icon names using the | operator?
Now we have 1263 shooting deaths, which is quite a bit more. In fact, the vast majority of homicides
in Baltimore are shooting deaths.
Another possible way to do this is to grep() on the cause of death field, which seems to have the
format Cause: shooting. We can grep() on this literally and get
Notice that we seem to be undercounting again. This is because for some of the entries, the word
shooting uses a captial S while other entries use a lower case s. We can handle this variation
by using a character class in our regular expression.
One thing you have to be careful of when processing text data is not not grep() things out of context.
For example, suppose we just grep()-ed on the expression [Ss]hooting.
Notice that we see to pick up 2 extra homicides this way. We can figure out which ones they are by
comparing the results of the two expressions.
First we can get the indices for the first expresssion match.
Now we just need to identify which are the entries that the vectors i and j do not have in common.
> setdiff(i, j)
integer(0)
> setdiff(j, i)
[1] 318 859
Here we can see that the index vector j has two entries that are not in i: entries 318, 859. We can
take a look at these entries directly to see what makes them different.
> homicides[859]
[1] "39.33743900000, -76.66316500000, icon_homicide_bluntforce, 'p914', '<dl><dt><a href=\\
"http://essentials.baltimoresun.com/micro_sun/homicides/victim/914/steven-harris\">Steven \
Harris</a></dt><dd class=\"address\">4200 Pimlico Road<br />Baltimore, MD 21215</dd><dd>Ra\
ce: Black<br />Gender: male<br />Age: 38 years old</dd><dd>Found on July 29, 2010</dd><dd>\
Victim died at Scene</dd><dd>Cause: Blunt Force</dd><dd class=\"popup-note\"><p>Harris was\
found dead July 22 and ruled a shooting victim; an autopsy subsequently showed that he ha\
d not been shot,...</dd></dl>'"
Here we can see that the word shooting appears in the narrative text that accompanies the data,
but the ultimate cause of death was in fact blunt force.
When developing a regular expression to extract entries from a large dataset, its important that you
understand the formatting of the dataset well enough so that you can develop a specific expression
that doesnt accidentally grep data out of context.
Sometimes we want to identify elements of a character vector that match a pattern, but instead of
returning their indices we want the actual values that satisfy the match. For example, we may want
to identify all of the states in the United States whose names start with New.
This gives us the indices into the state.name variable that match, but setting value = TRUE returns
the actual elements of the character vector that match.
Regular Expressions 117
19.4 grepl()
The function grepl() works much like grep() except that it differs in its return value. grepl()
returns a logical vector indicating which element of a character vector contains the match. For
example, suppose we want to know which states in the United States begin with word New.
Here, we can see that grepl() returns a logical vector that can be used to subset the original
state.name vector.
19.5 regexpr()
Both the grep() and the grepl() functions have some limitations. In particular, both functions tell
you which strings in a character vector match a certain pattern but they dont tell you exactly where
the match occurs or what the match is for a more complicated regular expression.
The regexpr() function gives you the (a) index into each string where the match begins and the (b)
length of the match for that string. regexpr() only gives you the first match of the string (reading
left to right). gregexpr() will give you all of the matches in a given string if there are is more than
one match.
In our Baltimore City homicides dataset, we might be interested in finding the date on which each
victim was found. Taking a look at the dataset
Regular Expressions 118
> homicides[1]
[1] "39.311024, -76.674227, iconHomicideShooting, 'p2', '<dl><dt>Leon Nelson</dt><dd class\
=\"address\">3400 Clifton Ave.<br />Baltimore, MD 21216</dd><dd>black male, 17 years old</\
dd><dd>Found on January 1, 2007</dd><dd>Victim died at Shock Trauma</dd><dd>Cause: shootin\
g</dd></dl>'"
it seems that we might be able to just grep on the word Found. However, the word found may be
found elsewhere in the entry, such as in this entry, where the word found appears in the narrative
text at the end.
> homicides[954]
[1] "39.30677400000, -76.59891100000, icon_homicide_shooting, 'p816', '<dl><dt><a href=\"h\
ttp://essentials.baltimoresun.com/micro_sun/homicides/victim/816/kenly-wheeler\">Kenly Whe\
eler</a></dt><dd class=\"address\">1400 N Caroline St<br />Baltimore, MD 21213</dd><dd>Rac\
e: Black<br />Gender: male<br />Age: 29 years old</dd><dd>Found on March 3, 2010</dd><dd>\
Victim died at Scene</dd><dd>Cause: Shooting</dd><dd class=\"popup-note\"><p>Wheeler\\'s b\
ody was found on the grounds of Dr. Bernard Harris Sr. Elementary School</p></dd\
></dl>'"
But we can see that the date is typically preceded by Found on and is surrounded by <dd></dd>
tags, so lets use the pattern <dd>[F|f]ound(.*)</dd> and see what it brings up.
We can use the substr() function to extract the first match in the first string.
Immediately, we can see that the regular expression picked up too much information. This is because
the previous pattern was too greedy and matched too much of the string. We need to use the ?
metacharacter to make the regular expression lazy so that it stops at the first </dd> tag.
Regular Expressions 119
Now when we look at the substrings indicated by the regexpr() output, we get
While its straightforward to take the output of regexpr() and feed it into substr() to get the
matches out of the original data, one handy function is regmatches() which extracts the matches
in the strings for you without you having to use substr().
We want to strip out the stuff surrounding the January 1, 2007 portion. We can do that by matching
on the text that comes before and after it using the | operator and then replacing it with the empty
string.
Notice that the sub() function found the first match (at the beginning of the string) and replaced it
and then stopped. However, there was another match at the end of the string that we also wanted
to replace. To get both matches, we need the gsub() function.
Regular Expressions 120
The sub() and gsub() functions can take vector arguments so we dont have to process each string
one by one.
Finally, it may be useful to convert these strings to the Date class so that we can do some date-related
computations.
19.7 regexec()
The regexec() function works like regexpr() except it gives you the indices for parenthesized sub-
expressions. For example, take a look at the following expression.
Notice first that the regular expression itself has a portion in parentheses (). That is the portion of the
expression that I presume will contain the date. In the output, youll notice that there are two indices
and two match.length values. The first index tells you where the overall match begins (character
177) and the second index tells you where the expression in the parentheses begins (character 190).
By contrast, if we only use the regexpr() function, we get
Regular Expressions 121
We can use the substr() function to demonstrate which parts of a strings are matched by the
regexec() function.
Heres the output for regexec().
All this can be done much more easily with the regmatches() function.
[[2]]
[1] "<dd>Found on January 2, 2007</dd>" "January 2, 2007"
Notice that regmatches() returns a list in this case, where each element of the list contains two
strings: the overall match and the parenthesized sub-expression.
As an example, we can make a plot of monthly homicide counts. First we need a regular expression
to capture the dates.
Regular Expressions 122
Then we can loop through the list returned by regmatches() and extract the second element of each
(the parenthesized sub-expression).
Finally, we can convert the date strings into the Date class and make a histogram of the counts.
We can see from the picture that homicides do not occur uniformly throughout the year and appear
to have some seasonality to them.
19.8 Summary
The primary R functions for dealing with regular expressions are
regexpr(), gregexpr(): Search a character vector for regular expression matches and
return the indices where the match begins; useful in conjunction with regmatches()
sub(), gsub(): Search a character vector for regular expression matches and replace that
match with another string
regexec(): Gives you indices of parethensized sub-expressions.
20. Debugging
20.1 Somethings Wrong!
Watch a video of this section (note that this video differs slightly from the material presented here)
R has a number of ways to indicate to you that somethings not right. There are different levels of
indication that can be used, ranging from mere notification to fatal error. Executing any function in
R may result in the following conditions.
Here is an example of a warning that you might receive in the course of using R.
> log(-1)
Warning in log(-1): NaNs produced
[1] NaN
This warning lets you know that taking the log of a negative number results in a NaN value because
you cant take the log of negative numbers. Nevertheless, R doesnt give an error, because it has a
useful value that it can return, the NaN value. The warning is just there to let you know that something
unexpected happen. Depending on what you are programming, you may have intentionally taken
the log of a negative number in order to move on to another section of code.
Here is another function that is designed to print a message to the console depending on the nature
of its input.
https://youtu.be/LHQxbRInyyc
Debugging 126
This function is simpleit prints a message telling you whether x is greater than zero or less than or
equal to zero. It also returns its input invisibly, which is a common practice with print functions.
Returning an object invisibly means that the return value does not get auto-printed when the
function is called.
Take a hard look at the function above and see if you can identify any bugs or problems.
We can execute the function as follows.
> printmessage(1)
[1] "x is greater than zero"
The function seems to work fine at this point. No errors, warnings, or messages.
> printmessage(NA)
Error in if (x > 0) print("x is greater than zero") else print("x is less than or equal to\
zero"): missing value where TRUE/FALSE needed
What happened?
Well, the first thing the function does is test if x > 0. But you cant do that test if x is a NA or NaN
value. R doesnt know what to do in this case so it stops with a fatal error.
We can fix this problem by anticipating the possibility of NA values and checking to see if the input
is NA with the is.na() function.
> printmessage2(NA)
[1] "x is a missing value!"
Now what?? Why are we getting this warning? The warning says the condition has length > 1 and
only the first element will be used.
The problem here is that I passed printmessage2() a vector x that was of length 2 rather then length
1. Inside the body of printmessage2() the expression is.na(x) returns a vector that is tested in the
if statement. However, if cannot take vector arguments so you get a warning. The fundamental
problem here is that printmessage2() is not vectorized.
We can solve this problem two ways. One is by simply not allowing vector arguments. The other
way is to vectorize the printmessage2() function to allow it to take vector arguments.
For the first way, we simply need to check the length of the input.
> printmessage3(1:2)
Error in printmessage3(1:2): 'x' has length > 1
Vectorizing the function can be accomplished easily with the Vectorize() function.
You can see now that the correct messages are printed without any warning or error. Note that I
stored the return value of printmessage4() in a separate R object called out. This is because when
I use the Vectorize() function it no longer preserves the invisibility of the return value.
What was your input? How did you call the function?
What were you expecting? Output, messages, other results?
What did you get?
How does what you get differ from what you were expecting?
Were your expectations correct in the first place?
Can you reproduce the problem (exactly)?
Being able to answer these questions is important not just for your own sake, but in situations where
you may need to ask someone else for help with debugging the problem. Seasoned programmers will
be asking you these exact questions.
traceback(): prints out the function call stack after an error occurs; does nothing if theres
no error
debug(): flags a function for debug mode which allows you to step through execution of a
function one line at a time
browser(): suspends the execution of a function wherever it is called and puts the function in
debug mode
trace(): allows you to insert debugging code into a function a specific places
recover(): allows you to modify the error behavior so that you can browse the function call
stack
These functions are interactive tools specifically designed to allow you to pick through a function.
Theres also the more blunt technique of inserting print() or cat() statements in the function.
> mean(x)
Error in mean(x) : object 'x' not found
> traceback()
1: mean(x)
Here, its clear that the error occurred inside the mean() function because the object x does not exist.
The traceback() function must be called immediately after an error occurs. Once another function
is called, you lose the traceback.
Here is a slightly more complicated example using the lm() function for linear modeling.
https://youtu.be/VT9ZxCp6o-I
Debugging 130
> lm(y ~ x)
Error in eval(expr, envir, enclos) : object y not found
> traceback()
7: eval(expr, envir, enclos)
6: eval(predvars, data, env)
5: model.frame.default(formula = y ~ x, drop.unused.levels = TRUE)
4: model.frame(formula = y ~ x, drop.unused.levels = TRUE)
3: eval(expr, envir, enclos)
2: eval(mf, parent.frame())
1: lm(y ~ x)
You can see now that the error did not get thrown until the 7th level of the function call stack, in
which case the eval() function tried to evaluate the formula y x and realized the object y did
not exist.
Looking at the traceback is useful for figuring out roughly where an error occurred but its not useful
for more detailed debugging. For that you might turn to the debug() function.
Now, every time you call the lm() function it will launch the interactive debugger. To turn this
behavior off you need to call the undebug() function.
The debugger calls the browser at the very top level of the function body. From there you can step
through each expression in the body. There are a few special commands you can call in the browser:
Debugging 131
While you are in the browser you can execute any other R function that might be available to you
in a regular session. In particular, you can use ls() to see what is in your current environment (the
function environment) and print() to print out the values of R objects in the function environment.
You can turn off interactive debugging with the undebug() function.
1: read.csv("nosuchfile")
2: read.table(file = file, header = header, sep = sep, quote = quote, dec =
3: file(file, "rt")
Selection:
The recover() function will first print out the function call stack when an error occurrs. Then, you
can choose to jump around the call stack and investigate the problem. When you choose a frame
number, you will be put in the browser (just like the interactive debugger triggered with debug())
and will have the ability to poke around.
20.7 Summary
There are three main indications of a problem/condition: message, warning, error; only an
error is fatal
When analyzing a function with a problem, make sure you can reproduce the problem, clearly
state your expectations and how the output differs from your expectation
Interactive debugging tools traceback, debug, browser, trace, and recover can be used to
find problematic code in functions
Debugging tools are not a substitute for thinking!
21. Profiling R Code
Lets solve the problem but lets not make it worse by guessing. Gene Kranz, Apollo
13 Lead Flight Director
We should forget about small efficiencies, say about 97% of the time: premature
optimization is the root of all evil Donald Knuth
Usually, the user time and elapsed time are relatively close, for straight computing tasks. But there
are a few situations where the two can diverge, sometimes dramatically. The elapsed time may be
greater than the user time if the CPU spends a lot of time waiting around. This commonly happens
if your R expression involes some input or output, which depends on the activity of the file system
and the disk (or the Internet, if using a network connection).
The elapsed time may be smaller than the user time if your machine has multiple cores/processors
(and is capable of using them). For example, multi-threaded BLAS libraries (vecLib/Accelerate,
ATLAS, ACML, MKL) can greatly speed up linear algebra calculations and are commonly installed
on even desktop systems these days. Also, parallel processing done via something like the parallell
package can make the elapsed time smaller than the user time. When you have multiple processors/-
cores/machines working in parallel, the amount of time that the collection of CPUs spends working
on a problem is the same as with a single CPU, but because they are operating in parallel, there is a
savings in elapsed time.
Heres an example of where the elapsed time is greater than the user time.
Most of the time in this expression is spent waiting for the connection to the web server and waiting
for the data to travel back to my computer. This doesnt involve the CPU and so the CPU simply
waits around for things to get done. Hence, the user time is small.
In this example, the elapsed time is smaller than the user time.
Profiling R Code 135
In this case I ran a singular value decomposition on the matrix in x, which is a common linear
algebra procedure. Because my computer is able to split the work across multiple processors, the
elapsed time is about half the user time.
> system.time({
+ n <- 1000
+ r <- numeric(n)
+ for(i in 1:n) {
+ x <- rnorm(n)
+ r[i] <- mean(x)
+ }
+ })
user system elapsed
0.105 0.002 0.116
If your expression is getting pretty long (more than 2 or 3 lines), it might be better to either break it
into smaller pieces or to use the profiler. The problem is that if the expression is too long, you wont
be able to identify which part of the code is causing the bottleneck.
This is where the profiler comes in handy. The Rprof() function starts the profiler in R. Note that R
must be compiled with profiler support (but this is usually the case). In conjunction with Rprof(),
we will use the summaryRprof() function which summarizes the output from Rprof() (otherwise
its not really readable). Note that you should NOT use system.time() and Rprof() together, or you
will be sad.
Rprof() keeps track of the function call stack at regularly sampled intervals and tabulates how much
time is spent inside each function. By default, the profiler samples the function call stack every 0.02
seconds. This means that if your code runs very quickly (say, under 0.02 seconds), the profiler is not
useful. But of your code runs that fast, you probably dont need the profiler.
The profiler is started by calling the Rprof() function.
You dont need any other arguments. By default it will write its output to a file called Rprof.out.
You can specify the name of the output file if you dont want to use this default.
Once you call the Rprof() function, everything that you do from then on will be measured by the
profiler. Therefore, you usually only want to run a single R function or expression once you turn on
the profiler and then immediately turn it off. The reason is that if you mix too many function calls
together when running the profiler, all of the results will be mixed together and you wont be able
to sort out where the bottlenecks are. In reality, I usually only run a single function with the profiler
on.
The profiler can be turned off by passing NULL to Rprof().
The raw output from the profiler looks something like this. Here Im calling the lm() function on
some data with the profiler running.
## lm(y ~ x)
sample.interval=10000
"list" "eval" "eval" "model.frame.default" "model.frame" "eval" "eval" "lm"
"list" "eval" "eval" "model.frame.default" "model.frame" "eval" "eval" "lm"
"list" "eval" "eval" "model.frame.default" "model.frame" "eval" "eval" "lm"
"list" "eval" "eval" "model.frame.default" "model.frame" "eval" "eval" "lm"
"na.omit" "model.frame.default" "model.frame" "eval" "eval" "lm"
"na.omit" "model.frame.default" "model.frame" "eval" "eval" "lm"
"na.omit" "model.frame.default" "model.frame" "eval" "eval" "lm"
"na.omit" "model.frame.default" "model.frame" "eval" "eval" "lm"
"na.omit" "model.frame.default" "model.frame" "eval" "eval" "lm"
"na.omit" "model.frame.default" "model.frame" "eval" "eval" "lm"
Profiling R Code 137
At each line of the output, the profiler writes out the function call stack. For example, on the very
first line of the output you can see that the code is 8 levels deep in the call stack. This is where you
need the summaryRprof() function to help you interpret this data.
by.total divides the time spend in each function by the total run time
by.self does the same as by.total but first subtracts out time spent in functions above the
current function in the call stack. I personally find this output to be much more useful.
$by.total
total.time total.pct self.time self.pct
"lm" 7.41 100.00 0.30 4.05
"lm.fit" 3.50 47.23 2.99 40.35
"model.frame.default" 2.24 30.23 0.12 1.62
"eval" 2.24 30.23 0.00 0.00
"model.frame" 2.24 30.23 0.00 0.00
"na.omit" 1.54 20.78 0.24 3.24
"na.omit.data.frame" 1.30 17.54 0.49 6.61
"lapply" 1.04 14.04 0.00 0.00
"[.data.frame" 1.03 13.90 0.79 10.66
"[" 1.03 13.90 0.00 0.00
"as.list.data.frame" 0.82 11.07 0.82 11.07
"as.list" 0.82 11.07 0.00 0.00
Because lm() is the function that I called from the command line, of course 100% of the time is
spent somewhere in that function. However, what this doesnt show is that if lm() immediately
calls another function (like lm.fit(), which does most of the heavy lifting), then in reality, most of
the time is spent in that function, rather than in the top-level lm() function.
The by.self output corrects for this discrepancy.
Profiling R Code 138
$by.self
self.time self.pct total.time total.pct
"lm.fit" 2.99 40.35 3.50 47.23
"as.list.data.frame" 0.82 11.07 0.82 11.07
"[.data.frame" 0.79 10.66 1.03 13.90
"structure" 0.73 9.85 0.73 9.85
"na.omit.data.frame" 0.49 6.61 1.30 17.54
"list" 0.46 6.21 0.46 6.21
"lm" 0.30 4.05 7.41 100.00
"model.matrix.default" 0.27 3.64 0.79 10.66
"na.omit" 0.24 3.24 1.54 20.78
"as.character" 0.18 2.43 0.18 2.43
"model.frame.default" 0.12 1.62 2.24 30.23
"anyDuplicated.default" 0.02 0.27 0.02 0.27
Now you can see that only about 4% of the runtime is spent in the actual lm() function, whereas
over 40% of the time is spent in lm.fit(). In this case, this is no surprise since the lm.fit() function
is the function that actually fits the linear model.
You can see that a reasonable amount of time is spent in functions not necessarily associated with
linear modeling (i.e. as.list.data.frame, [.data.frame). This is because the lm() function does a
bit of pre-processing and checking before it actually fits the model. This is common with modeling
functionsthe preprocessing and checking is useful to see if there are any errors. But those two
functions take up over 1.5 seconds of runtime. What if you want to fit this model 10,000 times?
Youre going to be spending a lot of time in preprocessing and checking.
The final bit of output that summaryRprof() provides is the sampling interval and the total runtime.
$sample.interval
[1] 0.02
$sampling.time
[1] 7.41
21.5 Summary
Rprof() runs the profiler for performance of analysis of R code
summaryRprof() summarizes the output of Rprof() and gives percent of time spent in each
function (with two types of normalization)
Good to break your code into functions so that the profiler can give useful information about
where time is being spent
C or Fortran code is not profiled
22. Simulation
22.1 Generating Random Numbers
Watch a video of this section
Simulation is an important (and big) topic for both statistics and for a variety of other areas
where there is a need to introduce randomness. Sometimes you want to implement a statistical
procedure that requires random number generation or sampling (i.e. Markov chain Monte Carlo,
the bootstrap, random forests, bagging) and sometimes you want to simulate a system and random
number generators can be used to model random inputs.
R comes with a set of pseuodo-random number generators that allow you to simulate from well-
known probability distributions like the Normal, Poisson, and binomial. Some example functions
for probability distributions in R
rnorm: generate random Normal variates with a given mean and standard deviation
dnorm: evaluate the Normal probability density (with a given mean/SD) at a point (or vector
of points)
pnorm: evaluate the cumulative distribution function for a Normal distribution
rpois: generate random Poisson variates with a given rate
For each probability distribution there are typically four functions available that start with a r,
d, p, and q. The r function is the one that actually simulates randon numbers from that
distribution. The other functions are prefixed with a
d for density
r for random number generation
p for cumulative distribution
q for quantile function (inverse cumulative distribution)
If youre only interested in simulating random numbers, then you will likely only need the
r functions and not the others. However, if you intend to simulate from arbitrary probability
distributions using something like rejection sampling, then you will need the other functions too.
Probably the most common probability distribution to work with the is the Normal distribution (also
known as the Gaussian). Working with the Normal distributions requires using these four functions
https://youtu.be/tzz4flrajr0
Simulation 140
Here we simulate standard Normal random numbers with mean 0 and standard deviation 1.
We can modify the default parameters to simulate numbers with mean 20 and standard deviation 2.
If you wanted to know what was the probability of a random Normal variable of being less than,
say, 2, you could use the pnorm() function to do that calculation.
> pnorm(2)
[1] 0.9772499
> set.seed(1)
> rnorm(5)
[1] -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078
Note that if I call rnorm() again I will of course get a different set of 5 random numbers.
> rnorm(5)
[1] -0.8204684 0.4874291 0.7383247 0.5757814 -0.3053884
If I want to reproduce the original set of random numbers, I can just reset the seed with set.seed().
> set.seed(1)
> rnorm(5) ## Same as before
[1] -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078
In general, you should always set the random number seed when conducting a simulation!
Otherwise, you will not be able to reconstruct the exact numbers that you produced in an analysis.
It is possible to generate random numbers from other probability distributions like the Poisson. The
Poisson distribution is commonly used to model data that come in the form of counts.
y = 0 + 1 x +
where N (0, 22 ). Assume x N (0, 12 ), 0 = 0.5 and 1 = 2. The variable x might represent
an important predictor of the outcome y. Heres how we could do that in R.
https://youtu.be/p7kSSSsv4ms
Simulation 142
> plot(x, y)
Simulation 143
What if we wanted to simulate a predictor variable x that is binary instead of having a Normal
distribution. We can use the rbinom() function to simulate binary random variables.
> set.seed(10)
> x <- rbinom(100, 1, 0.5)
> str(x) ## 'x' is now 0s and 1s
int [1:100] 1 0 0 1 0 0 0 0 1 0 ...
We can also simulate from generalized linear model where the errors are no longer from a Normal
distribution but come from some other distribution. For examples, suppose we want to simulate
from a Poisson log-linear model where
Simulation 145
Y P oisson()
log = 0 + 1 x
and 0 = 0.5 and 1 = 0.3. We need to use the rpois() function for this
> set.seed(1)
>
> ## Simulate the predictor variable as before
> x <- rnorm(100)
Now we need to compute the log mean of the model and then exponentiate it to get the mean to
pass to rpois().
You can build arbitrarily complex models like this by simulating more predictors or making
transformations of those predictors (e.g. squaring, log transformations, etc.).
The sample() function draws randomly from a specified set of (scalar) objects allowing you to
sample from arbitrary distributions of numbers.
> set.seed(1)
> sample(1:10, 4)
[1] 3 4 5 7
> sample(1:10, 4)
[1] 3 9 8 5
>
> ## Doesn't have to be numbers
> sample(letters, 5)
[1] "q" "b" "e" "x" "p"
>
> ## Do a random permutation
> sample(1:10)
[1] 4 7 10 6 9 2 8 3 1 5
> sample(1:10)
[1] 2 3 4 1 9 5 10 8 6 7
>
> ## Sample w/replacement
> sample(1:10, replace = TRUE)
[1] 2 9 7 8 2 8 5 9 7 8
To sample more complicated things, such as rows from a data frame or a list, you can sample the
indices into an object rather than the elements of the object itself.
Heres how you can sample rows from a data frame.
> library(datasets)
> data(airquality)
> head(airquality)
Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
5 NA NA 14.3 56 5 5
6 28 NA 14.9 66 5 6
Now we just need to create the index vector indexing the rows of the data frame and sample directly
from that index vector.
Simulation 148
> set.seed(20)
>
> ## Create index vector
> idx <- seq_len(nrow(airquality))
>
> ## Sample from the index vector
> samp <- sample(idx, 6)
> airquality[samp, ]
Ozone Solar.R Wind Temp Month Day
135 21 259 15.5 76 9 12
117 168 238 3.4 81 8 25
43 NA 250 9.2 92 6 12
80 79 187 5.1 87 7 19
144 13 238 12.6 64 9 21
146 36 139 10.3 81 9 23
Other more complex objects can be sampled in this way, as long as theres a way to index the sub-
elements of the object.
22.5 Summary
Drawing samples from specific probability distributions can be done with r functions
Standard distributions are built in: Normal, Poisson, Binomial, Exponential, Gamma, etc.
The sample() function can be used to draw random samples from arbitrary vectors
Setting the random number generator seed via set.seed() is critical for reproducibility
23. Data Analysis Case Study: Changes
in Fine Particle Air Pollution in the
U.S.
This chapter presents an example data analysis looking at changes in fine particulate matter (PM) air
pollution in the United States using the Environmental Protection Agencies freely available national
monitoring data. The purpose of the chapter is to just show how the various tools that we have
covered in this book can be used to read, manipulate, and summarize data so that you can develop
statistical evidence for relevant real-world questions.
Watch a video of this chapter
23.1 Synopsis
In this chapter we aim to describe the changes in fine particle (PM2.5) outdoor air pollution in the
United States between the years 1999 and 2012. Our overall hypothesis is that outdoor PM2.5 has
decreased on average across the U.S. due to nationwide regulatory requirements arising from the
Clean Air Act. To investigate this hypothesis, we obtained PM2.5 data from the U.S. Environmental
Protection Agency which is collected from monitors sited across the U.S. We specifically obtained
data for the years 1999 and 2012 (the most recent complete year available). From these data, we
found that, on average across the U.S., levels of PM2.5 have decreased between 1999 and 2012. At
one individual monitor, we found that levels have decreased and that the variability of PM2.5 has
decreased. Most individual states also experienced decreases in PM2.5, although some states saw
increases.
After reading in the 1999 we check the first few rows (there are 117,421) rows in this dataset.
> dim(pm0)
[1] 117421 28
> head(pm0[, 1:13])
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13
1 RD I 1 27 1 88101 1 7 105 120 19990103 00:00 NA
2 RD I 1 27 1 88101 1 7 105 120 19990106 00:00 NA
3 RD I 1 27 1 88101 1 7 105 120 19990109 00:00 NA
4 RD I 1 27 1 88101 1 7 105 120 19990112 00:00 8.841
5 RD I 1 27 1 88101 1 7 105 120 19990115 00:00 14.920
6 RD I 1 27 1 88101 1 7 105 120 19990118 00:00 3.878
We then attach the column headers to the dataset and make sure that they are properly formated
for R data frames.
The column we are interested in is the Sample.Value column which contains the PM2.5 measure-
ments. Here we extract that column and print a brief summary.
Missing values are a common problem with environmental data and so we check to se what
proportion of the observations are missing (i.e. coded as NA).
Because the proportion of missing values is relatively low (0.1125608), we choose to ignore missing
values for now.
We also set the column names (they are the same as the 1999 dataset) and extract the Sample.Value
column from this dataset.
23.3 Results
> summary(x0)
Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
0.00 7.20 11.50 13.74 17.90 157.10 13217
> summary(x1)
Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
-10.00 4.00 7.63 9.14 12.00 909.00 73133
Interestingly, from the summary of x1 it appears there are some negative values of PM, which in
general should not occur. We can investigate that somewhat to see if there is anything we should
worry about.
There is a relatively small proportion of values that are negative, which is perhaps reassuring. In
order to investigate this a step further we can extract the date of each measurement from the original
data frame. The idea here is that perhaps negative values occur more often in some parts of the year
than other parts. However, the original data are formatted as character strings so we convert them
to Rs Date format for easier manipulation.
We can then extract the month from each of the dates with negative values and attempt to identify
when negative values occur most often.
From the table above it appears that bulk of the negative values occur in the first six months of
the year (JanuaryJune). However, beyond that simple observation, it is not clear why the negative
values occur. That said, given the relatively low proportion of negative values, we will ignore them
for now.
Data Analysis Case Study: Changes in Fine Particle Air Pollution in the U.S. 154
Then we create a new variable that combines the county code and the site ID into a single string.
Finaly, we want the intersection between the sites present in 1999 and 2012 so that we might choose
a monitor that has data in both periods.
Here (above) we can see that there are 10 monitors that were operating in both time periods.
However, rather than choose one at random, it might best to choose one that had a reasonable
amount of data in each year.
Data Analysis Case Study: Changes in Fine Particle Air Pollution in the U.S. 155
Now that we have subsetted the original data frames to only include the data from the monitors that
overlap between 1999 and 2012, we can split the data frames and count the number of observations
at each monitor to see which ones have the most observations.
> ## 1999
> sapply(split(cnt0, cnt0$county.site), nrow)
1.12 1.5 101.3 13.11 29.5 31.3 5.80 63.2008 67.1015
61 122 152 61 61 183 61 122 122
85.55
7
> ## 2012
> sapply(split(cnt1, cnt1$county.site), nrow)
1.12 1.5 101.3 13.11 29.5 31.3 5.80 63.2008 67.1015
31 64 31 31 33 15 31 30 31
85.55
31
A number of monitors seem suitable from the output, but we will focus here on County 63 and site
ID 2008.
Now we plot the time series data of PM for the monitor in both years.
Data Analysis Case Study: Changes in Fine Particle Air Pollution in the U.S. 156
From the plot above, we can that median levels of PM (horizontal solid line) have decreased a little
from 10.45 in 1999 to 8.29 in 2012. However, perhaps more interesting is that the variation (spread)
in the PM values in 2012 is much smaller than it was in 1999. This suggest that not only are median
levels of PM lower in 2012, but that there are fewer large spikes from day to day. One issue with the
data here is that the 1999 data are from July through December while the 2012 data are recorded in
January through April. It would have been better if wed had full-year data for both years as there
could be some seasonal confounding going on.
Data Analysis Case Study: Changes in Fine Particle Air Pollution in the U.S. 157
> ## 1999
> mn0 <- with(pm0, tapply(Sample.Value, State.Code, mean, na.rm = TRUE))
> ## 2012
> mn1 <- with(pm1, tapply(Sample.Value, State.Code, mean, na.rm = TRUE))
>
> ## Make separate data frames for states / years
> d0 <- data.frame(state = names(mn0), mean = mn0)
> d1 <- data.frame(state = names(mn1), mean = mn1)
> mrg <- merge(d0, d1, by = "state")
> head(mrg)
state mean.x mean.y
1 1 19.956391 10.126190
2 10 14.492895 11.236059
3 11 15.786507 11.991697
4 12 11.137139 8.239690
5 13 19.943240 11.321364
6 15 4.861821 8.749336
Now make a plot that shows the 1999 state-wide means in one column and the 2012 state-wide
means in another columns. We then draw a line connecting the means for each year in the same
state to highlight the trend.
From the plot above we can see that many states have decreased the average PM levels from 1999
to 2012 (although a few states actually increased their levels).
24. Parallel Computation
Many computations in R can be made faster by the use of parallel computation. Generally, parallel
computation is the simultaneous execution of different pieces of a larger computation across multiple
computing processors or cores. The basic idea is that if you can execute a computation in X seconds
on a single processor, then you should be able to execute it in X/n seconds on n processors. Such a
speed-up is generally not possible because of overhead and various barriers to splitting up a problem
into n pieces, but it is often possible to come close in simple problems.
It used to be that parallel computation was squarely in the domain of high-performance computing,
where expensive machines were linked together via high-speed networking to create large clusters
of computers. In those kinds of settings, it was important to have sophisticated software to manage
the communication of data between different computers in the cluster. Parallel computing in that
setting was a highly tuned, and carefully customized operation and not something you could just
saunter into.
These days though, almost all computers contain multiple processors or cores on them. Even Apples
iPhone 6S comes with a dual-core CPU as part of its A9 system-on-a-chip. Getting access to a
cluster of CPUs, in this case all built into the same computer, is much easier than it used to be and
this has opened the door to parallel computing for a wide range of people.
In this chapter, we will discuss some of the basic funtionality in R for executing parallel compu-
tations. In particular, we will focus on functions that can be used on multi-core computers, which
these days is almost all computers. It is possible to do more traditional parallel computing via the
network-of-workstations style of computing, but we will not discuss that here.
Parallel BLAS
A common example in R is the use of linear algebra functions. Some versions of R that you use may
be linked to on optimized Basic Linear Algebra Subroutines (BLAS) library. Such libraries are custom
https://en.wikipedia.org/wiki/Apple_A9
Parallel Computation 160
coded for specific CPUs/chipsets to take advantage of the architecture of the chip. Its important to
realize that while R can do linear algebra out of the box, its default BLAS library is a reference
implementation that is not necessarily optimized to any particular chipset.
When possible, its always a good idea to install an optimized BLAS on your system because it
can dramatically improve the performance of those kinds of computations. Part of the increase in
performance comes from the customization of the code to a particular chipset while part of it comes
from the multi-threading that many libraries use to parallelize their computations.
For example, below I simulate a matrix X of 1 million observations by 100 predictors and generate
an outcome y.
Then I compute the least squares estimates of the linear regression coefficents when regressing the
response y on the predictor matrix X.
Here, you can see that the user time is just under 1 second while the elapsed time is about half
that. Here, the key task, matrix inversion, was handled by the optimized BLAS and was computed
in parallel so that the elapsed time was less than the user or CPU time. In this case, I was using a
Mac that was linked to Apples Accelerate framework which contains an optimized BLAS.
Heres a summary of some of the optimized BLAS libraries out there:
The AMD Core Math Library (ACML) is built for AMD chips and contains a full set of BLAS
and LAPACK routines. The library is closed-source and is maintained/released by AMD.
The Intel Math Kernel is an analogous optimized library for Intel-based chips
The Accelerate framework on the Mac contains an optimized BLAS built by Apple.
The Automatically Tuned Linear Algebra Software (ATLAS) library is a special adaptive
software package that is designed to be compiled on the computer where it will be used. As
part of the build process, the library extracts detailed CPU information and optimizes the code
as it goes along. The ATLAS library is hence a generic package that can be built on a wider
array of CPUs.
http://developer.amd.com/tools-and-sdks/archive/amd-core-math-library-acml/
https://software.intel.com/en-us/intel-mkl
https://developer.apple.com/library/tvos/documentation/Accelerate/Reference/AccelerateFWRef/index.html
http://math-atlas.sourceforge.net
Parallel Computation 161
Detailed instructions on how to use R with optimized BLAS libraries can be found in the R
Installation and Administration manual. In some cases, you may need to build R from the sources
in order to link it with the optimized BLAS library.
In general, it is NOT a good idea to use the functions described in this chapter with graphical user
interfaces (GUIs) because, to summarize the help page for mclapply(), bad things can happen. That
said, the functions in the parallel package seem two work okay in RStudio.
The basic mode of an embarrassingly parallel operation can be seen with the lapply() function,
which we have reviewed in a previous chapter. Recall that the lapply() function has two arguments:
Finally, recall that lapply() always returns a list whose length is equal to the length of the input
list.
The lapply() function works much like a loopit cycles through each element of the list and applies
the supplied function to that element. While lapply() is applying your function to a list element,
the other elements of the list are justsitting around in memory. Note that in the description of
lapply() above, theres no mention of the different elements of the list communicating with each
other, and the function being applied to a given list element does not need to know about other list
elements.
Just about any operation that is handled by the lapply() function can be parallelized. This approach
is analogous to the map-reduce approach in large-scale cluster systems. The idea is that a list object
can be split across multiple cores of a processor and then the function can be applied to each subset
of the list object on each of the cores. Conceptually, the steps in the parallel procedure are
https://cran.r-project.org/doc/manuals/r-release/R-admin.html#BLAS
https://en.wikipedia.org/wiki/MapReduce
Parallel Computation 162
The differences between the many packages/functions in R essentially come down to how each of
these steps are implemented. In this chapter we will cover the parallel package, which has a few
implementations of this paradigm. The goal of the functions in this package (and in other related
packages) is to abstract the complexities of the implemetation so that the R user is presented a
relatively clean interface for doing computations.
The mclapply() function essentially parallelizes calls to lapply(). The first two arguments to
mclapply() are exactly the same as they are for lapply(). However, mclapply() has further
arguments (that must be named), the most important of which is the mc.cores argument which
you can use to specify the number of processors/cores you want to split the computation across.
For example, if your machine has 4 cores on it, you might specify mc.cores = 4 to break your
parallelize your operation across 4 cores (although this may not be the best idea if you are running
other operations in the background besides R).
The mclapply() function (and related mc* functions) works via the fork mechanism on Unix-style
operating systems. Briefly, your R session is the main process and when you call a function like
mclapply(), you fork a series of sub-processes that operate independently from the main process
(although they share a few low-level features). These sub-processes then execute your function
on their subsets of the data, presumably on separate cores of your CPU. Once the computation
is complete, each sub-process returns its results and then the sub-process is killed. The parallel
package manages the logistics of forking the sub-processes and handling them once theyve finished.
Because of the use of the fork mechanism, the mc* functions are generally not available to users of
the Windows operating system.
The first thing you might want to check with the parallel package is if your computer in fact has
multiple cores that you can take advantage of.
Parallel Computation 163
> library(parallel)
> detectCores()
[1] 4
The computer on which this is being written is a circa 2016 MacBook Pro (with Touch Bar) with 2
physical CPUs. However, because each core allows for hyperthreading, each core is presented as 2
separate cores, allowing for 4 logical cores. This is what detectCores() returns. On some systems
you can call detectCores(logical = FALSE) to return the number of physical cores.
In general, the information from detectCores() should be used cautiously as obtaining this kind
of information from Unix-like operating systems is not always reliable. If you are going down this
road, its best if you get to know your hardware better in order to have an understanding of how
many CPUs/cores are available to you.
mclapply()
The simplest application of the parallel package is via the mclapply() function, which conceptually
splits what might be a call to lapply() across multiple cores. Just to show how the function works,
Ill run some code that splits a job across 10 cores and then just sleeps for 10 seconds.
While this job was running, I took a screen shot of the system activity monitor (top). Heres what
it looks like on Mac OS X.
Parallel Computation 164
In case you are not used to viewing this output, each row of the table is an application or process
running on your computer. You can see that there are 11 rows where the COMMAND is labelled
rsession. One of these is my primary R session (being run through RStudio), and the other 10 are
the sub-processes spawned by the mclapply() function.
We will use as a second (slightly more realistic) example processing data from multiple files. Often
this is something that can be easily parallelized.
Here we have data on ambient concentrations of sulfate particulate matter (PM) and nitrate PM from
332 monitors around the United States. First, we can read in the data via a simple call to lapply().
Now, specdata is a list of data frames, with each data frame corresponding to each of the 332
monitors in the dataset.
One thing we might want to do is compute a summary statistic across each of the monitors. For
example, we might want to compute the 90th percentile of sulfate for each of the monitors. This can
easily be implemented as a serial call to lapply().
Parallel Computation 165
Note that in the system.time() output, the user time (0.044 seconds) and the elapsed time (0.049
seconds) are roughly the same, which is what we would expect because there was no parallelization.
The equivalent call using mclapply() would be
Youll notice that the the elapsed time is now less than the user time. However, in general, the
elapsed time will not be 1/4th of the user time, which is what we might expect with 4 cores if there
were a perfect performance gain from parallelization.
R keeps track of how much time is spent in the main process and how much is spent in any child
processes.
In the call to mclapply() you can see that virtually all of the user time is spent in the child processes.
The total user time is the sum of the self and child times.
In some cases it is possible for the parallelized version of an R expression to actually be slower than
the serial version. This can occur if there is substantial overhead in creating the child processes. For
example, time must be spent copying information over to the child processes and communicating
the results back to the parent process. However, for most substantial computations, there will be
some benefit in parallelization.
Parallel Computation 166
One advantage of serial computations is that it allows you to better keep a handle on how much
memory your R job is using. When executing parallel jobs via mclapply() its important to pre-
calculate how much memory all of the processes will require and make sure this is less than the
total amount of memory on your computer.
The mclapply() function is useful for iterating over a single list or list-like object. If you have to
iterate over multiple objects together, you can use mcmapply(), which is the the multi-core equivalent
of the mapply() function.
Error Handling
When either mclapply() or mcmapply() are called, the functions supplied will be run in the sub-
process while effectively being wrapped in a call to try(). This allows for one of the sub-processes
to fail without disrupting the entire call to mclapply(), possibly causing you to lose much of your
work. If one sub-process fails, it may be that all of the others work just fine and produce good results.
This error handling behavior is a significant difference from the usual call to lapply(). With
lapply(), if the supplied function fails on one component of the list, the entire function call to
lapply() fails and you only get an error as a result.
With mclapply(), when a sub-process fails, the return value for that sub-process will be an R object
that inherits from the class "try-error", which is something you can test with the inherits()
function. Conceptually, each child process is executed with the try() function wrapped around it.
The code below deliberately causes an error in the 3 element of the list.
Here we see there was a warning but no error in the running of the above code. We can check the
return value.
Parallel Computation 167
> str(r)
List of 5
$ : chr "success!"
$ : chr "success!"
$ :Class 'try-error' atomic [1:1] Error in FUN(X[[i]], ...) : error in this process!
> class(r[[3]])
[1] "try-error"
> inherits(r[[3]], "try-error")
[1] TRUE
When running code where there may be errors in some of the sub-processes, its useful to check
afterwards to see if there are any errors in the output received.
You can subsequently subset your return object to only keep the good elements.
We can see from the histogram that the distribution of sulfate is skewed to the right. Therefore, it
would seem that the median might be a better summary of the distribution than the mean.
Parallel Computation 169
> summary(sulf)
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.613 2.210 2.870 3.881 4.730 19.100
How can we construct confidence interval for the median of sulfate for this monitor? The bootstrap
is simple procedure that can work well. Heres how we might do it in the usual (non-parallel) way.
> set.seed(1)
> med.boot <- replicate(5000, {
+ xnew <- sample(sulf, replace = TRUE)
+ median(xnew)
+ })
A 95% confidence interval would then take the 2.5th and 97.5th percentiles of this distribution (this
is known as the percentile method).
How could be done in parallel? We could simply wrap the expression passed to replicate() in
a function and pass it to mclapply(). However, one thing we need to be careful of is generating
random numbers.
However, the above expression is not reproducible because the next time you run it, you will get a
different set of random numbers. You cannot simply call set.seed() before running the expression
as you might in a non-parallel version of the code.
The parallel package provides a way to reproducibly generate random numbers in a parallel
environment via the LEcuyer-CMRG random number generator. Note that this is not the default
random number generator so you will have to set it explicitly.
Running the above code twice will generate the same random numbers in each of the sub-processes.
Now we can run our parallel bootstrap in a reproducible way.
> RNGkind("L'Ecuyer-CMRG")
> set.seed(1)
> med.boot <- mclapply(1:5000, function(i) {
+ xnew <- sample(sulf, replace = TRUE)
+ median(xnew)
+ }, mc.cores = 4)
> med.boot <- unlist(med.boot) ## Collapse list into vector
> quantile(med.boot, c(0.025, 0.975))
2.5% 97.5%
2.6995 3.4700
Although Ive rarely seen it done in practice (including in my own code), its a good idea to
explicitly set the random number generator via RNGkind(), in addition to setting the seed with
set.seed(). This way, you can be sure that the appropriate random number generator is being
used every time and your code will be reproducible even on a system where the default generator
has been changed.
Parallel Computation 171
> library(boot)
> b <- boot(sulf, function(x, i) median(x[i]), R = 5000, parallel = "multicore", ncpus = 4)
> boot.ci(b, type = "perc")
BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 5000 bootstrap replicates
CALL :
boot.ci(boot.out = b, type = "perc")
Intervals :
Level Percentile
95% ( 2.70, 3.47 )
Calculations and Intervals on Original Scale
The cl object is an abstraction of the entire cluster and is what well use to indicate to the various
cluster functions that we want to do parallel computation.
Youll notice that the makeCluster() function has a type argument that allows for different types
of clusters beyond using sockets (although the default is a socket cluster). We will not discuss these
other options here.
https://en.wikipedia.org/wiki/Network_socket
Parallel Computation 172
To do an lapply() operation over a socket cluster we can use the parLapply() function. For example,
we can use parLapply() to run our median bootstrap example described above.
Youll notice, unfortunately, that theres an error in running this code. The reason is that while
we have loaded the sulfate data into our R session, the data is not available to the independent
child processes that have been spawned by the makeCluster() function. The data, and any other
information that the child process will need to execute your code, needs to be exported to the child
process from the parent process via the clusterExport() function. The need to export data is a key
difference in behavior between the multicore approach and the socket approach.
The second argument to clusterExport() is a character vector, and so you can export an arbitrary
number of R objects to the child processes. You should be judicious in choosing what you export
simply because each R object will be replicated in each of the child processes, and hence take up
memory on your computer.
Once the data have been exported to the child processes, we can run our bootstrap code again.
Once youve finished working with your cluster, its good to clean up and stop the cluster child
processes (quitting R will also stop all of the child processes).
> stopCluster(cl)
Parallel Computation 173
24.6 Summary
In this chapter we reviewed two different approaches to executing parallel computations in R. Both
approaches used the parallel package, which comes with your installation of R. The multicore
approach, which makes use of the mclapply() function is perhaps the simplest and can be
implemented on just about any multi-core system (which nowadays is any system). The socket
approach is a bit more general and can be implemented on systems where the fork-ing mechanism
is not available. The approach used in the socket type cluster can also be extended to other parallel
cluster management systems which unfortunately are outside the scope of this book.
In general, using parallel computation can speed up embarrassingly parallel computations, typi-
cally with little additional effort. However, its important to remember that splitting a computation
across N processors usually does not result in a N -times speed up of your computation. This is
because there is some overhead involved with initiating the sub-processes and copying the data
over to those processes.
25. About the Author
Roger D. Peng is a Professor of Biostatistics at the Johns Hopkins Bloomberg School of Public Health.
He is also a Co-Founder of the Johns Hopkins Data Science Specialization, which has enrolled over
1.5 million students, the Johns Hopkins Executive Data Science Specialization, the Simply Statistics
blog where he writes about statistics and data science for the general public, and the Not So Standard
Deviations podcast. Roger can be found on Twitter and GitHub under the user name @rdpeng.
http://www.coursera.org/specialization/jhudatascience/1
https://www.coursera.org/specializations/executive-data-science
http://simplystatistics.org/
https://soundcloud.com/nssd-podcast
https://twitter.com/rdpeng