Preface
Help! I’m completely new to coding and I need to learn R and RStudio! What do I do?
If you’re asking yourself this question, then you’ve come to the right place! Start with the “Introduction for students” section.
- Are you an instructor hoping to use this book in your courses? We recommend reading the “Introduction for students” section first. Then, read the “Introduction for instructors” section for more information on how to teach with this book.
- Are you looking to connect with and contribute to ModernDive? Then, read the “Connect and contribute” section for information on how.
- Are you curious about the publishing of this book? Then, read the “About this book” section for more information on the open-source technology, in particular R Markdown and the bookdown package.
This is version 2.0.0 of ModernDive published on September 30, 2024. For previous versions of ModernDive, see the “About this book” section.
Introduction for students
This book assumes no prerequisites: no algebra, no calculus, and no prior programming/coding experience. This is intended to be a gentle introduction to the practice of analyzing data and answering questions using data the way data scientists, statisticians, data journalists, and other researchers would.
We present a map of your upcoming journey in Figure 0.1.
You’ll first get started with data in Chapter 1 where you’ll learn about the difference between R and RStudio, start coding in R, install and load your first R packages, and explore your first dataset: all domestic departure flights
from a New York City airport in 2023. Then you’ll cover the following three portions of this book (Parts 2 and 4 are combined into a single portion):
- Data science with
tidyverse
. You’ll assemble your data science toolbox usingtidyverse
packages. In particular, you’ll- Ch.2: Visualize data using the
ggplot2
package. - Ch.3: Wrangle data using the
dplyr
package. - Ch.4: Learn about the concept of “tidy” data as a standardized data input and output format for all packages in the
tidyverse
. Furthermore, you’ll learn how to import spreadsheet files into R using thereadr
package.
- Ch.2: Visualize data using the
- Statistical/Data modeling with
moderndive
. Using these data science tools and helper functions from themoderndive
package, you’ll fit your first data models. In particular, you’ll - Statistical inference with
infer
. Once again using your newly acquired data science tools, you’ll unpack statistical inference using theinfer
package. In particular, you’ll: - Statistical/Data modeling with
moderndive
(revisited): Armed with your understanding of statistical inference, you’ll revisit and review the models you’ve constructed in Ch.5 and Ch.6. In particular, you’ll:- Ch.10: Interpret confidence intervals and hypothesis tests in a regression setting.
We’ll end with a discussion on what it means to “tell your story with data” in Chapter 11 by presenting example case studies.1
What we hope you will learn from this book
We hope that by the end of this book, you’ll have learned how to:
- Use R and the
tidyverse
suite of R packages for data science. - Fit your first models to data, using a method known as linear regression.
- Perform statistical inference using sampling, confidence intervals, and hypothesis tests.
- Tell your story with data using these tools.
What do we mean by data stories? We mean any analysis involving data that engages the reader in answering questions with careful visuals and thoughtful discussion. Further discussions on data stories can be found in the blog post “Tell a Meaningful Story With Data.”
Over the course of this book, you will develop your “data science toolbox,” equipping yourself with tools such as data visualization, data formatting, data wrangling, and statistical/data modeling using regression.
In particular, this book will lean heavily on data visualization. In today’s world, we are bombarded with graphics that attempt to convey ideas. We will explore what makes a good graphic and what the standard ways are used to convey relationships within data. In general, we’ll use visualization as a way of building almost all of the ideas in this book.
To impart the statistical lessons of this book, we have intentionally minimized the number of mathematical formulas used. Instead, you’ll develop a conceptual understanding of statistics using data visualization and computer simulations. We hope this is a more intuitive experience than the way statistics has traditionally been taught in the past and how it is commonly perceived.
Finally, you’ll learn the importance of literate programming. By this we mean you’ll learn how to write code that is useful not just for a computer to execute, but also for readers to understand exactly what your analysis is doing and how you did it. This is part of a greater effort to encourage reproducible research (see the “Reproducible research” subsection in this Preface for more details). Hal Abelson coined the phrase that we will follow throughout this book:
Programs must be written for people to read, and only incidentally for machines to execute.
We understand that there may be challenging moments as you learn to program. Both of us continue to struggle and find ourselves often using web searches to find answers and reach out to colleagues for help. In the long run though, we all can solve problems faster and more elegantly via programming. We wrote this book as our way to help you get started and you should know that there is a huge community of R users that are happy to help everyone along as well. This community exists in particular on the internet on various forums and websites such as stackoverflow.com.
Data/science pipeline
You may think of statistics as just being a bunch of numbers. We commonly hear the phrase “statistician” when listening to broadcasts of sporting events. Statistics (in particular, data analysis), in addition to describing numbers like with baseball batting averages, plays a vital role in all of the sciences.
You’ll commonly hear the phrase “statistically significant” thrown around in the media. You’ll see articles that say, “Science now shows that chocolate is good for you.” Underpinning these claims is data analysis. By the end of this book, you’ll be able to better understand whether these claims should be trusted or whether we should be wary. Inside data analysis are many sub-fields that we will discuss throughout this book (though not necessarily in this order):
- data collection
- data wrangling
- data visualization
- statistical modeling
- inference
- correlation and regression
- interpretation of results
- data communication/storytelling
These sub-fields are summarized in what Garrett Grolemund and Hadley Wickham have previously termed the “data/science pipeline” in Figure 0.2.
We will begin by digging into the grey Understand portion of the cycle with data visualization, then with a discussion on what is meant by tidy data and data wrangling, and then conclude by talking about interpreting and discussing the results of our models via Communication. These steps are vital to any statistical analysis. But, why should you care about statistics?
There’s a reason that many fields require a statistics course. Scientific knowledge grows through an understanding of statistical significance and data analysis. You needn’t be intimidated by statistics. It’s not the beast that it used to be and, paired with computation, you’ll see how reproducible research in the sciences particularly increases scientific knowledge.
Reproducible research
The most important tool is the mindset, when starting, that the end product will be reproducible. – Keith Baggerly
Another goal of this book is to help readers understand the importance of reproducible analyses. The hope is to get readers into the habit of making their analyses reproducible from the very beginning. This means we’ll be trying to help you build new habits. This will take practice and be difficult at times. You’ll see just why it is so important for you to keep track of your code and document it well to help yourself later and any potential collaborators as well.
Copying and pasting results from one program into a word processor is not an ideal way to conduct efficient and effective scientific research. It’s much more important for time to be spent on data collection and data analysis and not on copying and pasting plots back and forth across a variety of programs.
In traditional analyses, if an error was made with the original data, we’d need to step through the entire process again: recreate the plots and copy-and-paste all of the new plots and our statistical analysis into our document. This is error prone and a frustrating use of time. We want to help you to get away from this tedious activity so that we can spend more time doing science.
We are talking about computational reproducibility. – Yihui Xie
Reproducibility means a lot of things in terms of different scientific fields. Are experiments conducted in a way that another researcher could follow the steps and get similar results? In this book, we will focus on what is known as computational reproducibility. This refers to being able to pass all of one’s data analysis, datasets, and conclusions to someone else and have them get exactly the same results on their machine. This allows for time to be spent interpreting results and considering assumptions instead of the more error prone way of starting from scratch or following a list of steps that may be different from machine to machine.
Final note for students
At this point, if you are interested in instructor perspectives on this book, ways to contribute and collaborate, or the technical details of this book’s construction and publishing, then continue with the rest of the chapter. Otherwise, let’s get started with R and RStudio in Chapter 1!
Introduction for instructors
Resources
Here are some resources to help you use ModernDive:
- We’ve included review questions posed as Learning checks. You can find all the solutions to all Learning checks in the Appendices of the online version of the book. The Appendices start at https://moderndive.com/v2/appendixa.
- Dr. Jenny Smetzer and Albert Y. Kim have written a series of labs and problem sets. You can find them at https://moderndive.com/labs.
- You can see the webpages for two courses that use ModernDive:
- Smith College “SDS192 Introduction to Data Science”: https://rudeboybert.github.io/SDS192/.
- Smith College “SDS220 Introduction to Probability and Statistics”: https://rudeboybert.github.io/SDS220/.
Why did we write this book?
This book is inspired by
- Mathematical Statistics with Resampling and R (Chihara and Hesterberg 2011)
- OpenIntro: Intro Stat with Randomization and Simulation (Diez, Barr, and Çetinkaya-Rundel 2014)
- R for Data Science (Grolemund and Wickham 2017)
The first book, designed for upper-level undergraduates and graduate students, provides an excellent resource on how to use resampling to impart statistical concepts like sampling distributions using computation instead of large-sample approximations and other mathematical formulas. The last two books are free options for learning about introductory statistics and data science, providing an alternative to the many traditionally expensive introductory statistics textbooks.
When looking over the introductory statistics textbooks that currently exist, we found there wasn’t one that incorporated many newly developed R packages directly into the text, in particular the many packages included in the tidyverse
set of packages, such as ggplot2
, dplyr
, tidyr
, and readr
that will be the focus of this book’s first part on “Data Science with tidyverse
.”
Additionally, there wasn’t an open-source and easily reproducible textbook available that exposed new learners to all four of the learning goals we listed in the “Introduction for students” subsection. We wanted to write a book that could develop theory via computational techniques and help novices master the R language in doing so.
Who is this book for?
This book is intended for instructors of traditional introductory statistics classes using RStudio, who would like to inject more data science topics into their syllabus. RStudio can be used in either the server version or the desktop version. (This is discussed further in Subsection 1.1.1.) We assume that students taking the class will have no prior algebra, no calculus, nor programming/coding experience.
Here are some principles and beliefs we kept in mind while writing this text. If you agree with them, this is the book for you.
-
Blur the lines between lecture and lab
- With increased availability and accessibility of laptops and open-source non-proprietary statistical software, the strict dichotomy between lab and lecture can be loosened.
- It’s much harder for students to understand the importance of using software if they only use it once a week or less. They forget the syntax in much the same way someone learning a foreign language forgets the grammar rules. Frequent reinforcement is key.
-
Focus on the entire data/science research pipeline
- We believe that the entirety of Grolemund and Wickham’s data/science pipeline as seen in Figure 0.2 should be taught.
- We heed George Cobb’s call to “minimize prerequisites to research”: students should be answering questions with data as soon as possible.
-
It’s all about the data
- We leverage R packages for rich, real, and realistic datasets that at the same time are easy-to-load into R, such as the
nycflights23
andfivethirtyeight
packages. - We believe that data visualization is a “gateway drug” for statistics and that the grammar of graphics as implemented in the
ggplot2
package is the best way to impart such lessons. However, we often hear: “You can’t teachggplot2
for data visualization in intro stats!” We, like David Robinson, are much more optimistic and have found our students have been largely successful in learning it. -
dplyr
has made data wrangling much more accessible to novices, and hence much more interesting datasets can be explored.
- We leverage R packages for rich, real, and realistic datasets that at the same time are easy-to-load into R, such as the
-
Use simulation/resampling to introduce statistical inference, not probability/mathematical formulas
- Instead of using formulas, large-sample approximations, and probability tables, we teach statistical concepts using simulation-based inference.
- This allows for a de-emphasis of traditional probability topics, freeing up room in the syllabus for other topics. Bridges to these mathematical concepts are given as well to help with relation of these traditional topics with more modern approaches.
-
Don’t fence off students from the computation pool, throw them in!
- Computing skills are essential to working with data in the 21st century. Given this fact, we feel that to shield students from computing is to ultimately do them a disservice.
- We are not teaching a course on coding/programming per se, but rather just enough of the computational and algorithmic thinking necessary for data analysis.
-
Complete reproducibility and customizability
- We are frustrated when textbooks give examples, but not the source code and the data itself. We give you the source code for all examples as well as the whole book! While we have made choices to occasionally hide the code that produces more complicated figures, reviewing the book’s GitHub repository will provide you with all the code (see in “About this book”).
- Ultimately the best textbook is one you’ve written yourself. You know best your audience, their background, and their priorities. You know best your own style and the types of examples and problems you like best. Customization is the ultimate end. We encourage you to take what we’ve provided and make it work for your own needs. For more about how to make this book your own, see “About this book” later in this Preface.
Connect and contribute
If you would like to connect with ModernDive, check out the following links:
- If you would like to receive periodic updates about ModernDive (roughly every 6 months), please sign up for our mailing list.
- We’re on X (formerly Twitter) at https://x.com/ModernDive.
If you would like to contribute to ModernDive, there are many ways! We would love your help and feedback to make this book as great as possible! For example, if you find any errors, typos, or areas for improvement, then please post an issue on our GitHub issues page. If you are familiar with GitHub and would like to contribute, see the “About this book” section.
Acknowledgements
The authors would like to thank Nina Sonneborn, Dr. Alison Hill, Kristin Bott, Dr. Jenny Smetzer, Prof. Katherine Kinnaird, and the participants of our 2017 and 2019 USCOTS workshops for their feedback and suggestions. We’d also like to thank Dr. Andrew Heiss for contributing nearly all of Subsection 1.2.3 on “Errors, warnings, and messages,” Evgeni Chasnovski for creating the geom_parallel_slopes()
extension to the ggplot2
package for plotting parallel slopes models, and Smith College Statistical & Data Sciences students Starry Zhou and Marium Tapal for their many edits to the book. A special thanks goes to Dr. Jude Weinstein-Jones, co-founder of The Learning Scientists, for their extensive feedback. Much appreciation also goes to Jasmin Lörchner for her thorough read, continued support, and thoughtful edits for the second edition of this book!
We were honored to have Dr. Kelly S. McConville write the Foreword of both editions of the book. Dr. McConville is a pioneer in statistics education and was a source of great inspiration to both of us as we continued to update the book to get it to its current form. Thanks additionally to the continued contributions by members of the community to the book on GitHub and to the many individuals that have recommended this book to others. We are so very appreciative of all of you!
Lastly, a special shout out to any student who has ever taken a class with us at Pacific University, Reed College, Middlebury College, Amherst College, Smith College, or Indiana University. We couldn’t have made this book without you!
About this book
This book was written using the bookdown package by Yihui Xie(Xie 2024). This package simplifies book publishing by having all content written in R Markdown. The R Markdown source code of ModernDive is available on GitHub:
-
Latest online version The most up-to-date release:
- Version 2.0.0 released on December 4, 2024 (source code)
- Available at https://moderndive.com/v2/
-
Print second edition The CRC Press print edition is what you are reading! It corresponds to Version 2.0.0. We welcomed Dr. Arturo Valdivia as a co-author for this edition. His deep knowledge of statistics and superb teaching experience have been invaluable in improving the book. Here is a summary of what was updated from v1.0.0 to v2.0.0 (first print edition to second print edition). Additional information about changes to the book over time are available on our GitHub page here.
-
Updated Datasets and Code: Replaced datasets (
promotions
,evals
, andpennies
) with new ones (un_member_states_2024
,spotify_sample
, andalmonds_bowl
). Adopted thenycflights23
package instead ofnycflights13
and introduced the base R pipe (|>
) instead of the tidyverse pipe (%>%
). Also incorporatedenvoy_flights
andearly_january_2023_weather
in themoderndive
package. - Content Reorganization: Restructured sections in Chapters 7 and 10 for improved readability. Moved “Model Selection” from Chapter 6 to Chapter 10 and split it into two new subsections as per suggestions.
- Enhanced Theoretical Discussions: Improved theory-based discussions in Chapters 7, 8, 10, and 11, and added sections to better connect statistical inference based on reviewer feedback.
-
New Examples and Functions: Introduced
coffee_quality
andold_faithful_2024
datasets with examples in Chapter 10, added use of thefit()
function from theinfer
package for simulation-based inference with multiple linear regression, and addedinfer
coverage into Chapter 11. -
Code Enhancements and Clarifications: Standardized code to use
|>
, addressed warnings forgroup_by()
, and addedrelocate()
to Chapter 3. - Revamped Learning Checks:: Updated and designed new Learning checks throughout the book to better assess student understanding.
-
Updated Datasets and Code: Replaced datasets (
- Print first edition The CRC Press print edition of ModernDive corresponds to Version 1.1.0 (with some typos fixed). Available at https://moderndive.com/.
-
Previous online versions Older versions that may be out of date:
- Version 1.0.0 released on November 25, 2019 (source code)
- Version 0.6.1 released on August 28, 2019 (source code)
- Version 0.6.0 released on August 7, 2019 (source code)
- Version 0.5.0 released on February 24, 2019 (source code)
- Version 0.4.0 released on July 21, 2018 (source code)
- Version 0.3.0 released on February 3, 2018 (source code)
- Version 0.2.0 released on August 2, 2017 (source code)
- Version 0.1.3 released on February 9, 2017 (source code)
- Version 0.1.2 released on January 22, 2017 (source code)
Could this be a new paradigm for textbooks? Instead of the traditional model of textbook companies publishing updated editions of the textbook every few years, we apply a software design influenced model of publishing more easily updated versions. We can then leverage open-source communities of instructors and developers for ideas, tools, resources, and feedback. As such, we welcome your GitHub pull requests.
Finally, since this book is under a Creative Commons Attribution - NonCommercial – ShareAlike 4.0 license, feel free to modify the book as you wish for your own non-commercial needs, but please list the authors at the top of index.Rmd
as: “Chester Ismay, Albert Y. Kim, Arturo Valdivia, and YOU!”
Versions of R packages used
If you’d like your output on your computer to match up exactly with the output presented throughout the book, you may want to use the exact versions of the packages that we used. You can find a full listing of these packages and their versions here. This likely won’t be relevant for novices, but we included it for reproducibility.
If you are seeing different results than what is in the book, we recommend installing the exact version of the packages we used. This can be done by first installing the remotes
package via install.packages("remotes")
. Then, use install_version()
replacing the package
argument with the package name in quotes and the version
argument with the particular version number to install such as
remotes::install_version(package = "moderndive", version = "0.6.1")
package | version |
---|---|
bookdown | 0.41 |
broom | 1.0.7 |
dplyr | 1.1.4 |
fivethirtyeight | 0.6.2 |
forcats | 1.0.0 |
gapminder | 1.0.0 |
ggplot2 | 3.5.1 |
ggplot2movies | 0.0.1 |
ggrepel | 0.9.6 |
gridExtra | 2.3 |
infer | 1.0.7.9000 |
ISLR2 | 1.3-2 |
janitor | 2.2.0 |
kableExtra | 1.4.0 |
knitr | 1.49 |
lubridate | 1.9.3 |
moderndive | 0.7.0 |
mvtnorm | 1.3-2 |
nycflights23 | 0.1.0 |
patchwork | 1.3.0 |
purrr | 1.0.2 |
readr | 2.1.5 |
scales | 1.3.0 |
sessioninfo | 1.2.2 |
stringr | 1.5.1 |
tibble | 3.2.1 |
tidyr | 1.3.1 |
tidyverse | 2.0.0 |
viridis | 0.6.5 |
viridisLite | 0.4.2 |