2022-05-14 04:46:49 +08:00
# Introduction {#sec-intro}
```{r}
#| results: "asis"
#| echo: false
source("_common.R")
```
2015-12-08 03:55:44 +08:00
2022-05-08 10:17:21 +08:00
Data science is an exciting discipline that allows you to transform raw data into understanding, insight, and knowledge.
2023-03-02 12:51:48 +08:00
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, and to have some fun along the way 😃.
2023-01-03 15:06:27 +08:00
After reading this book, you'll have the tools to tackle a wide variety of data science challenges using the best parts of R.
2015-09-21 21:21:59 +08:00
2015-12-08 03:55:44 +08:00
## What you will learn
2015-09-21 21:21:59 +08:00
2023-01-03 15:06:27 +08:00
Data science is a vast field, and there's no way you can master it all by reading a single book.
This book aims to give you a solid foundation in the most important tools and enough knowledge to find the resources to learn more when necessary.
2023-03-07 21:52:43 +08:00
Our model of the steps of a typical data science project looks something like @fig-ds-diagram.
2015-09-21 21:21:59 +08:00
2022-05-08 13:32:25 +08:00
```{r}
2022-08-29 18:24:32 +08:00
#| label: fig-ds-diagram
2022-05-08 13:32:25 +08:00
#| echo: false
2022-08-29 18:24:32 +08:00
#| fig-cap: >
2023-01-03 15:06:27 +08:00
#| 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
2022-08-29 18:24:32 +08:00
#| transforming, visualizing, and modeling. You finish the process
#| by communicating your results to other humans.
2022-05-14 04:46:49 +08:00
#| fig-alt: >
2022-05-08 13:32:25 +08:00
#| 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.
2022-08-29 18:24:32 +08:00
#| out.width: NULL
2022-05-08 13:32:25 +08:00
2022-08-29 18:24:32 +08:00
knitr::include_graphics("diagrams/data-science/base.png", dpi = 270)
2015-12-12 03:28:10 +08:00
```
2015-09-21 21:21:59 +08:00
2023-01-03 15:06:27 +08:00
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.
2021-02-21 23:40:40 +08:00
If you can't get your data into R, you can't do data science on it!
2015-09-21 21:21:59 +08:00
2021-02-21 23:40:40 +08:00
Once you've imported your data, it is a good idea to **tidy** it.
2023-01-03 15:06:27 +08:00
Tidying your data means storing it in a consistent form that matches the semantics of the dataset with how it is stored.
2021-02-21 23:40:40 +08:00
In brief, when your data is tidy, each column is a variable, and each row is an observation.
2022-05-08 10:17:21 +08:00
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.
2015-12-06 23:20:19 +08:00
2022-05-08 10:17:21 +08:00
Once you have tidy data, a common next step is to **transform** it.
2023-01-03 15:06:27 +08:00
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!
2015-09-21 21:21:59 +08:00
2023-01-03 15:06:27 +08:00
Once you have tidy data with the variables you need, there are two main engines of knowledge generation: visualization and modeling.
2023-03-07 21:52:43 +08:00
These have complementary strengths and weaknesses, so any real data analysis will iterate between them many times.
2015-12-08 03:55:44 +08:00
2022-12-05 15:46:05 +08:00
**Visualization** is a fundamentally human activity.
2023-01-03 15:06:27 +08:00
A good visualization will show you things you did not expect or raise new questions about the data.
A good visualization might also hint that you're asking the wrong question or that you need to collect different data.
Visualizations can surprise you, and they don't scale particularly well because they require a human to interpret them.
2015-12-08 03:55:44 +08:00
2023-03-02 12:51:48 +08:00
**Models** are complementary tools to visualization.
2023-02-08 00:10:26 +08:00
Once you have made your questions sufficiently precise, you can use a model to answer them.
Models are a fundamentally mathematical or computational tool, so they generally scale well.
2023-02-14 21:32:09 +08:00
Even when they don't, it's usually cheaper to buy more computers than it is to buy more brains!
2023-02-08 00:10:26 +08:00
But every model makes assumptions, and by its very nature a model cannot question its own assumptions.
That means a model cannot fundamentally surprise you.
2021-02-21 23:40:40 +08:00
The last step of data science is **communication**, an absolutely critical part of any data analysis project.
2022-12-05 15:46:05 +08:00
It doesn't matter how well your models and visualization have led you to understand the data unless you can also communicate your results to others.
2015-12-08 03:55:44 +08:00
2021-02-21 23:40:40 +08:00
Surrounding all these tools is **programming**.
2022-05-08 10:17:21 +08:00
Programming is a cross-cutting tool that you use in nearly every part of a data science project.
2023-01-03 15:06:27 +08:00
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.
2015-12-08 07:53:43 +08:00
2023-01-03 15:06:27 +08:00
You'll use these tools in every data science project, but they're not enough for most projects.
There's a rough 80-20 rule at play; you can tackle about 80% of every project using the tools you'll learn in this book, but you'll need other tools to tackle the remaining 20%.
2022-05-08 10:17:21 +08:00
Throughout this book, we'll point you to resources where you can learn more.
2015-12-08 07:53:43 +08:00
2023-01-03 15:06:27 +08:00
## How this book is organized
2015-12-08 03:55:44 +08:00
2023-01-03 15:06:27 +08:00
The previous description of the tools of data science is organized roughly according to the order in which you use them in an analysis (although, of course, you'll iterate through them multiple times).
2023-03-07 21:52:43 +08:00
In our experience, however, learning data importing 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.
2022-02-17 00:20:39 +08:00
That's a bad place to start learning a new subject!
2022-12-05 15:46:05 +08:00
Instead, we'll start with visualization and transformation of data that's already been imported and tidied.
2022-05-08 10:17:21 +08:00
That way, when you ingest and tidy your own data, your motivation will stay high because you know the pain is worth the effort.
2021-02-21 23:40:40 +08:00
2023-03-07 21:52:43 +08:00
Within each chapter, we try and adhere to a consistent pattern: start with some motivating examples so you can see the bigger picture and then dive into the details.
2021-02-21 23:40:40 +08:00
Each section of the book is paired with exercises to help you practice what you've learned.
2022-05-08 10:17:21 +08:00
Although it can be tempting to skip the exercises, there's no better way to learn than practicing on real problems.
2021-02-21 23:40:40 +08:00
## What you won't learn
2015-12-08 03:55:44 +08:00
2023-01-03 15:06:27 +08:00
There are several important topics that this book doesn't cover.
2021-02-21 23:40:40 +08:00
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.
2015-09-21 21:21:59 +08:00
2022-08-29 18:24:32 +08:00
### Modeling
2022-02-17 00:20:39 +08:00
2023-03-02 12:51:48 +08:00
Modelling is super important for data science, but it's a big topic and unfortunately we just don't have the space to give it the coverage it deserves here.
To learn more modeling, we highly recommend [Tidy Modeling with R](https://www.tmwr.org) by our colleagues Max Kuhn and Julia Silge.
2022-08-29 18:24:32 +08:00
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.
2021-02-21 23:40:40 +08:00
### Big data
2015-09-21 21:21:59 +08:00
2023-02-28 10:54:34 +08:00
This book proudly and primarily focuses on small, in-memory datasets.
2021-02-21 23:40:40 +08:00
This is the right place to start because you can't tackle big data unless you have experience with small data.
2023-03-02 12:51:48 +08:00
The tools you learn in majority of this book will easily handle hundreds of megabytes of data, and with a bit of care, you can typically use them to work a few gigabytes of data.
We'll also show you how to get data out of databases and parquet files, both of which are often used to store big data.
You won't necessarily be able to work with the entire dataset, but that's not a problem because you only need a subset or subsample to answer the question that you're interested in.
2023-02-28 10:54:34 +08:00
2023-03-02 12:51:48 +08:00
If you're routinely working with larger data (10-100 Gb, say), we recommend learning more about [data.table](https://github.com/Rdatatable/data.table).
We don't teach it here because it uses a different interface to the tidyverse and requires you ot learn some different conventions.
However, it is incredible faster and the performance payoff is worth investing some time learning it if you're working with large data.
2015-09-21 21:21:59 +08:00
2016-07-11 23:31:30 +08:00
### Python, Julia, and friends
2015-07-30 08:58:29 +08:00
2021-02-21 23:40:40 +08:00
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.
2023-03-02 12:51:48 +08:00
But we strongly believe that it's best to master one tool at a time, and R is a great place to start.
2016-10-05 00:08:12 +08:00
2015-12-08 03:55:44 +08:00
## Prerequisites
2015-07-30 08:58:29 +08:00
2023-01-03 15:06:27 +08:00
We've made a few assumptions about what you already know to get the most out of this book.
2023-03-02 12:51:48 +08:00
You should be generally numerically literate, and it's helpful if you have some basic programming experience already.
2023-01-03 15:06:27 +08:00
If you've never programmed before, you might find [Hands on Programming with R](https://rstudio-education.github.io/hopr/) by Garrett to be a valuable adjunct to this book.
2015-12-06 23:20:19 +08:00
2023-01-03 15:06:27 +08:00
You need four things to run the code in this book: R, RStudio, a collection of R packages called the **tidyverse**, and a handful of other packages.
2021-02-21 23:40:40 +08:00
Packages are the fundamental units of reproducible R code.
2023-01-03 15:06:27 +08:00
They include reusable functions, documentation that describes how to use them, and sample data.
2015-12-06 23:20:19 +08:00
2021-02-21 23:40:40 +08:00
### R
2016-10-04 01:30:24 +08:00
2023-03-02 12:51:48 +08:00
To download R, go to CRAN, the **c**omprehensive **R** **a**rchive **n**etwork, <https://cloud.r-project.org>.
2021-02-21 23:40:40 +08:00
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.
2023-01-03 15:06:27 +08:00
Upgrading can be a bit of a hassle, especially for major versions requiring you to re-install all your packages, but putting it off only makes it worse.
2023-03-02 12:51:48 +08:00
We recommend R 4.2.0 or later for this book.
2016-10-04 03:10:29 +08:00
2015-12-08 20:53:57 +08:00
### RStudio
2023-03-02 12:51:48 +08:00
RStudio is an integrated development environment, or IDE, for R programming, which you can download from <https://posit.co/download/rstudio-desktop/>.
RStudio is updated a couple of times a year, and it will automatically let you know when a new version is out so there's no need to check back.
2023-01-03 15:06:27 +08:00
It's a good idea to upgrade regularly to take advantage of the latest and greatest features.
2022-08-09 02:47:35 +08:00
For this book, make sure you have at least RStudio 2022.02.0.
2016-10-04 01:30:24 +08:00
2023-01-03 15:06:27 +08:00
When you start RStudio, @fig-rstudio-console, 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 the R code in the console pane and press enter to run it.
2022-08-29 18:24:32 +08:00
You'll learn more as we go along!
2015-12-08 20:53:57 +08:00
2022-05-08 13:32:25 +08:00
```{r}
2022-08-29 18:24:32 +08:00
#| label: fig-rstudio-console
2022-05-08 13:32:25 +08:00
#| echo: false
2022-08-29 18:24:32 +08:00
#| out-width: ~
#| fig-cap: >
#| 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.
2022-05-14 04:46:49 +08:00
#| fig-alt: >
2022-05-08 13:32:25 +08:00
#| The RStudio IDE with the panes Console and Output highlighted.
2022-08-29 18:24:32 +08:00
knitr::include_graphics("diagrams/rstudio/console.png", dpi = 270)
2015-12-12 03:28:10 +08:00
```
2015-12-08 20:53:57 +08:00
2016-10-04 01:30:24 +08:00
### The tidyverse
2021-02-21 23:40:40 +08:00
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.
2023-03-02 12:51:48 +08:00
All packages in the tidyverse share a common philosophy of data and R programming and are designed to work together.
2015-12-06 23:20:19 +08:00
2016-10-04 01:30:24 +08:00
You can install the complete tidyverse with a single line of code:
2015-07-29 03:15:28 +08:00
2022-05-08 13:32:25 +08:00
```{r}
#| eval: false
2016-10-04 01:30:24 +08:00
install.packages("tidyverse")
2016-07-20 23:07:51 +08:00
```
2016-10-04 01:30:24 +08:00
2023-01-03 15:06:27 +08:00
On your 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 your computer.
2016-10-04 01:30:24 +08:00
2022-05-08 10:17:21 +08:00
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:
2016-10-04 01:30:24 +08:00
2015-12-08 03:55:44 +08:00
```{r}
2016-10-04 01:30:24 +08:00
library(tidyverse)
2015-07-29 03:15:28 +08:00
```
2023-01-23 21:48:36 +08:00
This tells you that tidyverse loads nine packages: dplyr, forcats, ggplot2, lubridate, purrr, readr, stringr, tibble, tidyr.
2023-01-03 15:06:27 +08:00
These are considered the **core** of the tidyverse because you'll use them in almost every analysis.
2016-10-04 01:30:24 +08:00
2021-02-21 23:40:40 +08:00
Packages in the tidyverse change fairly frequently.
2023-03-02 12:51:48 +08:00
You can see if updates are available by running `tidyverse_update()`.
2016-10-04 03:10:29 +08:00
2016-10-04 01:30:24 +08:00
### Other packages
2023-01-03 15:06:27 +08:00
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.
2021-02-21 23:40:40 +08:00
This doesn't make them better or worse, just different.
2023-01-03 15:06:27 +08:00
In other words, the complement to the tidyverse is not the messyverse but many other universes of interrelated packages.
2021-02-21 23:40:40 +08:00
As you tackle more data science projects with R, you'll learn new packages and new ways of thinking about data.
2015-07-30 08:58:29 +08:00
2023-01-23 22:27:51 +08:00
We'll use many packages from outside the tidyverse in this book.
2023-03-07 21:52:43 +08:00
For example, we use the following packages to that provide interesting data sets:
2015-07-30 08:58:29 +08:00
2022-05-08 13:32:25 +08:00
```{r}
#| eval: false
2023-01-23 22:27:51 +08:00
install.packages(c("babynames", "gapminder", "nycflights13", "palmerpenguins"))
2015-07-30 08:58:29 +08:00
```
2023-01-23 22:27:51 +08:00
We'll also use a selection of other packages for one off examples.
You don't need to install them now, just remember that whenever you see an error like this:
```{r}
#| eval: false
library(ggrepel)
#> Error in library(ggrepel) : there is no package called ‘ ggrepel’
```
You need to run `install.packages("ggrepel")` to install the package.
2015-09-22 20:59:27 +08:00
2016-10-04 03:10:29 +08:00
## Running R code
2022-05-08 10:17:21 +08:00
The previous section showed you several examples of running R code.
2023-01-03 15:06:27 +08:00
The code in the book looks like this:
2016-10-04 03:10:29 +08:00
2022-05-08 13:32:25 +08:00
```{r}
#| eval: true
2016-10-04 03:10:29 +08:00
1 + 2
```
2016-10-05 00:08:12 +08:00
If you run the same code in your local console, it will look like this:
2016-10-04 03:10:29 +08:00
2021-02-21 23:40:40 +08:00
> 1 + 2
[1] 3
2016-10-04 03:10:29 +08:00
2021-02-21 23:40:40 +08:00
There are two main differences.
In your console, you type after the `>`, called the **prompt**; we don't show the prompt in the book.
2023-01-03 15:06:27 +08:00
In the book, the output is commented out with `#>`; in your console, it appears directly after your code.
2021-02-21 23:40:40 +08:00
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.
2016-07-20 23:07:51 +08:00
2022-05-08 10:17:21 +08:00
Throughout the book, we use a consistent set of conventions to refer to code:
2016-07-20 23:07:51 +08:00
2023-01-03 15:06:27 +08:00
- Functions are displayed in a code font and followed by parentheses, like `sum()` or `mean()`.
2016-07-21 20:37:10 +08:00
2022-05-08 10:17:21 +08:00
- Other R objects (such as data or function arguments) are in a code font, without parentheses, like `flights` or `x`.
2021-02-21 23:40:40 +08:00
2023-01-03 15:06:27 +08:00
- Sometimes, to make it clear which package an object comes from, we'll use the package name followed by two colons, like `dplyr::mutate()` or\
2022-02-17 00:20:39 +08:00
`nycflights13::flights`.
This is also valid R code.
2016-07-20 23:07:51 +08:00
2023-01-03 15:06:27 +08:00
## Acknowledgments
2015-11-26 04:39:53 +08:00
2023-01-03 15:06:27 +08:00
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:
2021-02-21 23:40:40 +08:00
- Jenny Bryan and Lionel Henry for many helpful discussions around working with lists and list-columns.
2016-07-11 23:31:30 +08:00
2023-01-03 15:06:27 +08:00
- The three chapters on workflow were adapted (with permission) from <https://stat545.com/block002_hello-r-workspace-wd-project.html> by Jenny Bryan.
2015-12-08 03:55:44 +08:00
2023-01-03 15:06:27 +08:00
- Yihui Xie for his work on the [bookdown](https://github.com/rstudio/bookdown) package and for tirelessly responding to my feature requests.
2016-07-11 23:31:30 +08:00
2023-01-03 15:06:27 +08:00
- Bill Behrman for his thoughtful reading of the entire book and for trying it out with his data science class at Stanford.
2016-07-20 23:07:51 +08:00
2023-01-03 15:06:27 +08:00
- The #rstats Twitter community who reviewed all of the draft chapters and provided tons of helpful feedback.
2016-08-24 21:24:14 +08:00
2021-02-21 23:40:40 +08:00
This book was written in the open, and many people contributed pull requests to fix minor problems.
2023-01-03 15:06:27 +08:00
Special thanks go to everyone who contributed via GitHub:
2016-07-11 23:31:30 +08:00
2022-05-08 13:32:25 +08:00
```{r}
2022-11-05 01:45:16 +08:00
#| eval: false
2022-05-08 13:32:25 +08:00
#| echo: false
2022-11-05 01:45:16 +08:00
library(tidyverse)
contribs_all_json <- gh::gh("/repos/:owner/:repo/contributors",
owner = "hadley",
repo = "r4ds",
.limit = Inf
)
contribs_all <- tibble(
login = contribs_all_json %>% map_chr("login"),
n = contribs_all_json %>% map_int("contributions")
)
contribs_old <- read_csv("contributors.csv", col_types = list())
contribs_new <- contribs_all %>% anti_join(contribs_old, by = "login")
# Get info for new contributors
needed_json <- map(
contribs_new$login,
~ gh::gh("/users/:username", username = .x),
.progress = TRUE
)
info_new <- tibble(
login = contribs_new$login,
name = map_chr(needed_json, "name", .default = NA),
blog = map_chr(needed_json, "blog", .default = NA)
)
info_old <- contribs_old %>% select(login, name, blog)
info_all <- bind_rows(info_old, info_new)
contribs_all <- contribs_all %>%
left_join(info_all, by = "login") %>%
arrange(login)
write_csv(contribs_all, "contributors.csv")
```
2016-07-20 23:07:51 +08:00
2022-11-05 01:45:16 +08:00
```{r}
#| results: asis
#| echo: false
#| message: false
2016-07-20 23:07:51 +08:00
2022-11-05 01:45:16 +08:00
library(dplyr)
contributors <- readr::read_csv("contributors.csv")
contributors <- contributors %>%
filter(!login %in% c("hadley", "garrettgman", "mine-cetinkaya-rundel")) %>%
mutate(
login = paste0("\\@", login),
desc = ifelse(is.na(name), login, paste0(name, " (", login, ")"))
)
cat("A big thank you to all ", nrow(contributors), " people who contributed specific improvements via GitHub pull requests (in alphabetical order by username): ", sep = "")
cat(paste0(contributors$desc, collapse = ", "))
2016-07-20 23:07:51 +08:00
cat(".\n")
```
2016-06-20 22:56:46 +08:00
2015-12-08 03:55:44 +08:00
## Colophon
2022-11-05 01:45:16 +08:00
An online version of this book is available at <https://r4ds.hadley.nz>.
2021-02-21 23:40:40 +08:00
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>.
2023-01-03 15:06:27 +08:00
The book is powered by [Quarto](https://quarto.org), which makes it easy to write books that combine text and executable code.
2016-07-11 23:31:30 +08:00
2015-12-08 03:55:44 +08:00
```{r}
2023-03-09 11:02:03 +08:00
#| eval: false
2022-11-19 01:05:00 +08:00
#| echo: false
#| results: asis
pkgs <- sessioninfo::package_info(
tidyverse:::tidyverse_packages(),
dependencies = FALSE
)
df <- tibble(
package = pkgs$package,
version = pkgs$ondiskversion,
source = gsub("@", "\\\\@", pkgs$source)
)
knitr::kable(df, format = "markdown")
```
```{r}
2023-01-27 00:36:07 +08:00
#| include: false
2022-12-16 14:41:10 +08:00
2022-11-19 00:23:53 +08:00
cli:::ruler()
2015-12-08 03:55:44 +08:00
```