Merge branch 'master' of github.com:hadley/r4ds

This commit is contained in:
Garrett 2015-12-18 17:16:06 -05:00
commit 1767198f6e
18 changed files with 199 additions and 34 deletions

View File

@ -51,6 +51,5 @@ deploy:
secret_access_key:
secure: "KB6D4dRFyqABOUBC6q6CTI7WZQ+4kFOSDWNQFAbXJQR4TzR8J6uddAiSZyG8T1/8z+9Lm1VK417Zi0dGm3r3epbSnLClitBetvE11DoByomK+ey+NJ0MdXuXbFCJhX9l+8QDbDRLd/b2MEr36JXNaNQaLf5wdHImVVfcCm5STAIOM42plYMvz4Uhao+VjIKo+0IqiGHQHsNcU4qQXS4jd4FtO/t1xCwa7SgH0wwV2yJmeh8mM7QpmUEpBcZTHDvqZu6BitxtkYQDCh1iuBwhbPlYug/WOtyHmKYgU/c3+C+xW4OLv10OsE+eK6noEzIXQ80sPIyKMpkn+9P+7MnoRU/oZTXmYJOuXE5mvy+CiJ4TzZZxzB/g8HzklRRI4eFBmJ/zTTMmJMwBdbUhCXepARe4gr7pDFKhSTXvBVxljJBrkiGz6W1JeZ9nKzUbuIlWNJ9aaYM2UDMbRef7xyKlKbBNw1+90aTTW8Jo+0Sz3/R7daBTcnr0Bszg4QCaOMoxJJF/Ty/tTHiComAt/kNRqlSiU2g/Ch0jOz5TRV3c29OjQQ/a9ftf5pqlvgStwjjszgHQfRrd4mxGq2E/1gkPGL7ada+TWPAVjCc8HtPGK/36IjSccFB6qGkwTFf3uOBmAC2XVnJJlwG8v20nL5ZZwpCCbQANeQq/ILQsYUmk7RM="
bucket: r4ds.had.co.nz
endpoint: r4ds.had.co.nz.s3-website-us-east-1.amazonaws.com
local-dir: _site
skip_cleanup: true

View File

@ -21,13 +21,13 @@ module Jekyll
# http://rubyquicktips.com/post/5862861056/execute-shell-commands
content = `_plugins/knit.r temp.Rmd`
if $?.exitstatus != 0
raise "Knitting failed"
raise "Knitting failed"
end
content
# File.unlink f.path
end
end
end
end

View File

@ -1,3 +1,8 @@
---
layout: default
title: Data structures
---
# Data structures
Might be quite brief.

View File

@ -1 +1,9 @@
---
layout: default
title: Dates and times
---
# Dates and times
If you have trouble remembering these abbreviations, check out the [strptimer package](https://cran.r-project.org/web/packages/strptimer/vignettes/strptimer.html).

View File

@ -1,3 +1,8 @@
---
layout: default
title: Exploratory data analysis
---
# Exploratory data analysis
```{r, include = FALSE}

View File

@ -1,3 +1,8 @@
---
layout: default
title: Expressing yourself in code
---
# Expressing yourself in code
```{r, include = FALSE}

View File

@ -1,3 +1,8 @@
---
layout: default
title: Data import
---
# Data import
```{r, include = FALSE}

View File

@ -1,3 +1,8 @@
---
title: Introduction
layout: default
---
# Introduction
```{r setup-intro, include = FALSE}
@ -71,7 +76,7 @@ Another class of big data problem consists of many small data problems. Each ind
### Python
In this book, you won't learn anything about Python, Juli, 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.
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 be only know one thing, just that you'll generally learn faster if you stick to one thing at a time.
@ -104,7 +109,7 @@ To run the code in this book, you will need to install both R and the RStudio ID
RStudio is an integated development environment, or IDE, for R programming. There are three key regions:
```{r}
```{r, echo = FALSE}
knitr::include_graphics("screenshots/rstudio-layout.png")
```
@ -124,7 +129,7 @@ If you want to see a list of all keyboard shortcuts, use the meta keyboard short
We strongly recommend making two changes to the default RStudio options:
```{r}
```{r, echo = FALSE}
knitr::include_graphics("screenshots/rstudio-workspace.png")
```

View File

@ -1,3 +1,8 @@
---
layout: default
title: Lists
---
# Lists
```{r setup-lists, include=FALSE}
@ -44,7 +49,7 @@ x <- list(1, 2, 3)
str(x)
x_named <- list(a = 1, b = 2, c = 3)
str(x)
str(x_named)
```
Unlike atomic vectors, `lists()` can contain a mix of objects:
@ -536,7 +541,7 @@ You'll see an example of this in the next section, as `transpose()` is particula
It's called transpose by analogy to matrices. When you subset a transposed matrix, you switch indices: `x[i, j]` is the same as `t(x)[j, i]`. It's the same idea when transposing a list, but the subsetting looks a little different: `x[[i]][[j]]` is equivalent to `transpose(x)[[j]][[i]]`. Similarly, a transpose is its own inverse so `transpose(transpose(x))` is equal to `x`.
Tranpose is also useful when working with JSON apis. Many JSON APIs represent data frames in a row-based format, rather than R's column-based format. `transpose()` makes it easy to switch between the two:
Transpose is also useful when working with JSON apis. Many JSON APIs represent data frames in a row-based format, rather than R's column-based format. `transpose()` makes it easy to switch between the two:
```{r}
df <- dplyr::data_frame(x = 1:3, y = c("a", "b", "c"))

View File

@ -1,3 +1,8 @@
---
layout: default
title: Model assessment
---
# Model assessment
```{r setup-model, include=FALSE}

View File

@ -1,3 +1,8 @@
---
layout: default
title: Model visualisation
---
# Model visualisation
Gap minder

View File

@ -1,3 +1,8 @@
---
layout: default
title: Model
---
# Model
Models are one of the most important tools for data scientists, because models describe relationships. Would you list out every value of a variable, or would you state the mean? Would you list out every pair of values, or would you state the function between variables?

View File

@ -1,9 +1,16 @@
---
layout: default
title: R Markdown
---
# R Markdown
Recommendations for learning more about communication:
For writing: [Style: Lessons in Clarity and Grace](http://amzn.com/0321898680), <http://www.americanscientist.org/issues/id.877,y.0,no.,content.true,page.1,css.print/issue.aspx>
For presentations: [slide:ology](http://amzn.com/0596522347), <http://www.howtogiveatalk.com>, <https://github.com/jtleek/talkguide> (academic).
For presentations: [slide:ology](http://amzn.com/0596522347), <http://www.howtogiveatalk.com>, <https://github.com/jtleek/talkguide> (academic), http://speaking.io, https://www.coursera.org/learn/public-speaking
For expository visulisations: WSJ guide?
Design: [The Non-Designer's Design Book](http://amzn.com/0133966151)

View File

@ -1 +1,6 @@
---
layout: default
title: Shiny
---
# Shiny

View File

@ -1,4 +1,9 @@
# String manipulation
---
layout: default
title: Strings
---
# Strings
```{r setup-strings, include = FALSE}
library(stringr)

View File

@ -1,3 +1,8 @@
---
layout: default
title: Tidy data
---
# Tidy data
> "Tidy datasets are all alike but every messy dataset is messy in its

View File

@ -1,3 +1,8 @@
---
layout: default
title: Transform
---
# Data transformation {#transform}
```{r setup-transform, include = FALSE}
@ -6,6 +11,7 @@ library(nycflights13)
library(ggplot2)
source("common.R")
options(dplyr.print_min = 6)
knitr::opts_chunk$set(fig.path = "figures/")
```
Visualisation is an important tool for insight generation, but it is rare that you get the data in exactly the right form you need for visualisation. Often you'll need to create some new variables or summaries, or maybe you just want to rename the variables or reorder the observations in order to make the data a little easier to work with. You'll learn how to do all that (and more!) in this chapter which will teach you how to transform your data using the dplyr package.
@ -525,6 +531,19 @@ by_day <- group_by(flights, year, month, day)
summarise(by_day, delay = mean(dep_delay, na.rm = TRUE))
```
### Grouping by multiple variables
When you group by multiple variables, each summary peels off one level of the grouping. That makes it easy to progressively roll-up a dataset:
```{r}
daily <- group_by(flights, year, month, day)
(per_day <- summarise(daily, flights = n()))
(per_month <- summarise(per_day, flights = sum(flights)))
(per_year <- summarise(per_month, flights = sum(flights)))
```
However you need to be careful when progressively rolling up summaries like this: it's ok for sums and counts, but you need to think about weighting for means and variances, and it's not possible to do it exactly for medians.
### Useful summaries
You use `summarise()` with __aggregate functions__, which take a vector of values and return a single number.
@ -570,6 +589,21 @@ mean(c(1, 5, 10, NA), na.rm = TRUE)
### Exercises
1. Brainstorm at least 5 different ways to assess the typically delay
characteristics of a group of flights. Consider the following scenarios:
* A flight is 15 minutes early 50% of the time, and 15 minutes late 50% of
the time.
* A flight is always 10 minutes late.
* A flight is 30 minutes early 50% of the time, and 30 minutes late 50% of
the time.
* 99% of the time a flight is on time. 1% of the time it's 2 hours late.
Which is more important: arrival delay or departure delay?
## Multiple operations
Imagine we want to explore the relationship between the distance and average delay for each location. Using what you already know about dplyr, you might write code like this:
@ -618,6 +652,10 @@ Behind the scenes, `x %>% f(y)` turns into `f(x, y)` so you can use it to rewrit
The pipe makes it easier to solve complex problems by joining together simple pieces. Each dplyr function does one thing well, helping you advance to your goal with one small step. You can check your work frequently, and if you get stuck, you just need to think: "what's one small thing I could do to advance towards a solution".
Where does `%>%` come from.
Most of the packages you'll learn through this book have been designed to work with the pipe (tidyr, dplyr, stringr, purrr, ...). The only exception is ggplot2: it was developed considerably before the discovery of the pipe. Unfortunately the next iteration of ggplot2, ggvis, which does use the pipe, isn't ready from prime time yet.
The rest of this section explores some practical uses of the pipe when combining multiple dplyr operations to solve real problems.
### Counts
@ -655,7 +693,22 @@ ggplot(delays, aes(n, delay)) +
You'll see that most of the very delayed flight numbers happen very rarely. The shape of this plot is very characteristic: whenever you plot a mean (or many other summaries) vs number of observations, you'll see that the variation decreases as the sample size increases.
There's another variation on this type of plot as shown below. Here I use the Lahman package to compute the batting average (number of hits / number of attempts) of every major league baseball player. When I plot the skill of the batter against the number of times batted, you see two patterns:
When looking at this sort of plot, it's often useful to filter out the groups with the smallest numbers of observations, so you can see more of the pattern and less of the extreme variation in the smallest groups. This what the following code does, and also shows you a handy pattern for integrating ggplot2 into dplyr flows. It's a bit painful that you have to switch from `%>%` to `+`, but once you get the hang of it, it's quite convenient.
```{r}
delays %>%
filter(n > 25) %>%
ggplot(aes(n, delay)) +
geom_point()
```
--------------------------------------------------------------------------------
RStudio tip: useful keyboard shortcut is Cmd + Shift + P. This resends the previously sent chunk from the editor to the console. This is very convenient when you're (e.g.) exploring the value of `n` in the example above. You send the whole block once with Cmd + Enter, then you modify the value of `n` and press Cmd + Shift + P to resend the complete block.
--------------------------------------------------------------------------------
There's another common variation of this type of pattern. Let's look at how the average performance of batters in baseball is related to the number of times they're at bat. Here I use the Lahman package to compute the batting average (number of hits / number of attempts) of every major league baseball player. When I plot the skill of the batter against the number of times batted, you see two patterns:
1. As above, the variation in our aggregate decreases as we get more
data points.
@ -672,34 +725,69 @@ batters <- batting %>%
summarise(
ba = sum(H) / sum(AB),
ab = sum(AB)
) %>%
filter(ab > 100)
)
ggplot(batters, aes(ab, ba)) +
geom_point() +
geom_smooth(se = FALSE)
batters %>%
filter(ab > 100) %>%
ggplot(aes(ab, ba)) +
geom_point() +
geom_smooth(se = FALSE)
```
### Grouping by multiple variables
When you group by multiple variables, each summary peels off one level of the grouping. That makes it easy to progressively roll-up a dataset:
This also has important implications for ranking. If you naively sort on `desc(ba)`, the people with the best batting averages are clearly lucky, not skilled:
```{r}
daily <- group_by(flights, year, month, day)
(per_day <- summarise(daily, flights = n()))
(per_month <- summarise(per_day, flights = sum(flights)))
(per_year <- summarise(per_month, flights = sum(flights)))
batters %>% arrange(desc(ba))
```
However you need to be careful when progressively rolling up summaries like this: it's ok for sums and counts, but you need to think about weighting for means and variances, and it's not possible to do it exactly for medians.
You can find a good explanation of this problem at <http://varianceexplained.org/r/empirical_bayes_baseball/> and <http://www.evanmiller.org/how-not-to-sort-by-average-rating.html>.
### Grouped mutates (and filters)
* `mutate()` and `filter()` are most useful in conjunction with window
functions (like `rank()`, or `min(x) == x`). They are described in detail in
the windows function vignette `vignette("window-functions")`.
Grouping is definitely most useful in conjunction with `summarise()`, but you can also do convenient operations with `mutate()` and `filter()`:
A grouped filter is basically like a grouped mutate followed by a regular filter. I generally avoid them except for quick and dirty manipulations. Otherwise it's too hard to check that you've done the manipulation correctly.
* Find the worst members of each group:
```{r}
flights %>%
group_by(year, month, day) %>%
filter(rank(arr_delay) < 10)
```
* Find all groups bigger than a threshold:
```{r}
popular_dests <- flights %>%
group_by(dest) %>%
filter(n() > 365)
```
* Standardise to compute per group metrics:
```{r}
popular_dests %>%
filter(arr_delay > 0) %>%
mutate(prop_delay = arr_delay / sum(arr_delay))
```
A grouped filter is basically like a grouped mutate followed by an ungrouped filter. I generally avoid them except for quick and dirty manipulations. Otherwise it's too hard to check that you've done the manipulation correctly.
Function that work most naturally in grouped mutates and filtered are known as window functions (vs. aggregate or summary functions used in grouped summaries). You can learn more about useful window functions in the corresponding vignette: `vignette("window-functions")`.
### Exercises
1. Which plane (`tailnum`) has the worst on-time record?
1. What time of day should you fly if you want to avoid delays as much
as possible?
1. Look at each destination. Can you find flights that are suspiciously
fast? (i.e. flights that represent a potential data entry error). Compute
the air time a flight relative to the shortest flight to that destination.
Which flights were most delayed in the air?
1. Find all destinations that are flown by at least two carriers. Use that
information to rank the carriers.
## Multiple tables of data
@ -722,8 +810,7 @@ All two-table verbs work similarly. The first two arguments are `x` and `y`, and
Mutating joins allow you to combine variables from multiple tables. For example, take the nycflights13 data. In one table we have flight information with an abbreviation for carrier, and in another we have a mapping between abbreviations and full names. You can use a join to add the carrier names to the flight data:
```{r, warning = FALSE}
library("nycflights13")
```{r}
# Drop unimportant variables so it's easier to understand the join results.
flights2 <- flights %>% select(year:day, hour, origin, dest, tailnum, carrier)
@ -827,7 +914,6 @@ Filtering joins match obserations in the same way as mutating joins, but affect
These are most useful for diagnosing join mismatches. For example, there are many flights in the nycflights13 dataset that don't have a matching tail number in the planes table:
```{r}
library("nycflights13")
flights %>%
anti_join(planes, by = "tailnum") %>%
count(tailnum, sort = TRUE)
@ -931,7 +1017,7 @@ When joining tables, dplyr is a little more conservative than base R about the t
Otherwise logicals will be silently upcast to integer, and integer to numeric, but coercing to character will raise an error:
```{r, error = TRUE, purl = FALSE}
```{r, error = TRUE}
df1 <- data_frame(x = 1, y = 1L)
df2 <- data_frame(x = 2, y = 1.5)
full_join(df1, df2) %>% str()

View File

@ -1,3 +1,8 @@
---
layout: default
title: Visualize
---
# Data visualisation
```{r setup-visualise, include = FALSE}