<p>Numeric vectors are the backbone of data science, and you’ve already used them a bunch of times earlier in the book. Now it’s time to systematically survey what you can do with them in R, ensuring that you’re well situated to tackle any future problem involving numeric vectors.</p>
<p>We’ll start by giving you a couple of tools to make numbers if you have strings, and then going into a little more detail of <code><ahref="https://dplyr.tidyverse.org/reference/count.html">count()</a></code>. Then we’ll dive into various numeric transformations that pair well with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>, including more general transformations that can be applied to other types of vector, but are often used with numeric vectors. We’ll finish off by covering the summary functions that pair well with <code><ahref="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code> and show you how they can also be used with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>.</p>
<p>This chapter relies on features only found in dplyr 1.1.0, which is still in development. If you want to live on the edge, you can get the dev versions with <code>devtools::install_github("tidyverse/dplyr")</code>.</p></div>
<p>This chapter mostly uses functions from base R, which are available without loading any packages. But we still need the tidyverse because we’ll use these base R functions inside of tidyverse functions like <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code>. Like in the last chapter, we’ll use real examples from nycflights13, as well as toy examples made with <code><ahref="https://rdrr.io/r/base/c.html">c()</a></code> and <code><ahref="https://tibble.tidyverse.org/reference/tribble.html">tribble()</a></code>.</p>
<p>In most cases, you’ll get numbers already recorded in one of R’s numeric types: integer or double. In some cases, however, you’ll encounter them as strings, possibly because you’ve created them by pivoting from column headers or because something has gone wrong in your data import process.</p>
<p>readr provides two useful functions for parsing strings into numbers: <code><ahref="https://readr.tidyverse.org/reference/parse_atomic.html">parse_double()</a></code> and <code><ahref="https://readr.tidyverse.org/reference/parse_number.html">parse_number()</a></code>. Use <code><ahref="https://readr.tidyverse.org/reference/parse_atomic.html">parse_double()</a></code> when you have numbers that have been written as strings:</p>
<p>Use <code><ahref="https://readr.tidyverse.org/reference/parse_number.html">parse_number()</a></code> when the string contains non-numeric text that you want to ignore. This is particularly useful for currency data and percentages:</p>
<p>It’s surprising how much data science you can do with just counts and a little basic arithmetic, so dplyr strives to make counting as easy as possible with <code><ahref="https://dplyr.tidyverse.org/reference/count.html">count()</a></code>. This function is great for quick exploration and checks during analysis:</p>
<p>(Despite the advice in <ahref="#chp-workflow-style"data-type="xref">#chp-workflow-style</a>, we usually put <code><ahref="https://dplyr.tidyverse.org/reference/count.html">count()</a></code> on a single line because it’s usually used at the console for a quick check that a calculation is working as expected.)</p>
<p>You can perform the same computation “by hand” with <code><ahref="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a></code>, <code><ahref="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/context.html">n()</a></code>. This is useful because it allows you to compute other summaries at the same time:</p>
<p><code><ahref="https://dplyr.tidyverse.org/reference/context.html">n()</a></code> is a special summary function that doesn’t take any arguments and instead accesses information about the “current” group. This means that it only works inside dplyr verbs:</p>
<p><code>n_distinct(x)</code> counts the number of distinct (unique) values of one or more variables. For example, we could figure out which destinations are served by the most carriers:</p>
<p>Weighted counts are a common problem so <code><ahref="https://dplyr.tidyverse.org/reference/count.html">count()</a></code> has a <code>wt</code> argument that does the same thing:</p>
<p>You can count missing values by combining <code><ahref="https://rdrr.io/r/base/sum.html">sum()</a></code> and <code><ahref="https://rdrr.io/r/base/NA.html">is.na()</a></code>. In the <code>flights</code> dataset this represents flights that are cancelled:</p>
<oltype="1"><li>How can you use <code><ahref="https://dplyr.tidyverse.org/reference/count.html">count()</a></code> to count the number rows with a missing value for a given variable?</li>
<li>Expand the following calls to <code><ahref="https://dplyr.tidyverse.org/reference/count.html">count()</a></code> to instead use <code><ahref="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a></code>, <code><ahref="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code>, and <code><ahref="https://dplyr.tidyverse.org/reference/arrange.html">arrange()</a></code>:
<p>Transformation functions work well with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> because their output is the same length as the input. The vast majority of transformation functions are already built into base R. It’s impractical to list them all so this section will show the most useful ones. As an example, while R provides all the trigonometric functions that you might dream of, we don’t list them here because they’re rarely needed for data science.</p>
<p>We introduced the basics of arithmetic (<code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>^</code>) in <ahref="#chp-workflow-basics"data-type="xref">#chp-workflow-basics</a> and have used them a bunch since. These functions don’t need a huge amount of explanation because they do what you learned in grade school. But we need to briefly talk about the <strong>recycling rules</strong> which determine what happens when the left and right hand sides have different lengths. This is important for operations like <code>flights |> mutate(air_time = air_time / 60)</code> because there are 336,776 numbers on the left of <code>/</code> but only one on the right.</p>
<p>R handles mismatched lengths by <strong>recycling,</strong> or repeating, the short vector. We can see this in operation more easily if we create some vectors outside of a data frame:</p>
<p>Generally, you only want to recycle single numbers (i.e.vectors of length 1), but R will recycle any shorter length vector. It usually (but not always) gives you a warning if the longer vector isn’t a multiple of the shorter:</p>
#> Warning in x * c(1, 2, 3): longer object length is not a multiple of shorter
#> object length
#> [1] 1 4 30 20</pre>
</div>
<p>These recycling rules are also applied to logical comparisons (<code>==</code>, <code><</code>, <code><=</code>, <code>></code>, <code>>=</code>, <code>!=</code>) and can lead to a surprising result if you accidentally use <code>==</code> instead of <code>%in%</code> and the data frame has an unfortunate number of rows. For example, take this code which attempts to find all flights in January and February:</p>
<p>The code runs without error, but it doesn’t return what you want. Because of the recycling rules it finds flights in odd numbered rows that departed in January and flights in even numbered rows that departed in February. And unfortunately there’s no warning because <code>flights</code> has an even number of rows.</p>
<p>To protect you from this type of silent failure, most tidyverse functions use a stricter form of recycling that only recycles single values. Unfortunately that doesn’t help here, or in many other cases, because the key computation is performed by the base R function <code>==</code>, not <code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code>.</p>
<p>The arithmetic functions work with pairs of variables. Two closely related functions are <code><ahref="https://rdrr.io/r/base/Extremes.html">pmin()</a></code> and <code><ahref="https://rdrr.io/r/base/Extremes.html">pmax()</a></code>, which when given two or more variables will return the smallest or largest value in each row:</p>
<p>Note that these are different to the summary functions <code><ahref="https://rdrr.io/r/base/Extremes.html">min()</a></code> and <code><ahref="https://rdrr.io/r/base/Extremes.html">max()</a></code> which take multiple observations and return a single value. You can tell that you’ve used the wrong form when all the minimums and all the maximums have the same value:</p>
<p>Modular arithmetic is the technical name for the type of math you did before you learned about real numbers, i.e.division that yields a whole number and a remainder. In R, <code>%/%</code> does integer division and <code>%%</code> computes the remainder:</p>
<p>Modular arithmetic is handy for the flights dataset, because we can use it to unpack the <code>sched_dep_time</code> variable into <code>hour</code> and <code>minute</code>:</p>
<p>We can combine that with the <code>mean(is.na(x))</code> trick from <ahref="#sec-logical-summaries"data-type="xref">#sec-logical-summaries</a> to see how the proportion of cancelled flights varies over the course of the day. The results are shown in <ahref="#fig-prop-cancelled"data-type="xref">#fig-prop-cancelled</a>.</p>
<figureid="fig-prop-cancelled"><p><imgsrc="numbers_files/figure-html/fig-prop-cancelled-1.png"alt="A line plot showing how proportion of cancelled flights changes over the course of the day. The proportion starts low at around 0.5% at 6am, then steadily increases over the course of the day until peaking at 4% at 7pm. The proportion of cancelled flights then drops rapidly getting down to around 1% by midnight."width="576"/></p>
<figcaption>A line plot with scheduled departure hour on the x-axis, and proportion of cancelled flights on the y-axis. Cancellations seem to accumulate over the course of the day until 8pm, very late flights are much less likely to be cancelled.</figcaption>
<p>Logarithms are an incredibly useful transformation for dealing with data that ranges across multiple orders of magnitude. They also convert exponential growth to linear growth. For example, take compounding interest — the amount of money you have at <code>year + 1</code> is the amount of money you had at <code>year</code> multiplied by the interest rate. That gives a formula like <code>money = starting * interest ^ year</code>:</p>
<p>This a straight line because a little algebra reveals that <code>log10(money) = log10(interest) * year + log10(starting)</code>, which matches the pattern for a line, <code>y = m * x + b</code>. This is a useful pattern: if you see a (roughly) straight line after log-transforming the y-axis, you know that there’s underlying exponential growth.</p>
<p>If you’re log-transforming your data with dplyr you have a choice of three logarithms provided by base R: <code><ahref="https://rdrr.io/r/base/Log.html">log()</a></code> (the natural log, base e), <code><ahref="https://rdrr.io/r/base/Log.html">log2()</a></code> (base 2), and <code><ahref="https://rdrr.io/r/base/Log.html">log10()</a></code> (base 10). We recommend using <code><ahref="https://rdrr.io/r/base/Log.html">log2()</a></code> or <code><ahref="https://rdrr.io/r/base/Log.html">log10()</a></code>. <code><ahref="https://rdrr.io/r/base/Log.html">log2()</a></code> is easy to interpret because a difference of 1 on the log scale corresponds to doubling on the original scale and a difference of -1 corresponds to halving; whereas <code><ahref="https://rdrr.io/r/base/Log.html">log10()</a></code> is easy to back-transform because (e.g.) 3 is 10^3 = 1000.</p>
<p>The inverse of <code><ahref="https://rdrr.io/r/base/Log.html">log()</a></code> is <code><ahref="https://rdrr.io/r/base/Log.html">exp()</a></code>; to compute the inverse of <code><ahref="https://rdrr.io/r/base/Log.html">log2()</a></code> or <code><ahref="https://rdrr.io/r/base/Log.html">log10()</a></code> you’ll need to use <code>2^</code> or <code>10^</code>.</p>
<p>You can control the precision of the rounding with the second argument, <code>digits</code>. <code>round(x, digits)</code> rounds to the nearest <code>10^-n</code> so <code>digits = 2</code> will round to the nearest 0.01. This definition is useful because it implies <code>round(x, -3)</code> will round to the nearest thousand, which indeed it does:</p>
<p><code><ahref="https://rdrr.io/r/base/Round.html">round()</a></code> uses what’s known as “round half to even” or Banker’s rounding: if a number is half way between two integers, it will be rounded to the <strong>even</strong> integer. This is a good strategy because it keeps the rounding unbiased: half of all 0.5s are rounded up, and half are rounded down.</p>
<p><code><ahref="https://rdrr.io/r/base/Round.html">round()</a></code> is paired with <code><ahref="https://rdrr.io/r/base/Round.html">floor()</a></code> which always rounds down and <code><ahref="https://rdrr.io/r/base/Round.html">ceiling()</a></code> which always rounds up:</p>
<p>You can use the same technique if you want to <code><ahref="https://rdrr.io/r/base/Round.html">round()</a></code> to a multiple of some other number:</p>
<p>Use <code><ahref="https://rdrr.io/r/base/cut.html">cut()</a></code><spandata-type="footnote">ggplot2 provides some helpers for common cases in <code><ahref="https://ggplot2.tidyverse.org/reference/cut_interval.html">cut_interval()</a></code>, <code><ahref="https://ggplot2.tidyverse.org/reference/cut_interval.html">cut_number()</a></code>, and <code><ahref="https://ggplot2.tidyverse.org/reference/cut_interval.html">cut_width()</a></code>. ggplot2 is an admittedly weird place for these functions to live, but they are useful as part of histogram computation and were written before any other parts of the tidyverse existed.</span> to break up a numeric vector into discrete buckets:</p>
<p>See the documentation for other useful arguments like <code>right</code> and <code>include.lowest</code>, which control if the intervals are <code>[a, b)</code> or <code>(a, b]</code> and if the lowest interval should be <code>[a, b]</code>.</p>
<p>Base R provides <code><ahref="https://rdrr.io/r/base/cumsum.html">cumsum()</a></code>, <code><ahref="https://rdrr.io/r/base/cumsum.html">cumprod()</a></code>, <code><ahref="https://rdrr.io/r/base/cumsum.html">cummin()</a></code>, <code><ahref="https://rdrr.io/r/base/cumsum.html">cummax()</a></code> for running, or cumulative, sums, products, mins and maxes. dplyr provides <code><ahref="https://dplyr.tidyverse.org/reference/cumall.html">cummean()</a></code> for cumulative means. Cumulative sums tend to come up the most in practice:</p>
<p>If you need more complex rolling or sliding aggregates, try the <ahref="https://davisvaughan.github.io/slider/">slider</a> package by Davis Vaughan. The following example illustrates some of its features.</p>
<oltype="1"><li><p>Explain in words what each line of the code used to generate <ahref="#fig-prop-cancelled"data-type="xref">#fig-prop-cancelled</a> does.</p></li>
<li><p>What trigonometric functions does R provide? Guess some names and look up the documentation. Do they use degrees or radians?</p></li>
<li>
<p>Currently <code>dep_time</code> and <code>sched_dep_time</code> are convenient to look at, but hard to compute with because they’re not really continuous numbers. You can see the basic problem in this plot: there’s a gap between each hour.</p>
<p>The following sections describe some general transformations which are often used with numeric vectors, but can be applied to all other column types.</p>
<p>dplyr provides a number of ranking functions inspired by SQL, but you should always start with <code><ahref="https://dplyr.tidyverse.org/reference/row_number.html">dplyr::min_rank()</a></code>. It uses the typical method for dealing with ties, e.g.1st, 2nd, 2nd, 4th.</p>
<p>If <code><ahref="https://dplyr.tidyverse.org/reference/row_number.html">min_rank()</a></code> doesn’t do what you need, look at the variants <code><ahref="https://dplyr.tidyverse.org/reference/row_number.html">dplyr::row_number()</a></code>, <code><ahref="https://dplyr.tidyverse.org/reference/row_number.html">dplyr::dense_rank()</a></code>, <code><ahref="https://dplyr.tidyverse.org/reference/percent_rank.html">dplyr::percent_rank()</a></code>, and <code><ahref="https://dplyr.tidyverse.org/reference/percent_rank.html">dplyr::cume_dist()</a></code>. See the documentation for details.</p>
<p>You can achieve many of the same results by picking the appropriate <code>ties.method</code> argument to base R’s <code><ahref="https://rdrr.io/r/base/rank.html">rank()</a></code>; you’ll probably also want to set <code>na.last = "keep"</code> to keep <code>NA</code>s as <code>NA</code>.</p>
<p><code><ahref="https://dplyr.tidyverse.org/reference/row_number.html">row_number()</a></code> can also be used without any arguments when inside a dplyr verb. In this case, it’ll give the number of the “current” row. When combined with <code>%%</code> or <code>%/%</code> this can be a useful tool for dividing data into similarly sized groups:</p>
<p><code><ahref="https://dplyr.tidyverse.org/reference/lead-lag.html">dplyr::lead()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/lead-lag.html">dplyr::lag()</a></code> allow you to refer the values just before or just after the “current” value. They return a vector of the same length as the input, padded with <code>NA</code>s at the start or end:</p>
<p>Sometimes you want to start a new group every time some event occurs. For example, when you’re looking at website data, it’s common to want to break up events into sessions, where a session is defined as a gap of more than x minutes since the last activity.</p>
<p>For example, imagine you have the times when someone visited a website:</p>
<p>But how do we go from that logical vector to something that we can <code><ahref="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a></code>? <code><ahref="https://rdrr.io/r/base/cumsum.html">cumsum()</a></code> from <ahref="#sec-cumulative-and-rolling-aggregates"data-type="xref">#sec-cumulative-and-rolling-aggregates</a> comes to the rescue as each occurring gap, i.e., <code>gap</code> is <code>TRUE</code>, increments <code>group</code> by one (see <ahref="#sec-numeric-summaries-of-logicals"data-type="xref">#sec-numeric-summaries-of-logicals</a> on the numerical interpretation of logicals):</p>
<p>Another approach for creating grouping variables is <code><ahref="https://dplyr.tidyverse.org/reference/consecutive_id.html">consecutive_id()</a></code>, which starts a new group every time one of its arguments changes. For example, inspired by <ahref="https://stackoverflow.com/questions/27482712">this stackoverflow question</a>, imagine you have a data frame with a bunch of repeated values:</p>
<p>You want to keep the first row from each repeated <code>x</code>. That’s easier to express with a combination of <code><ahref="https://dplyr.tidyverse.org/reference/consecutive_id.html">consecutive_id()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/slice.html">slice_head()</a></code>:</p>
<oltype="1"><li><p>Find the 10 most delayed flights using a ranking function. How do you want to handle ties? Carefully read the documentation for <code><ahref="https://dplyr.tidyverse.org/reference/row_number.html">min_rank()</a></code>.</p></li>
<li><p>For each destination, compute the total minutes of delay. For each flight, compute the proportion of the total delay for its destination.</p></li>
<p>Delays are typically temporally correlated: even once the problem that caused the initial delay has been resolved, later flights are delayed to allow earlier flights to leave. Using <code><ahref="https://dplyr.tidyverse.org/reference/lead-lag.html">lag()</a></code>, explore how the average flight delay for an hour is related to the average delay for the previous hour.</p>
<li><p>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 of a flight relative to the shortest flight to that destination. Which flights were most delayed in the air?</p></li>
<li><p>Find all destinations that are flown by at least two carriers. Use those destinations to come up with a relative ranking of the carriers based on their performance for the same destination.</p></li>
<p>Just using the counts, means, and sums that we’ve introduced already can get you a long way, but R provides many other useful summary functions. Here is a selection that you might find useful.</p>
<p>So far, we’ve mostly used <code><ahref="https://rdrr.io/r/base/mean.html">mean()</a></code> to summarize the center of a vector of values. Because the mean is the sum divided by the count, it is sensitive to even just a few unusually high or low values. An alternative is to use the <code><ahref="https://rdrr.io/r/stats/median.html">median()</a></code>, which finds a value that lies in the “middle” of the vector, i.e.50% of the values is above it and 50% are below it. Depending on the shape of the distribution of the variable you’re interested in, mean or median might be a better measure of center. For example, for symmetric distributions we generally report the mean while for skewed distributions we usually report the median.</p>
<p><ahref="#fig-mean-vs-median"data-type="xref">#fig-mean-vs-median</a> compares the mean vs.the median when looking at the hourly vs.median departure delay. The median delay is always smaller than the mean delay because flights sometimes leave multiple hours late, but never leave multiple hours early.</p>
<figureid="fig-mean-vs-median"><p><imgsrc="numbers_files/figure-html/fig-mean-vs-median-1.png"alt="All points fall below a 45° line, meaning that the median delay is always less than the mean delay. Most points are clustered in a dense region of mean [0, 20] and median [0, 5]. As the mean delay increases, the spread of the median also increases. There are two outlying points with mean ~60, median ~50, and mean ~85, median ~55."width="576"/></p>
<figcaption>A scatterplot showing the differences of summarising hourly depature delay with median instead of mean.</figcaption>
<p>You might also wonder about the <strong>mode</strong>, or the most common value. This is a summary that only works well for very simple cases (which is why you might have learned about it in high school), but it doesn’t work well for many real datasets. If the data is discrete, there may be multiple most common values, and if the data is continuous, there might be no most common value because every value is ever so slightly different. For these reasons, the mode tends not to be used by statisticians and there’s no mode function included in base R<spandata-type="footnote">The <code><ahref="https://rdrr.io/r/base/mode.html">mode()</a></code> function does something quite different!</span>.</p>
<p>What if you’re interested in locations other than the center? <code><ahref="https://rdrr.io/r/base/Extremes.html">min()</a></code> and <code><ahref="https://rdrr.io/r/base/Extremes.html">max()</a></code> will give you the largest and smallest values. Another powerful tool is <code><ahref="https://rdrr.io/r/stats/quantile.html">quantile()</a></code> which is a generalization of the median: <code>quantile(x, 0.25)</code> will find the value of <code>x</code> that is greater than 25% of the values, <code>quantile(x, 0.5)</code> is equivalent to the median, and <code>quantile(x, 0.95)</code> will find the value that’s greater than 95% of the values.</p>
<p>For the <code>flights</code> data, you might want to look at the 95% quantile of delays rather than the maximum, because it will ignore the 5% of most delayed flights which can be quite extreme.</p>
<p>Sometimes you’re not so interested in where the bulk of the data lies, but in how it is spread out. Two commonly used summaries are the standard deviation, <code>sd(x)</code>, and the inter-quartile range, <code><ahref="https://rdrr.io/r/stats/IQR.html">IQR()</a></code>. We won’t explain <code><ahref="https://rdrr.io/r/stats/sd.html">sd()</a></code> here since you’re probably already familiar with it, but <code><ahref="https://rdrr.io/r/stats/IQR.html">IQR()</a></code> might be new — it’s <code>quantile(x, 0.75) - quantile(x, 0.25)</code> and gives you the range that contains the middle 50% of the data.</p>
<p>We can use this to reveal a small oddity in the <code>flights</code> data. You might expect the spread of the distance between origin and destination to be zero, since airports are always in the same place. But the code below makes it looks like one airport, <ahref="https://en.wikipedia.org/wiki/Eagle_County_Regional_Airport">EGE</a>, might have moved.</p>
<p>It’s worth remembering that all of the summary statistics described above are a way of reducing the distribution down to a single number. This means that they’re fundamentally reductive, and if you pick the wrong summary, you can easily miss important differences between groups. That’s why it’s always a good idea to visualize the distribution before committing to your summary statistics.</p>
<p><ahref="#fig-flights-dist"data-type="xref">#fig-flights-dist</a> shows the overall distribution of departure delays. The distribution is so skewed that we have to zoom in to see the bulk of the data. This suggests that the mean is unlikely to be a good summary and we might prefer the median instead.</p>
<figureid="fig-flights-dist-1"><p><imgsrc="numbers_files/figure-html/fig-flights-dist-1.png"alt="Two histograms of `dep_delay`. On the left, it's very hard to see any pattern except that there's a very large spike around zero, the bars rapidly decay in height, and for most of the plot, you can't see any bars because they are too short to see. On the right, where we've discarded delays of greater than two hours, we can see that the spike occurs slightly below zero (i.e. most flights leave a couple of minutes early), but there's still a very steep decay after that. "data-ref-parent="fig-flights-dist"width="384"/></p>
<figcaption>(a) Histogram shows the full range of delays.</figcaption>
<figureid="fig-flights-dist-2"><p><imgsrc="numbers_files/figure-html/fig-flights-dist-2.png"alt="Two histograms of `dep_delay`. On the left, it's very hard to see any pattern except that there's a very large spike around zero, the bars rapidly decay in height, and for most of the plot, you can't see any bars because they are too short to see. On the right, where we've discarded delays of greater than two hours, we can see that the spike occurs slightly below zero (i.e. most flights leave a couple of minutes early), but there's still a very steep decay after that. "data-ref-parent="fig-flights-dist"width="384"/></p>
<figcaption>(b) Histogram is zoomed in to show delays less than 2 hours.</figcaption>
<p/><figcaptionclass="figure-caption">Figure15.3: The distribution of <code>dep_delay</code> appears highly skewed to the right in both histograms.</figcaption><p/>
<p>It’s also a good idea to check that distributions for subgroups resemble the whole. <ahref="#fig-flights-dist-daily"data-type="xref">#fig-flights-dist-daily</a> overlays a frequency polygon for each day. The distributions seem to follow a common pattern, suggesting it’s fine to use the same summary for each day.</p>
<figureid="fig-flights-dist-daily"><p><imgsrc="numbers_files/figure-html/fig-flights-dist-daily-1.png"alt="The distribution of `dep_delay` is highly right skewed with a strong peak slightly less than 0. The 365 frequency polygons are mostly overlapping forming a thick black bland."width="576"/></p>
<figcaption>365 frequency polygons of <code>dep_delay</code>, one for each day. The frequency polygons appear to have the same shape, suggesting that it’s reasonable to compare days by looking at just a few summary statistics.</figcaption>
<p>Don’t be afraid to explore your own custom summaries specifically tailored for the data that you’re working with. In this case, that might mean separately summarizing the flights that left early vs.the flights that left late, or given that the values are so heavily skewed, you might try a log-transformation. Finally, don’t forget what you learned in <ahref="#sec-sample-size"data-type="xref">#sec-sample-size</a>: whenever creating numerical summaries, it’s a good idea to include the number of observations in each group.</p>
<p>There’s one final type of summary that’s useful for numeric vectors, but also works with every other type of value: extracting a value at a specific position. You can do this with the base R <code>[</code> function, but we’re not going to cover it in detail until <ahref="#sec-subset-many"data-type="xref">#sec-subset-many</a>, because it’s a very powerful and general function. For now we’ll introduce three specialized functions that you can use to extract values at a specified position: <code>first(x)</code>, <code>last(x)</code>, and <code>nth(x, n)</code>.</p>
<p>(These functions currently lack an <code>na.rm</code> argument but will hopefully be fixed by the time you read this book: <ahref="https://github.com/tidyverse/dplyr/issues/6242"class="uri">https://github.com/tidyverse/dplyr/issues/6242</a>).</p>
<p>If you’re familiar with <code>[</code>, you might wonder if you ever need these functions. There are two main reasons: the <code>default</code> argument and the <code>order_by</code> argument. <code>default</code> allows you to set a default value that’s used if the requested position doesn’t exist, e.g.you’re trying to get the 3rd element from a two element group. <code>order_by</code> lets you locally override the existing ordering of the rows, so you can get the element at the position in the ordering by <code><ahref="https://dplyr.tidyverse.org/reference/order_by.html">order_by()</a></code>.</p>
<p>Extracting values at positions is complementary to filtering on ranks. Filtering gives you all variables, with each observation in a separate row:</p>
<p>As the names suggest, the summary functions are typically paired with <code><ahref="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code>. However, because of the recycling rules we discussed in <ahref="#sec-recycling"data-type="xref">#sec-recycling</a> they can also be usefully paired with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>, particularly when you want do some sort of group standardization. For example:</p>
<code>x / sum(x)</code> calculates the proportion of a total.</li>
<li>
<code>(x - mean(x)) / sd(x)</code> computes a Z-score (standardized to mean 0 and sd 1).</li>
<li>
<code>x / first(x)</code> computes an index based on the first observation.</li>
</ul></section>
<sectionid="exercises-3"data-type="sect2">
<h2>
Exercises</h2>
<oltype="1"><li>
<p>Brainstorm at least 5 different ways to assess the typical delay characteristics of a group of flights. Consider the following scenarios:</p>
<ul><li>A flight is 15 minutes early 50% of the time, and 15 minutes late 50% of the time.</li>
<li>A flight is always 10 minutes late.</li>
<li>A flight is 30 minutes early 50% of the time, and 30 minutes late 50% of the time.</li>
<li>99% of the time a flight is on time. 1% of the time it’s 2 hours late.</li>
</ul><p>Which do you think is more important: arrival delay or departure delay?</p>
</li>
<li><p>Which destinations show the greatest variation in air speed?</p></li>
<li><p>Create a plot to further explore the adventures of EGE. Can you find any evidence that the airport moved locations?</p></li>
</ol></section>
</section>
<sectionid="summary"data-type="sect1">
<h1>
Summary</h1>
<p>You’re already familiar with many tools for working with numbers, and after reading this chapter you now know how to use them in R. You’ve also learned a handful of useful general transformations that are commonly, but not exclusively, applied to numeric vectors like ranks and offsets. Finally, you worked through a number of numeric summaries, and discussed a few of the statistical challenges that you should consider.</p>
<p>Over the next two chapters, we’ll dive into working with strings with the stringr package. Strings are a big topic so they get two chapters, one on the fundamentals of strings and one on regular expressions.</p>