<p>In this chapter, you’ll learn tools for working with logical vectors. Logical vectors are the simplest type of vector because each element can only be one of three possible values: <code>TRUE</code>, <code>FALSE</code>, and <code>NA</code>. It’s relatively rare to find logical vectors in your raw data, but you’ll create and manipulate them in the course of almost every analysis.</p>
<p>We’ll begin by discussing the most common way of creating logical vectors: with numeric comparisons. Then you’ll learn about how you can use Boolean algebra to combine different logical vectors, as well as some useful summaries. We’ll finish off with <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/case_when.html">case_when()</a></code>, two useful functions for making conditional changes powered by logical vectors.</p>
<p>Most of the functions you’ll learn about in this chapter are provided by base R, so we don’t need the tidyverse, but we’ll still load it so we can use <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>, <code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code>, and friends to work with data frames. We’ll also continue to draw examples from the nycflights13 dataset.</p>
<p>However, as we start to cover more tools, there won’t always be a perfect real example. So we’ll start making up some dummy data with <code><ahref="https://rdrr.io/r/base/c.html">c()</a></code>:</p>
<p>This makes it easier to explain individual functions at the cost of making it harder to see how it might apply to your data problems. Just remember that any manipulation we do to a free-floating vector, you can do to a variable inside a data frame with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> and friends.</p>
<p>A very common way to create a logical vector is via a numeric comparison with <code><</code>, <code><=</code>, <code>></code>, <code>>=</code>, <code>!=</code>, and <code>==</code>. So far, we’ve mostly created logical variables transiently within <code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code> — they are computed, used, and then thrown away. For example, the following filter finds all daytime departures that leave roughly on time:</p>
<p>It’s useful to know that this is a shortcut and you can explicitly create the underlying logical variables with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>:</p>
daytime = dep_time > 600 & dep_time < 2000,
approx_ontime = abs(arr_delay) < 20,
.keep = "used"
)
#> # A tibble: 336,776 × 4
#> dep_time arr_delay daytime approx_ontime
#><int><dbl><lgl><lgl>
#> 1 517 11 FALSE TRUE
#> 2 533 20 FALSE FALSE
#> 3 542 33 FALSE FALSE
#> 4 544 -18 FALSE TRUE
#> 5 554 -25 FALSE FALSE
#> 6 554 12 FALSE TRUE
#> # … with 336,770 more rows</pre>
</div>
<p>This is particularly useful for more complicated logic because naming the intermediate steps makes it easier to both read your code and check that each step has been computed correctly.</p>
<p>All up, the initial filter is equivalent to:</p>
<p>What’s going on? Computers store numbers with a fixed number of decimal places so there’s no way to exactly represent 1/49 or <code>sqrt(2)</code> and subsequent computations will be very slightly off. We can see the exact values by calling <code><ahref="https://rdrr.io/r/base/print.html">print()</a></code> with the <code>digits</code><spandata-type="footnote">R normally calls print for you (i.e.<code>x</code> is a shortcut for <code>print(x)</code>), but calling it explicitly is useful if you want to provide other arguments.</span> argument:</p>
<p>Now that you’ve seen why <code>==</code> is failing, what can you do about it? One option is to use <code><ahref="https://dplyr.tidyverse.org/reference/near.html">dplyr::near()</a></code> which ignores small differences:</p>
<p>So if you want to find all flights where <code>dep_time</code> is missing, the following code doesn’t work because <code>dep_time == NA</code> will yield <code>NA</code> for every single row, and <code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code> automatically drops missing values:</p>
<p><code>is.na(x)</code> works with any type of vector and returns <code>TRUE</code> for missing values and <code>FALSE</code> for everything else:</p>
<p><code><ahref="https://rdrr.io/r/base/NA.html">is.na()</a></code> can also be useful in <code><ahref="https://dplyr.tidyverse.org/reference/arrange.html">arrange()</a></code>. <code><ahref="https://dplyr.tidyverse.org/reference/arrange.html">arrange()</a></code> usually puts all the missing values at the end but you can override this default by first sorting by <code><ahref="https://rdrr.io/r/base/NA.html">is.na()</a></code>:</p>
<oltype="1"><li>How does <code><ahref="https://dplyr.tidyverse.org/reference/near.html">dplyr::near()</a></code> work? Type <code>near</code> to see the source code.</li>
<li>Use <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>, <code><ahref="https://rdrr.io/r/base/NA.html">is.na()</a></code>, and <code><ahref="https://dplyr.tidyverse.org/reference/count.html">count()</a></code> together to describe how the missing values in <code>dep_time</code>, <code>sched_dep_time</code> and <code>dep_delay</code> are connected.</li>
<p>Once you have multiple logical vectors, you can combine them together using Boolean algebra. In R, <code>&</code> is “and”, <code>|</code> is “or”, <code>!</code> is “not”, and <code><ahref="https://rdrr.io/r/base/Logic.html">xor()</a></code> is exclusive or<spandata-type="footnote">That is, <code>xor(x, y)</code> is true if x is true, or y is true, but not both. This is how we usually use “or” In English. “Both” is not usually an acceptable answer to the question “would you like ice cream or cake?”.</span>. <ahref="#fig-bool-ops"data-type="xref">#fig-bool-ops</a> shows the complete set of Boolean operations and how they work.</p>
<figureid="fig-bool-ops"><p><imgsrc="diagrams/transform.png"alt="Six Venn diagrams, each explaining a given logical operator. The circles (sets) in each of the Venn diagrams represent x and y. 1. y & !x is y but none of x; x & y is the intersection of x and y; x & !y is x but none of y; x is all of x none of y; xor(x, y) is everything except the intersection of x and y; y is all of y and none of x; and x | y is everything."width="395"/></p>
<figcaption>The complete set of boolean operations. <code>x</code> is the left-hand circle, <code>y</code> is the right-hand circle, and the shaded region show which parts each operator selects.</figcaption>
<p>As well as <code>&</code> and <code>|</code>, R also has <code>&&</code> and <code>||</code>. Don’t use them in dplyr functions! These are called short-circuiting operators and only ever return a single <code>TRUE</code> or <code>FALSE</code>. They’re important for programming, not data science.</p>
<p>To understand what’s going on, think about <code>NA | TRUE</code>. A missing value in a logical vector means that the value could either be <code>TRUE</code> or <code>FALSE</code>. <code>TRUE | TRUE</code> and <code>FALSE | TRUE</code> are both <code>TRUE</code>, so <code>NA | TRUE</code> must also be <code>TRUE</code>. Similar reasoning applies with <code>NA & FALSE</code>.</p>
<p>Note that the order of operations doesn’t work like English. Take the following code that finds all flights that departed in November or December:</p>
<p>This code doesn’t error but it also doesn’t seem to have worked. What’s going on? Here, R first evaluates <code>month == 11</code> creating a logical vector, which we call <code>nov</code>. It computes <code>nov | 12</code>. When you use a number with a logical operator it converts everything apart from 0 to <code>TRUE</code>, so this is equivalent to <code>nov | TRUE</code> which will always be <code>TRUE</code>, so every row will be selected:</p>
<p>An easy way to avoid the problem of getting your <code>==</code>s and <code>|</code>s in the right order is to use <code>%in%</code>. <code>x %in% y</code> returns a logical vector the same length as <code>x</code> that is <code>TRUE</code> whenever a value in <code>x</code> is anywhere in <code>y</code> .</p>
<oltype="1"><li>Find all flights where <code>arr_delay</code> is missing but <code>dep_delay</code> is not. Find all flights where neither <code>arr_time</code> nor <code>sched_arr_time</code> are missing, but <code>arr_delay</code> is.</li>
<li>How many flights have a missing <code>dep_time</code>? What other variables are missing in these rows? What might these rows represent?</li>
<li>Assuming that a missing <code>dep_time</code> implies that a flight is cancelled, look at the number of cancelled flights per day. Is there a pattern? Is there a connection between the proportion of cancelled flights and the average delay of non-cancelled flights?</li>
<p>The following sections describe some useful techniques for summarizing logical vectors. As well as functions that only work specifically with logical vectors, you can also use functions that work with numeric vectors.</p>
<p>There are two main logical summaries: <code><ahref="https://rdrr.io/r/base/any.html">any()</a></code> and <code><ahref="https://rdrr.io/r/base/all.html">all()</a></code>. <code>any(x)</code> is the equivalent of <code>|</code>; it’ll return <code>TRUE</code> if there are any <code>TRUE</code>’s in <code>x</code>. <code>all(x)</code> is equivalent of <code>&</code>; it’ll return <code>TRUE</code> only if all values of <code>x</code> are <code>TRUE</code>’s. Like all summary functions, they’ll return <code>NA</code> if there are any missing values present, and as usual you can make the missing values go away with <code>na.rm = TRUE</code>.</p>
<p>For example, we could use <code><ahref="https://rdrr.io/r/base/all.html">all()</a></code> to find out if there were days where every flight was delayed:</p>
<p>In most cases, however, <code><ahref="https://rdrr.io/r/base/any.html">any()</a></code> and <code><ahref="https://rdrr.io/r/base/all.html">all()</a></code> are a little too crude, and it would be nice to be able to get a little more detail about how many values are <code>TRUE</code> or <code>FALSE</code>. That leads us to the numeric summaries.</p>
<p>When you use a logical vector in a numeric context, <code>TRUE</code> becomes 1 and <code>FALSE</code> becomes 0. This makes <code><ahref="https://rdrr.io/r/base/sum.html">sum()</a></code> and <code><ahref="https://rdrr.io/r/base/mean.html">mean()</a></code> very useful with logical vectors because <code>sum(x)</code> will give the number of <code>TRUE</code>s and <code>mean(x)</code> the proportion of <code>TRUE</code>s. That lets us see the distribution of delays across the days of the year as shown in <ahref="#fig-prop-delayed-dist"data-type="xref">#fig-prop-delayed-dist</a></p>
<figureid="fig-prop-delayed-dist"><p><imgsrc="logicals_files/figure-html/fig-prop-delayed-dist-1.png"alt="The distribution is unimodal and mildly right skewed. The distribution peaks around 30% delayed flights."width="576"/></p>
<figcaption>A histogram showing the proportion of delayed flights each day.</figcaption>
<p>There’s one final use for logical vectors in summaries: you can use a logical vector to filter a single variable to a subset of interest. This makes use of the base <code>[</code> (pronounced subset) operator, which you’ll learn more about in <ahref="#sec-subset-many"data-type="xref">#sec-subset-many</a>.</p>
<p>Imagine we wanted to look at the average delay just for flights that were actually delayed. One way to do so would be to first filter the flights and then calculate the average delay:</p>
<p>This works, but what if we wanted to also compute the average delay for flights that arrived early? We’d need to perform a separate filter step, and then figure out how to combine the two data frames together<spandata-type="footnote">We’ll cover this in <ahref="#chp-joins"data-type="xref">#chp-joins</a>]</span>. Instead you could use <code>[</code> to perform an inline filtering: <code>arr_delay[arr_delay > 0]</code> will yield only the positive arrival delays.</p>
<p>Also note the difference in the group size: in the first chunk <code><ahref="https://dplyr.tidyverse.org/reference/context.html">n()</a></code> gives the number of delayed flights per day; in the second, <code><ahref="https://dplyr.tidyverse.org/reference/context.html">n()</a></code> gives the total number of flights.</p>
<li>What does <code><ahref="https://rdrr.io/r/base/prod.html">prod()</a></code> return when applied to a logical vector? What logical summary function is it equivalent to? What does <code><ahref="https://rdrr.io/r/base/Extremes.html">min()</a></code> return when applied to a logical vector? What logical summary function is it equivalent to? Read the documentation and perform a few experiments.</li>
<p>One of the most powerful features of logical vectors are their use for conditional transformations, i.e.doing one thing for condition x, and something different for condition y. There are two important tools for this: <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/case_when.html">case_when()</a></code>.</p>
<p>If you want to use one value when a condition is <code>TRUE</code> and another value when it’s <code>FALSE</code>, you can use <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">dplyr::if_else()</a></code><spandata-type="footnote">dplyr’s <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code> is very similar to base R’s <code><ahref="https://rdrr.io/r/base/ifelse.html">ifelse()</a></code>. There are two main advantages of <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code>over <code><ahref="https://rdrr.io/r/base/ifelse.html">ifelse()</a></code>: you can choose what should happen to missing values, and <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code> is much more likely to give you a meaningful error if you variables have incompatible types.</span>. You’ll always use the first three argument of <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code>. The first argument, <code>condition</code>, is a logical vector, the second, <code>true</code>, gives the output when the condition is true, and the third, <code>false</code>, gives the output if the condition is false.</p>
<p>You can also use vectors for the the <code>true</code> and <code>false</code> arguments. For example, this allows us to create a minimal implementation of <code><ahref="https://rdrr.io/r/base/MathFun.html">abs()</a></code>:</p>
<p>So far all the arguments have used the same vectors, but you can of course mix and match. For example, you could implement a simple version of <code><ahref="https://dplyr.tidyverse.org/reference/coalesce.html">coalesce()</a></code> like this:</p>
<p>You might have noticed a small infelicity in our labeling example above: zero is neither positive nor negative. We could resolve this by adding an additional <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code>:</p>
<p>This is already a little hard to read, and you can imagine it would only get harder if you have more conditions. Instead, you can switch to <code><ahref="https://dplyr.tidyverse.org/reference/case_when.html">dplyr::case_when()</a></code>.</p>
<p>dplyr’s <code><ahref="https://dplyr.tidyverse.org/reference/case_when.html">case_when()</a></code> is inspired by SQL’s <code>CASE</code> statement and provides a flexible way of performing different computations for different conditions. It has a special syntax that unfortunately looks like nothing else you’ll use in the tidyverse. It takes pairs that look like <code>condition ~ output</code>. <code>condition</code> must be a logical vector; when it’s <code>TRUE</code>, <code>output</code> will be used.</p>
<p>This means we could recreate our previous nested <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code> as follows:</p>
<p>To explain how <code><ahref="https://dplyr.tidyverse.org/reference/case_when.html">case_when()</a></code> works, lets explore some simpler cases. If none of the cases match, the output gets an <code>NA</code>:</p>
<p>Just like with <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code> you can use variables on both sides of the <code>~</code> and you can mix and match variables as needed for your problem. For example, we could use <code><ahref="https://dplyr.tidyverse.org/reference/case_when.html">case_when()</a></code> to provide some human readable labels for the arrival delay:</p>
<p>Be wary when writing this sort of complex <code><ahref="https://dplyr.tidyverse.org/reference/case_when.html">case_when()</a></code> statement; my first two attempts used a mix of <code><</code> and <code>></code> and I kept accidentally creating overlapping conditions.</p>
<p>Note that both <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/case_when.html">case_when()</a></code> require <strong>compatible</strong> types in the output. If they’re not compatible, you’ll see errors like this:</p>
#> ! Can't combine `true` <character> and `false` <double>.
case_when(
x < -1 ~ TRUE,
x > 0 ~ lubridate::now()
)
#> Error in `case_when()`:
#> ! Can't combine `TRUE` <logical> and `lubridate::now()` <datetime<local>>.</pre>
</div>
<p>Overall, relatively few types are compatible, because automatically converting one type of vector to another is a common source of errors. Here are the most important cases that are compatible:</p>
<ul><li>Numeric and logical vectors are compatible, as we discussed in <ahref="#sec-numeric-summaries-of-logicals"data-type="xref">#sec-numeric-summaries-of-logicals</a>.</li>
<li>Strings and factors (<ahref="#chp-factors"data-type="xref">#chp-factors</a>) are compatible, because you can think of a factor as a string with a restricted set of values.</li>
<li>Dates and date-times, which we’ll discuss in <ahref="#chp-datetimes"data-type="xref">#chp-datetimes</a>, are compatible because you can think of a date as a special case of date-time.</li>
<li>
<code>NA</code>, which is technically a logical vector, is compatible with everything because every vector has some way of representing a missing value.</li>
</ul><p>We don’t expect you to memorize these rules, but they should become second nature over time because they are applied consistently throughout the tidyverse.</p>
<p>The definition of a logical vector is simple because each value must be either <code>TRUE</code>, <code>FALSE</code>, or <code>NA</code>. But logical vectors provide a huge amount of power. In this chapter, you learned how to create logical vectors with <code>></code>, <code><</code>, <code><=</code>, <code>=></code>, <code>==</code>, <code>!=</code>, and <code><ahref="https://rdrr.io/r/base/NA.html">is.na()</a></code>, how to combine them with <code>!</code>, <code>&</code>, and <code>|</code>, and how to summarize them with <code><ahref="https://rdrr.io/r/base/any.html">any()</a></code>, <code><ahref="https://rdrr.io/r/base/all.html">all()</a></code>, <code><ahref="https://rdrr.io/r/base/sum.html">sum()</a></code>, and <code><ahref="https://rdrr.io/r/base/mean.html">mean()</a></code>. You also learned the powerful <code><ahref="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/case_when.html">case_when()</a></code> functions that allow you to return values depending on the value of a logical vector.</p>
<p>We’ll see logical vectors again and again in the following chapters. For example in <ahref="#chp-strings"data-type="xref">#chp-strings</a> you’ll learn about <code>str_detect(x, pattern)</code> which returns a logical vector that’s <code>TRUE</code> for the elements of <code>x</code> that match the <code>pattern</code>, and in <ahref="#chp-datetimes"data-type="xref">#chp-datetimes</a> you’ll create logical vectors from the comparison of dates and times. But for now, we’re going to move onto the next most important type of vector: numeric vectors.</p>