Learn R

Author
Affiliation

Jeff Webb

David Eccles School of Business

Introduction

These lessons introduce R in a simple step-by-step fashion, with the goal of equipping you—quickly and efficiently—to analyze data. While some examples are drawn from statistics, the focus is on R programming only (with some attention to other tools in the R ecosystem). The objective is to help you develop programming skills quickly with brief but thorough explanations using examples.

  • Practice: As you work through each lesson I recommend you type the example code into R or RStudio to run on your own computer. Active learning—typing rather than just reading—will help you better understand, and remember, the material. Additionally, some of the sections include practice exercises with embedded R code boxes for writing and evaluating code. You can use these to immediately test your understanding of the material.

  • Non-programmers: We start from the beginning and build up step-by-step to develop the advanced skills needed for professional data roles in industry.

  • Functional workflows: These lessons start with “base R”—the software that is automatically included when you download and install R—but later introduce a collection of add-on packages called the “tidyverse.” You will learn how to combine base R with tidyverse functions and coding paradigms to write code with maximum efficiency and readability.

  • Motivating: From the start you will be doing work in R that has immediate application for uncovering insights from data. You won’t get bogged down in overly detailed explanations of lesser used features of the language. Advanced material will be introduced later as needed.

  • No frills: The focus is on R programming only, without including statistics or other data analysis techniques except as examples. This will make it easier for you to really concentrate on learning R programming.

Conventions:

  • The first appearance of a key term is bolded for easy reference. You should know and remember these words.
  • R code is presented in highlighted text: mean(x).
  • Additional details are presented in the marginal notes and in blue “tip” or “detail” blocks:
Tip

I’d like to acknowledge Norm Matloff’s introduction to R programming, “FasteR,” which served as inspiration for these lessons.

Let’s start!

1 Install R and RStudio

R is a free, open source statistical programming language that consists in a set of tools for doing stuff with data: wrangling, plotting, summarizing and modeling it (among other things). Go to the Comprehensive R Archive Network (CRAN) to download R, making sure to pick the latest release for your operating system. Install R by opening the downloaded installer.

There are a very large number of supplementary packages that extend R’s usefulness; these must be downloaded and installed separately. (We will cover that later.) One of the great things about R is that the development community is extremely active and new packages implementing cutting edge techniques are being added all the time. (As of October 2022 there were over 18,000 packages.)

R can be used by itself but the user interface is minimalistic. RStudio is a free integrated design environment or IDE1 that will improve your productivity in R by supplying a much richer GUI with menu-driven support for many programming and organizational tasks. Go to posit.com to download the free desktop version of RStudio.2 Pick the version that is appropriate for your operating system. Note that you must have R installed before you install RStudio.

1 Wikipedia: “An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development.”

2 A free cloud-hosted version of RStudio is also available, RStudio Cloud, that has the same appearance and functionality as the desktop version. Be aware that the free tier is capped at 25 hours per month.

RStudio is a complicated piece of software at this point. Don’t be intimidated! You will be using just a few very basic features at first.

RStudio is not itself a programming language; it simply supplies a computer environment for interacting with the programming language of your choice — not just R but also Python, SQL and others. Think of it like this: The plumbing in your home supplies water, but the plumbing system is not the water. RStudio is a bit like plumbing. You could carry water in from outside, just as you could use R by itself, but it is faster and more convenient to use an IDE like RStudio.

2 The Console

Open RStudio. If this is your first time using the software you will see three windows (or “panes”). On the left is a large window filling the screen from top to bottom with a tab titled console.

RStudio layout

This is where you interact directly with R by typing commands and getting results.

You should see two other windows on the right with multiple tabs in each. We will call these the Environment pane (upper right) and the Files pane (lower right). We will discuss these windows in later lessons (along with other RStudio features). For now let’s concentrate just on the console and begin learning to program in R.

3 First Steps

The R command prompt is >. This indicates where you will type R code in the console to perform various tasks. You don’t need to type the > since R automatically includes it on each new line.

Most simply, R is a calculator. Type 2 + 2 at the command prompt in the console and press Return.

2 + 2
[1] 4

The output or return value is [1] 4. The [1] just refers to the row label of the output in the console. Labels are helpful for reference when the output becomes lengthy.

Here we have used +. But all the other mathematical operators you would expect are available for doing arithmetic in R:

  • Subtract: -.
  • Divide: /.
  • Multiply: *.
  • Raise to a power: ^. For example, 2^2 returns 4.
  • Calculate the remainder of division (the modulo operator): %%. For example, 5 %% 2 returns 1.

Parentheses are used to define the order of operations in calculations. For example, 2 * 2 - 3 is not the same as 2 * (2 - 3). The first expression returns 1, while the second returns -2. As expected, R will evaluate multiplication and division before addition and subtraction.3

3 You may recall a mnemonic for order of operations from earlier schooling: “Please Excuse My Dear Aunt Sally.” This applies in R. Evaluate expressions in Parentheses, followed by Exponents, then Multiplication, Division, Addition and Subtraction.

Tip: Using the Arrow Keys in the Console

Notice that when after R produces a return value the cursor advances to the next line with another command prompt appearing automatically. As you repeat this process the console window scrolls up and you can no longer see the earlier code you typed. However, you can navigate to code you typed earlier using the up key. And you can then navigate to more recent code using the down key. This can be a time saver if you want to adapt and run earlier code rather than typing new code.

3.1 Practice Questions

R can be used as a calculator but you must be careful to use parentheses appropriately for complicated calculations.

Use the console in RStudio to experiment with the mathematical operators described above. Alternatively, you could use the code box embedded below to write and evaluate code for these practice questions.

Code Boxes

All the practice sections of this document include R code boxes. These are similar to the console in RStudio, except that you evaluate your code not by pressing return but by clicking the “Run Code” button. For assistance, click the “Show answers” button included below each code box. You can run the code from the answer box by cutting and pasting it into the code box. (Notice that the upper right corner of the answer box includes a copy button.)

Basically the code boxes are running R in your browser. When you first open Learn R the button above the code boxes will show a yellow dot as the software is first being installed then loaded. This will turn green when the programming environment is ready to go. Note that your code will not be preserved when you close the page.

The code boxes are included for your convenience and immediate practice. Whether you use them is entirely up to you. You may prefer to work in RStudio.

  1. Attempt a couple of calculations:

    • Subtract 5 from 10 and multiply the result by 2.

    • Add 4 and 5 then square the result.

  2. Here are several more:

    • \(\frac{5^3 \text{ x } (6-3)}{60-3+4}\).

    • \(\frac{5^{3 \text{ x } 6} -3}{60-3+4}\).

    • \(\frac{.55 - (1 - .55)^\frac{1}{2}}{29}\).

    • \(\frac{.55 - 1 - .55^\frac{1}{2}}{29}\).

  3. Explore the modulo operator. (Remember: modulo calculates the remainder after division.)

    • What is 10 modulo 1?
    • 7 modulo 2?
    • What is the remainder of 99 divided by 2?
    • What is the remainder of 1.25 divided by 15?
Show answers
## Question 1 -------------------------------

# Subtract 5 from 10 and multiply the result by 2. 
(10 - 5) * 2

# Add 4 and 5 then square the result. 
(4 + 5)^2 

## Question 2 -------------------------------

5^3 * (6 - 3) / (60 -3 + 4) 

(5^(3 * 6) - 3) / (60 - 3 + 4)

(.55 - (1 - .55)^(1/2)) / 29

(.55 - 1 - .55^(1/2)) / 29

## Question 3 -------------------------------

# What is 10 %% 1?  This equals 0 because there is no remainder: 
# 10 / 1 = 10 + 0. The "+ 0" is the remainder.

10 %% 1

# 7 %% 2? This is 1 because 7 / 2 = 3 + 1.  The "+ 1" is the remainder. 

7 %% 2

# What is the remainder of 99 divided by 2? 

99 %% 2    

# What is the remainder of 1.25 divided by 15? 

1.25 %% 15

# Think about this answer. Consider that 1.25 / 15 is .08333333, which, 
# multiplied by 15, is 1.25.

4 Objects

We can assign the result of a calculation—or, really, any value we wish— to an object stored in memory for use later. For example:

x <- 1 + 2

Let’s back up for a moment. The <- in the code above is the assignment operator. It says: take the value on the right and assign it to (store it in) the object on the left. <- is like a pointer. For example, this code does exactly the same thing:

1 + 2 -> x

Based on the reversed direction of assignment, this code says: take the value on the left and assign it to the object on the right. (Could we use = for assignment, as in Python? Yes, for the most part, although there are some situations where = will lead to problems. Best to stick with <- for clarity.)

To explore objects further, try this code:

3 <- 1 + 2
Error in 3 <- 1 + 2: invalid (do_set) left-hand side to assignment

We get an error. Errors in R (which on your local machine will be printed in red, to get your attention) attempt to supply some useful information so that you can correct the problem. Don’t panic about errors: they are an unavoidable part of programming, such that it is largely accurate to say that “coding is debugging.” The key is to figure out how to understand and use error messages. Here we are told: “invalid (do_set) left-hand side to assignment.” (I’m not sure what “(do_set)” means. But I could probably figure it out by googling: “do_set R.”)4 Take a moment to think about the error message. Something is wrong with the left-hand side of the assignment, which makes sense. We can’t assign 3 a value because, as a number, it already has a value intrinsically. For objects, we must instead pick letters or words which do not already have an assigned value. (Think of this as analogous to math when “x” is used to represent a value. Same thing here.)5

4 Googling R errors will often take you to the Stack Overflow site, which hosts a community Q & A forum. Stack Overflow discussions can be useful, but are sometimes incomplete or incorrect. As always, you need to think critically about (rather than just blindly accepting) information on the internet. Best practice here would be to google the non-specific part of the error message: “invalid (do_set) left-hand side to assignment.”

5 As a rule, names in R must start with a letter and avoid the special characters accessed with the shift key—for example, on the top row of the keyboard— which are reserved for other uses. The exception to the rule is the underscore, _. We’ll come back to naming conventions in a later lesson.

This code will work:

three <- 1 + 2

Notice that, as above, no output value is returned to the console. That’s because the assignment operation happens in the background, in R’s memory. We can return the value of the object simply by typing “three” and pressing return:

three
[1] 3

So, we have now defined two R objects, x and three, both with the value of 3. These are stored in memory and are available for use in further calculations. Observe:

x + three
[1] 6

Using objects, we can even do further assignment without typing any numbers at all:

y <- x + three

And, again, to check the value of y type it in the console and press Return.

y
[1] 6

4.1 Practice Questions

One of the strengths of R is to assign values to objects with the assignment operator, <-. Practice creating and working with R objects.

  1. Define two objects, a and b, to be 5 and 10, respectively. Calculate:

    • \(a + b\)

    • \(a ^2 + b^2\)

    • \(a^b\)

    • \(\frac{a-b}{a+b}\)

  2. You can store a new value in an existing object. (This will overwrite the old value.) Try this with the a you have defined above: a <- a / a. Now what is the value of a?

Show answers
## Define objects -------------------------------

a <- 5

b <- 10
 
## Question 1 -----------------------------------

a + b

a^2 + b^2

a^b

(a - b) / (a + b)
 
## Question 2 -------------------------------

a <- a / a

a

5 Vectors

So far we have assigned single numeric values—numbers—to R objects. Could a collection of numbers be stored in an object? Yes. Rather than doing the assignment ourselves, let’s use some data already included in R. The rivers dataset records the lengths of major North American rivers.

rivers
  [1]  735  320  325  392  524  450 1459  135  465  600  330  336  280  315  870
 [16]  906  202  329  290 1000  600  505 1450  840 1243  890  350  407  286  280
 [31]  525  720  390  250  327  230  265  850  210  630  260  230  360  730  600
 [46]  306  390  420  291  710  340  217  281  352  259  250  470  680  570  350
 [61]  300  560  900  625  332 2348 1171 3710 2315 2533  780  280  410  460  260
 [76]  255  431  350  760  618  338  981 1306  500  696  605  250  411 1054  735
 [91]  233  435  490  310  460  383  375 1270  545  445 1885  380  300  380  377
[106]  425  276  210  800  420  350  360  538 1100 1205  314  237  610  360  540
[121] 1038  424  310  300  444  301  268  620  215  652  900  525  246  360  529
[136]  500  720  270  430  671 1770

This type of data is called a vector. A vector is any collection of similar items, observations or measurements in R, such as: the letters in the alphabet, salaries of bank managers, heights of students in a class, whole numbers between 1 and 100, the names of trees.

The bracketed row labels printed along the left-hand side of the output refer to the vector index of the first item in each row.6 What do we mean by index? An item’s index is simply its position in the vector. For example, the [1] indicates the first item, and also serves as a row label. The row labels make it easy to refer to individual observations.7

6 Note that the length of the rows, and hence the row labels, will change depending on the width of your console on your local machine.

7 We will often refer to the index of an observation within a vector using a subscript. The item in the first position, 735, is rivers\(_1\), while the item in the last position, 1770, is rivers\(_{141}\). To refer abstractly to individual items within a vector the convention is to use \(i\) for “index”: rivers\(_{i}\).

We can do arithmetic with vectors. For example, to add 1 to every item in rivers simply type rivers + 1:

rivers + 1
  [1]  736  321  326  393  525  451 1460  136  466  601  331  337  281  316  871
 [16]  907  203  330  291 1001  601  506 1451  841 1244  891  351  408  287  281
 [31]  526  721  391  251  328  231  266  851  211  631  261  231  361  731  601
 [46]  307  391  421  292  711  341  218  282  353  260  251  471  681  571  351
 [61]  301  561  901  626  333 2349 1172 3711 2316 2534  781  281  411  461  261
 [76]  256  432  351  761  619  339  982 1307  501  697  606  251  412 1055  736
 [91]  234  436  491  311  461  384  376 1271  546  446 1886  381  301  381  378
[106]  426  277  211  801  421  351  361  539 1101 1206  315  238  611  361  541
[121] 1039  425  311  301  445  302  269  621  216  653  901  526  247  361  530
[136]  501  721  271  431  672 1771

The other mathematical operators we discussed above also work with vectors. For example, suppose that we want a quick way to figure out whether river mile lengths are odd. We could divide rivers by 2 and calculate the remainder with the modulo operator.

rivers %% 2
  [1] 1 0 1 0 0 0 1 1 1 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 1
 [38] 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 1 1 0 0 0 0
 [75] 0 1 1 0 0 0 0 1 0 0 0 1 0 1 0 1 1 1 0 0 0 1 1 0 1 1 1 0 0 0 1 1 0 0 0 0 0
[112] 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 0 1 0

A remainder of 1 indicates that the river length is odd.

These results illustrate an important fact: vector arithmetic is performed element-wise in R. The operation of adding a number to a vector can be represented abstractly like this:

\[ a + \begin{bmatrix} b \\ c \\ d \end{bmatrix} = \begin{bmatrix} a + b \\ a + c \\ a + d \end{bmatrix} \]

where \(a\) is a single number and \([b, c, d]\) is a vector.

We can also do arithmetic with entire vectors.

rivers / rivers
  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 [38] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 [75] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[112] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Again, the calculation is done element-wise: each element of rivers has been divided by itself. We can represent this operation as:

\[ \begin{bmatrix} a \\ b \\ c \end{bmatrix} \div \begin{bmatrix} a \\ b \\ c \end{bmatrix} = \begin{bmatrix} \frac{a}{a} = 1\\ \frac{b}{b} = 1\\ \frac{c}{c} =1 \end{bmatrix} \] One nuance is important to mention. I referred to a “single number” above. But even single numbers are vectors.8 Vectors are the most basic data type in R. This tells us something about the way vector arithmetic is working: the single number vector is being recycled for each element-wise operation.

8 From R Language Definition, section 2.1.1 Vectors: “Single numbers, such as 4.2, and strings, such as ‘four point two’ are still vectors, of length 1; there are no more basic types. Vectors with length zero are possible (and useful).”

To understand recycling, consider how a 2 item vector would be added to a 3 item vector. The situation can be represented abstractly like this:

\[ \begin{bmatrix} a \\ b \end{bmatrix} + \begin{bmatrix} c \\ d \\ e \end{bmatrix} \]

The output would be:

\[ \begin{bmatrix} a + c \\ b + d\\ a + e \end{bmatrix}\]

R would recycle the shorter vector and perform the calculation but with a warning: “longer object length is not a multiple of shorter object length.”9 In this case the “b” element of the first vector gets used only once, whereas “a” is recycled and used twice.

9 Keep in mind that warnings are not errors! An error prevents code from running, whereas a warning simply makes you aware of a potential problem.

Detail: Vector Arithmetic

Of course, we need numbers to do this sort of of vector arithmetic. But, as noted above, a vector in R does not need to be numbers. A distinction is helpful here. In math a vector is a sequence of numbers. In R a vector is a type of data structure.

Here is another dataset already included in R: the letters of the alphabet.

letters
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"

Can we add 1 to this vector of letters?

letters + 1
Error in letters + 1: non-numeric argument to binary operator

We get an error, which is pretty self-explanatory. The addition operator does not work with non-numeric data.

5.1 Practice Questions

Arithmetic operations performed on numbers can also be performed on collections of numbers called vectors.

  1. Type “rivers” in the console and press Return. The return values are the river lengths included in the data set.

  2. Assign the rivers vector to an object, r, for use in these questions. (It is often convenient to shorten the name of a data set to eliminate unnecessary typing.)

  3. In r the lengths of rivers are recorded in miles. Convert river lengths to kilometers (1 mile = 1.60934 kilometers).

  4. Convert river lengths to meters.

  5. Think: suppose you have a vector, \(a\), consisting in the values [1, 2]. What is the return value of 2 * \(a\)?

  6. Think: in an R vector, \(y\), consisting in [16, 25, 36, 49, 64], what is \(y_4\)?

  7. Think: what would R output for \(a\) + \(b\) , where \(a\) is the vector [1, 2] and \(b\) is the vector [7, 8, 9, 10]?

  8. Think: what would R output for \(a\) + \(b\) , where \(a\) is the vector [1, 2, 3] and \(b\) is the vector [7, 8, 9, 10]?

Show answers
## Question 1 -------------------------------

rivers

## Question 2 -------------------------------

r <- rivers

## Question 3 -------------------------------

r * 1.60934

## Question 4 -------------------------------

r * 1.60934 * 1000

## Question 5 -------------------------------

# Suppose you have a vector, a, consisting in the values [1, 2]. 
# What is the return value of 2 * a?  Answer: [2 * 1, 2 * 2] = [2, 4]

## Question 6 -------------------------------

# Answer: 49.  This the fourth element of the vector y.

## Question 7 -------------------------------

# What would R output for a + b, where a is the vector [1, 2] and 
# b is the vector [7, 8, 9, 10]?  Remember: the shorter vector 
# will get recycled. 

# Answer: [1 + 7, 2 + 8, 1 + 9, 2 + 10] = [8, 10, 10, 12]

## Question 8 -------------------------------

# What would R output for a + b , where a is the vector [1, 2, 3] 
# and b is the vector [7, 8, 9, 10]? 

# Answer: [1 + 7, 2 + 8, 3 + 9, 1 + 10] = [8, 10, 12, 11]

6 Functions

Let’s visualize river lengths by creating a histogram.10

10 Recall that a histogram is a frequency plot in which the height of the bars corresponds to the number of observations in the interval on the horizontal axis represented by the bar.

hist(rivers)

The plot will show up in the plot tab of the Files pane in the lower right quadrant of RStudio.

hist() is an example of a R function. It takes a vector of numbers as an argument and then (in this case) prints the histogram. The resulting plot provides insight into river lengths in North America, showing that the majority of rivers are shorter than 1000 miles, with the most common length less than 500 miles. There is at least one extreme observation—the Mississippi?— on the right.

To see another function in action, let’s calculate median river length using median().11 (Using a function is also known as “calling a function”. )

11 Recall that the median is the middle observation in the sorted data.

median(rivers)
[1] 425

In R, functions are often named exactly as you’d expect. Here is how we calculate the mean:

mean(rivers)
[1] 591.1844

If we know the formula for the mean we can easily replicate this result using other aptly named functions.

sum(rivers) / length(rivers)
[1] 591.1844
  • sum() adds the values in a numeric vector.
  • length() counts the number of items in a vector.
Detail: Computing the Mean

Why does this code work? The formula for the sample mean, \(\bar{x}\) (pronounced “x bar”), is:

\[\bar{x}= \frac{1}{n}\sum_{i=1}^{n}x_{i}\]

where \(n\) is the total number of observations and \(x_i\) represents the index of each individual observation. That funny E symbol, called sigma or the summation symbol, indicates that all the observations, the \(x_i\), should be summed up, from index position \(i=1\) to \(n\). The first \(x\) observation would be indexed as \(x_1\) but all the individual observations can be abstractly represented as \(x_i\).

Calling the sum()function has the effect of adding up the \(x_i\) values in the vector, the river lengths, performing the work of the summation symbol, while length() calculates \(n\), the number of observations.

Most functions have multiple arguments. For example, hist() has an additional argument, breaks, that allows us to adjust the number of bins in the histogram.12

12 Note that the number of bins is not exactly the number of bars in this case since, as you can see, some bins—defined by intervals on the horizontal axis—are empty.

hist(rivers, breaks = 20)

This plot gives us more detail, higher resolution.

But: how did hist() know the number of bins to use earlier, before we included the breaks argument explicitly? Functions in R include default settings for arguments. hist() was using the default for breaks until we explicitly set a value. In general, R has useful default settings—the mark of good software.

How would we discover the arguments to a function, along with the default settings, in case we wanted to make adjustments?

That is the next topic.

6.1 Practice Questions

It is no exaggeration to say that R is nothing more than a (very large) set of functions. Coding in R consequently requires that you learn to use functions.

  1. Open RStudio. Type ?mean in the console and press Return. What are the default arguments to this function?

  2. Think. How would including the argument trim = .1 impact the calculation of a mean?

  3. Run this code in the console: mean(.1, rivers). It produces an error. Why? Does the error message make sense? How would you fix the error?

  4. Consider a vector, \(v\), defined as [1, 2, 3, NA]. (In data analysis NA usually means “missing.”) Calculating the mean of v with mean(v) produces NA as the return value. How would you adapt this function call, based on the information in the help pages, to ignore the NA and calculate the mean of the non-missing items in the vector?

Show answers
## Question 1 -------------------------------

# The default arguments are x, trim and na.rm.  x is a numeric or 
# logical vector.  The default value for trim is 0, which means 
# that no trimming will be performed.  The default argument for na.rm 
# is FALSE, which means that NAs will not be removed.

## Question 2 -------------------------------  

# The trim argument is used to trim a certain proportion of observations 
# from each end of the vector before calculating the mean.  For
# trim = .1, the 10% of observations from each end of the vector will 
# be removed before calculating the mean.

## Question 3 -------------------------------

# This produces an error because the first argument is not a vector 
# of numbers. And the trim argument should be a single number, not a vector. 
# The code can be revised as follows:

mean(rivers, .1)

## Question 4 -------------------------------

# The vector, v, is defined as [1, 2, 3, NA]. mean(v) produces NA
# as the return value. to calculate the mean of the non-missing 
# items in the vector, we can use the na.rm argument and set it to 
# TRUE: mean(v, na.rm = TRUE).

7 Getting Help in RStudio

Type ?hist in the console and press return.

The ? command opens the Help tab in the Files pane in RStudio’s lower right quadrant and displays the help file for the function, with multiple sections. This information is very instructive. In the Usage section, for example, we can see that only one argument to the function, x, does not already have a defined default value indicated by the equals sign.

Help File for hist()

This is why, incidentally, we could get away with the simple function call hist(river) above. Although we did not explicitly include the breaks argument, the function automatically defaulted to a method called “Sturges” for producing the number of bars.13 The default settings kicked in for all the other arguments also, the details of which are listed in the Arguments section.

13 What is that method exactly? I’m not sure, but if you look further down in the help file under Details there is a link with additional information.

There are a lot of arguments to this function! In general, R functions are designed to be highly customizable— the arguments offer fine-grained control over outputs—while also remaining user friendly with sensible defaults. Feel free to keep things simple and stick with the defaults for now.

Note that function arguments are positional. For example, suppose we do not explicitly define the breaks argument to hist(), but simply supply a value in the second position:

hist(rivers, 20)

This code works because R expects the breaks argument in the second position. Similarly hist(rivers) works without needing to specify x = rivers because the function expects the data argument in the first position. By contrast, this code will not work:

hist(20, rivers)
Error in hist.default(20, rivers): some 'x' not counted; maybe 'breaks' do not span range of 'x'

However, we can fix this error if we name the arguments. Naming overrides position in function calls.14

14 Note that in these lessons I will usually rely on position rather naming to define the x argument for functions like hist(). This is because I think hist(rivers) is sufficiently clear, and a little less cluttered than hist(x = rivers). Likewise for routine summary statistics: I’ll usually write mean(rivers) rather than mean(x = rivers).

hist(breaks = 20, x = rivers)

One final point for now. All function help files in R include an Examples section with code illustrating how to use the function. You can click “Run examples” in most help files to bring up a document that displays code and results, or you can simply cut and paste that code into the console and run it by pressing Return.

8 Logical Vectors

How many North American rivers are longer than 1000 miles? Here is code to answer that question:

sum(rivers > 1000)
[1] 16

How is this working? First, let’s examine what is happening within the parentheses:

rivers > 1000
  [1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
 [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
 [25]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [37] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [49] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [61] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
 [73] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
 [85] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [97] FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[109] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE
[121]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[133] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE

So far, we have worked with numeric and character vectors.15 This output is an example of a logical vector, created by a logical condition with the help of the logical operator >. The logical operator essentially asks a question about each item in rivers: is it greater than 1000? The question has a yes or no answer which R casts as a logical value: TRUE or FALSE (which can be abbreviated as T or F).

15 Numeric vector: [1, 2, 3, …], where the items include the machine representation of any real number. Character vector: [“a,” “b,” “c,” …], where the items are letters or words, or, indeed, any object contained within quotation marks. For example, this is also a character vector: [“1”, “2”, “3”].

Here is a list of the main logical operators in R that will produce logical values:

  • >: greater than.
  • <: less than.
  • ==: equal to.
  • !=: not equal to.
  • >=: greater than or equal to.
  • <=: less than or equal to.
  • !x: not x.
  • x | y: x OR y.
  • x & y: x AND y.

Importantly, logical values in R have an unexpected but useful characteristic: T is treated as 1, F as 0. That is why the code above works: R sums up the Ts in the logical vector produced by rivers > 1000. This characteristic—that logicals are numbers— opens up an important strategy for extracting information from logical vectors using math functions.

Example: are any rivers exactly 1000 miles long?

sum(rivers == 1000)
[1] 1

As it turns out—surprisingly—one river is indeed exactly 1000 miles.

Another example: what proportion of rivers are longer than 1000 miles?16

16 Remember: A proportion is a fraction expressing the relative frequency of an event, and is scaled between 0 and 1. A percentage expresses the same information but is scaled between 0 and 100. To convert a proportion to a percentage simply multiply by 100.

sum(rivers > 1000) / length(rivers)
[1] 0.1134752

Or, more simply:

mean(rivers > 1000)
[1] 0.1134752

The mean of a logical vector is simply the proportion of Ts.

How many rivers are longer than 2000 miles or less than 200?

sum(rivers > 2000 | rivers < 200)
[1] 5

8.1 Practice Questions

Logical vectors are created by a logical condition with the help of the logical operator. They can be used to help answer analytic questions.

Using the rivers dataset, answer the following questions:

  1. How many rivers are longer than 1500 miles?

  2. How many rivers are shorter than 100 miles?

  3. How many rivers are above average in length?

  4. What proportion of rivers are above average in length?

  5. What percentage of rivers are above average in length?

  6. What percentage of rivers are longer than the median length?

Show answers
## Question 1 -------------------------------

sum(rivers > 1500) 

# or, using ! to reverse a result:

sum(!(rivers < 1500))

## Question 2 -------------------------------

sum(rivers < 100) # or

sum(!(rivers > 100))

## Question 3 -------------------------------

sum(rivers > mean(rivers))

## Question 4 -------------------------------

sum(rivers > mean(rivers)) / length(rivers) 

# or, mean() will do the same calculation:

mean(rivers > mean(rivers))

## Question 5 -------------------------------

sum(rivers > mean(rivers)) / length(rivers) * 100 # or

mean(rivers > mean(rivers)) * 100

## Question 6 -------------------------------

sum(rivers > median(rivers)) / length(rivers) * 100 # or

mean(rivers > median(rivers)) * 100

# This should be right around 50%.  Why? Think about the definition 
# of median. In sorted data with an odd number of observations it is 
# the middle observation.  For an even number of observations, it is 
# the number midway between the  two middle observations.

9 Subsetting Vectors

We have seen how to do calculations with logical vectors. We can also use them to subset or filter data. This is an extremely common and important task in data analysis.

For example, earlier we calculated the number of rivers that are longer than 1000 miles. But what if we wanted to know the lengths of those rivers? This would involve, in effect, returning a subset of the data based on a logical condition: rivers > 1000. We will use square bracket notation for this task.

Before getting into complicated subsetting, let’s see how the square bracket notation works.

rivers[1]
[1] 735

This code creates a subset of the data with only the first observation. The number in square brackets is the item’s index, its position in the vector. Another example: rivers[2] creates a subset that includes only the observation in the second position.

rivers[2]
[1] 320

Suppose we’d like to return a subset with more than one item. We could use the c() function to return the river lengths at indices 1 and 2.17 The “c” stands for “concatenate” because the function concatenates (or, more familiarly, combines) items into a vector.

17 “Indices” is just the plural of “index,” the position of an item within a vector, which was discussed above.

rivers[c(1, 2)]
[1] 735 320

Equivalently we could use “colon” notation, which is convenient when indexing a sequence of observations:

rivers[1:2]
[1] 735 320

Suppose, instead, we wanted to retrieve the indices of observations based on a logical condition. We could use the which() function:

which(rivers > 1000)
 [1]   7  23  25  66  67  68  69  70  83  89  98 101 114 115 121 141

These are not observations from the data, but the indices of observations. To get the river lengths themselves we would then subset the data using those indices:

rivers[which(rivers > 1000)]
 [1] 1459 1450 1243 2348 1171 3710 2315 2533 1306 1054 1270 1885 1100 1205 1038
[16] 1770

These are the river lengths that satisfy the condition rivers > 1000.

We can simplify this code, however, by using a logical vector directly to do the subsetting.

rivers[rivers > 1000]
 [1] 1459 1450 1243 2348 1171 3710 2315 2533 1306 1054 1270 1885 1100 1205 1038
[16] 1770

Same result. In the background R has used the logical vector produced by rivers > 1000—and in particular the index of each TRUE—to subset the data in exactly the way we did previously when we supplied the indices directly using which().

One last example. Which river lengths are greater than 2000 or less than 200?

rivers[rivers > 2000 | rivers < 200]
[1]  135 2348 3710 2315 2533

If we wanted to count the number of observations in this subset we could use the length() function:

length(rivers[rivers > 2000 | rivers < 200])
[1] 5

9.1 Practice Questions

Subsetting data is a common and important task in data analysis.

  1. Select the first 10 observations in rivers using square brackets with colon notation. Now do the same subsetting using square brackets with the c() function. Which method is easier?

  2. Select the the first 10 observations in rivers and the 100th observation using square bracket notation. Use colon notation and the c() function together.

  3. Define a vector, \(v\), as the squared elements of the sequence 1:10: v <- 1:10 * 1:10. Write code to return the indices of the observations in \(v\) greater than 50. (Also, think: why does 1:10 * 1:10 work to produce v?)

  4. Use square bracket notation to subset \(v\) to include observations greater than 50. Use three different methods, supplying the indices:

    • by hand with either the c() function or colon notation.
    • with the which() function.
    • with a logical vector.
  5. Write code to calculate how many river lengths in rivers are greater than 2000 miles or less than 500.

Show answers
## Question 1 -------------------------------

rivers[1:10] # vs.

rivers[c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)]

## Question 2 -------------------------------

rivers[c(1:10, 100)]

## Question 3 -------------------------------

v <- 1:10 * 1:10 # and

which(v > 50)

## Question 4 -------------------------------

v[8:10] # or

v[which(v > 50)] # or

v[v > 50]

## Question 5 -------------------------------

sum(rivers > 2000 | rivers < 500) # or

length(rivers[rivers > 2000 | rivers < 500]) # but, note, this won't work:

length(rivers > 2000 | rivers < 500)

10 Data Frames

So far we have discussed vectors, which are one dimensional data structures consisting in a collection of observations. R includes several two-dimensional data structures also.

Matrices are like vectors, in that the elements have the same data type (numeric, character, or logical), but with two dimensions: they have rows and columns.

Data frames also have rows and columns, like matrices, but are more flexible, allowing different data types. For this reason data frames are probably the most used data structure in R for doing statistics and data analysis. They have the following characteristics:

  • They are “square”: all rows have the same number of columns, and all columns have the same number of rows.
  • The columns are vectors. This means that the observations in each column all have the same data type: numeric, character or logical.
  • Each column can have a different data type.
  • The rows are not vectors, due to the point above. If columns can have different data types then rows cannot be vectors. Rows in a data frame are in fact themselves data frames—single row data frames.

These distinctions may all sound complicated but I think you’ll find that working with data frames is pretty intuitive. In fact, you can think of a data frame as R’s version of a spreadsheet.

Let’s look at an example data frame, mtcars, which contains information on cars from the 1970s.18 Here are some useful functions for exploring data frames:

18 Remember: type ?mtcars in the console to get the help pages on this data set. Included there is a data dictionary: a collection of metadata about the dataset, with the name and description of each column, as well as its type and format. Metadata just means: data about the data.

  • head()
  • summary()
  • str()

The head() function displays the first 6 rows of the data (using the default n = 6).

head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

What appears to be the first column, with the names of the cars, is actually not a column. These are row names. (For what its worth, I almost never use row names, preferring instead to store row information explicitly in a column.)

Note: “dbl” = Numeric

If you run head(mtcars) in Rstudio you will notice that each column in the snapshot includes a label with the data type listed as “dbl.” (The label is left out in the HTML document you are reading.) “dbl” stands for “double,” which stands for “double-precision floating-point number,” a data type that can represent very large or very small fractional numbers with a high degree of accuracy. It typically uses 64 bits of memory to store a numerical value, which allows it to represent a much wider range of numbers than other data types that use fewer bits, roughly \(10^{-308}\) to \(10^{308}\). In R “dbl” is basically a synonym for “numeric.”

The str()function provides helpful information about the structure of a data frame. (“str” stands for “structure.”)

str(mtcars)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

This is a general function (it works also with vectors) that usefully displays the structure and dimensions of the data, summarizes the data type of each column, and prints the first 10 observations.

The summary() function provides a five number summary19 of the columns.

19 The five number summary describes numeric data using five values: the minimum value, the first quartile (25th percentile), the median, the third quartile (75th percentile), and the maximum value. These provide a quick and easy way to understand the spread of numeric data.

summary(mtcars)
      mpg             cyl             disp             hp       
 Min.   :10.40   Min.   :4.000   Min.   : 71.1   Min.   : 52.0  
 1st Qu.:15.43   1st Qu.:4.000   1st Qu.:120.8   1st Qu.: 96.5  
 Median :19.20   Median :6.000   Median :196.3   Median :123.0  
 Mean   :20.09   Mean   :6.188   Mean   :230.7   Mean   :146.7  
 3rd Qu.:22.80   3rd Qu.:8.000   3rd Qu.:326.0   3rd Qu.:180.0  
 Max.   :33.90   Max.   :8.000   Max.   :472.0   Max.   :335.0  
      drat             wt             qsec             vs        
 Min.   :2.760   Min.   :1.513   Min.   :14.50   Min.   :0.0000  
 1st Qu.:3.080   1st Qu.:2.581   1st Qu.:16.89   1st Qu.:0.0000  
 Median :3.695   Median :3.325   Median :17.71   Median :0.0000  
 Mean   :3.597   Mean   :3.217   Mean   :17.85   Mean   :0.4375  
 3rd Qu.:3.920   3rd Qu.:3.610   3rd Qu.:18.90   3rd Qu.:1.0000  
 Max.   :4.930   Max.   :5.424   Max.   :22.90   Max.   :1.0000  
       am              gear            carb      
 Min.   :0.0000   Min.   :3.000   Min.   :1.000  
 1st Qu.:0.0000   1st Qu.:3.000   1st Qu.:2.000  
 Median :0.0000   Median :4.000   Median :2.000  
 Mean   :0.4062   Mean   :3.688   Mean   :2.812  
 3rd Qu.:1.0000   3rd Qu.:4.000   3rd Qu.:4.000  
 Max.   :1.0000   Max.   :5.000   Max.   :8.000  

This function will produce different output for different kinds of data. For example, columns with character data will be summarized with a count of the total observations. Like str() the summary() function is a general function that works with vectors also.

summary(rivers)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  135.0   310.0   425.0   591.2   680.0  3710.0 

It is a good idea at the beginning of a project to use these three functions to inspect your data as a first step towards understanding it.

Lastly, one of the amenities offered by RStudio is the Data Viewer20—a spreadsheet-like interface for viewing and exploring data frames. To pull up the Data Viewer simply type View() in the console with the name of the data frame as an argument. For example, to open the Data Viewer for mtcars type View(mtcars) in the console.

20 Here is a detailed description of the Data Viewer.

10.1 Practice Questions

Data frames are two-dimensional data structures commonly used in R for doing statistics and data analysis.

Let’s investigate a investigate a macroeconomic data set, longley. It includes 7 economic variables observed yearly from 1947 to 1962:

  • GNP.deflator: GNP implicit price deflator (1954=100)
  • GNP: Gross National Product.
  • Unemployed: number of unemployed.
  • Armed.Forces: number of people in the armed forces.
  • Population: “noninstitutionalized” population older than 14 years of age.
  • Year: the year.
  • Employed: number of people employed.
  1. Save longley in an object l for the purposes of answering these questions.
  2. View the first 6 rows of l.
  3. Write code to get an overview of the structure and dimensions of the data.
  4. Get a five number summary of each column.
  5. Load longley in RStudio and open up the Data Viewer to see the data set as a spreadsheet.
Show answers
## Question 1 -------------------------------

l <- longley

## Question 2 -------------------------------

l[1:6]

## Question 3 -------------------------------

str(l)

## Question 4 -------------------------------

summary(l)

11 Subsetting Data Frames

Subsetting or filtering data frames is a common and important task.

Previously we saw how to subset vectors. To return the first observation in the rivers data, for example, we would type rivers[1] in the console, placing that observation’s index within square brackets. Or, to return all the river lengths greater than 1000 miles we would type rivers[rivers > 1000]. The condition specified within the square brackets evaluates as a logical vector. R uses the location of the TRUEs in that vector to index the observations.

For vectors, then, we index in one dimension: data[the observations we want].

For data frames, we index in two dimensions: data[the rows we want, the columns we want]. The first slot within the square brackets, before the comma, specifies the rows to return, while the second specifies the columns. All the tactics you learned for vectors work also for data frames

To demonstrate we’ll use mtcars. As a reminder, here is snapshot of the data:

head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Which observation is in row 1 of column 1? (This is mpg for the Mazda RX4.)

mtcars[1, 1]
[1] 21

What are the first 5 observations in column 1? Use colon notation.

mtcars[1:5, 1]
[1] 21.0 21.0 22.8 21.4 18.7

What are the first 5 observations in columns 1 and 3? Use colon notation along with the c() function.

mtcars[1:5, c(1, 3)]
                   mpg disp
Mazda RX4         21.0  160
Mazda RX4 Wag     21.0  160
Datsun 710        22.8  108
Hornet 4 Drive    21.4  258
Hornet Sportabout 18.7  360

What are all the observations in row 1? Leave the column slot empty to select all columns.

mtcars[1, ]
          mpg cyl disp  hp drat   wt  qsec vs am gear carb
Mazda RX4  21   6  160 110  3.9 2.62 16.46  0  1    4    4

What are all observations for column 1? Leave the row slot empty to select all rows.

mtcars[ , 1]
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4

Notice the difference between these last two sets of results. The first column is a vector of mileage observations, while the first row is a data frame with columns containing information on the Mazda RX4. This is because, as discussed in the previous lesson, a single column in a data frame is a vector, while a single row is a data frame.

To extract an individual column it is often convenient to use dollar sign notation, where the $ stands for column:

mtcars$mpg
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4

Incidentally, we can accomplish the same task using the column name (in quotes) within square brackets.21

21 To select just the mpg column I used double quotation marks: mtcars[ , "mpg"]. But single quotation marks would have worked also. In R single and double are interchangeable.

mtcars[ , "mpg"]
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4

Often, we will want to use logical conditions to subset a data frame. The strategy is analogous to what we did earlier with vectors when we used logical operators to define the logical condition for keeping rows.

Which cars have mpg greater than 30?

mtcars[mtcars$mpg > 30, ]
                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2

What is mpg for the heaviest car? We’ll use the max() function to pick out the maximum weight.

mtcars[mtcars$wt == max(mtcars$wt), "mpg"]
[1] 10.4

What is mpg for the lightest car? We’ll use the min() function to pick out the minimum weight.

mtcars[mtcars$wt == min(mtcars$wt), "mpg"]
[1] 30.4

We can also subset a data frame based on multiple conditions using logical operators such as & or |.

Which cars have mpg greater than 30 or wt less than 2?

mtcars[mtcars$mpg > 30 | mtcars$wt < 2, ]
                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4 79.0  66 4.08 1.935 18.90  1  1    4    1
Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2

Which cars have mpg greater than 30 and wt less than 2?

mtcars[mtcars$mpg > 30 & mtcars$wt < 2, ]
                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2

How many cars have both these characteristics? Of course, here we can just count the number of rows in the filtered data set. But in other situations we might want to write code to get this information. The nrow() function (standing for “number of rows”) will do the counting for us.

nrow(mtcars[mtcars$mpg > 30 & mtcars$wt < 2, ])
[1] 3

There are obviously a lot of possibilities for combining logical conditions to subset a data frame. Hopefully these examples give you some sense of how the process works. To master subsetting in R requires practice!

11.1 Practice Questions

Subsetting data frames is a common task.

Using longley:

  1. Again, save longley as l.
  2. The year with the highest GNP.
  3. The year with the lowest GNP.
  4. The row with the smallest value for Unemployed.
  5. The year and the population when GNP was the largest or when Unemployed was the largest.
  6. The number of years in which Employed was greater than 65.
Show answers
## Question 1 -------------------------------

l <- longley

## Question 2 -------------------------------

l[l$GNP == max(l$GNP), "Year"]

## Question 3 -------------------------------

l[l$GNP == min(l$GNP), "Year"]

## Question 4 -------------------------------

l[l$Unemployed == min(l$Unemployed), ]

## Question 5 -------------------------------

l[(l$GNP == max(l$GNP)) | (l$Unemployed == max(l$Unemployed)) , c("Year", "Population")]

## Question 6 -------------------------------

nrow(l[l$Employed > 65, ]) 

# Note, this does not work to answer the question:
length(l[l$Employed > 65, ]) 

# But this does:
length(l[l$Employed > 65, "Year"])

12 Visualizing Data

Plotting is a powerful way to understand relationships in data.

Earlier we used hist() to create a frequency plot of river lengths. This plot choice was appropriate because rivers is one dimensional: we were examining the frequency of observations in the vector.

hist(rivers)

Working with data frames allows us to explore data in two-dimensions, answering questions such as: is there a relationship between the weight of a car and its gas mileage? (Some of our subsetting in the previous lesson suggested this.) The plot() function in R will create a scatterplot used to display the relationship between two quantitative variables.

What is a Variable?

We will use the term “variable” somewhat interchangeably with “column” and “data” to mean a set of observations contained in a data set. The meaning is different than in algebra where a variable is used to represent an unknown numeric value. In data analysis the term derives from the fact that observations vary within the data. For example, mpg and wt are characteristics that vary for every car in mtcars. If a variable is numeric, then we call it a quantitative variable. If, instead, the variable represents a type or category, where the data is divided into groups or categories with a limited number of possible values, then we call it a categorical variable. For example, survey respondents might be asked to rate their satisfaction with a particular service as “satisfied,” “neutral” or “not satisfied.” This rating would produce categorical data since satisfaction is organized into a limited number of categories. In mtcars the number of cylinders is an integer: 4, 6 or 8. But if we think of these numbers as essentially representing different engine types, then the data could plausibly be thought of as categorical. Decisions about how to represent information in the data are not always clear cut.

Back to scatterplots. The data is plotted as a “scatter” of points on a coordinate grid, with the horizontal axis (or \(x\)-axis) representing one variable and the vertical axis (or \(y\)-axis) representing the other. The position of each point is determined by the \(x\)-\(y\) coordinates of the two variables for a particular observation. Take the example of a car in mtcars. Each car has a wt-mpg pair. In a scatterplot showing the relationship between weight and mileage the points thus represent each car’s wt-mpg pair. To create this scatterplot we use the wt and mpg vectors for the x and y arguments to plot().22

22 Note that by convention the phenomenon you want to explain or understand in a plot goes on the \(y\)-axis. Here it makes sense to put mpg on the \(y\)-axis because car weight can be thought of as explaining gas mileage. Weight is a cause, mileage the effect. It would be strange to explain car weight with gas mileage.

plot(x = mtcars$wt, y = mtcars$mpg)

Plots should always be titled. We can add a title using the main argument:

plot(mtcars$wt, mtcars$mpg, main = "Scatterplot of wt vs. mpg")

And yes, there definitely seems to be a generally negative relationship between weight and miles per gallon: as wt goes up, mpg goes down.

What about the relationship between number of cylinders and gas mileage?

plot(mtcars$cyl, mtcars$mpg, main = "Scatterplot of cyl vs. mpg")

This also shows a negative relationship: as cyl goes up, mpg goes down. This makes sense, since more cylinders use more gas. But there’s something strange about this plot, in that the observations of cyl are overplotted, clustered at only 4, 6, or 8. In mtcars these data are numeric, consisting in counts of cylinders. But, as discussed above, we could think of the counts as essentially representing different engine types, in which case the data would be categorical. The go-to plot for comparing categorical and numeric data is the boxplot.23 It is better suited than a scatterplot for showing the distribution of numeric data at different levels of a categorical variable.24

23 Check out the entry at Wikipedia to learn more about boxplots. There is also an entry on scatterplots.

24 The term “distribution” has a somewhat technical meaning in statistics. We will typically use it to refer to the observed values of a variable and how often they occur. Of course, a histogram is the most common plot for visualizing a variable’s distribution. But a boxplot also shows the distribution, since the box represents the most frequent observations.

boxplot(formula = mpg ~ cyl, data = mtcars, main = "Boxplot of cyl vs. mpg")

The first argument to boxplot() uses the formula syntax that is common in R. The tilde (~) means “explained by.” And rather than supplying the vectors of observations using dollar sign notation, as we did above when using plot(), we instead name the columns and identify the source with the data argument. (Remember, if you need help with the syntax: ?boxplot.)

The box represents the most frequent observations in the data, the middle 50%, extending from the first quartile to the third quartile.25 The bars, extending above and below the box, known as “whiskers,” show the tails of the data up to 1.5 times the width of the box or, if smaller, the minimum/maximum in the data. The middle line is the median.

25 What are quartiles? Arrange the data from smallest to largest. The first quartile will be the observation that is 25% of the way through the data from the smallest to the largest, the second quartile (or median) and third quartile will be the observations that are, respectively, 50% and 75% of the way from the smallest to largest.

The plot shows us that 4 cylinder cars have the greatest variability in mileage (this box is the widest), and that there is strong negative relationship between the number of cylinders and mileage: as cyl goes up, mpg goes down.

The fact that the syntax for creating a scatterplot is different than for a boxplot illustrates one of the frustrations of base R plotting. Our next foray into plotting will use a different system known as ggplot2.

12.1 Practice Questions

Plotting is a powerful way to understand relationships in data.

Using longley (and making sure to title your plots) answer the following questions:

  1. Again, save longley as l.
  2. Create a histogram of the GNP column.
  3. Create a scatterplot showing the relationship between Unemployed and GNP. Think: which variable should go on the x-axis in which should go on the y-axis? Think: how would you describe the relationship?
  4. Plot the relationship between Population and Armed.Forces, also with a scatterplot. Think: which variable should go on the x-axis in which should go on the y-axis? Think: what is a possible explanation for the pattern in the plot?
  5. Think: would a boxplot work to show the relationship between Year and Population? Why or why not?

Let’s work with another dataset in R, iris, which gives the measurements in centimeters of the variables Sepal.Length, Sepal.Width, Petal.Length, Petal.Width for 50 flowers from each of 3 species.

  1. Type summary(iris) in the console. Notice that the result is a 5 number summary for the numeric variables, and a count of observations at each level of Species, a categorical variable.
  2. Create a plot to answer the question: Is there a relationship between petal length and width?
  3. Does the distribution of Petal.Width differ for species? Create a boxplot to answer this question.
Show answers
## Question 1 -------------------------------

l <- longley

## Question 2 -------------------------------

hist(l$GNP, main = "Histogram of GNP")

Show answers
## Question 3 -------------------------------

plot(l$Unemployed, l$GNP, 
     main = "Scatterplot of GNP vs number of unemployed")

Show answers
## Question 4 -------------------------------

plot(l$Population, l$Armed.Forces)

Show answers
## Question 5 -------------------------------

boxplot(Year ~ Population, data = l) # This does not work!

Show answers
## Question 6 -------------------------------

summary(iris)

## Question 7 -------------------------------

plot(iris$Petal.Length, iris$Petal.Width, 
     main = "Scatterplot of petal length vs petal width")

Show answers
## Question 6 -------------------------------

boxplot(Petal.Width ~ Species, data = iris, 
        main = "Distribution of petal width by species")

13 Factors

Factors are a special data type in R for representing categorical data. They look like character data — text within quotation marks—but they are stored internally in R as numbers. Consider Species in the iris data set.

str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

Here the names of the species are in quotation marks (listed as the “levels” of the factor) but the observations themselves are numbers: 1, 1, 1 ….

To understand how factors differ from character data, consider the difference between, say, a property’s address and its type. Address is a unique identifier, one that could take on a potentially infinite number of possibilities. Non-repeating data like address is best represented as character data. By contrast, there are only a limited number of options for recording property type such as condo, apartment or single family home. Categorical data like this, in which all possible values fall into a relatively small number of categories, is best represented using factors.

Create factors using the factor() function.

factor(c("a","b","c"))
[1] a b c
Levels: a b c

Numbers can also be made into factors.

factor(c(3, 2, 1))
[1] 3 2 1
Levels: 1 2 3

In these examples, R has chosen a default ordering of the factor (based on numeric and alphabetic priority). But we can change this using the levels argument:

factor(c("a","b","c"), levels = c("c", "b", "a"))
[1] a b c
Levels: c b a

We will come back to factors again in later lessons.

13.1 Practice Questions

Factors are a special data type for representing categorical data in R.

Suppose that guests at an Airbnb rental are asked to fill out a survey. The survey has a question about the guest’s level of satisfaction, with two possible answers: “satisfied” or “not satisfied.” The next question asks: “Please explain your answer.”

  1. Think: what is the best data type for encoding answers to the first question?
  2. Think: what is the best data type for the second question?
  3. Turn quality into a factor variable, assign it to a new object, quality_fct, and show that the new variable is a factor. (Notice that the factor levels have been set using the default alphabetic ordering.)
  4. Again turn quality into a factor variable, assign it to a new object, quality_fct, but change the factor levels to be: poor, average, good. Show that this transformation was successful.
  5. Again turn quality into a factor variable, assign it to a new object, quality_fct, but change the factor levels to be: poor, average, excellent. Check the transformation. Think: why are some of the observations in quality_fct now listed as NA?
Show answers
## Construct the quality vector:

quality <- c("good", "good", "poor", "good", "average", "poor","poor", "average")


## Question 1 ------------------------------- 

# Factor.  The answers consist in categorical data, featuring 
# a small number of repeating categories. 

## Question 2 -------------------------------

# Character.  The second question is open-ended, and the answers
# consist in unique text strings.

## Question 3 -------------------------------

quality_fct <- factor(quality)

str(quality_fct)

## Question 4 -------------------------------

quality_fct <- factor(quality, levels = c("poor", "average", "good"))

str(quality_fct)

## Question 5 -------------------------------

quality_fct <- factor(quality, levels = c("poor", "average", "excellent"))

str(quality_fct)

# There are NAs listed because the levels do not match the data.  R does not know
# what to do with the "good" observations, so it lists them as missing.

14 The tapply() Function

Suppose you would like to find average miles per gallon for cars with different numbers of cylinders. Well, we could subset the data for each cylinder category and then calculate the mean, like this:

mean(mtcars[mtcars$cyl == 4, "mpg"])
[1] 26.66364
mean(mtcars[mtcars$cyl == 6, "mpg"])
[1] 19.74286
mean(mtcars[mtcars$cyl == 8, "mpg"])
[1] 15.1

That works perfectly well, but we could also calculate the conditional means more compactly using the tapply() function. Observe:

tapply(X = mtcars$mpg, INDEX = mtcars$cyl, FUN = mean)
       4        6        8 
26.66364 19.74286 15.10000 

How did this work? In English: split the vector mtcars$mpg into groups according to the unique values in mtcars$cyl, then “apply” the mean to each group. (Hence the name of the function: “tapply” stands for “table apply.”) These are conditional means because they are conditional on the number of cylinders. (We could calculate an unconditional mean for miles per gallon with mean(mtcars$mpg).)

We can use any function in the FUN argument to tapply(), as long as it works with vectors. For example, how many cars have 4, 6, and cylinders, respectively? (For brevity we will omit the argument names.)

tapply(mtcars$mpg, mtcars$cyl, length)
 4  6  8 
11  7 14 

What is the standard deviation of mpg for different values of cyl? Use the sd(), the R function for calculating standard deviation.

tapply(mtcars$mpg, mtcars$cyl, sd)
       4        6        8 
4.509828 1.453567 2.560048 

Median?

tapply(mtcars$mpg, mtcars$cyl, median)
   4    6    8 
26.0 19.7 15.2 

Note that this would not work:

tapply(mtcars$mpg, mtcars$cyl, nrow)
$`4`
NULL

$`6`
NULL

$`8`
NULL

Why not? nrow() counts the number of rows in a data frame, but mtcars$mpg—to which the function is being applied— is a vector.

The tapply() function is very efficient and should give you some sense of what is possible in R.

14.1 Practice Questions

tapply() splits a vector into groups according to the unique values in a grouping variable, and then “applies” a function (usually to calculate a summary statistic) to each group.

Using the iris dataset calculate mean, median, and standard deviation for Sepal.Length, Sepal.Width, Petal.Length, and Petal.Width by species. (That is, you should find 3 summary statistics for each characteristic for each species.)

Show answers
## Summary statistics for sepal length by species

tapply(iris$Sepal.Length, iris$Species, mean)

tapply(iris$Sepal.Length, iris$Species, median)

tapply(iris$Sepal.Length, iris$Species, sd)

## Summary statistics for sepal width by species

tapply(iris$Sepal.Width, iris$Species, mean)

tapply(iris$Sepal.Width, iris$Species, median)

tapply(iris$Sepal.Width, iris$Species, sd)

## Summary statistics for petal length by species

tapply(iris$Petal.Length, iris$Species, mean)

tapply(iris$Petal.Length, iris$Species, median)

tapply(iris$Petal.Length, iris$Species, sd)

## Summary statistics sepal width by species

tapply(iris$Petal.Width, iris$Species, mean)

tapply(iris$Petal.Width, iris$Species, median)

tapply(iris$Petal.Width, iris$Species, sd)

15 R Scripts

We’ve covered a lot of ground so far. Great job!

Let’s switch gears briefly and introduce some of the important tools available in RStudio.

So far, you’ve been running commands in the console. This works fine up to a point. But you may have noticed that when you open a new RStudio session the code and results from the previous session have disappeared. As you get into more complicated work you might want to save your code. You can do this with an R script—a plain text file with the extension “.R” that contains R code. Script files can easily be saved, updated and shared.

To create a script file in RStudio, go to the top menu and click File >>> New File >>> R Script. This will automatically bring up an untitled R script in the Document pane, the window immediately above the console in the upper left quadrant.

An R Script File

To run a line of code in the script, position the cursor on that line and press Control-Return.26 (This is similar to copying and pasting the code from the file and running it in the console.) Results will appear in the console.

26 Note that you can also run the code by clicking the Run button in the upper right menu immediately above the Document pane.

27 Why should you make comments in a script file? Comments help a collaborator—or your future self!—understand your code. Ideally the code you write will be easy to read (that is one of the goals of these lessons) but it is best practice is to add comments to ensure interpretability.

To create a comment in the script use a hashtag (#). R will not attempt to execute any text after a hashtag.27

Try it. Create a script file using the directions above. Type the code below into your script, then position your cursor on the first line and press Control-Return twice.

# A simple addition example
2 + 2   
[1] 4

You should see [1] 4 appear in the console. (Notice that the comment was indeed ignored by R.)

That’s it. You’ve created your first R script. Any code you’d like to save you can now write in a script rather than the console.

How do you save the script? Click File >>> Save As and use the dialogue box that comes up to name your file and save it to a folder on your computer.

Tips for R Scripts

R scripts make it easy to share code through email. You could attach the script to an email message, of course, but you could also simply cut and paste the finished code into the body of the message.

It is also easy to turn an R script into an HTML document by clicking on File >>> Render Document. This works pretty well, but other document types, such as RMarkdown or Quarto, offer more control over formatting details. We will introduce these in later lessons.

16 R Packages

So far we have been using functions that are automatically included in R. These functions are known as “base R.” But the larger R language includes many, many functions contributed as external packages by the R community and stored on CRAN28 These extend R’s functionality dramatically. Users can find packages implementing everything from cutting edge machine learning algorithms to routines for data wrangling and plotting. In the latter category is a collection of packages known as the “tidyverse.”29 Later lessons will focus on two of the most useful: dplyr and ggplot2.

28 Comprehensive R Archive Network. See, specifically, the “Packages” menu item on the left.

29 See tidyverse.org for details.

30 You can also install packages using the top menu in RStudio: Tools >>> Install Packages. This will bring up a dialog box that allows you to search for packages on CRAN. Select a package then click “Install.”

You must install a package before you can use it. This can be done using the install.packages() function, which downloads and installs the package.30 Once a package is installed you must use the library() function to load it into memory. This makes its functions available for use. This point bears repeating: to use a package it must be loaded at the beginning of a session. There is an exception to this rule that we will discuss in a moment.

As an example, let’s install the tidyverse. Most packages are installed one by one, but we can install all of the tidyverse packages at once with this command:

install.packages("tidyverse")

(Note that name of the package needs to be within quotation marks.)

The main tidyverse packages include:

  • ggplot2, for data visualization.
  • dplyr, for data manipulation.
  • tidyr, for data tidying.
  • readr, for data import.
  • purrr, for functional programming.
  • tibble, for tibbles, a modern re-imagining of data frames.
  • stringr, for strings.
  • forcats, for factors.

After installing the packages, use the library() function to load them into memory.

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.4.4     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.0
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

Loading the tidyverse has produced some warnings about naming conflicts. The base R stats package has a function called filter() as does the dplyr package in the tidyverse. So, what happens when, after loading the tidyverse, you use the filter() function? The function in the most recently loaded package—filter() in dplyr— will “mask” or overwrite the other function. This is formally known as a “name space conflict.” Such conflicts can be very confusing since functions typically have different behaviors. One way of avoiding namespace conflicts (and the resulting confusion) is to simply append the source package name to the desired function with a double colon, like this: dplyr::filter() or stats::filter().

Incidentally, this way of calling function is not only more explicit; it also eliminates the need to load the package at the beginning of a session.

17 Reading and Writing Data

So far we have been using data sets that are included in R, such as rivers, mtcars, and iris.31 At some point you will want to work with external data in R, which is most commonly stored in .csv format. (This is not a necessity: there are utility functions available in R for reading virtually any file format into memory.) To read a .csv file into memory as a data frame we’ll use the read.csv() function. Let’s cover several scenarios.

31 Note that many R packages include data sets within them for illustrating the use of the package’s functions. For example, the dplyr package includes five built-in data sets for illustration: band_instruments, band_instruments2, band_members, starwars, storms.

  • Download data from the internet.
  • Write data to a file on your computer.
  • Read in data from a file on your computer.

Downloading data from the internet is easy. Conveniently, the file argument in read.csv() will accept a URL.

bikeshare <- read.csv(file ="https://raw.githubusercontent.com/jefftwebb/data/main/day.csv")

str(bikeshare)
'data.frame':   731 obs. of  17 variables:
 $ X         : int  1 2 3 4 5 6 7 8 9 10 ...
 $ instant   : int  1 2 3 4 5 6 7 8 9 10 ...
 $ dteday    : chr  "2011-01-01" "2011-01-02" "2011-01-03" "2011-01-04" ...
 $ season    : int  1 1 1 1 1 1 1 1 1 1 ...
 $ yr        : int  0 0 0 0 0 0 0 0 0 0 ...
 $ mnth      : int  1 1 1 1 1 1 1 1 1 1 ...
 $ holiday   : int  0 0 0 0 0 0 0 0 0 0 ...
 $ weekday   : int  6 0 1 2 3 4 5 6 0 1 ...
 $ workingday: int  0 0 1 1 1 1 1 0 0 1 ...
 $ weathersit: int  2 2 1 1 1 1 2 2 1 1 ...
 $ temp      : num  0.344 0.363 0.196 0.2 0.227 ...
 $ atemp     : num  0.364 0.354 0.189 0.212 0.229 ...
 $ hum       : num  0.806 0.696 0.437 0.59 0.437 ...
 $ windspeed : num  0.16 0.249 0.248 0.16 0.187 ...
 $ casual    : int  331 131 120 108 82 88 148 68 54 41 ...
 $ registered: int  654 670 1229 1454 1518 1518 1362 891 768 1280 ...
 $ cnt       : int  985 801 1349 1562 1600 1606 1510 959 822 1321 ...

Comments:

  • This data set is from one of the nation’s first bike share programs in Washington DC. It records daily information on bike rentals for 2011 and 2012.
  • The read.csv() function is doing the work of reading in the .csv file from the website and converting it to a data frame. Note that the file argument requires the URL to be within quotation marks.
  • The data frame is then assigned to an object, bikeshare, that is stored temporarily in the environment or workspace for the current R session.32

32 Previously we have described objects as being stored “in memory.” This refers to the collection of objects—data frames, vectors, functions—that are available for use in the current R session. “Environment” and “workspace” are more formal terms for the objects in memory. The environment can be thought of as a kind of container that holds a set of symbols—that is, the names of objects— and their corresponding values.

Objects in the environment are not saved permanently. To understand why let’s take a brief tour of the Environment pane, and specifically the environment tab, in the upper right quadrant in RStudio. Here RStudio provides functionality for managing and exploring the environment. For example:

  • Click the blue button to the left of the data frame object to see the columns.

The Environment Pane
  • Click the spreadsheet icon to the right of the data frame object to bring up the Viewer.

  • Clear the environment by clicking the little broom icon at the top of window. You should do this periodically since a cluttered environment can lead to problems. (For example, if a file mistakenly gets renamed or overwritten you might find yourself working with the wrong data.)

So, the environment is not the place to store data permanently. Instead, to save data it is necessary to write it to a file, using the write.csv() function.33 The write.csv() function has two main arguments:

33 We could, of course, use a different file format, but .csv is common and convenient.

  • x: The data frame in the environment to be written as a .csv file.
  • file: The directory path culminating in the file name.
write.csv(x = bikeshare, file = "path/to/file")
Detail: Paths

Getting the path right for a given file turns out to be surprisingly tricky, since it requires that you understand the directory structure of your computer. Here is a quick primer.

A directory is simply a folder. Directories can contain other directories as well as files. A directory path is the specific location in the hierarchy of directories on a computer. It indicates the sequence of directories that must be followed to reach it.

On a Windows computer, the root directory of each drive is represented by a drive letter followed by a colon such as “C:” or “D:”). Each directory in the file system is represented by a name, and the names of directories are separated by a backslash (““). For example, the path”C:” specifies the location of the Documents directory within the Username directory, which is located within the Users directory, which is located on the C: drive.

On a Mac, the Finder application is used to browse and manage directories. The root directory is represented by a forward slash (“/”). Each directory in the file system is represented by a name, and the names of directories are separated by forward slashes. For example, the path “/Users/Username/Documents” specifies the location of the Documents directory within the Username directory, which is located within the Users directory, which is the root directory.

To load a .csv file into your workspace as a data frame use the read.csv() function. Rather than supplying a URL for the file argument (as we did earlier) simply specify the file’s location on your computer using the path:

bikeshare <- read.csv(file = "path/to/file")

Let’s say that you have downloaded a .csv file to your computer. By default that file will be located in the downloads folder. To load the file into your workspace, you would supply the path to your downloads folder with the name of the file.

18 The Working Directory

Keeping paths straight can be confusing if documents are located in different locations. For example, you may have a script file in one location but a data file in another location. You can simplify things tremendously by creating a dedicated folder for a project, and then specifying that folder as the working directory. The working directory is simply R’s default directory for reading and writing files.

To find the current working directory in the RStudio interface look at the Files pane on the lower right quadrant. The folder displayed there is the working directory. (You can also use the getwd() function in the R console to print the path of the current working directory.) With the working directory set, you don’t need to specify the path when reading or writing files, but just the file name:

write.csv(x = bikeshare, file = "file")

bikeshare <- read.csv(file = "file")

Use the setwd() function in the R console to set the working directory.34

34 The working directory can also be set in RStudio’s File pane. With the desired folder showing, click More >>> Set As Working Directory.

19 RStudio Projects

As noted above, to keep your project work organized you should:

  1. Create a dedicated folder for the project.
  2. Set that folder as your working directory.

You could do these things manually, but RStudio will also do them for you automatically when you create a project. An RStudio project is a working directory that contains the files associated with a particular analysis.35

35 For more detail see Using Projects at posit.com.

To create a project in RStudio click on File >>> New Project. (Alternatively, you can click in on the button in the upper right corner of RStudio and select New Project.) Follow the prompts to choose a location for the project on your computer and indicate whether you want to create a new directory for the project or use an existing directory. RStudio will then produce the necessary project structure (including the project folder for a new directory), and open the project. At this point you can add R script files, data files, and other resources. Importantly, the root project directory will automatically be set as the working directory.

A project is like your desk at work: everything you need for a particular analysis is in a familiar location, and, when you return to work, is still right where you expect it. Rather than using one folder for multiple different analyses, use multiple projects, one for each analysis.

20 The dplyr Package

Let’s get back to R programming! Time to introduce the dplyr package in the tidyverse.

dplyr (pronounced “dee-ply-r”) consists in a set of tools for fast data wrangling—in effect, it provides pliers for manipulating data frames.36 In earlier lessons we saw how to use base R to subset and summarize data. Why do we need more tools? dplyr has an edge over base R in terms of:

36 It is worth emphasizing that dplyr was specifically designed to work with data frames, not other data structures.

  • Ease of use. dplyr functions have an intuitive syntax.
  • Readability. dplyr code is easy to understand, particularly when combined with pipes.
  • Performance. The back end of dplyr is written in C++, making the performance blazingly fast, especially for large data sets.
  • Consistency. dplyr functions use a consistent syntax and follow a similar set of conventions.

dplyr implements a “split-apply-combine” strategy for data analysis: “break up a big problem into manageable pieces, operate on each piece independently and then put all the pieces back together.”37 To do that dplyr provides five core functions, or “verbs”:

37 For more detail, see Hadley Wickham’s original paper on this topic: “The Split-Apply-Combine Strategy for Data Analysis”

  1. filter() subsets a data frame by rows, taking only certain rows as specified by logical criteria.
  2. arrange() sorts a data frame by rows.
  3. select() subsets by columns.
  4. mutate() creates a new column.
  5. summarize() creates a summary table.

Importantly, these functions can be used in conjunction with another one, group_by(), which allows us to perform operations on data frames within groups, conditionally.

dplyr includes a lot of complexity at this point. We will try to keep things simple in this introduction, focusing on typical uses that should suffice for most data wrangling tasks.38

38 A cheatsheet of functions is helpful. You can either create your own or browse the ones available at posit.com: the dplyr cheatsheet is about halfway down the page. These PDFs can be printed out and kept near your workstation for easy reference.

21 Pipes

Before getting into the dplyr verbs, let’s introduce an important syntactic development in R programming: the pipe operator, |>. Pipes make code easier to read and therefore improve collaboration. This is a stylistic innovation that substantively impacts productivity.

Briefly:

  • Traditionally R functions are “nested,” a coding style that can be represented as h(g(f(x))). Nested code runs just fine but is hard to read. In fact, the first function we encounter when reading, h(), is actually the last one to be executed; vice versa for f(): it is the first to be executed but the last in reading order.

  • Pipes unpack this nested structure, representing a clear sequence of operations: x |> f() |> g() |> h(). The pipe operator should be pronounced “and then.” This code can be therefore be understood as a sequence: use x and then perform f() and then g() and then h(). The pipe passes the object on its left hand side to the first argument of the function on the right-hand side.

Here is an example of nested syntax with mtcars:

head(arrange(filter(mtcars, mpg > 25), wt), 5)
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2

We haven’t yet discussed the details of filter() and arrange() but the difficulties involved in reading traditional R syntax should be apparent. The operations are hard to parse due to the nested functions. The head() function is first in reading order but the last executed. In sequence the operations are:

  1. Filter the data frame to include only rows where mpg is greater than 25.
  2. Sort by wt.
  3. Print the first 5 rows.

Here is the above example rewritten with pipes.

mtcars |>
     filter(mpg > 25) |>
     arrange(wt) |>
     head(5)
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2

Same result, but the code is much easier to read and understand. We can now just scan down the verbs to see the operations in order.39 To reiterate the point above, the pipe passes the object on its left hand side to the first argument of the function on the right-hand side. For example, the first argument of filter() is the data argument. So, in the first line of this code chunk the pipe passes mtcars to the second line as the first argument in filter(). And so forth.

39 In fairness, we should note that it is possible to represent the sequence of operations without pipes. But doing so requires the creation of named intermediate objects, which clutter the environment and require a lot of naming and typing. For example: first, assign the subsetted data frame to an object: filtered_df <- filter(mtcars, mpg > 25); next, sort that data frame object, and assign the result to another object: arranged_filtered_df <- arrange(filtered_df, wt); third, print the top rows of that object: head(arrranged_filtered_df).

We will be using pipes throughout the remainder of these lessons.

22 Filter and Arrange

The two main dplyr verbs for manipulating rows in a data frame are filter() and arrange().

Which cars have high mpg? Previously we used square bracket notation to answer this sort of a question:

mtcars[mtcars$mpg > 25 , ]
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

Here is how we would perform the same operation with filter():

mtcars |>
     filter(mpg > 25)
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

Note that the same logical operators we used earlier with square bracket notation can also be passed to filter().40

40 See the list of logical operators in the lesson on logical vectors.

Common Mistakes

Common mistakes with filter() include:

  1. Forgetting about the double equals sign to express identity, ==:
mtcars |> 
     filter(cyl = 4) |>
     head()
Error in `filter()`:
! We detected a named input.
ℹ This usually means that you've used `=` instead of `==`.
ℹ Did you mean `cyl == 4`?

As the error message suggests, the code should be: filter(cyl == 4).

  1. Writing an “or” statement as in English:
mtcars |> 
     filter(cyl == 4 | 6) |>
     head()
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

This doesn’t produce an error, but it also doesn’t have the desired effect: the resulting data frame includes 8 cylinder cars. The code should be: filter(cyl == 4 | cyl == 6).

We can then pipe the filtered data frame into the arrange() function for sorting:

mtcars |>
     filter(mpg > 25) |>
     arrange(wt)
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1

arrange() preserves the integrity of the rows but changes their order based on the values in a specified column. By default, sorting is low to high. The sorting can be reversed with desc() (which stands for “descending”):

mtcars |>
     filter(mpg > 25) |>
     arrange(desc(wt))
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
dplyr Verbs: What to Expect

The consistent behaviors we have observed above for filter() and arrange() hold for all dplyr verbs:

  1. The first argument is always a data frame.

  2. The subsequent arguments describe what to do with the data frame, using the variable names.

  3. The result is always a new data frame.

22.1 Practice Questions

The filter() function produces a subset of the data frame, retaining all rows that satisfy the specified logical conditions. The arrange() function sorts the data frame.

Using the iris and mtcars data frames, answer the following questions.

(Remember you can use str() to see the column and row information for these data frames.)

  1. Filter iris to include only rows where Species is not virginica.

  2. Filter iris to include only rows where Species is versicolor, and where both Sepal.Length and Petal.Length are greater than 3.

  3. Filter iris to include rows where Petal.width is less than the average Petal.width of all Species. Sort by Petal.width.

  4. Filter iris to find which species have the highest Sepal.width and the smallest Petal.Length.

  5. Filter mtcars to include rows where carb is 1 and then sort by gear in descending order.

  6. Filter mtcars to include rows where hp is greater than the median value of hp for all cars. Sort by mpg.

  7. Return the count of cars in mtcars where wt is less than 400 and vs is 0. (Tip: Use the nrow() function.)

  8. Return a five number summary for a subset of mtcars including only rows where disp is above 100 or am is not 1. (Tip: use the summary() function).

  9. Filter mtcars to include rows with the lowest qsec or highest mpg and sort by cyl in descending order.

  10. Filter the mtcars to include rows where hp lies between 100 and 250 and then sort by hp.

dplyr has been loaded into the code box for your use.

Show answers
# Load the data (if working in RStudio)
data(mtcars)
data(iris)

## Question 1 -------------------------------

iris |> 
   filter(Species != "virginica")

## Question 2 -------------------------------

iris |>
   filter(Sepal.Length > 3 & Petal.Length > 3 & Species == "versicolor")

## Question 3 -------------------------------

iris |> 
   filter(Petal.Width < mean(Petal.Width)) |>
   arrange(Petal.Width)

#Question 4 -------------------------------
iris |> 
   filter(Sepal.Width == max(Sepal.Width) | Petal.Length == min(Petal.Length)) 
   
## Question 5 -------------------------------

mtcars |>
     filter(carb == 1) |>
     arrange(desc(gear))

## Question 6 -------------------------------

mtcars |>
     filter(hp > median(hp)) |>
     arrange(mpg)

## Question 7 -------------------------------

mtcars |>
     filter(wt < 400 & vs == 0) |>
     nrow()
       
## Question 8 -------------------------------

mtcars |>
     filter(disp > 100 | am != 1) |>
     summary()

## Question 9 -------------------------------

mtcars |>
     filter(qsec == min(qsec) | mpg == max(mpg)) |>
     arrange(desc(cyl))

## Question 10 -------------------------------

mtcars |>
     filter(hp > 100 & hp < 250) |>
     arrange(gear)

23 Select and Mutate

The two main dplyr verbs for working with columns in a data frame are select() and mutate().

  • select() selects or renames columns in a data frame.41
  • mutate() creates a new column.

41 Sometimes data sets have hundreds or thousand of columns. In these situations, it can be essential to subset the data by selecting a subset of columns.

mtcars |>
     mutate(hp_wt_ratio = hp/wt,
            cyl = factor(cyl)) |>
     filter(mpg > 25) |>
     arrange(desc(wt)) |>
     select(miles_per_gallon = mpg, wt, hp, cyl, hp_wt_ratio)
               miles_per_gallon    wt  hp cyl hp_wt_ratio
Fiat 128                   32.4 2.200  66   4    30.00000
Porsche 914-2              26.0 2.140  91   4    42.52336
Fiat X1-9                  27.3 1.935  66   4    34.10853
Toyota Corolla             33.9 1.835  65   4    35.42234
Honda Civic                30.4 1.615  52   4    32.19814
Lotus Europa               30.4 1.513 113   4    74.68605

In effect, this code chunk is a six-line program that wrangles the data into a new shape and prints the result.

Code explanation:

  • mtcars |>: pipes the data from the first line into the first argument of the second line.
  • mutate(hp_wt_ratio = hp/wt,: creates a new column named hp_wt_ratio that consists in the hp column divided by the wt column. Notice that we put each individual mutate operation on its own line separated by a comma.
  • cyl = factor(cyl) |>: factors cyl, overwriting the existing numeric variable, and then pipes the resulting data frame into the next line. Notice that this line includes the closing parenthesis for the mutate() function.
  • filter(mpg > 25) |>: filters the data frame to include only rows with mpg greater than 25 and pipes the resulting data frame into the next line.
  • arrange(desc(wt)) |>: sorts the rows of the data frame by wt, from high to low and pipes the resulting data frame into the next line.
  • select(miles_per_gallon = mpg, wt, hp, hp_wt_ratio): renames the mpg column to be miles_per_gallon then selects the renamed column along with wt, hp, cyl, hp_wt_ratio. (To select columns we simply include the names separated by commas.)

A couple of things to note:

  • The new data frame produced by this code chunk is being printed, not saved as an object in the environment. To save it, we would, of course, need to use the assignment operator.
  • The new columns created with the mutate() function in the second and third lines is available for use in any subsequent line (even within the same mutate() call).
Tips for using select()

The select() function offers lots of time-saving shortcuts for selecting columns. Observe:

mtcars |>
     select(1:2) |>
     head()
                   mpg cyl
Mazda RX4         21.0   6
Mazda RX4 Wag     21.0   6
Datsun 710        22.8   4
Hornet 4 Drive    21.4   6
Hornet Sportabout 18.7   8
Valiant           18.1   6
mtcars |>
     select(mpg:hp) |>
     head()
                   mpg cyl disp  hp
Mazda RX4         21.0   6  160 110
Mazda RX4 Wag     21.0   6  160 110
Datsun 710        22.8   4  108  93
Hornet 4 Drive    21.4   6  258 110
Hornet Sportabout 18.7   8  360 175
Valiant           18.1   6  225 105

See ?select for more details.

One last point. A very useful function to combine with mutate() is ifelse(). It can be used to transform data based on a logical condition—for example, to make a continuous variable into a binary variable, or to change the values of a categorical variable.42 It has the following syntax: ifelse(logical condition, code to be executed if the condition is TRUE, code to be executed if the condition is FALSE).

42 While useful, the ifelse() function can become cumbersome if used to make multiple changes requiring nested ifelse() statements. At that point, another dplyr function, which we’ll cover in detail later, works better: case_when().

As an example, let’s create a binary version of the wt variable, which will take the following values: above_avg if the weight is above average, below_avg otherwise.

mtcars |>
     mutate(binary_wt = ifelse(wt > mean(wt), "above_avg", "below_avg")) |>
     select(wt, binary_wt) |>
     head()
                     wt binary_wt
Mazda RX4         2.620 below_avg
Mazda RX4 Wag     2.875 below_avg
Datsun 710        2.320 below_avg
Hornet 4 Drive    3.215 below_avg
Hornet Sportabout 3.440 above_avg
Valiant           3.460 above_avg

Looks good. Here is an explanation of the code:

  • mtcars |>: pipes the data from the first line into the first argument of the second line.
  • mutate(binary_wt = ifelse(wt > mean(wt), "above_avg", "below_avg")) |>: creates a new column in the data frame, binary_wt—the name, by the way, is arbitrary—based on this transformation logic: if observed wt in a given row is greater than average weight, then return a value of “above_avg,” otherwise (that is, if wt is below average) return a value of “below average.” The resulting data frame with this new variable is then piped into the next line.
  • select(wt, binary_wt) |>: selects just two columns and pipes the resulting data frame to the next line.
  • head(): filters the data frame to include just the first 6 lines.

The last two lines — the select() command and the head() command— are included just for convenience, making it easier to see the result of the mutate()-ifelse() combination.

Saving vs. Printing

Again, remember that we are not saving the result of the above code to an object, but simply printing it. How would we save it? Easy. Use the assignment operator to assign the new data frame to an object.

mtcars |>
     mutate(binary_wt = ifelse(wt > mean(wt), "above_avg", "below_avg")) |>
     select(wt, binary_wt) |>
     head() -> mtcars_binary_wt 

We could have done the assignment in the first line, but putting it at the end makes more sense since the typical dplyr sequence is left-to-right and top-to-bottom.

23.1 Practice Questions

The select() function is used to select or rename columns in a data frame. The mutate() function creates a new column.

Use the mtcars and iris data frames to answer the following questions.

  1. Select hp and gear columns from mtcars.

  2. Subset mtcars to include only the cyl column, and change the name of cyl to Cylinders.

  3. filter mtcars to include rows where disp is greater than 400 and vs not equal to 1, then create a five number summary of hp.

  4. Convert gear in mtcars to a factor variable and then select mpg, cyl, hp, qsec, and gear. Sort the resulting data frame by gear.

  5. Create a new column in mtcars, mpg_cyl, consisting in mpg/cyl, and then select just three columns from the data frame: mpg_cyl, mpg, and cyl.

  6. What is the name of the species with the highest Sepal.Length in iris?

  7. Show the rows of Species and Petal. Length where Petal. Length is greater than average Petal.Length.

Show answers
## Question 1 -------------------------------

mtcars |> 
     select(hp, gear)

## Question 2 -------------------------------

mtcars |>
     select(Cylinders = cyl)

## Question 3 -------------------------------

mtcars |> 
     filter(disp > 400 | vs != 1 ) |> 
     select(hp) |>
     summary()

## Question 4 -------------------------------

mtcars |>
     mutate(gear = factor(gear)) |>
     select(mpg, cyl, hp, qsec, gear) |>
     arrange(gear)

## Question 5 -------------------------------

mtcars |>
     mutate(mpg_cyl = mpg / cyl) |>
     select(mpg_cyl, mpg, cyl)

## Question 6 -------------------------------

iris |> 
   filter(Sepal.Length == max(Sepal.Length)) |>
   select(Species)

## Question 7 -------------------------------

iris |> 
   filter(Petal.Length > mean(Petal.Length)) |>
   select(Species, Petal.Length)

24 Summarize and Group_by

Creating summary tables is an essential step in any analytics project.43 Such tables provide an overview of the data’s structure and content, with information such as:

43 This step is part of exploratory data analysis or EDA. It involves summarizing and visualizing data to understand its main characteristics, to highlight trends and patterns, and to identify anomalies and relationships. It is a way to get familiar with the data prior to formal modeling.

  • The dimensions of the data set—number of rows and columns.
  • The data types of the variables.
  • The distribution of values for each variable.
  • Missing or unusual values.
  • Summary statistics such as mean, median, and standard deviation for each numeric variable.
  • Counts and percentages for categorical variables.

In earlier lessons we presented a couple of built-in methods for summarizing data frames: str() and summary(). And we also saw how to flexibly extract summary information from a data frame, conditional on levels of a categorical grouping variable, using base R’s tapply() function:

tapply(X = mtcars$mpg, INDEX = mtcars$cyl, FUN = mean)
       4        6        8 
26.66364 19.74286 15.10000 

The return value is a vector of average mpg for each level of cyl.

The tapply() function is useful but has the limitation of accepting only one summary function at a time. What if we would like to calculate median mpg and the standard deviation of mpg at the same time? Can’t do it.

Let’s rewrite the tapply() code using dplyr’s summarize() function. Note that in dplyr group_by() performs the work of the Index argument in tapply():

mtcars |>
     group_by(cyl) |>
     summarize(avg = mean(mpg))
# A tibble: 3 × 2
    cyl   avg
  <dbl> <dbl>
1     4  26.7
2     6  19.7
3     8  15.1

The return value here is a data frame with a row for each level of the grouping variable.44 The two columns correspond to the grouping variable and the mean of mpg. In the latter case the name of the column comes from the arbitrary name, avg, we used within the summarize() function. We can easily add information to this table by defining more summary statistics, with one per line, and lines separated by commas:

44 This data frame is technically a “tibble,” a special type of data frame used by the tidyverse. The main difference is in the way a tibble prints to the screen—it will show the first few rows and only the columns that fit on one screen.

mtcars |>
     group_by(cyl) |>
     summarize(avg = mean(mpg),
               median = median(mpg),
               sd = sd(mpg),
               n = n()) |>
     round(digits = 2)
# A tibble: 3 × 5
    cyl   avg median    sd     n
  <dbl> <dbl>  <dbl> <dbl> <dbl>
1     4  26.7   26    4.51    11
2     6  19.7   19.7  1.45     7
3     8  15.1   15.2  2.56    14

There is are two new functions here:

  • n() does the work of nrow() from base R. It simply counts the number of observations. It is best practice to include a count of observations in a summary table.
  • round() rounds the elements of a numeric table to the specified number of digits. This is also best practice for a summary table—precision beyond two decimal places is not usually needed.

Here is an explanation of the code:

  • mtcars |>: pipes the data frame from the first line into the first argument of the second line.
  • group_by(cyl) |>: groups the data frame by the levels in cyl and pipes it to the next line.
  • summarize(avg = mean(mpg),: defines the first summary statistic, the mean of mpg within each cyl level, the result of which is titled avg. This line ends with a comma, indicating that there are more summary statistics to come in this call to summarize().
  • median = median(mpg): defines another summary statistic as the median of mpg within each level, creatively titled median.
  • sd = sd(mpg): defines another summary statistic as the standard deviation of mpg within each level.
  • n = n(): defines another summary statistic as the number of observations within each level of cyl. This line includes the closing parenthesis for this call to summarize().
  • round(digits = 2): rounds all the elements of a table to two decimal places.

Pretty cool!

Shortcut: count()

The count() function offers a shortcut for creating a table of counts. The method from above used group_by() and summarize(n = n()):

mtcars |>
     group_by(cyl) |>
     summarize(n = n())
# A tibble: 3 × 2
    cyl     n
  <dbl> <int>
1     4    11
2     6     7
3     8    14

count() combines the two, and automatically supplies a column entitled n:

mtcars |>
     count(cyl)
  cyl  n
1   4 11
2   6  7
3   8 14

The upside of count() is less typing; the downside is having to remember another function.

The combination of group_by() and summarize() is an amazingly powerful and flexible programming construct.45 For example, it is straightforward to add more information to the above table by including more grouping variables and more summary statistics:

45 Of course, group_by() can also be combined with the other dplyr verbs to great advantage.

mtcars |>
     group_by(cyl, gear) |>
     summarize(avg = mean(mpg),
               median = median(mpg),
               sd = sd(mpg),
               min = min(mpg),
               max = max(mpg),
               n = n()) |>
     round(2)
# A tibble: 8 × 8
# Groups:   cyl [3]
    cyl  gear   avg median    sd   min   max     n
  <dbl> <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl>
1     4     3  21.5   21.5 NA     21.5  21.5     1
2     4     4  26.9   25.8  4.81  21.4  33.9     8
3     4     5  28.2   28.2  3.11  26    30.4     2
4     6     3  19.8   19.8  2.33  18.1  21.4     2
5     6     4  19.8   20.1  1.55  17.8  21       4
6     6     5  19.7   19.7 NA     19.7  19.7     1
7     8     3  15.0   15.2  2.77  10.4  19.2    12
8     8     5  15.4   15.4  0.57  15    15.8     2

Each row in this summary table represents the unique combinations of the levels in cyl and gear. Notice that the sd column includes NAs for the rows with just one observation—cars with 4 cylinders and 3 gears or 6 cylinders and 5 gears. This is because standard deviation is a measure of spread and can’t be computed for just one observation.

Beware: Ungrouping

It is important to understand that a table created with summarize() and group_by() includes grouping information in its metadata. To perform an operation on the entire table you first need to remove the grouping structure with the ungroup() command. For example, suppose you want to add a column showing the percentage of observations in each row out of the total number of rows. Use a mutate() command following summarize()—this would add a new column to the summary table—but first ungroup the table:

mtcars |>
     group_by(cyl, gear) |>
     summarize(avg = mean(mpg),
               median = median(mpg),
               sd = sd(mpg),
               min = min(mpg),
               max = max(mpg),
               n = n()) |>
     ungroup() |>
     mutate(percent = n / sum(n) * 100) |>
     round(2)
# A tibble: 8 × 9
    cyl  gear   avg median    sd   min   max     n percent
  <dbl> <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl>   <dbl>
1     4     3  21.5   21.5 NA     21.5  21.5     1    3.12
2     4     4  26.9   25.8  4.81  21.4  33.9     8   25   
3     4     5  28.2   28.2  3.11  26    30.4     2    6.25
4     6     3  19.8   19.8  2.33  18.1  21.4     2    6.25
5     6     4  19.8   20.1  1.55  17.8  21       4   12.5 
6     6     5  19.7   19.7 NA     19.7  19.7     1    3.12
7     8     3  15.0   15.2  2.77  10.4  19.2    12   37.5 
8     8     5  15.4   15.4  0.57  15    15.8     2    6.25

The ungroup() command allows sum(n) to add up the entire n column and ensures that the new percent column adds up to 100.

Of course, we could also use summarize() without group_by() to compute summary statistics for the entire data set:

mtcars |>
     summarize(avg = mean(mpg),
               median = median(mpg),
               sd = sd(mpg),
               min = min(mpg),
               max = max(mpg),
               n = n()) |>
     round(2)
    avg median   sd  min  max  n
1 20.09   19.2 6.03 10.4 33.9 32

24.1 Practice Questions

The summarize() function in dplyr is used to create a summary table. (Note: summarize() and summarise() are the same.)

The group_by() function groups rows by column values, often to calculate conditional statistics for groups, like tapply().

Questions

Using mtcars answer the following questions:

  1. What is average hp of cars grouped by cyl? Round to 2 decimal places.

  2. What is the number of observations and the average mpg of cars grouped by carb? Subset the summary table to include only carb greater than 3. Round to 2 decimal places.

  3. What is the number of observations, mean, median, and standard deviation of qsec for cars grouped by gear in the mtcars? Round to 2 decimal places.

  4. What are the minimum and maximum disp values for cars grouped by cyl and vs?

  5. What is the number of observations, mean wt, and maximum wt of cars with gear equal to 4 and vs equal to 0, grouped by am and carb? Round to 2 decimal places. Here is code to answer that question, but it contains errors. Correct the errors to return the correct information.

mtcars |>
     group_by(am, carb) 
     filter(gear = 4 & vs = '0') |>
     summarize()
Error: <text>:3:27: unexpected '='
2:      group_by(am, carb) 
3:      filter(gear = 4 & vs =
                             ^
  1. Calculate summary statistics for hp, grouped by carb and gear. The summary statistics should include mean, median, standard deviation, minimum, maximum, the count of observations in each group and (finally) what percentage of the total that count represents. The results should be rounded to two decimal places. Here is code to answer that question, but it contains errors. Correct the errors to return the correct information. Once you’ve done so, think about why there are NA values in the standard deviation column.
mtcars |>
     group_by(cyl, gear) |>
     summarize(avg = mean('mpg'),
               median = median(mpg),
               'sd' = sd(mpg),
               min = min(mpg),
               max = max(mpg),
               n = n(10)) |>
     ungroup() |>
     mutate(percent = n / sum(n) * 100)) |>
     round(2)
Error: <text>:10:40: unexpected ')'
9:      ungroup() |>
10:      mutate(percent = n / sum(n) * 100))
                                           ^

Using iris:

  1. Calculate the range of Sepal.Length by Species. Hint: remember that range is defined as maximum - minimum.

  2. Calculate the standard deviation of Petal.Width by Species but include only versicolor in the summary table. Also, include a count of observations. Round to 2 decimal places.

  3. Calculate median Petal.Length— call it median_petal_length— for each Species.

  4. Calculate mean Sepal.Width, standard deviation of Petal.Length, and count of observations for each Species. Sort this table in reverse alphabetical order by Species. Round to 2 decimal places.

Show answers
## Question 1 -------------------------------

mtcars |> 
  group_by(cyl) |> 
  summarize(average_hp = mean(hp)) |> 
  round(2)

## Question 2 -------------------------------

mtcars |> 
  group_by(carb) |> 
  summarize(n = n(),
            average_mpg = mean(mpg)) |> 
  filter(carb > 3 ) |> 
  round(2)

## Question 3 -------------------------------

mtcars |> 
  group_by(gear) |> 
  summarize(n = n(),
            avg_qsec = mean(qsec),
            median_qsec = median(qsec),
            sd_qsec = sd(qsec)) |> 
  round(2)

## Question 4 -------------------------------

mtcars |> 
  group_by(cyl, vs) |> 
  summarize(min_disp = min(disp),
            max_disp = max(disp)) 

## Question 5 -------------------------------

mtcars |> 
  group_by(am, carb) |> 
  filter(gear == 4, vs == 0) |> 
  summarize(n = n(),
            avg_wt = mean(wt),
            max_wt = max(wt)) |> 
  round(2)

## Question 6 -------------------------------

mtcars |> 
  group_by(carb, gear) |> 
  summarize(avg = mean(hp),
            median = median(hp),
            sd = sd(hp),
            min = min(hp),
            max = max(hp),
            n = n()) |> 
  ungroup() |> 
  mutate(percent = n / sum(n) * 100) |> 
  round(2)

## Question 7 -------------------------------

iris |> 
  group_by(Species) |> 
  summarize(max = max(Sepal.Length),
            min = min(Sepal.Length),
            range = max - min)

## Question 8 -------------------------------

iris |> 
  group_by(Species) |> 
  summarize(n = n(), 
            sd = sd(Petal.Width),
            sd = round(sd, 2)) |> 
  filter(Species == "versicolor") 

## Question 9 -------------------------------

iris |> 
  group_by(Species) |> 
  summarize(median_petal_length = median(Petal.Length))

## Question 10 -------------------------------

iris |> 
  group_by(Species) |> 
  summarize(mean_sw = mean(Sepal.Width), 
            mean_sw = round(mean_sw, 2),
            sd_pl = sd(Petal.Length), 
            sd_pl = round(sd_pl, 2),
            n = n()) |> 
  arrange(desc(Species))

25 The ggplot2 Package

The ggplot2 package is a fantastic visualization package for exploring data and communicating insights. Developed in R by Hadley Wickham, it is an implementation of Leland Wilkinson’s Grammar of Graphics (as described in a 1999 book of that title), a general framework for data visualization that breaks up plots into semantic components. Thinking about graphics in terms of components makes it easier to design and customize visualizations. The ggplot package construes these components as “layers” to be added incrementally to a plot. These include (among others):

  • The blank canvas.
  • Aesthetic mappings.
  • The plot type.
  • Plot labels.

Each ggplot visualization starts with a blank canvas created by the ggplot() function. The first argument to ggplot() is the data argument, where we specify a source data frame. (Like dplyr, ggplot2 is designed to work with data frames.)

ggplot(data = mtcars)

This is the blank canvas.

Now we now add “layers”—additional plot components—starting with mapping from the variables in the data to the visual and aesthetic properties of the plot. This is accomplished with the mapping argument to ggplot(), which always uses the aes() function (“aes” stands for “aesthetic”).

The syntax goes: ggplot(data = ..., mapping = aes(...)).

Within aes() we specify which variable goes on the \(x\)-axis (horizontal axis), which goes on the \(y\)-axis (vertical axis), and which variables (if any) will be used to show relationships in additional dimensions. For example, let’s recreate the base R scatterplot from an earlier lesson and show the relationship between wt and mpg. The guiding question is whether the weight of a car affects miles per gallon.

ggplot(data = mtcars,
       mapping = aes(x = wt, y = mpg))

The mapping argument has added a layer with labeled axes and labeled tick marks, which show numeric ranges derived from the data.

The next layer is the plot type. What sort of plot should this be? Well, both wt and mpg are numeric, so a natural choice would be a scatterplot in which each point is determined by its \(x\)-\(y\) or, in this case, wt-mpg coordinates.

In ggplot, plot types are called “geoms” (pronounced “gee-omes”)— geometrical objects that a plot uses to represent data. There are lots of geoms; here are some of the common ones:

  • geom_point(): a scatterplot.
  • geom_histogram(): a histogram.
  • geom_boxplot(): a boxplot.
  • geom_bar(): a bar plot.
  • geom_col(): a bar plot.

And there are others. Basically any plot you can think of (and many you probably haven’t heard of—violin plots? heat maps?) can be created with ggplot geoms.

To add plot layers after ggplot() we use a + rather than a pipe.46 Here is how we add a scatterplot to this canvas:

46 Mistakenly using a pipe rather than a + is very common error. Beware!

ggplot(data = mtcars,
       mapping = aes(x = wt, y = mpg)) +
     geom_point()

Nice! Aesthetic differences aside, this plot is the same as the one we created in an earlier lesson with base R’s plot() function, showing a negative relationship between wt and mpg.

We should always include a title for a plot. To do so in ggplot, simply create another layer using the labs() function (“labs” stands for “labels”) with the title argument specified.47 The title needs to be in quotes.

47 The labs() function can also be used to add a subtitle (subtitle = "..."), or to change the \(x\)- or \(y\)-axis labels (x = "...", y = "...").

ggplot(data = mtcars,
       mapping = aes(x = wt, y = mpg)) +
     geom_point() +
     labs(title = "Scatterplot of wt vs. mpg")

Suppose we’d like to represent a third dimension on the plot—say, the relationship between wt, mpg and cyl? One way to do this would be to color the points by number of cylinders. This is easy to do in ggplot. The mapping —cyl to color— is defined within the aes() function with the color argument. ggplot handles the plotting details for you, including automatically creating a legend for cyl in the right hand margin!

ggplot(data = mtcars,
       mapping = aes(x = wt, y = mpg, color = cyl)) +
     geom_point() +
     labs(title = "Scatterplot of wt vs. mpg  by cyl")

Has something has gone wrong here? Yes. The legend shows cylinder numbers that don’t exist in the data. The problem is that cyl is properly a categorical variable but is encoded in mtcars as an integer. As as consequence, ggplot misunderstands it as a continuous variable. So, the plot works—there is no error—but not as intended. Changes in cyl are represented by gradations of color rather than the expected differences in color suited for a categorical variable.48 We need to recode cyl.

48 In ggplot differences in a continuous variable are represented by changes in hue—the default is gradations of blue—whereas differences in a categorical variable are represented by discrete changes in color—default red/green/blue.

We could change cyl on the fly within ggplot() using the factor() function. This is a quick and dirty fix:

ggplot(data = mtcars,
       mapping = aes(x = wt, y = mpg, color = factor(cyl))) +
     geom_point() +
     labs(title = "Scatterplot of wt vs. mpg  by cyl")

This one small change produces the desired plot, but the legend title on the right is inelegant and potentially confusing.

Another approach would be combine dplyr and ggplot, using mutate() to make the needed changes to cyl and then piping the resulting data frame into ggplot().

mtcars |>
     mutate(cyl = factor(cyl)) |>
     ggplot(mapping = aes(x = wt, y = mpg, color = cyl)) +
     geom_point() +
     labs(title = "Scatterplot of wt vs. mpg  by cyl")

Now the legend is appropriately titled. Combining dplyr and ggplot in this way will be a frequent strategy for us.

Here is an explanation of the code:

  • mtcars |>: pipes the data frame from the first line into the first argument of the second line.
  • mutate(cyl = factor(cyl)) |>: recodes the existing integer-valued cyl variable as a factor (overwriting the original variable) and pipes the new data frame to the next line. Note that we are not saving this new data frame but simply creating it temporarily for the visualization.
  • ggplot(mapping = aes(x = wt, y = mpg, color = cyl)) +: creates the blank canvas for plot and sets up the next ggplot layer with +. We can omit the data argument to ggplot() since that is being piped in from the dplyr portion of the code chunk above. Remember to switch from a pipe to a +!
  • geom_point() +: creates a scatterplot and sets up the next layer.
  • labs(title = "Scatterplot of wt vs. mpg by cyl"): uses the title argument to the labs() function to add a plot title.

These are the basics. We will cover additional plot components in the context of introducing additional geoms.

26 Histogram and Density Plots

A histogram, as we saw in an earlier lesson, is a frequency plot in which the \(y\)-axis is a count of the observations in a “bin” defined by an interval on the \(x\)-axis, and represented by the bars in the plot. It is helpful to look at the distribution of observations to see whether, for example, there are any natural groupings in the data.

Because a histogram does not show a relationship, there is no \(y\) argument. By default, the \(y\)-axis in a histogram is a count.

ggplot(data = mtcars,
       mapping = aes(x = mpg)) +
     geom_histogram() +
     labs(title = "Histogram of mpg")

ggplot will automatically pick the number of bins based on the data. We can adjust that number manually within the geom_histogram() function with the bins argument.49

49 You might ask: why does the bins argument go within geom_histogram() rather than ggplot()? Because the number of bins is not part of the blank canvas but is rather an instruction for how to draw the plot.

ggplot(data = mtcars,
       mapping = aes(x = mpg)) +
     geom_histogram(bins = 10) +
     labs(title = "Histogram of mpg")

As you can see, the fewer the bins the lower resolution. You must use your judgment to pick the resolution that best communicates an insight. In this case both plots show the same thing: a modest right skew to the data, with the majority of the observations centered about 15 miles per gallon. However, a few cars are quite a bit higher—above 30. This could be something to explore further.

A density plot is essentially a smoothed version of a histogram.50 Use geom_density():

50 In a density plot the vertical axis is not a count but a density—technically, a probability density over an interval on the \(x\)-axis. A thorough explanation of the difference is beyond the scope of these lessons on ggplot. But for most applications it suffices to think of a density plot as a smoothed histogram.

ggplot(data = mtcars,
       mapping = aes(x = mpg)) +
     geom_density() +
     labs(title = "Density plot of mpg")

As you can see, this density plot shows the same pattern as the histogram.

One of the advantages of using a density plot is that we can draw separate lines for subgroups using the color argument. For this plot to work, as for the scatterplot in the previous lesson, cyl needs to be categorical. We’ll use use dplyr to make the change, then pipe the new data frame into ggplot.

mtcars |>
     mutate(cyl = factor(cyl)) |>
     ggplot(mapping = aes(x = mpg, color = cyl)) +
     geom_density() +
     labs(title = "Density plot of mpg by cyl")

Clearly miles per gallon is strongly related to number of cylinders. The curves shift to the left as we go from 4 to 6 to 8 cylinders. Note that this same visualization strategy —coloring by groups—does not tend to work as well with histograms since the bars are often superimposed. Compare the density plot above with this plot:

mtcars |>
     mutate(cyl = factor(cyl)) |>
     ggplot(mapping = aes(x = mpg, fill = cyl)) +
     geom_histogram() +
     labs(title = "Histogram of mpg by cyl")

Hard to read.

Notice that we used the fill argument above rather than color because here we are “filling” bars. The color argument is reserved for lines. The arguments both have the same purpose—to add a third dimension to a plot—but which one you use depends on the type of plot—whether you are coloring lines or bars.

27 Facets

To show patterns in data it can be helpful to use a small multiples plot.51 The idea is to split the data into groups represented on small plots with the same axes and scale for comparison. For example, rather than combining all the cylinder groups in a single histogram, as above, we could create separate histograms. This would eliminate messy overplotting.

51 See small multiples at Wikipedia for a definition and some examples.

The ggplot facet_wrap() function will make a small multiples plot.

mtcars |>
     mutate(cyl = factor(cyl)) |>
     ggplot(mapping = aes(x = mpg)) +
     geom_histogram() +
     facet_wrap(facets = ~cyl) +
     labs(title = "Histogram of mpg by cyl")

The first argument to facet_wrap() is facets where we use a tilde (~) to identify the categorical variable that will define the different plots.52 This is called “faceting.” The code above, facet_wrap(facet = ~cyl), can be read as: facet the histogram by cyl.

52 Note that this code would also work: facet_wrap(facets = "cyl"). In this case you need to put the grouping variable in quotes.

We need to be strategic in how we orient the facets. The default horizontal orientation is good for comparing the height of the bars. But in this case it might be more useful to compare the groups by mpg, in which case a vertical orientation would work better, making \(x\)-axis differences more apparent. We can override the default by explicitly setting the ncol argument in facet_wrap() to 1 (“ncol” stands for “number of columns”). This will produce three plots in one column.

mtcars |>
     mutate(cyl = factor(cyl)) |>
     ggplot(mapping = aes(x = mpg)) +
     geom_histogram() +
     facet_wrap(facet = ~cyl, ncol = 1) +
     labs(title = "Histogram of mpg by cyl")

This provides a much clearer view of how the groups differ by mpg.

One thing you may have noticed in these lessons on ggplot is that the process of making plots is iterative and interactive: we start by creating a basic visualization and then tweak it to make improvements in order to better tell a story. This requires judgment and creativity.

28 Boxplot

A boxplot shows the relationship between a categorical variable on the \(x\)-axis and a numeric variable on the \(y\)-axis.

ggplot(data = mtcars,
       mapping = aes(x = cyl, y = mpg)) +
     geom_boxplot() +
     labs(title = "Boxplot of cyl vs. mpg")

Whoops! There should be three boxplots—one each for 4, 6 and 8 cylinder vehicles.

We again need to recode cyl as a factor variable; ggplot is misunderstanding it as continuous.

mtcars |>
     mutate(cyl = factor(cyl)) |>
     ggplot(mapping = aes(x = cyl, y = mpg)) +
     geom_boxplot() +
     labs(title = "Boxplot of cyl vs. mpg")

That’s better.

Think of boxplots as simplified histograms lying on their sides, with the box representing the central 50% of the distribution—often involving the tallest middle bars in the histogram— between the first and third quartiles of the data.53

53 For more details, see the discussion of boxplots in the earlier lesson, “Visualizing Data.”

29 Bar Plot

Bar plots are great for showing differences between groups. Of course, histograms are also a type of bar plot—but for continuous variables. Bar plots are for categorical variables.

There are two geoms in ggplot that will create bar plots:

  • geom_bar() makes the height of the bar proportional to the number of cases at each level of a categorical variable.
  • geom_col() derives the height of the bar from the source data, which can be a summary table. For this reason, geom_col() works well in conjunction with tables created using dplyr.

Here is a bar plot showing the number of observations at each level of cyl:

mtcars |>
     mutate(cyl = factor(cyl)) |>
     ggplot(mapping = aes(x = cyl)) +
     geom_bar() +
     labs(title = "Bar plot of cyl")

Admittedly, this is not very insightful. A summary table might have worked just as well to convey this information:

mtcars |>
     count(cyl)
  cyl  n
1   4 11
2   6  7
3   8 14

The more flexible geom for creating a bar plot is geom_col() because it allows us to visualize calculated numbers from a summary table—for example: a mean, a median or, indeed, even a count, among others. Here is the same bar plot from above rewritten using geom_col() and the table of counts:

mtcars |>
     count(cyl) |>
     ggplot(mapping = aes(x = cyl, y = n)) +
     geom_col() +
     labs(title = "Bar plot of cyl")

How about average mpg by cyl? First, create the summary table:

mtcars |>
     group_by(cyl) |>
     summarize(avg_mpg = mean(mpg)) 
# A tibble: 3 × 2
    cyl avg_mpg
  <dbl>   <dbl>
1     4    26.7
2     6    19.7
3     8    15.1

Now pipe this table in geom_col(), using the titles of these columns for the plot, with cyl on the \(x\)-axis and the new variable, avg_mpg, on the \(y\)-axis.

mtcars |>
     group_by(cyl) |>
     summarize(avg_mpg = mean(mpg)) |>
     ggplot(mapping = aes(x = cyl, y = avg_mpg)) +
     geom_col() +
     labs(title = "Bar plot of average mpg by cyl")

Is this better than just summarizing the averages in the table or even just listing them in a sentence? Maybe. It depends on the audience. But as the data gets more complicated, visualizations with bar plots allow us to see relationships and differences that aren’t obvious in a summary table. For example, does mpg differ by cyl and gear?

First, create the underlying summary table:

mtcars |>
     group_by(cyl, gear) |>
     summarize(avg_mpg = mean(mpg))
# A tibble: 8 × 3
# Groups:   cyl [3]
    cyl  gear avg_mpg
  <dbl> <dbl>   <dbl>
1     4     3    21.5
2     4     4    26.9
3     4     5    28.2
4     6     3    19.8
5     6     4    19.8
6     6     5    19.7
7     8     3    15.0
8     8     5    15.4

This table is too complicated to scan the numbers and pick out a pattern. So, pipe the table into ggplot! We will use the fill argument for gear, the third dimension variable, since the color should “fill” the bars.

mtcars |>
     group_by(cyl, gear) |>
     summarize(avg_mpg = mean(mpg)) |>
     ggplot(mapping = aes(x = cyl, y = avg_mpg, fill = gear)) +
     geom_col() +
     labs(title = "Bar plot of average mpg by cyl and gear")

This doesn’t look right. We need to factor the categorical variables.

mtcars |>
     mutate(gear = factor(gear),
            cyl = factor(cyl)) |>
     group_by(cyl, gear) |>
     summarize(avg_mpg = mean(mpg)) |>
     ggplot(mapping = aes(x = cyl, y = avg_mpg, fill = gear)) +
     geom_col() +
     labs(title = "Bar plot of average mpg by cyl and gear")

This is hard to read for the same reason pie charts are hard to read: our visual systems are better at picking out differences in length than in area.54 The plot would work better with the bars side by side for comparison. This is called a “dodged bar plot.” Use the position = "dodge" argument to geom_col().

54 For more information on visual channels (and visualization generally) see Tamara Munzer’s comprehensive book, Visualization Analysis and Design, in particular chapter 5: “Marks and Chanels.” The book’s website includes links to videos on each of the chapters. I should also mention, in this vein, that Kieran Healey’s book, Data Visualization: A practical introduction, is superb on visualization in R.

mtcars |>
     mutate(gear = factor(gear),
            cyl = factor(cyl)) |>
     group_by(cyl, gear) |>
     summarize(avg_mpg = mean(mpg)) |>
     ggplot(mapping = aes(x = cyl, y = avg_mpg, fill = gear)) +
     geom_col(position = "dodge") +
     labs(title = "Bar plot of average mpg by cyl and gear")

Much better! The plot gives us insight into a pattern that was invisible in the summary table. The number of gears has little to no influence on miles per gallon for cars with 6 or 8 cylinders. But among 4 cylinder cars it does, with average miles per gallon increasing with the number of gears.

The code for this plot is pretty complicated. Before moving on, let’s review how it is working.

  • mtcars |>: pipes the source data frame to the mutate() function on the next two lines.
  • mutate(gear = factor(gear),: factors the gear variable, overwriting the original; the comma indicates that there will be another operation within mutate().
  • cyl = factor(cyl)) |>: factors the cyl variable, overwriting the original, and pipes the result into the next function.
  • group_by(cyl, gear) |>: groups by both cyl and gear and pipes the tibble with this grouping metadata to the next function.
  • summarize(avg_mpg = mean(mpg)) |>: calculates average miles per gallon for groups defined by the unique combinations of the levels in cyl and gear, and pipes the resulting summary table into ggplot.
  • ggplot(mapping = aes(x = cyl, y = avg_mpg, fill = gear)) +: sets up the blank canvas with cyl on the \(x\)-axis, the calculated value of avg-mpg on the \(y\)-axis, and determines that bars will colored by levels in gear. The line ends with a +, signalling that the next line will be adding another layer to the plot.
  • geom_col(position = "dodge") +: adds the plot type—a bar plot—with values coming directly from the summary table. (If you wanted to have ggplot count the number of observations then use geom_bar().) The position argument indicates that the bars should be dodged—positioned side-by-side.
  • labs(title = "Bar plot of average mpg by cyl and gear"): adds a title.

29.1 Practice Questions

The ggplot2 package is great for exploring data and communicating insights. Here is a quick review of the key functions:

  • ggplot() creates the blank canvas. It has two arguments: data and mapping.
  • geom_point() creates a scatter plot.
  • geom_histogram() creates a histogram plot.
  • geom_density() creates a density plot—a smoothed version of a histogram.
  • geom_boxplot() creates a boxplot.
  • geom_bar creates a bar plot for a categorical variable with the heights of the bars determined by counts.
  • geom_col function creates a bar plot for a categorical variable with the heights of the bars drawn from a summary table.
  • labs() adds labeling details to a plot, like a title.
  • facet_wrap() creates a small multiples plot.

Using iris:

  1. Create a scatter plot showing the relationship between the Sepal.Length and Sepal.Width variables on the \(x\)- and \(y\)-axes, respectively, and the points colored according to the Species variable. Make sure to add a title to the plot: “Scatter Plot of Sepal Length and Sepal Width by Iris Species.”

  2. Create a scatter plot showing the relationship between the Petal.Length and Petal.Width variables on the \(x\)- and \(y\)-axes, respectively, and the points colored according to the Species variable. Create separate subplots for each species. Add a title to the plot: “Scatter Plot of Petal Length and Petal Width by Iris Species”. Think: is this style of plot better than the one above at showing species-level differences?

  3. Create a histogram of Petal.Length with bars colored by Species. (Hint: use the fill argument.) Add a title to the plot: “Histogram of Petal Length by Iris Species.”

  4. Create a histogram of Petal.Length with bars colored by Species. Create separate subplots for each species. Add a title to the plot: “Histogram of Petal Length by Species.” Think: is this plot better than the one above to show species-level differences in petal length? How could you improve it?

  5. Create a density plot showing Sepal.Width. Exclude the Setosa species and filter for Sepal.Width greater than 3. Color of the density line according to the Species variable. Add a title to the plot: “Density Plot of Sepal Width for Versicolor and Virginica Species.” (Hint: use filter() in dplyr to subset the data.)

  6. Create a bar plot of Species with the height of the bars determined by a count of observations. Add a title: “Bar Plot of Iris Species.”

  7. Create a bar plot of Species with the height of the bars determined by average petal length. Add a title: “Bar Plot of Average Petal Length by Iris Species.” (Hint: use group_by() and summarize() in dplyr.)

Using mtcars:

  1. Create a boxplot of hp by vs. Add a title: “Boxplot of hp by vs.” (Hint: use mutate() in dplyr.)

  2. Create a dodged bar plot of average hp by am (that is, am is the grouping variable) and color the bars by the values of carb. Add a title to the plot: “Bar Plot of hp by am and carb.” (Hint: use geom_col() with the position = "dodge" argument and create a summary table in dplyr using group_by().)

  3. Create a plot showing the relationships between 4 variables. Make a dodged bar plot of the relationship between am and average mpg, with bars colored by vs variable and subplots for each level of cyl. Add a title to the plot: “Bar Plot of Average mpg by am, cyl and vs.” (Hint: you should use mutate(), group_by(), and summarize() in dplyr and—among other functions in ggplot2—facet_wrap()).

The dplyr and ggplot2 packages have been loaded in the code box for your use.

Show answers
# Note: in the code below the plots are being saved as objects. To print
# p1, for example, you would type p1 in the console or code box.

## Question 1 -------------------------------

p1 <- iris |>
   ggplot(mapping = aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
   geom_point() +
   labs(title = "Scatter Plot of Sepal Length and Sepal Width by Iris Species")

## Question 2 -------------------------------

p2 <- iris |>
   ggplot(mapping = aes(x = Petal.Length, y = Petal.Width, color = Species)) +
   geom_point() +
   facet_wrap(facets = ~Species) +
   labs(title = "Scatter Plot of Petal Length and  Petal Width by Iris Species")

## Question 3 -------------------------------

p3 <- iris |>
   ggplot(mapping = aes(x = Petal.Length, fill = Species)) +
   geom_histogram() +
   labs(title = "Histogram of Petal Length by Iris Species")
    
## Question 4 -------------------------------

p4 <- iris |>
   ggplot(mapping = aes(x = Petal.Length)) +
   geom_histogram() +
   facet_wrap(facets = ~Species) +
   labs(title = "Histogram for Petal Length by Species")

## Question 5 -------------------------------

p5 <- iris |>
   filter(Sepal.Width > 3, Species != "setosa") |>
   ggplot(mapping = aes(x = Sepal.Width, color = Species)) +
   geom_density() +
   labs(title = "Density Plot of Sepal Width for Versicolor and Virginica Species")

## Question 6 -------------------------------

p6 <- iris |> 
   ggplot(mapping = aes(x = Species)) +
   geom_bar() +
   labs(title = "Bar Plot of Iris Species")

## Question 7 -------------------------------

p7 <- iris |>
     group_by(Species) |> 
     summarize(avg_length = mean(Petal.Length)) |> 
   ggplot(mapping = aes(x = Species, y = avg_length)) +
   geom_col() +
   labs(title = "Bar Plot of Average Petal Length by Iris Species")

## Question 8 -------------------------------

p8 <- mtcars |>
     mutate(vs = factor(vs)) |>
     ggplot(mapping = aes(x = vs, y = hp)) +
     geom_boxplot() +
     labs(title = "Box plot of hp by vs")
    
## Question 9 -------------------------------

p9 <- mtcars |> 
     mutate(carb = factor(carb), 
            am = factor(am)) |>
     group_by(carb, am) |> 
     summarize(avg_hp = mean(hp)) |> 
     ggplot(mapping = aes(x = am,y = avg_hp, fill = carb)) +
     geom_col(position = "dodge") +
     labs(title = "Bar plot of Average hp by am and carb")

## Question 10 -------------------------------

p10 <- mtcars |> 
     mutate(am = factor(am),
            cyl = factor(cyl),
            vs = factor(vs)) |> 
     group_by(am, cyl, vs) |>
     summarize(mean_mpg = mean(mpg)) |>
     ggplot(mapping = aes(x = am, y = mean_mpg, fill = vs)) +
     geom_col(position = "dodge") +
     facet_wrap(~ cyl) +
     labs(title = "Bar plot of Average mpg by am, cyl and vs")

30 Taking Stock

We’ve covered a lot of ground! The lessons so far have introduced functions from base R, dplyr and ggplot2, as well as some productivity tools in RStudio. The number of functions probably seems a little overwhelming. That can’t be avoided at this point. But if you can master this material you will have established a solid foundation for a career in data analysis. Keep practicing!

In the R world you will sometimes see strong opinions about coding paradigms. Some people advocate using only base R, regarding the tidyverse as essentially another programming language (or dialect) that is too difficult or convoluted for beginners. Others think beginners should start with the tidyverse, and avoid classic programming structures like loops. My approach in these lessons is pragmatic and non-ideological, which is why we started with base R, introduced dplyr and ggplot2, and will definitely cover loops. I find it works best to combine newer functions from the tidyverse with older functions from base R as needed for a particular data analysis task. Sometimes a loop is exactly what you need! At the same time, I can’t imagine a modern data scientist using base R alone—the fast data wrangling tools in dplyr and the exploratory graphics capabilities in ggplot2 are just too powerful to pass up. The important thing is to learn how to combine these functions flexibly and creatively to achieve your larger analytic goals. As Norm Matloff says: “Programming is a creative process. It’s like a grocery store and cooking: The store has lots of different potential ingredients, and you decide which ones to buy and combine into a meal.”

31 R Markdown

Earlier we saw how to create an R script. Scripts are great for saving and sharing work, but they are pretty rough aesthetically, without many formatting options. A notebook solves this problem. Similar to a script with comments, a notebook combines code and text, but can be compiled into a publishable-quality article or report—or, indeed, even a book or web page. The notebook format we’ll be using in RStudio is R Markdown.55 Beyond the improvements in formatting, though, notebooks like R Markdown also represent an advance in reproducible data science in that the finished document contains the code for the analysis within it, in so-called code chunks, woven together with written content. An author’s analysis and interpretation in a notebook can then easily be examined and evaluated by a collaborator or reviewer, making results more transparent and less error-prone.56

55 Notebooks are not unique to R or RStudio. The popular Jupityr Notebooks can be used with both R and Python. (“Jupityr” is actually a combination of the names of the major open source statistical programming languages— Julia, Python, R.) And Google offers a web-hosted version of Jupityr notebooks called Google Colab. RStudio even offers a new multi-language publishing system, Quarto, that allows authors to create documents that include executable code in Python, R or Julia.

56 In the bad old days researchers would do an analysis in Excel and then interpret the results in a paper. The problem with this workflow was (and is) two-fold: (1) Data manipulation steps in Excel are rarely recorded, making results difficult, if not impossible, to reproduce, even for the author. There is a famous case of an Excel error leading to incorrect conclusions in an influential economics paper. See this article on the Reinhart-Rogoff Error. (2) Using a script to record data manipulation steps would be a big improvement over Excel, but even then it would be possible for the script and the written content to get separated, in which case the author’s conclusions would be unsubstantiated by an analysis of the data.

57 Notice that .Rmd is the file type for an R Markdown document.

Go to RStudio and open an R Markdown document: File >>> New File >>> R Markdown (or click on the document icon in the upper left corner of RStudio and select R Markdown). A template file will automatically be opened (after you have been prompted to supply the title, author and date):57

RMarkdown Template

The template is helpful because it can easily be adapted. Among other things, it illustrates how writing is woven with code in an R Markdown document. The code is included in grayed-out code chunks in between blocks of text, which includes formatting instructions in a very simple language called Markdown.

We won’t cover Markdown syntax in much detail here since for the most part text is compiled exactly as you write it.58 In the template document are some examples of simple Markdown for creating headings (double hashtags: ## R Markdown and ## Including Plots) and bolded text (double asterisks: **Knit**).

58 Explore the syntax for the formatting language at this excellent introductory site: R Markdown. See, in particular, these lessons. At the bottom of the introduction page is a link to a helpful R Markdown Cheat Sheet.

At the top of the document is the yaml header with instructions for compiling the document. The header is enclosed by—starts and ends with— three dashes. In the above screenshot the output or document type has been automatically defined as html_document. (You could also choose pdf_document or word_document.)

Code chunks are opened and closed with three back ticks, and include some chunk information in curly braces. Here is the first code chunk from the template, which defines global settings for the document:

Global Settings Code Chunk
  • r: Defines this as an R code chunk.
  • setup: Provides the optional title for the chunk. (Notice there is no comma between r and the title.)
  • include = FALSE: Tells RStudio not to include this code chunk in the compiled document.
  • knitr::opts_chunks$set(echo = TRUE): Sets the global behavior for code chunks in the entire document to be echo = TRUE, meaning that the compiled document will show the code from the chunk along with the results.59

59 The syntax in this opts_chunk() function from the knitr package is not very clear but the details are not critical to understand. Just include this code chunk at the top of the document to set the global echo option.

The next code chunk creates a summary table:

Table Code Chunk

When the document is compiled R will show the code from the chunk, summary(cars), and display the result. If you don’t want the code shown (if, for example, you are writing a formal report) then override the global setting with echo = FALSE, as in the next code chunk:

Plot Code Chunk with Echo Off

In RStudio go ahead and click the Knit button in the menu immediately above the document. This will compile the document and open it automatically (as a web page, if you left the file type as html_document). This should give you a good sense of how R Markdown translates to HTML.

32 Coding Style

Analyzing data in a notebook like R Markdown will help make your work reproducible—thereby improving collaboration and productivity—but only if your code is readable. The example code in these lessons has been written to model readability. I hope you have started to internalize that style. Let’s review some guidelines for R coding style.

This code is hard to understand:

SnapshotOfData<-head(arrange(filter(mtcars,mpg>25),wt),5)

Here is the same code rewritten to be more readable:

# Filter for mpg > 25, sort by weight, take the top rows
mtcars |> 
     filter(mpg > 25) |> 
     arrange(wt) |> 
     head(5) -> data_snapshot # assigns the result to an object

Clearly, pipes help a lot to untangle the code. Here is a (very) brief of list the stylistic features of readable code.60

60 For all the details see the Tidyverse Style Guide.

  • Put functions on separate lines connected by pipes. This way we can see easily see the operations on the data in sequence.61
  • Add spaces to better show arguments. mpg > 25 is better than mpg>25, and x[, 1] is better than x[,1].
  • Object names should be in “snake_case”—lower case letters with with words separated with an underscore. Ideally names should be concise and meaningful.
  • Use double quotes not single quotes: mtcars[, "mpg"] not mtcars[, 'mpg'].
  • Comment your code. There haven’t been many comments in these lessons but that’s because the the written text functions as comments. Code that is not explained the text of a document should be briefly but clearly explained with comments.

61 I usually don’t use a pipe for just one function: filter(mtcars, wt > 25) is fine. But when two or more functions are nested it is best to unpack them with pipes.

These are opinionated guidelines; style is style, after all—each to their own. For example, in the last code chunk I added the object assignment on the last line. That is because I think it is more readable, especially for people new to R, for the flow of the piped code to go consistently top-to-bottom, right-to-left. You may choose to do the assignment in the first line going right to left. That would be fine. Just remember that readability should be one of your main goals in data science programming.

32.1 Practice Questions

Some standard coding style guidelines in R include:

  • Using snake_case for variable and function names (rather than camelCase or PascalCase).
  • Using # for comments.
  • Using the pipe operator |> for chaining together multiple operations in a single block of code.
  • Adding a space between operators and their operands (e.g., x + y, not x+y).
  • Using double rather than single quotes.

Using mtcars:

  1. Suppose you have written code to create a new variable—hp divided by wt—named Car_HP_To_WT_Ratio. Re-write the code to name the variable using snake case.

  2. Write code to calculate average mpg for cars with hp greater than 100, grouped by am. Add comments to explain the steps in the code. Think: What is the appropriate amount of commenting for readability?

  3. Write code to calculate median hp (saved as median_hp) for cars with gear greater than 3, grouped by cyl. Then pipe that data into ggplot to create a bar plot that shows the median_hp on the y-axis and cyl on the x-axis. Comment each step. (Hint: the plot type should be geom_col().) Again, think: What is the appropriate amount of commenting?

  4. How would you rewrite this code snippet to be more readable? filter(mtcars,vs==1&wt<3).

Show answers
## Question 1 -------------------------------

mtcars |>
     mutate(car_power_to_weight_ratio = hp/wt)

## Question 2 -------------------------------
     
# Calculates a conditional mean for mpg
mtcars |>
     filter(hp > 100) |> # keep rows where hp > 100
     group_by(am) |> # calculate avg mpg for am groups
     summarize(mean_mpg = mean(mpg))

## Question 3 -------------------------------

# Visualizes a conditional median for hp
p1 <- mtcars |>
     filter(gear > 3) |> # keeps rows for gear > 3
     group_by(cyl) |> # calculate median hp for cyl groups
     summarize(median_hp = median(hp)) |>
     ggplot(aes(x = cyl, y = median_hp)) + # create bar plot
     geom_col()

## Question 4 -------------------------------

mtcars |>
     filter(vs == 1, wt < 3)

33 Lists

The data structures we’ve discussed so far include vectors and data frames.

  • Vectors are one dimensional data structures, consisting in a set of observations with the same data type.
  • Data Frames are two-dimensional tabular data structures, with rows and columns. Each column is a vector, with the same data type.

Lists are also a very useful and common data structure. They are more flexible than either vectors or data frames in that they can be used to group together any mix of R structures and objects. For example, a list could contain a vector, a data frame, or even another list.

Use the list() function to create a list, with the elements separated by commas.

random_objects <- list(mtcars, 
                       rivers, 
                       list(1:8, letters), 
                       c("curly", "moe", "larry"))

These elements can be named while creating the list. Just add name = ... before the item.

random_objects <- list(old_cars = mtcars, 
                       river_lengths = rivers, 
                       numbers_letters = list(numbers = 1:8, 
                                              letters = c("a", "b", "c")), 
                       three_stooges = c("curly", "moe", "larry"))

The familiar str() function will show the list structure:

str(random_objects)
List of 4
 $ old_cars       :'data.frame':    32 obs. of  11 variables:
  ..$ mpg : num [1:32] 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
  ..$ cyl : num [1:32] 6 6 4 6 8 6 8 4 4 6 ...
  ..$ disp: num [1:32] 160 160 108 258 360 ...
  ..$ hp  : num [1:32] 110 110 93 110 175 105 245 62 95 123 ...
  ..$ drat: num [1:32] 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
  ..$ wt  : num [1:32] 2.62 2.88 2.32 3.21 3.44 ...
  ..$ qsec: num [1:32] 16.5 17 18.6 19.4 17 ...
  ..$ vs  : num [1:32] 0 0 1 1 0 1 0 1 1 1 ...
  ..$ am  : num [1:32] 1 1 1 0 0 0 0 0 0 0 ...
  ..$ gear: num [1:32] 4 4 4 3 3 3 3 4 4 4 ...
  ..$ carb: num [1:32] 4 4 1 1 2 1 4 2 2 4 ...
 $ river_lengths  : num [1:141] 735 320 325 392 524 ...
 $ numbers_letters:List of 2
  ..$ numbers: int [1:8] 1 2 3 4 5 6 7 8
  ..$ letters: chr [1:3] "a" "b" "c"
 $ three_stooges  : chr [1:3] "curly" "moe" "larry"

From this output we can see that there are 4 list elements:

  1. A data frame, old_cars, with 32 rows.
  2. A numeric vector, river_lengths, with 141 observations.
  3. A list, numbers-letters, consisting in a numeric vector,numbers, and a character vector, letters, with 8 and 3 observations, respectively.
  4. A character vector, three_stooges, with 3 items.

These individual list elements can be extracted using either dollar sign notation or square bracket notation. For example, here is how we would use dollar sign notation to return three_stooges:

random_objects$three_stooges
[1] "curly" "moe"   "larry"

Equivalently, since three_stooges is the fourth element we can index the list with 4 in double square brackets.62

62 We could also use the name of the list element: random_objects[["three_stooges"]]. Note that indexing with a name requires using quotation marks.

random_objects[[4]] 
[1] "curly" "moe"   "larry"
Detail: Double Brackets

Why double square brackets?

What would happen if we were to use single brackets on a list element?

random_objects[4]
$three_stooges
[1] "curly" "moe"   "larry"

There is a subtle difference here compared to the output above using double square brackets. This code has returned the list element, $three_stooges, but not the items themselves. Indeed, this is simply the fourth list element returned as a list:

str(random_objects[4])
List of 1
 $ three_stooges: chr [1:3] "curly" "moe" "larry"

Think of a list as a freight train with multiple cars. Indexing with single brackets returns a car (which is still a list). Indexing with double brackets returns the items in the car.

To extract individual items from three_stooges we index them using a single bracket, as is appropriate for a vector.

random_objects$three_stooges[1]
[1] "curly"

Or, same result:

random_objects[[4]][1]
[1] "curly"

What about items in the list within the list, the third element, numbers_letters? Index these items by stacking the brackets. This code returns the first element of that list, numbers:

random_objects[[3]][[1]]
[1] 1 2 3 4 5 6 7 8

And here is how we would extract the first number of that vector:

random_objects[[3]][[1]][1]
[1] 1

We could also stack dollar signs and then subset the resulting vector with square bracket notation:

random_objects$numbers_letters$numbers[1]
[1] 1

Is there a reason to prefer one approach—dollar sign notation rather than square bracket notation with numeric indexes—when subsetting? Not really. They both work. Keep in mind, though, that numeric indexing can run into problems if, say, the list is updated with another element. That could throw off the numeric indexes and cause the code to break.

33.1 Practice Questions

In R, a list is a collection of elements of different data types, such as numbers, strings, and other lists. Lists are created using the list() function, with the elements separated by commas.

In the code box, iris has been converted into a list, iris_list, for you to practice with.

  1. Write code to extract the second element of iris_list as a list.

  2. Write code to extract the second element of iris_list as a numeric value.

  3. Write code to return only the virginica species from the first element of iris_list.

  4. Write code to extract average sepal length for setosa and versicolor species from iris_list. Use dollar sign notation and square bracket notation.

  5. Write code to extract the standard deviation of sepal length for versicolor and virginica species from iris_list. Use only square bracket notation.

  6. Rename iris_list as new_iris_list and add an element to it: the ratio of Sepal.Length to Petal.Length. Using this new list calculate the average of this ratio.

Show answers
# Convert iris into a list:
iris_list <- list(species = iris$Species, 
                  avg_sepal_length = mean(iris$Sepal.Length), 
                  sd_sepal_length = sd(iris$Sepal.Length),
                  avg_by_species = tapply(iris$Sepal.Length, iris$Species, mean),
                  sd_by_species = tapply(iris$Sepal.Length, iris$Species, sd))

## Question 1 -------------------------------

iris_list[2]

str(iris_list[2]) # single brackets return a list

## Question 2 -------------------------------

iris_list[[2]]

str(iris_list[[2]]) # double brackets return the values within the list

## Question 3 -------------------------------

iris_list[[1]][iris_list[[1]]=="virginica"]

## Question 4 -------------------------------

iris_list$avg_by_species[1:2]

## Question 5 -------------------------------

iris_list[[5]][2:3]

## Question 6 -------------------------------

new_iris_list <- iris_list

new_iris_list$ratio <- iris$Sepal.Length / iris$Petal.Length

mean(new_iris_list$ratio)

34 Linear Regression (optional)

Lists are used in R for storing, among other things, model objects—the information returned after fitting a model. Let’s use linear regression as an example. The purpose here is not to explain regression but to continue working with lists by exploring a common use case.

Briefly, the simple linear regression model is defined as:

\[ \hat{y_i} = \beta_{0} + \beta_{1} x_{i} \]

where \(i\) indexes the observations, and

  • \(\hat{y_i}\) is the \(i^{th}\) predicted value of the target variable;63
  • \(\beta_{0}\) is the intercept;
  • \(\beta_{1}\) is the slope;
  • \(x_i\) is the \(i^{th}\) value of the predictor variable.

63 In statistics hat notation—the caret symbol over the \(y\)—means “predicted.”

The lm() function in R fits a linear model and by default returns the estimated intercept and slope of the regression line. Let’s demonstrate with mtcars by creating a model of mpg using wt as a predictor:

model <- lm(mpg ~ wt, data = mtcars)
model

Call:
lm(formula = mpg ~ wt, data = mtcars)

Coefficients:
(Intercept)           wt  
     37.285       -5.344  

The regression model equation can be written: \(\widehat{mpg} = 37.285 - 5.344 \space \text{x} \space wt\). With this equation we can predict mpg for any value of wt. Those predictions lie on the regression line defined by the intercept and slope:

`geom_smooth()` using formula = 'y ~ x'

Of course, there are other potentially interesting aspects of a model, beyond just the intercept and slope. Additional information is available in the model object and—the most common source—the model summary:

summary(model)

Call:
lm(formula = mpg ~ wt, data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.5432 -2.3647 -0.1252  1.4096  6.8727 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  37.2851     1.8776  19.858  < 2e-16 ***
wt           -5.3445     0.5591  -9.559 1.29e-10 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.046 on 30 degrees of freedom
Multiple R-squared:  0.7528,    Adjusted R-squared:  0.7446 
F-statistic: 91.38 on 1 and 30 DF,  p-value: 1.294e-10

The summary() function prints this information to the console but also, in the background, creates a list object that we can look at with str():

summary(model) |> 
     str()
List of 11
 $ call         : language lm(formula = mpg ~ wt, data = mtcars)
 $ terms        :Classes 'terms', 'formula'  language mpg ~ wt
  .. ..- attr(*, "variables")= language list(mpg, wt)
  .. ..- attr(*, "factors")= int [1:2, 1] 0 1
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:2] "mpg" "wt"
  .. .. .. ..$ : chr "wt"
  .. ..- attr(*, "term.labels")= chr "wt"
  .. ..- attr(*, "order")= int 1
  .. ..- attr(*, "intercept")= int 1
  .. ..- attr(*, "response")= int 1
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
  .. ..- attr(*, "predvars")= language list(mpg, wt)
  .. ..- attr(*, "dataClasses")= Named chr [1:2] "numeric" "numeric"
  .. .. ..- attr(*, "names")= chr [1:2] "mpg" "wt"
 $ residuals    : Named num [1:32] -2.28 -0.92 -2.09 1.3 -0.2 ...
  ..- attr(*, "names")= chr [1:32] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Hornet 4 Drive" ...
 $ coefficients : num [1:2, 1:4] 37.285 -5.344 1.878 0.559 19.858 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:2] "(Intercept)" "wt"
  .. ..$ : chr [1:4] "Estimate" "Std. Error" "t value" "Pr(>|t|)"
 $ aliased      : Named logi [1:2] FALSE FALSE
  ..- attr(*, "names")= chr [1:2] "(Intercept)" "wt"
 $ sigma        : num 3.05
 $ df           : int [1:3] 2 30 2
 $ r.squared    : num 0.753
 $ adj.r.squared: num 0.745
 $ fstatistic   : Named num [1:3] 91.4 1 30
  ..- attr(*, "names")= chr [1:3] "value" "numdf" "dendf"
 $ cov.unscaled : num [1:2, 1:2] 0.38 -0.1084 -0.1084 0.0337
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:2] "(Intercept)" "wt"
  .. ..$ : chr [1:2] "(Intercept)" "wt"
 - attr(*, "class")= chr "summary.lm"

Wow. This is a complicated list object! The intercept and slope appear here (under $ coefficients) along with a lot of other information, including model fit statistics such as R-squared and Adjusted R-squared. Let’s take a look at coefficients.

summary(model)$coefficients
             Estimate Std. Error   t value     Pr(>|t|)
(Intercept) 37.285126   1.877627 19.857575 8.241799e-19
wt          -5.344472   0.559101 -9.559044 1.293959e-10

This is technically a matrix—essentially a two dimensional vector—with row and column names.64 (What looks like the first column is actually the row names.) To extract the intercept and slope numbers from this matrix we would use square bracket notation, as in a data frame:

64 Matrices are similar to data frames in having both rows and columns, but are dissimilar in not mixing data types. Numeric matrices are the workhorses of scientific computing in R.

summary(model)$coefficients[1:2, 1]
(Intercept)          wt 
  37.285126   -5.344472 

And to extract R-squared:

summary(model)$r.squared
[1] 0.7528328
Tip: Inline Code

The output from the summary of a model object is designed to be looked at and interpreted. However, it is sometimes useful to write code to extract an element directly from the summary, to include in the text of a report, for example, without needing to manually transcribe it. In RMarkdown, I could write inline code (which works like a mini code chunk) to extract R-squared from the model and insert it into my sentence, like this: “The model R-squared is 0.75.” To get that R-squared number I used a single backtick to open the inline code, followed by an r (to indicate that it is R code), and then a concluding backtick after the code: “The model R-squared is ‘r summary(model)$r.squared |> round(2)’.” Extracting information directly from the model like this is especially helpful if you are writing a repeating report that includes numbers that will change.

35 Creating Data Frames

We have been using data frames extensively in these lessons. How would we create a data frame?

Easy. Use the data.frame() function to name and define columns. The process is similar to creating a list, except that data frames are more restrictive.

Here is a simple example:

data.frame(numbers = 1:3,
           letters = c("a", "b", "c"))
  numbers letters
1       1       a
2       2       b
3       3       c

Both columns, numbers and letters, have 3 observations. What if the column lengths were different?

data.frame(numbers = 1:8,
           letters = c("a", "b", "c"))
Error in data.frame(numbers = 1:8, letters = c("a", "b", "c")): arguments imply differing number of rows: 8, 3

An error.

Most modeling algorithms require tabular data, which is why data frames are so common in analytics. If you need to store non-tabular data then use a list.

I should mention a couple of helpful functions for efficiently creating vectors or—the same thing— data frame columns:

  • seq() stands for “sequence” and has three main arguments: from (the start of the sequence), to (the end) and by (the increment).
  • rep() stands for “repeat” and has two main arguments: x (the item to be repeated), times (the number of repetitions).

Here are some examples:

seq(from = 2, to = 20, by = 2)
 [1]  2  4  6  8 10 12 14 16 18 20
rep(x = "a", times = 10)
 [1] "a" "a" "a" "a" "a" "a" "a" "a" "a" "a"

Take care to define columns with the same number of rows:

data.frame(numbers = seq(from = 2, to = 20, by = 2),
           letters = c(rep(x = "a", times = 5),
                       rep(x = "b", times = 5)))
   numbers letters
1        2       a
2        4       a
3        6       a
4        8       a
5       10       a
6       12       b
7       14       b
8       16       b
9       18       b
10      20       b

It can be convenient to replace the to argument with an alternative, length.out, which ensures a certain length of output.

data.frame(numbers = seq(from = 2, by = 2, length.out = 10),
           letters = c(rep(x = "a", times = 5),
                       rep(x = "b", times = 5)))
   numbers letters
1        2       a
2        4       a
3        6       a
4        8       a
5       10       a
6       12       b
7       14       b
8       16       b
9       18       b
10      20       b

35.1 Practice Questions

Use the data.frame() function to name and define columns. Creating a data frame is similar to creating a list, except data frames are more restrictive in being strictly tabular.

  1. Create a data frame with two columns, I and J, where I goes from 1 to 10 (by increments of 1) and J is a repeating sequence of the word “Success.”

  2. Create a data frame with two columns, numbers and words, where numbers goes from 2 to 20 in increments of 2 and words alternate between “Won” and “Lost” with the same number of observations as numbers.

  3. Create a data frame with two columns, name and age, where the name is a repeating sequence of the names “Mahesh Babu”, “Pawan Kalyan”, “Prabas”, and “Allu Arjun.” (These names should repeat twice.). Their ages are: 24, 26, 22, 27.

  4. Create a data frame with two columns, A and B. The A column should contain the sequence of numbers from 2 to 5 with a step of 0.5 and a length of 20, and the B column should contain the repeated value “17.02” for 20 times.

  5. Create a data frame with two columns, C and D. The C column should contain the first 10 observations of hp from mtcars. The D column should contain the next 10 observations of hp (i.e., from hp\(_{11}\) to hp\(_{20}\)).

Show answers
## Question 1 -------------------------------

I <- 1:10

J <- rep("Success", times = length(I))

df1 <- data.frame(I, J)

df1

## Question 2 -------------------------------

numbers <- seq(from = 2, to = 20, by = 2)

words <- rep(c("Won", "Lost"), times = length(numbers)/2)

df2 <- data.frame(numbers, words)

df2

## Question 3 -------------------------------

name <- rep(c("Mahesh Babu", "Pawan Kalyan", "Prabas", "Allu Arjun"), times = 2)

age <- rep(c(24, 26, 22, 27), times = 2)

df3 <- data.frame(name, age)

df3

## Question 4 -------------------------------

df4 <- data.frame(A = seq(from = 2, by = 0.5, length.out = 20), 
                  B = rep("17.02", 20))

head(df4) # Returns the first 6 rows of the data frame

## Question 5 -------------------------------

df5 <- data.frame(C = mtcars$hp[1:10], 
                  D = mtcars$hp[11:20])

head(df5) # Returns the first 6 rows of the data frame

36 Writing Functions

As you know, learning R consists in learning a daunting number of functions. Indeed, it is not an exaggeration to say that R is really nothing but a set of functions for performing various routine tasks, usually with data. But one of the features that makes R so powerful is that we are not restricted merely to using the functions from base R or contributed packages. We can also write functions of our own. This is easier than it sounds!

Here is a simple example:

return_items <- function (items) {
     items
}

Let’s unpack the details:

  • return_items <-: Saves the function as a named object in the environment.
  • function (items) { }: Defines the function with a single argument, items. The arguments go within the parentheses, while the body of the function, containing the code to be executed, goes within the curly braces. The name of the argument is arbitrary but should be descriptive.
  • items: Executes the the code in the body of the function by returning items. The code uses the named argument as an input.

Once defined, this function can be called like any other by supplying an input for the argument:

return_items(items = 1:5)
[1] 1 2 3 4 5

The value of creating a function is that it performs routine tasks with varying inputs. So, if you find yourself writing the same code repeatedly to solve similar tasks, consider writing a function!

Admittedly, return_items() isn’t very useful since we could get the same result by simply typing (with fewer keystrokes) 1:5 in the console.

An example of a more useful—and more complicated— function would be one that finds the mode, or most common level, for a factor variable in a vector or data frame column. To my knowledge, base R does not have such a function. Let’s make it!

mode <- function(x) {
     
    data.frame(x) |> 
          count(x) |> 
          arrange(desc(n)) -> df
     
     df[1, 1]
     
}

How does this function work?

  • mode <- function(x){ }: Defines a function, mode, with one named argument, x, for a factor variable. Notice that x is used to write the code in the body of the function.
  • data.frame(x) |>: Creates a data frame (since dplyr only works with data frames) and pipes it into the next line.
  • count(x) |>: Creates a summary table with counts of unique observations in a column titled n.
  • arrange(desc(n)) -> df: Arranges the summary table with the largest n in the top row and saves it in a data frame, df.
  • df[1, 1]: Extracts the value with the largest n from df.
Memory in R

What does it mean to say that df is “saved”? Saved where?

To answer this question requires touching on the notion of scoping in computer science:

“In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity.

A fundamental distinction in scope is what “part of a program” means. In languages with lexical scope, name resolution depends on the location in the source code and the lexical context, which is defined by where the named variable or function is defined.” Wikipedia

The R language is lexically scoped; name resolution depends on context. So, df is saved, but not in the global environment. Instead, its lexical context is the mode() function, within which the name binding is valid. In effect, R compartmentalizes memory. Objects like df saved within a function will not appear in RStudio’s Environment pane.

To understand the action inside a function it can be helpful to run the code piece by piece. We’ll use cyl in mtcars as the test input. Here is the output from first two lines:

data.frame(x = mtcars$cyl) |> 
     count(x) 
  x  n
1 4 11
2 6  7
3 8 14

Now, sort the table by n:

data.frame(x = mtcars$cyl) |> 
     count(x) |> 
     arrange(desc(n))
  x  n
1 8 14
2 4 11
3 6  7

The final step in the function is to extract the highest frequency value—8 cylinders— from the table with df[1, 1].

Let’s see if the function works as expected.

mode(mtcars$cyl)
[1] 8

Great! We can now use it as we would any other function in a summary table.

mtcars |> 
     summarize(avg_mpg = mean(mpg),
               avg_wt = mean(wt),
               avg_hp = mean(hp),
               mode_cyl = mode(cyl),
               mode_carb = mode(carb),
               mode_gear = mode(gear)) |> 
     round(2)
  avg_mpg avg_wt avg_hp mode_cyl mode_carb mode_gear
1   20.09   3.22 146.69        8         2         3

We should acknowledge that there are some situations in which mode() would fail or produce misleading results.

  1. It should not be used with a continuous vector. (The mode is a summary statistic for factor variables.)
  2. It will produce an error for any input other than a vector. (Try it with a data frame.)
  3. If there are two factor levels with the same number of observations it would return one of them arbitrarily.

So, this function could use some further development—we might want to build in some error messages and warnings, for example, depending on how (and by whom) it will be used—but it is a good first effort.

36.1 Practice Questions

In R, a function is a block of code that performs a specific task. Functions are a way to organize and reuse code, making it more modular and easier to maintain. Functions take one or more input parameters, called arguments, and return one or more output values, called the return value.

Note that using dplyr inside functions—if it involves column names—requires some advanced programming techniques. For that reason use base R for these exercises.

Using mtcars:

  1. Create a function reciprocal_var that takes in a data frame and a variable name as inputs and returns the data frame with the specified variable column replaced by its reciprocal values. (The reciprocal of a variable, var, is 1/var.) Show that the function works by using it with the mpg.

  2. Create a function filter_by_threshold that takes in a data frame, a variable name, and a threshold value as inputs and returns the rows of the data frame where the specified variable is greater than the given threshold. Show that the function works by using it with the hp with a threshold of 100.

  3. Create a function conditional_median that takes in (1) a data frame (2) a grouping variable and (3) a variable to be summarized. The function should return the conditional median. Use it to calculate the conditional median of the disp column. (Hint: use tapply().)

  4. Create a function cube_var that takes in a vector of number and cubes each one. Show that your function works using the wt column in mtcars.

Show answers
## Question 1 -------------------------------

reciprocal_var <- function(data, var){
  
  data[,var] <- 1/data[,var]
  data
}

reciprocal_var(mtcars, "mpg")

## Question 2 -------------------------------

filter_by_threshold <- function(data, var, threshold){
  
  data[data[,var] > threshold,]
  
}

filter_by_threshold(mtcars, "hp", 100)

## Question 3 -------------------------------

conditional_median <- function(data, grouping_var, target_var) {
  
  tapply(data[, target_var], data[, grouping_var], median)
}

conditional_median(mtcars, "cyl", "disp")


## Question 4 -------------------------------

cube_var <- function(var){
  
  var^3
}

cube_var(mtcars$wt)

37 Loops

In R, many functions are vectorized, meaning that they work on an entire vector at once, without needing to explicitly perform an operation on each individual element. Such functions are extremely fast and efficient. For example, in an earlier lesson we saw that we could add 1 to each river length in the rivers data with rivers + 1. The alternative would be tedious (to say the least), requiring a huge amount of typing: c(rivers[1] + 1, rivers[2] + 1, ... rivers[141] + 1). However, we could easily automate this addition procedure with a loop, a fundamental programming construct in R that would iterate over each individual vector element in rivers and add a 1. We’ll see how to do that in a moment. A loop in this case would not have much practical value, however. The vectorized approach would certainly be faster and easier.

When—and why—would it be advantageous to use a loop? Let’s start with the main disadvantage: loops are slow, at least compared to a vectorized alternative. That may not always matter, of course. You might be working with a relatively small data set, for example, in which case the difference in execution speed would be negligible. The main advantage of loops—also related to speed— is that they are easy to conceptualize and set up. Sometimes it can be difficult to think of how to vectorize certain complicated operations that would be simple with a loop. In such cases, a loop might be slower to run but faster to set up, perhaps saving time overall.

There are two main features of a loop:

  1. Sequence. The counter and the sequence for the loop iterations.
  2. Body. The code to be executed in each loop.

Here is a (very) basic for loop.65

65 Another common loop type in R is a while loop, which continues the loop while a defined condition is true. When that condition stops being true the loop ends. This type of loop uses the “while” keyword.

for (i in 1:5) {         # 1. Sequence
     
     print(i)            # 2. Body

     }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

This result shows the inner workings of the loop. In each loop the counter, i, increments by 1 for the length of the sequence 1:5. In the first loop i equals 1, which is what gets printed.66 In the second loop i equals 2, and so forth. The counter name is arbitrary, created by the programmer, and functions as a placeholder for each numbered iteration, to be used in the body of the loop.

66 To print a return value inside a loop we cannot just type the name of the object but must call print() explicitly.

In more complicated loops the counter is used to index observations from a variety of data structures. To see how this works let’s return to the rivers + 1 example. In this case we need to add a beginning step to initialize an empty vector that will hold the new values.

new_rivers <- rep(0, 141)               # Initialize output vector

for(n in 1:141){                        # 1. Sequence
     
     new_rivers[n] <- rivers[n] + 1     # 2. Body

     }

sum(new_rivers == rivers + 1)           # Check. Should equal 141.
[1] 141

Looks good. Let’s unpack the code.

  • new_rivers <- rep(0, 141): Creates an empty vector, new_rivers, that is equal to the length of rivers and consists in 0s. These are placeholder values that will be incrementally replaced with the new values as the loop runs.
  • for(n in 1:141){ }: Defines the counter, n, and sequence, 1:141, to be looped over.
  • new_rivers[n] <- rivers[n] + 1: Assigns a value to the \(n\)th observation of new_rivers based on the \(n\)th observation in rivers, after adding 1.

We’ve just done a lot of programming to perform a simple task! When would it actually be easier to use a loop?

Consider the following situation. A researcher has conducted a large-scale experiment involving 50 different labs across the country. The data sets from each lab have been stored in a Github repository as .csv files. How could they efficiently be downloaded and combined? With a loop! This could be accomplished manually, of course, but a loop will be faster and less tedious. Fortunately the file names are numbered systematically—experimental_data1.csv through experimental_data50.csv—so it will be easy to loop through them. The files have the same three columns— lab_number, patient_id, result—but different numbers of rows. The end goal is to produce a single data frame that can be used for analysis.

For this example we will be using a couple of new functions:

  • paste0(): “Pastes” objects together into a single text string without spaces (that’s what the 0 means). To paste with spaces use paste().
  • rbind(): Combines data frames with the same columns by stacking rows. The function name stands for “row bind.”

Here is the loop:

experimental_data <- data.frame()

for(i in 1:50){
     
     url <- paste0("https://raw.githubusercontent.com/jefftwebb/data/main/experimental_data", i,".csv")
     df <- read.csv(url)
     experimental_data <- rbind(experimental_data, df)
     print(i)
     
     }

Code explanation:

  • experimental_data <- data.frame(): Initializes an empty data frame without specifying the exact columns or number of rows.
  • for(i in 1:50){ }: Defines the counter and sequence.
  • url <- paste0("...", i,".csv"): Constructs the temporary URL by pasting together the path to the data, the file number and the file type. Why temporary? The URL will get overwritten in each loop as the counter increments. That is by design: we only need the current URL.
  • df <- read.csv(url): Reads the data from the URL and temporarily stores it in df, which will also get overwritten in each loop.
  • experimental_data <- rbind(experimental_data, df): Adds the rows from df in each loop to the output data frame.
  • print(i): Prints the loop counter. This is helpful to keep track of loop progress for potentially long running operations.

The resulting data frame looks like this.

str(experimental_data)
'data.frame':   5513 obs. of  4 variables:
 $ X         : int  1 2 3 4 5 6 7 8 9 10 ...
 $ lab_number: int  415 415 415 415 415 415 415 415 415 415 ...
 $ patient_id: chr  "415_4179" "415_9525" "415_3429" "415_5802" ...
 $ result    : num  9.3 9 7.1 9.9 7.6 5 8.9 12.8 8.3 11.8 ...

Suppose the researcher would like a summary table with a count of patients and the average result from each lab. This analysis is now straightforward using dplyr:

experimental_data |> 
     group_by(lab_number) |> 
     summarize(patient_count = n(),
               avg_result = mean(result),
               avg_result = round(avg_result, 2)) 
# A tibble: 50 × 3
   lab_number patient_count avg_result
        <int>         <int>      <dbl>
 1         14           191      10.2 
 2         23           158      10.0 
 3         26           187      10.3 
 4         91           174       9.96
 5        118            80      10.0 
 6        135            24      10.2 
 7        143           107       9.72
 8        179            44      10.3 
 9        195            29       9.42
10        211           108      10.0 
# ℹ 40 more rows

Bon Voyage

These lessons have introduced the basics of R programming, with a focus on the practical skills needed for exploring and wrangling data. You now have a solid foundation for doing data analysis in R. Best of luck in your continued learning journey!

Appendix: List of R Functions

Functions are listed roughly in the order of appearance in these lessons.

  • Mathematical operators:
    • -: Subtract.
    • /: Divide.
    • *: Multiply.
    • ^: Raise to a power.
    • %%: Calculate the remainder of division (the modulo operator).
  • <-: The assignment operator for assigning a value to an object in the environment.
  • hist(): Creates a frequency plot, or histogram, from a vector of numbers.
  • median(): Calculates the median of a vector. If there are an odd number of values in the vector, the function returns the middle value. If there are an even number of values in the vector, the function returns the average of the two middle numbers.
  • mean(): Returns the average of a numeric vector.
  • sd(): Calculates the the standard deviation of a vector.
  • sum(): Adds up the values in a numeric vector.
  • length(): Counts the number of items in a vector.
  • min() and max(): Finds the minimum/maximum observation in as vector.
  • ?: Get help for a function. For example to get help on the hist() function type ?hist in the console.
  • Logical operators:
    • >: greater than.
    • <: less than.
    • ==: equal to.
    • !=: not equal to.
    • >=: greater than or equal to.
    • <=: less than or equal to.
    • !x: not x.
    • x | y: x OR y.
    • x & y: x AND y.
  • [ ]: Square bracket notation for subsetting vectors.
  • c(): Create a vector by combining elements together.
  • which(): Returns the index of the values satisfying a given condition.
  • head(): Returns the first n rows a data frame. (By default, n is 6.)
  • summary(): Provides a five-number summary of the numeric columns in a data frame: the minimum value, the first quartile (25th percentile), the median, the third quartile (75th percentile), and the maximum value.
  • str(): Provides helpful information about the structure of a data frame. (The “str” stands for “structure.”).
  • View(): Brings up a spreadsheet-style data viewer within RStudio.
  • [ , ]: Square bracket notation for subsetting data frames. Before the comma is the rows slot, after is the column slot: data[rows we want, columns we want].
  • Colon notation: a shorthand method combined for selecting rows or columns in a range when using square bracket notation.
  • nrow(): Returns the number of rows of in a data frame.
  • $: dollar sign notation picks out a single column from a data frame—data$column.
  • plot(): Creates a scatterplot showing the relationship between two quantitative variables. (It can also be used to create different kinds of plots.)
  • boxplot(): Creates a boxplot to display the relationship between a quantitative and a categorical variable.
  • factor(): Creates a factor variable.
  • tapply(): Applies a function over subsets of a vector defined by the levels of a factor variable.
  • install.packages(): Downloads and installs a package.
  • library(): Loads the installed packages into the environment.
  • read.csv(): Reads a .csv file into the environment as a data frame.
  • write.csv(): Exports a data frame to a .csv file with fields separated by comma delimiter.
  • getwd(): Returns the path to the working directory.
  • setwd(): Sets the working directory.
  • |>: The pipe operator. The pipe passes the object on its left hand side to the first argument in the function on its right-hand side, on the next line.
  • filter(): A dplyr verb that subsets a data frame by rows, returning only specific rows as specified by logical criteria.
  • arrange(): A dplyr verb that sorts a data frame by rows based on the variable included as an argument. (Default sorting is from low to high.)
  • desc(): Reverses the default sorting in arrange() to be high to low.
  • select(): A dplyr verb that subsets a data frame by columns.
  • mutate(): A dplyr verb that creates a new data frame column.
  • summarize(): A dplyr verb that creates a summary table.
  • group_by(): A dplyr verb that partitions a data frame according the levels in a categorical grouping variable for performing conditional operations with other dplyr verbs.
  • n(): a dplyr helper function for counting the number of observations.
  • round(): A base R function that rounds a numeric vector input to the specified number of digits.
  • count(): A dplyr verb that creates a tables of counts, in effect combining group_by() and summarize(n = n()).
  • ungroup(): A dplyr verb that removes the grouping metadata from a data frame.
  • ggplot(): The first function used in a ggplot2 plot visualization to create the blank canvas. It has two arguments: data and mapping.
  • aes(): The function used within the mapping argument to ggplot() to specify the visual relationships in the plot: which variables map to the \(x\) and \(y\) axes.
  • +: The operator that adds another layer to a ggplot2 visualization. Not to be confused with |>! It is easy to type |> out of habit.
  • geom_point(): The ggplot2 geom that makes a scatterplot.
  • geom_histogram(): The ggplot2 geom that makes a histogram.
  • geom_boxplot(): The ggplot2 geom that makes a boxplot.
  • geom_bar(): The ggplot2 geom that makes a bar plot for a categorical variable with the heights of the bars determined by counts.
  • geom_col(): The ggplot2 geom that makes a bar plot for a categorical variable with the heights of the bars drawn from a summary table.
  • labs(): The ggplot2 function for adding a title to a plot.
  • facet_wrap(): A ggplot2 function for creating a small multiples plot.
  • list(): Creates a list.
  • data.frame(): Creates a data frame.
  • seq() stands for “sequence” and has three main arguments: from (the start of the sequence), to (the end) and by (the increment).
  • rep() stands for “repeat” and has two main arguments: x (the item to be repeated), times (the number of repetitions).
  • function(){}: Defines a function. The arguments to the function go within the parentheses and the body of the function —the code to be executed—within the curly braces.
  • `for(i in seq){}” Defines a counter and sequence for a loop. The code to be executed in the loop goes within the curly braces.
  • paste0(): Concatenates objects and “pastes” them together into a single text string without spaces (that’s what the 0 means). paste() is the same except that spaces are added.
  • rbind(): Combines data frames with the same columns by stacking rows. The function name stands for “row bind.”