1  Introduction

Data science is an exciting discipline that allows you to transform raw data into understanding, insight, and knowledge. The goal of “R for Data Science” is to help you learn the most important tools in R that will allow you to do data science efficiently and reproducibly. After reading this book, you’ll have the tools to tackle a wide variety of data science challenges, using the best parts of R.

1.1 What you will learn

Data science is a huge field, and there’s no way you can master it all by reading a single book. The goal of this book is to give you a solid foundation in the most important tools, and enough knowledge to find the resources to learn more when necessary. Our model of the tools needed in a typical data science project looks something like Figure 1.1.

A diagram displaying the data science cycle: Import -> Tidy -> Understand (which has the phases Transform -> Visualize -> Model in a cycle) -> Communicate. Surrounding all of these is Communicate.

Figure 1.1: In our model of the data science process you start with data import and tidying. Next you understand your data with an iterative cycle of transforming, visualizing, and modeling. You finish the process by communicating your results to other humans.

First you must import your data into R. This typically means that you take data stored in a file, database, or web application programming interface (API), and load it into a data frame in R. If you can’t get your data into R, you can’t do data science on it!

Once you’ve imported your data, it is a good idea to tidy it. Tidying your data means storing it in a consistent form that matches the semantics of the dataset with the way it is stored. In brief, when your data is tidy, each column is a variable, and each row is an observation. Tidy data is important because the consistent structure lets you focus your efforts on answering questions about the data, not fighting to get the data into the right form for different functions.

Once you have tidy data, a common next step is to transform it. Transformation includes narrowing in on observations of interest (like all people in one city, or all data from the last year), creating new variables that are functions of existing variables (like computing speed from distance and time), and calculating a set of summary statistics (like counts or means). Together, tidying and transforming are called wrangling, because getting your data in a form that’s natural to work with often feels like a fight!

Once you have tidy data with the variables you need, there are two main engines of knowledge generation: visualisation and modelling. These have complementary strengths and weaknesses so any real analysis will iterate between them many times.

Visualisation is a fundamentally human activity. A good visualisation will show you things that you did not expect, or raise new questions about the data. A good visualisation might also hint that you’re asking the wrong question, or that you need to collect different data. Visualisations can surprise you and they don’t scale particularly well because they require a human to interpret them.

The last step of data science is communication, an absolutely critical part of any data analysis project. It doesn’t matter how well your models and visualisation have led you to understand the data unless you can also communicate your results to others.

Surrounding all these tools is programming. Programming is a cross-cutting tool that you use in nearly every part of a data science project. You don’t need to be an expert programmer to be a successful data scientist, but learning more about programming pays off, because becoming a better programmer allows you to automate common tasks, and solve new problems with greater ease.

You’ll use these tools in every data science project, but for most projects they’re not enough. There’s a rough 80-20 rule at play; you can tackle about 80% of every project using the tools that you’ll learn in this book, but you’ll need other tools to tackle the remaining 20%. Throughout this book, we’ll point you to resources where you can learn more.

1.2 How this book is organised

The previous description of the tools of data science is organised roughly according to the order in which you use them in an analysis (although of course you’ll iterate through them multiple times). In our experience, however, learning data ingest and tidying first is sub-optimal, because 80% of the time it’s routine and boring, and the other 20% of the time it’s weird and frustrating. That’s a bad place to start learning a new subject! Instead, we’ll start with visualisation and transformation of data that’s already been imported and tidied. That way, when you ingest and tidy your own data, your motivation will stay high because you know the pain is worth the effort.

Within each chapter, we try and adhere to a similar pattern: start with some motivating examples so you can see the bigger picture, and then dive into the details. Each section of the book is paired with exercises to help you practice what you’ve learned. Although it can be tempting to skip the exercises, there’s no better way to learn than practicing on real problems.

1.3 What you won’t learn

There are a number of important topics that this book doesn’t cover. We believe it’s important to stay ruthlessly focused on the essentials so you can get up and running as quickly as possible. That means this book can’t cover every important topic.

1.3.1 Modeling

To learn more about modeling, we highly recommend Tidy Modeling with R, by our colleagues Max Kuhn and Julia Silge. This book will teach you the tidymodels family of packages, which, as you might guess from the name, share many conventions with the tidyverse packages we use in this book.

1.3.2 Big data

This book proudly focuses on small, in-memory datasets. This is the right place to start because you can’t tackle big data unless you have experience with small data. The tools you learn in this book will easily handle hundreds of megabytes of data, and with a little care, you can typically use them to work with 1-2 Gb of data. If you’re routinely working with larger data (10-100 Gb, say), you should learn more about data.table. This book doesn’t teach data.table because it has a very concise interface that offers fewer linguistic cues, which makes it harder to learn. However, if you’re working with large data, the performance payoff is well worth the effort required to learn it.

If your data is bigger than this, carefully consider whether your big data problem is actually a small data problem in disguise. While the complete data set might be big, often the data needed to answer a specific question is small. You might be able to find a subset, subsample, or summary that fits in memory and still allows you to answer the question that you’re interested in. The challenge here is finding the right small data, which often requires a lot of iteration.

Another possibility is that your big data problem is actually a large number of small data problems in disguise. Each individual problem might fit in memory, but you have millions of them. For example, you might want to fit a model to each person in your dataset. This would be trivial if you had just 10 or 100 people, but instead you have a million. Fortunately, each problem is independent of the others (a setup that is sometimes called embarrassingly parallel), so you just need a system (like Hadoop or Spark) that allows you to send different datasets to different computers for processing. Once you’ve figured out how to answer your question for a single subset using the tools described in this book, you can learn new tools like sparklyr to solve it for the full dataset.

1.3.3 Python, Julia, and friends

In this book, you won’t learn anything about Python, Julia, or any other programming language useful for data science. This isn’t because we think these tools are bad. They’re not! And in practice, most data science teams use a mix of languages, often at least R and Python.

However, we strongly believe that it’s best to master one tool at a time. You will get better faster if you dive deep, rather than spreading yourself thinly over many topics. This doesn’t mean you should only know one thing, just that you’ll generally learn faster if you stick to one thing at a time. You should strive to learn new things throughout your career, but make sure your understanding is solid before you move on to the next interesting thing.

We think R is a great place to start your data science journey because it is an environment designed from the ground up to support data science. R is not just a programming language, it is also an interactive environment for doing data science. To support interaction, R is a much more flexible language than many of its peers. This flexibility comes with its downsides, but the big upside is how easy it is to evolve tailored grammars for specific parts of the data science process. These mini languages help you think about problems as a data scientist, while supporting fluent interaction between your brain and the computer.

1.4 Prerequisites

We’ve made a few assumptions about what you already know in order to get the most out of this book. You should be generally numerically literate, and it’s helpful if you have some programming experience already. If you’ve never programmed before, you might find Hands on Programming with R by Garrett to be a useful adjunct to this book.

There are four things you need to run the code in this book: R, RStudio, a collection of R packages called the tidyverse, and a handful of other packages. Packages are the fundamental units of reproducible R code. They include reusable functions, the documentation that describes how to use them, and sample data.

1.4.1 R

To download R, go to CRAN, the comprehensive R archive network. CRAN is composed of a set of mirror servers distributed around the world and is used to distribute R and R packages. Don’t try and pick a mirror that’s close to you: instead use the cloud mirror, https://cloud.r-project.org, which automatically figures it out for you.

A new major version of R comes out once a year, and there are 2-3 minor releases each year. It’s a good idea to update regularly. Upgrading can be a bit of a hassle, especially for major versions, which require you to re-install all your packages, but putting it off only makes it worse. You’ll need at least R 4.1.0 for this book.

1.4.2 RStudio

RStudio is an integrated development environment, or IDE, for R programming. Download and install it from https://www.rstudio.com/download. RStudio is updated a couple of times a year. When a new version is available, RStudio will let you know. It’s a good idea to upgrade regularly so you can take advantage of the latest and greatest features. For this book, make sure you have at least RStudio 2022.02.0.

When you start RStudio, Figure 1.2, you’ll see two key regions in the interface: the console pane, and the output pane. For now, all you need to know is that you type R code in the console pane, and press enter to run it. You’ll learn more as we go along!

The RStudio IDE with the panes Console and Output highlighted.

Figure 1.2: The RStudio IDE has two key regions: type R code in the console pane on the left, and look for plots in the output pane on the right.

1.4.3 The tidyverse

You’ll also need to install some R packages. An R package is a collection of functions, data, and documentation that extends the capabilities of base R. Using packages is key to the successful use of R. The majority of the packages that you will learn in this book are part of the so-called tidyverse. All packages in the tidyverse share a common philosophy of data and R programming, and are designed to work together naturally.

You can install the complete tidyverse with a single line of code:

install.packages("tidyverse")

On your own computer, type that line of code in the console, and then press enter to run it. R will download the packages from CRAN and install them on to your computer. If you have problems installing, make sure that you are connected to the internet, and that https://cloud.r-project.org/ isn’t blocked by your firewall or proxy.

You will not be able to use the functions, objects, or help files in a package until you load it with library(). Once you have installed a package, you can load it using the library() function:

library(tidyverse)
#> ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
#> ✔ ggplot2 3.3.6.9000        ✔ purrr   0.9000.0.9000
#> ✔ tibble  3.1.8             ✔ dplyr   1.0.99.9000  
#> ✔ tidyr   1.2.1.9000        ✔ stringr 1.4.1.9000   
#> ✔ readr   2.1.2             ✔ forcats 0.5.2        
#> ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag()    masks stats::lag()

This tells you that tidyverse is loading eight packages: ggplot2, tibble, tidyr, readr, purrr, dplyr, stringr, and forcats packages. These are considered to be the core of the tidyverse because you’ll use them in almost every analysis.

Packages in the tidyverse change fairly frequently. You can check whether updates are available, and optionally install them, by running tidyverse_update().

1.4.4 Other packages

There are many other excellent packages that are not part of the tidyverse, because they solve problems in a different domain, or are designed with a different set of underlying principles. This doesn’t make them better or worse, just different. In other words, the complement to the tidyverse is not the messyverse, but many other universes of interrelated packages. As you tackle more data science projects with R, you’ll learn new packages and new ways of thinking about data.

In this book we’ll use three data packages from outside the tidyverse:

install.packages(c("nycflights13", "gapminder", "Lahman"))

These packages provide data on airline flights, world development, and baseball that we’ll use to illustrate key data science ideas.

1.5 Running R code

The previous section showed you several examples of running R code. Code in the book looks like this:

1 + 2
#> [1] 3

If you run the same code in your local console, it will look like this:

> 1 + 2
[1] 3

There are two main differences. In your console, you type after the >, called the prompt; we don’t show the prompt in the book. In the book, output is commented out with #>; in your console it appears directly after your code. These two differences mean that if you’re working with an electronic version of the book, you can easily copy code out of the book and into the console.

Throughout the book, we use a consistent set of conventions to refer to code:

  • Functions are displayed in a code font and followed by parentheses, like sum(), or mean().

  • Other R objects (such as data or function arguments) are in a code font, without parentheses, like flights or x.

  • Sometimes, to make it clear which package an object comes from, we’ll use we’ll use the package name followed by two colons, like dplyr::mutate(), or
    nycflights13::flights. This is also valid R code.

1.6 Acknowledgements

This book isn’t just the product of Hadley, Mine, and Garrett, but is the result of many conversations (in person and online) that we’ve had with many people in the R community. There are a few people we’d like to thank in particular, because they have spent many hours answering our questions and helping us to better think about data science:

  • Jenny Bryan and Lionel Henry for many helpful discussions around working with lists and list-columns.

  • The three chapters on workflow were adapted (with permission), from https://stat545.com/block002_hello-r-workspace-wd-project.html by Jenny Bryan.

  • Yihui Xie for his work on the bookdown package, and for tirelessly responding to my feature requests.

  • Bill Behrman for his thoughtful reading of the entire book, and for trying it out with his data science class at Stanford.

  • The #rstats Twitter community who reviewed all of the draft chapters and provided tons of useful feedback.

This book was written in the open, and many people contributed pull requests to fix minor problems. Special thanks goes to everyone who contributed via GitHub:

Thanks go to all contributers in alphabetical order: A. s, Abhinav Singh, Ahmed ElGabbas, Ajay Deonarine, @AlanFeder, Albert Y. Kim, @Alex, Andrea Gilardi, Andrew Landgraf, Angela Li, Azza Ahmed, Ben Herbertson, Ben Marwick, Ben Steinberg, Benjamin Yeh, Bianca Peterson, Bill Behrman, @BirgerNi, Brandon Greenwell, Brent Brewington, Brett Klamer, Brian G. Barkley, Charlotte Wickham, Christian G. Warden, Christian Heinrich, Christian Mongeau, Colin Gillespie, Cooper Morris, Curtis Alexander, @DSGeoff, Daniel Gromer, David Clark, David Rubinger, Derwin McGeary, Devin Pastoor, Dirk Eddelbuettel, Dylan Cashman, Earl Brown, Edwin Thoen, Eric Watt, Erik Erhardt, Etienne B. Racine, Everett Robinson, Flemming Villalona, Floris Vanderhaeghe, Garrick Aden-Buie, George Wang, Gregory Jefferis, Gustav W Delius, Hao Chen, Hengni Cai, Hiroaki Yutani, Hojjat Salmasian, Ian Lyttle, Ian Sealy, Ivan Krukov, Jacek Kolacz, Jacob Kaplan, Jakub Nowosad, Jazz Weisman, Jeff Boichuk, Jeffrey Arnold, Jen Ren, Jennifer (Jenny) Bryan, Jeroen Janssens, Jim Hester, Joanne Jang, Johannes Gruber, John Blischak, John D. Storey, John Sears, Jon Calder, @Jonas, Jonathan Page, Jose Roberto Ayala Solares, Josh Goldberg, Julia Stewart Lowndes, Julian During, Justinas Petuchovas, Kara Woo, Kara de la Marck, Katrin Leinweber, Kenny Darrell, Kirill Müller, Kirill Sevastyanenko, Kunal Marwaha, @KyleHumphrey, Lawrence Wu, Luke Smith, Luke W Johnston, @MJMarshall, Mara Averick, Maria Paula Caldas, Mark Beveridge, Matt Herman, @MattWittbrodt, Matthew Hendrickson, Matthew Sedaghatfar, Mauro Lepore, Michael Henry, Mustafa Ascha, Nelson Areal, Nicholas Tierney, Nick Clark, Nina Munkholt Jakobsen, Nirmal Patel, Nischal Shrestha, Noah Landesberg, @OaCantona, Pablo E, Patrick Kennedy, @Paul, Peter Hurford, Rademeyer Vermaak, Radu Grosu, Ranae Dietzel, Riva Quiroga, Rob Tenorio, Robert Schuessler, Robin Gertenbach, Rohan Alexander, @RomeroBarata, S’busiso Mkhondwane, @Saghir, Sam Firke, Seamus McKinsey, Sebastian Kraus, Shannon Ellis, @Sophiazj, Steve Mortimer, Stéphane Guillou, TJ Mahr, Tal Galili, Terence Teo, Thomas Klebel, Tim Waterhouse, Tom Prior, Ulrik Lyngs, Will Beasley, Yihui Xie, Yiming (Paul) Li, Yu Yu Aung, Zach Bogart, Zhuoer Dong, @a-rosenberg, adi pradhan, @andrewmacfarland, bahadir cankardes, @batpigandme, @behrman, @boardtc, @djbirke, @harrismcgehee, @jennybc, @jjchern, @jonathanflint, @juandering, @kaetschap, @kdpsingh, @koalabearski, @lindbrook, @nate-d-olson, @nattalides, @nickelas, @nwaff, @pete, @rlzijdeman, @robertchu03, @robinlovelace, @robinsones, @seamus-mckinsey, @seanpwilliams, @shoili, @sibusiso16, @spirgel, @svenski, @twgardner2, @yahwes, @zeal626, @蒋雨蒙.

1.7 Colophon

An online version of this book is available at https://r4ds.had.co.nz. It will continue to evolve in between reprints of the physical book. The source of the book is available at https://github.com/hadley/r4ds. The book is powered by https://bookdown.org which makes it easy to turn R Markdown files into HTML, PDF, and EPUB.

This book was built with:

sessioninfo::session_info(c("tidyverse"))
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  setting  value
#>  version  R version 4.2.1 (2022-06-23)
#>  os       Ubuntu 20.04.5 LTS
#>  system   x86_64, linux-gnu
#>  ui       X11
#>  language (EN)
#>  collate  C.UTF-8
#>  ctype    C.UTF-8
#>  tz       UTC
#>  date     2022-09-28
#>  pandoc   2.5 @ /usr/bin/ (via rmarkdown)
#> 
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  package       * version       date (UTC) lib source
#>  askpass         1.1           2019-01-13 [1] RSPM
#>  assertthat      0.2.1         2019-03-21 [1] RSPM
#>  backports       1.4.1         2021-12-13 [1] RSPM
#>  base64enc       0.1-3         2015-07-28 [1] RSPM
#>  bit             4.0.4         2020-08-04 [1] RSPM
#>  bit64           4.0.5         2020-08-30 [1] RSPM
#>  blob            1.2.3         2022-04-10 [1] RSPM
#>  broom           1.0.1         2022-08-29 [1] RSPM
#>  bslib           0.4.0         2022-07-16 [1] RSPM
#>  cachem          1.0.6         2021-08-19 [1] RSPM
#>  callr           3.7.2         2022-08-22 [1] RSPM
#>  cellranger      1.1.0         2016-07-27 [1] RSPM
#>  cli             3.4.1         2022-09-23 [1] RSPM
#>  clipr           0.8.0         2022-02-22 [1] RSPM
#>  colorspace      2.0-3         2022-02-21 [1] RSPM
#>  cpp11           0.4.2         2021-11-30 [1] RSPM
#>  crayon          1.5.1         2022-03-26 [1] RSPM
#>  curl            4.3.2         2021-06-23 [1] RSPM
#>  data.table      1.14.2        2021-09-27 [1] RSPM
#>  DBI             1.1.3         2022-06-18 [1] RSPM
#>  dbplyr          2.2.1.9000    2022-09-28 [1] Github (tidyverse/dbplyr@24147b8)
#>  digest          0.6.29        2021-12-01 [1] RSPM
#>  dplyr         * 1.0.99.9000   2022-09-28 [1] Github (tidyverse/dplyr@148969a)
#>  dtplyr          1.2.2         2022-08-20 [1] RSPM
#>  ellipsis        0.3.2         2021-04-29 [1] RSPM
#>  evaluate        0.16          2022-08-09 [1] RSPM
#>  fansi           1.0.3         2022-03-24 [1] RSPM
#>  farver          2.1.1         2022-07-06 [1] RSPM
#>  fastmap         1.1.0         2021-01-25 [1] RSPM
#>  forcats       * 0.5.2         2022-08-19 [1] RSPM
#>  fs              1.5.2         2021-12-08 [1] RSPM
#>  gargle          1.2.1         2022-09-08 [1] RSPM
#>  generics        0.1.3         2022-07-05 [1] RSPM
#>  ggplot2       * 3.3.6.9000    2022-09-26 [1] Github (tidyverse/ggplot2@a58b48c)
#>  glue            1.6.2         2022-02-24 [1] RSPM
#>  googledrive     2.0.0         2021-07-08 [1] RSPM
#>  googlesheets4   1.0.1         2022-08-13 [1] RSPM
#>  gtable          0.3.1         2022-09-01 [1] RSPM
#>  haven           2.5.1         2022-08-22 [1] RSPM
#>  highr           0.9           2021-04-16 [1] RSPM
#>  hms             1.1.2         2022-08-19 [1] RSPM
#>  htmltools       0.5.3         2022-07-18 [1] RSPM
#>  httr            1.4.4         2022-08-17 [1] RSPM
#>  ids             1.0.1         2017-05-31 [1] RSPM
#>  isoband         0.2.5         2021-07-13 [1] RSPM
#>  jquerylib       0.1.4         2021-04-26 [1] RSPM
#>  jsonlite        1.8.0         2022-02-22 [1] RSPM
#>  knitr           1.40          2022-08-24 [1] RSPM
#>  labeling        0.4.2         2020-10-20 [1] RSPM
#>  lattice         0.20-45       2021-09-22 [2] CRAN (R 4.2.1)
#>  lifecycle       1.0.2.9000    2022-09-27 [1] Github (r-lib/lifecycle@f7289f7)
#>  lubridate       1.8.0         2021-10-07 [1] RSPM
#>  magrittr        2.0.3         2022-03-30 [1] RSPM
#>  MASS            7.3-57        2022-04-22 [2] CRAN (R 4.2.1)
#>  Matrix          1.4-1         2022-03-23 [2] CRAN (R 4.2.1)
#>  memoise         2.0.1         2021-11-26 [1] RSPM
#>  mgcv            1.8-40        2022-03-29 [2] CRAN (R 4.2.1)
#>  mime            0.12          2021-09-28 [1] RSPM
#>  modelr          0.1.9         2022-08-19 [1] RSPM
#>  munsell         0.5.0         2018-06-12 [1] RSPM
#>  nlme            3.1-157       2022-03-25 [2] CRAN (R 4.2.1)
#>  openssl         2.0.3         2022-09-14 [1] RSPM
#>  pillar          1.8.1         2022-08-19 [1] RSPM
#>  pkgconfig       2.0.3         2019-09-22 [1] RSPM
#>  prettyunits     1.1.1         2020-01-24 [1] RSPM
#>  processx        3.7.0         2022-07-07 [1] RSPM
#>  progress        1.2.2         2019-05-16 [1] RSPM
#>  ps              1.7.1         2022-06-18 [1] RSPM
#>  purrr         * 0.9000.0.9000 2022-09-28 [1] Github (tidyverse/purrr@f67f771)
#>  R6              2.5.1         2021-08-19 [1] RSPM
#>  rappdirs        0.3.3         2021-01-31 [1] RSPM
#>  RColorBrewer    1.1-3         2022-04-03 [1] RSPM
#>  readr         * 2.1.2         2022-01-30 [1] RSPM
#>  readxl          1.4.1         2022-08-17 [1] RSPM
#>  rematch         1.0.1         2016-04-21 [1] RSPM
#>  rematch2        2.1.2         2020-05-01 [1] RSPM
#>  reprex          2.0.2         2022-08-17 [1] RSPM
#>  rlang           1.0.6         2022-09-24 [1] RSPM
#>  rmarkdown       2.16          2022-08-24 [1] RSPM
#>  rstudioapi      0.14          2022-08-22 [1] RSPM
#>  rvest           1.0.3         2022-08-19 [1] RSPM
#>  sass            0.4.2         2022-07-16 [1] RSPM
#>  scales          1.2.1         2022-08-20 [1] RSPM
#>  selectr         0.4-2         2019-11-20 [1] RSPM
#>  stringi         1.7.8         2022-07-11 [1] RSPM
#>  stringr       * 1.4.1.9000    2022-09-06 [1] Github (tidyverse/stringr@792bc92)
#>  sys             3.4           2020-07-23 [1] RSPM
#>  tibble        * 3.1.8         2022-07-22 [1] RSPM
#>  tidyr         * 1.2.1.9000    2022-09-09 [1] Github (tidyverse/tidyr@653def2)
#>  tidyselect      1.1.2.9000    2022-09-27 [1] Github (r-lib/tidyselect@ac4b8ef)
#>  tidyverse     * 1.3.2         2022-07-18 [1] RSPM
#>  tinytex         0.42          2022-09-27 [1] RSPM
#>  tzdb            0.3.0         2022-03-28 [1] RSPM
#>  utf8            1.2.2         2021-07-24 [1] RSPM
#>  uuid            1.1-0         2022-04-19 [1] RSPM
#>  vctrs           0.4.1.9001    2022-09-28 [1] Github (r-lib/vctrs@c0bf5ab)
#>  viridisLite     0.4.1         2022-08-22 [1] RSPM
#>  vroom           1.5.7         2021-11-30 [1] RSPM
#>  withr           2.5.0         2022-03-03 [1] RSPM
#>  xfun            0.33          2022-09-12 [1] RSPM
#>  xml2            1.3.3         2021-11-30 [1] RSPM
#>  yaml            2.3.5         2022-02-21 [1] RSPM
#> 
#>  [1] /home/runner/work/_temp/Library
#>  [2] /opt/R/4.2.1/lib/R/library
#> 
#> ──────────────────────────────────────────────────────────────────────────────