Don't transform non-crossref links
This commit is contained in:
		@@ -14,11 +14,11 @@ Introduction</h1>
 | 
			
		||||
<p>In this chapter, you’ll learn tools for iteration, repeatedly performing the same action on different objects. Iteration in R generally tends to look rather different from other programming languages because so much of it is implicit and we get it for free. For example, if you want to double a numeric vector <code>x</code> in R, you can just write <code>2 * x</code>. In most other languages, you’d need to explicitly double each element of x using some sort of for loop.</p>
 | 
			
		||||
<p>This book has already given you a small but powerful number of tools that perform the same action for multiple “things”:</p>
 | 
			
		||||
<ul><li>
 | 
			
		||||
<code><a href="#chp-https://ggplot2.tidyverse.org/reference/facet_wrap" data-type="xref">#chp-https://ggplot2.tidyverse.org/reference/facet_wrap</a></code> and <code><a href="#chp-https://ggplot2.tidyverse.org/reference/facet_grid" data-type="xref">#chp-https://ggplot2.tidyverse.org/reference/facet_grid</a></code> draws a plot for each subset.</li>
 | 
			
		||||
<code><a href="https://ggplot2.tidyverse.org/reference/facet_wrap.html">facet_wrap()</a></code> and <code><a href="https://ggplot2.tidyverse.org/reference/facet_grid.html">facet_grid()</a></code> draws a plot for each subset.</li>
 | 
			
		||||
<li>
 | 
			
		||||
<code><a href="#chp-https://dplyr.tidyverse.org/reference/group_by" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/group_by</a></code> plus <code><a href="#chp-https://dplyr.tidyverse.org/reference/summarise" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/summarise</a></code> computes a summary statistics for each subset.</li>
 | 
			
		||||
<code><a href="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a></code> plus <code><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarise()</a></code> computes a summary statistics for each subset.</li>
 | 
			
		||||
<li>
 | 
			
		||||
<code><a href="#chp-https://tidyr.tidyverse.org/reference/unnest_wider" data-type="xref">#chp-https://tidyr.tidyverse.org/reference/unnest_wider</a></code> and <code><a href="#chp-https://tidyr.tidyverse.org/reference/unnest_longer" data-type="xref">#chp-https://tidyr.tidyverse.org/reference/unnest_longer</a></code> create new rows and columns for each element of a list-column.</li>
 | 
			
		||||
<code><a href="https://tidyr.tidyverse.org/reference/unnest_wider.html">unnest_wider()</a></code> and <code><a href="https://tidyr.tidyverse.org/reference/unnest_longer.html">unnest_longer()</a></code> create new rows and columns for each element of a list-column.</li>
 | 
			
		||||
</ul><p>Now it’s time to learn some more general tools, often called <strong>functional programming</strong> tools because they are built around functions that take other functions as inputs. Learning functional programming can easily veer into the abstract, but in this chapter we’ll keep things concrete by focusing on three common tasks: modifying multiple columns, reading multiple files, and saving multiple objects.</p>
 | 
			
		||||
 | 
			
		||||
<section id="prerequisites" data-type="sect2">
 | 
			
		||||
@@ -33,7 +33,7 @@ Prerequisites</h2>
 | 
			
		||||
 | 
			
		||||
<p>This chapter relies on features only found in purrr 1.0.0 and dplyr 1.1.0, which are still in development. If you want to live life on the edge you can get the dev version with <code>devtools::install_github(c("tidyverse/purrr", "tidyverse/dplyr"))</code>.</p></div>
 | 
			
		||||
 | 
			
		||||
<p>In this chapter, we’ll focus on tools provided by dplyr and purrr, both core members of the tidyverse. You’ve seen dplyr before, but <a href="#chp-http://purrr.tidyverse.org/" data-type="xref">#chp-http://purrr.tidyverse.org/</a> is new. We’re going to use just a couple of purrr functions from in this chapter, but it’s a great package to explore as you improve your programming skills.</p>
 | 
			
		||||
<p>In this chapter, we’ll focus on tools provided by dplyr and purrr, both core members of the tidyverse. You’ve seen dplyr before, but <a href="http://purrr.tidyverse.org/">purrr</a> is new. We’re going to use just a couple of purrr functions from in this chapter, but it’s a great package to explore as you improve your programming skills.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">library(tidyverse)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
@@ -66,7 +66,7 @@ Modifying multiple columns</h1>
 | 
			
		||||
#>   <int>  <dbl>  <dbl>   <dbl> <dbl>
 | 
			
		||||
#> 1    10 -0.246 -0.287 -0.0567 0.144</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>That breaks our rule of thumb to never copy and paste more than twice, and you can imagine that this will get very tedious if you have tens or even hundreds of columns. Instead you can use <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>:</p>
 | 
			
		||||
<p>That breaks our rule of thumb to never copy and paste more than twice, and you can imagine that this will get very tedious if you have tens or even hundreds of columns. Instead you can use <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df |> summarise(
 | 
			
		||||
  n = n(),
 | 
			
		||||
@@ -77,14 +77,14 @@ Modifying multiple columns</h1>
 | 
			
		||||
#>   <int>  <dbl>  <dbl>   <dbl> <dbl>
 | 
			
		||||
#> 1    10 -0.246 -0.287 -0.0567 0.144</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p><code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> has three particularly important arguments, which we’ll discuss in detail in the following sections. You’ll use the first two every time you use <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>: the first argument, <code>.cols</code>, specifies which columns you want to iterate over, and the second argument, <code>.fns</code>, specifies what to do with each column. You can use the <code>.names</code> argument when you need additional control over the names of output columns, which is particularly important when you use <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> with <code><a href="#chp-https://dplyr.tidyverse.org/reference/mutate" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/mutate</a></code>. We’ll also discuss two important variations, <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> and <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>, which work with <code><a href="#chp-https://dplyr.tidyverse.org/reference/filter" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/filter</a></code>.</p>
 | 
			
		||||
<p><code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> has three particularly important arguments, which we’ll discuss in detail in the following sections. You’ll use the first two every time you use <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>: the first argument, <code>.cols</code>, specifies which columns you want to iterate over, and the second argument, <code>.fns</code>, specifies what to do with each column. You can use the <code>.names</code> argument when you need additional control over the names of output columns, which is particularly important when you use <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> with <code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>. We’ll also discuss two important variations, <code><a href="https://dplyr.tidyverse.org/reference/across.html">if_any()</a></code> and <code><a href="https://dplyr.tidyverse.org/reference/across.html">if_all()</a></code>, which work with <code><a href="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code>.</p>
 | 
			
		||||
 | 
			
		||||
<section id="selecting-columns-with-.cols" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Selecting columns with<code>.cols</code>
 | 
			
		||||
</h2>
 | 
			
		||||
<p>The first argument to <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>, <code>.cols</code>, selects the columns to transform. This uses the same specifications as <code><a href="#chp-https://dplyr.tidyverse.org/reference/select" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/select</a></code>, <a href="#sec-select" data-type="xref">#sec-select</a>, so you can use functions like <code><a href="#chp-https://tidyselect.r-lib.org/reference/starts_with" data-type="xref">#chp-https://tidyselect.r-lib.org/reference/starts_with</a></code> and <code><a href="#chp-https://tidyselect.r-lib.org/reference/starts_with" data-type="xref">#chp-https://tidyselect.r-lib.org/reference/starts_with</a></code> to select columns based on their name.</p>
 | 
			
		||||
<p>There are two additional selection techniques that are particularly useful for <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>: <code><a href="#chp-https://tidyselect.r-lib.org/reference/everything" data-type="xref">#chp-https://tidyselect.r-lib.org/reference/everything</a></code> and <code>where()</code>. <code><a href="#chp-https://tidyselect.r-lib.org/reference/everything" data-type="xref">#chp-https://tidyselect.r-lib.org/reference/everything</a></code> is straightforward: it selects every (non-grouping) column:</p>
 | 
			
		||||
<p>The first argument to <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>, <code>.cols</code>, selects the columns to transform. This uses the same specifications as <code><a href="https://dplyr.tidyverse.org/reference/select.html">select()</a></code>, <a href="#sec-select" data-type="xref">#sec-select</a>, so you can use functions like <code><a href="https://tidyselect.r-lib.org/reference/starts_with.html">starts_with()</a></code> and <code><a href="https://tidyselect.r-lib.org/reference/starts_with.html">ends_with()</a></code> to select columns based on their name.</p>
 | 
			
		||||
<p>There are two additional selection techniques that are particularly useful for <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>: <code><a href="https://tidyselect.r-lib.org/reference/everything.html">everything()</a></code> and <code>where()</code>. <code><a href="https://tidyselect.r-lib.org/reference/everything.html">everything()</a></code> is straightforward: it selects every (non-grouping) column:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df <- tibble(
 | 
			
		||||
  grp = sample(2, 10, replace = TRUE),
 | 
			
		||||
@@ -103,7 +103,7 @@ df |>
 | 
			
		||||
#> 1     1 -0.0935 -0.0163 0.363 0.364
 | 
			
		||||
#> 2     2  0.312  -0.0576 0.208 0.565</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Note grouping columns (<code>grp</code> here) are not included in <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>, because they’re automatically preserved by <code><a href="#chp-https://dplyr.tidyverse.org/reference/summarise" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/summarise</a></code>.</p>
 | 
			
		||||
<p>Note grouping columns (<code>grp</code> here) are not included in <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>, because they’re automatically preserved by <code><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarise()</a></code>.</p>
 | 
			
		||||
<p><code>where()</code> allows you to select columns based on their type:</p>
 | 
			
		||||
<ul><li>
 | 
			
		||||
<code>where(is.numeric)</code> selects all numeric columns.</li>
 | 
			
		||||
@@ -143,8 +143,8 @@ df_types |>
 | 
			
		||||
<section id="calling-a-single-function" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Calling a single function</h2>
 | 
			
		||||
<p>The second argument to <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> defines how each column will be transformed. In simple cases, as above, this will be a single existing function. This is a pretty special feature of R: we’re passing one function (<code>median</code>, <code>mean</code>, <code>str_flatten</code>, …) to another function (<code>across</code>). This is one of the features that makes R a function programming language.</p>
 | 
			
		||||
<p>It’s important to note that we’re passing this function to <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>, so <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> can call it, not calling it ourselves. That means the function name should never be followed by <code>()</code>. If you forget, you’ll get an error:</p>
 | 
			
		||||
<p>The second argument to <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> defines how each column will be transformed. In simple cases, as above, this will be a single existing function. This is a pretty special feature of R: we’re passing one function (<code>median</code>, <code>mean</code>, <code>str_flatten</code>, …) to another function (<code>across</code>). This is one of the features that makes R a function programming language.</p>
 | 
			
		||||
<p>It’s important to note that we’re passing this function to <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>, so <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> can call it, not calling it ourselves. That means the function name should never be followed by <code>()</code>. If you forget, you’ll get an error:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df |> 
 | 
			
		||||
  group_by(grp) |> 
 | 
			
		||||
@@ -162,7 +162,7 @@ Calling a single function</h2>
 | 
			
		||||
<section id="calling-multiple-functions" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Calling multiple functions</h2>
 | 
			
		||||
<p>In more complex cases, you might want to supply additional arguments or perform multiple transformations. Lets motivate this problem with a simple example: what happens if we have some missing values in our data? <code><a href="#chp-https://rdrr.io/r/stats/median" data-type="xref">#chp-https://rdrr.io/r/stats/median</a></code> propagates those missing values, giving us a suboptimal output:</p>
 | 
			
		||||
<p>In more complex cases, you might want to supply additional arguments or perform multiple transformations. Lets motivate this problem with a simple example: what happens if we have some missing values in our data? <code><a href="https://rdrr.io/r/stats/median.html">median()</a></code> propagates those missing values, giving us a suboptimal output:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">rnorm_na <- function(n, n_na, mean = 0, sd = 1) {
 | 
			
		||||
  sample(c(rnorm(n - n_na, mean = mean, sd = 1), rep(NA, n_na)))
 | 
			
		||||
@@ -184,7 +184,7 @@ df_miss |>
 | 
			
		||||
#>   <dbl> <dbl> <dbl> <dbl> <int>
 | 
			
		||||
#> 1    NA    NA    NA 0.704     5</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>It would be nice if we could pass along <code>na.rm = TRUE</code> to <code><a href="#chp-https://rdrr.io/r/stats/median" data-type="xref">#chp-https://rdrr.io/r/stats/median</a></code> to remove these missing values. To do so, instead of calling <code><a href="#chp-https://rdrr.io/r/stats/median" data-type="xref">#chp-https://rdrr.io/r/stats/median</a></code> directly, we need to create a new function that calls <code><a href="#chp-https://rdrr.io/r/stats/median" data-type="xref">#chp-https://rdrr.io/r/stats/median</a></code> with the desired arguments:</p>
 | 
			
		||||
<p>It would be nice if we could pass along <code>na.rm = TRUE</code> to <code><a href="https://rdrr.io/r/stats/median.html">median()</a></code> to remove these missing values. To do so, instead of calling <code><a href="https://rdrr.io/r/stats/median.html">median()</a></code> directly, we need to create a new function that calls <code><a href="https://rdrr.io/r/stats/median.html">median()</a></code> with the desired arguments:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df_miss |> 
 | 
			
		||||
  summarise(
 | 
			
		||||
@@ -204,7 +204,7 @@ df_miss |>
 | 
			
		||||
    n = n()
 | 
			
		||||
  )</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>In either case, <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> effectively expands to the following code:</p>
 | 
			
		||||
<p>In either case, <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> effectively expands to the following code:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df_miss |> 
 | 
			
		||||
  summarise(
 | 
			
		||||
@@ -215,7 +215,7 @@ df_miss |>
 | 
			
		||||
    n = n()
 | 
			
		||||
  )</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>When we remove the missing values from the <code><a href="#chp-https://rdrr.io/r/stats/median" data-type="xref">#chp-https://rdrr.io/r/stats/median</a></code>, it would be nice to know just how many values we were removing. We can find that out by supplying two functions to <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>: one to compute the median and the other to count the missing values. You supply multiple functions by using a named list to <code>.fns</code>:</p>
 | 
			
		||||
<p>When we remove the missing values from the <code><a href="https://rdrr.io/r/stats/median.html">median()</a></code>, it would be nice to know just how many values we were removing. We can find that out by supplying two functions to <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>: one to compute the median and the other to count the missing values. You supply multiple functions by using a named list to <code>.fns</code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df_miss |> 
 | 
			
		||||
  summarise(
 | 
			
		||||
@@ -236,7 +236,7 @@ df_miss |>
 | 
			
		||||
<section id="column-names" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Column names</h2>
 | 
			
		||||
<p>The result of <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> is named according to the specification provided in the <code>.names</code> argument. We could specify our own if we wanted the name of the function to come first<span data-type="footnote">You can’t currently change the order of the columns, but you could reorder them after the fact using <code><a href="#chp-https://dplyr.tidyverse.org/reference/relocate" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/relocate</a></code> or similar.</span>:</p>
 | 
			
		||||
<p>The result of <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> is named according to the specification provided in the <code>.names</code> argument. We could specify our own if we wanted the name of the function to come first<span data-type="footnote">You can’t currently change the order of the columns, but you could reorder them after the fact using <code><a href="https://dplyr.tidyverse.org/reference/relocate.html">relocate()</a></code> or similar.</span>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df_miss |> 
 | 
			
		||||
  summarise(
 | 
			
		||||
@@ -255,7 +255,7 @@ Column names</h2>
 | 
			
		||||
#>      <dbl>    <int>    <dbl>    <int>    <dbl>    <int>    <dbl>    <int> <int>
 | 
			
		||||
#> 1    0.429        1   -0.721        1   -0.796        2    0.704        0     5</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>The <code>.names</code> argument is particularly important when you use <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> with <code><a href="#chp-https://dplyr.tidyverse.org/reference/mutate" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/mutate</a></code>. By default the output of <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> is given the same names as the inputs. This means that <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> inside of <code><a href="#chp-https://dplyr.tidyverse.org/reference/mutate" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/mutate</a></code> will replace existing columns. For example, here we use <code><a href="#chp-https://dplyr.tidyverse.org/reference/coalesce" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/coalesce</a></code> to replace <code>NA</code>s with <code>0</code>:</p>
 | 
			
		||||
<p>The <code>.names</code> argument is particularly important when you use <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> with <code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>. By default the output of <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> is given the same names as the inputs. This means that <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> inside of <code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> will replace existing columns. For example, here we use <code><a href="https://dplyr.tidyverse.org/reference/coalesce.html">coalesce()</a></code> to replace <code>NA</code>s with <code>0</code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df_miss |> 
 | 
			
		||||
  mutate(
 | 
			
		||||
@@ -290,7 +290,7 @@ Column names</h2>
 | 
			
		||||
<section id="filtering" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Filtering</h2>
 | 
			
		||||
<p><code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> is a great match for <code><a href="#chp-https://dplyr.tidyverse.org/reference/summarise" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/summarise</a></code> and <code><a href="#chp-https://dplyr.tidyverse.org/reference/mutate" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/mutate</a></code> but it’s more awkward to use with <code><a href="#chp-https://dplyr.tidyverse.org/reference/filter" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/filter</a></code>, because you usually combine multiple conditions with either <code>|</code> or <code>&</code>. It’s clear that <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> can help to create multiple logical columns, but then what? So dplyr provides two variants of <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> called <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> and <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>:</p>
 | 
			
		||||
<p><code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> is a great match for <code><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarise()</a></code> and <code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> but it’s more awkward to use with <code><a href="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code>, because you usually combine multiple conditions with either <code>|</code> or <code>&</code>. It’s clear that <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> can help to create multiple logical columns, but then what? So dplyr provides two variants of <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> called <code><a href="https://dplyr.tidyverse.org/reference/across.html">if_any()</a></code> and <code><a href="https://dplyr.tidyverse.org/reference/across.html">if_all()</a></code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df_miss |> filter(is.na(a) | is.na(b) | is.na(c) | is.na(d))
 | 
			
		||||
#> # A tibble: 3 × 4
 | 
			
		||||
@@ -321,7 +321,7 @@ df_miss |> filter(if_all(a:d, is.na))
 | 
			
		||||
<section id="across-in-functions" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
<code>across()</code> in functions</h2>
 | 
			
		||||
<p><code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> is particularly useful to program with because it allows you to operate on multiple columns. For example, <a href="#chp-https://twitter.com/_wurli/status/1571836746899283969" data-type="xref">#chp-https://twitter.com/_wurli/status/1571836746899283969</a> uses this little helper which wraps a bunch of lubridate function to expand all date columns into year, month, and day columns:</p>
 | 
			
		||||
<p><code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> is particularly useful to program with because it allows you to operate on multiple columns. For example, <a href="https://twitter.com/_wurli/status/1571836746899283969">Jacob Scott</a> uses this little helper which wraps a bunch of lubridate function to expand all date columns into year, month, and day columns:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">library(lubridate)
 | 
			
		||||
#> Loading required package: timechange
 | 
			
		||||
@@ -351,7 +351,7 @@ df_date |>
 | 
			
		||||
#> 1 Amy   2009-08-03      2009          8        3
 | 
			
		||||
#> 2 Bob   2010-01-16      2010          1       16</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p><code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> also makes it easy to supply multiple columns in a single argument because the first argument uses tidy-select; you just need to remember to embrace that argument, as we discussed in <a href="#sec-embracing" data-type="xref">#sec-embracing</a>. For example, this function will compute the means of numeric columns by default. But by supplying the second argument you can choose to summarize just selected columns:</p>
 | 
			
		||||
<p><code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> also makes it easy to supply multiple columns in a single argument because the first argument uses tidy-select; you just need to remember to embrace that argument, as we discussed in <a href="#sec-embracing" data-type="xref">#sec-embracing</a>. For example, this function will compute the means of numeric columns by default. But by supplying the second argument you can choose to summarize just selected columns:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">summarise_means <- function(df, summary_vars = where(is.numeric)) {
 | 
			
		||||
  df |> 
 | 
			
		||||
@@ -394,7 +394,7 @@ diamonds |>
 | 
			
		||||
<h2>
 | 
			
		||||
Vs<code>pivot_longer()</code>
 | 
			
		||||
</h2>
 | 
			
		||||
<p>Before we go on, it’s worth pointing out an interesting connection between <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> and <code><a href="#chp-https://tidyr.tidyverse.org/reference/pivot_longer" data-type="xref">#chp-https://tidyr.tidyverse.org/reference/pivot_longer</a></code> (<a href="#sec-pivoting" data-type="xref">#sec-pivoting</a>). In many cases, you perform the same calculations by first pivoting the data and then performing the operations by group rather than by column. For example, take this multi-function summary:</p>
 | 
			
		||||
<p>Before we go on, it’s worth pointing out an interesting connection between <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> and <code><a href="https://tidyr.tidyverse.org/reference/pivot_longer.html">pivot_longer()</a></code> (<a href="#sec-pivoting" data-type="xref">#sec-pivoting</a>). In many cases, you perform the same calculations by first pivoting the data and then performing the operations by group rather than by column. For example, take this multi-function summary:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df |> 
 | 
			
		||||
  summarise(across(a:d, list(median = median, mean = mean)))
 | 
			
		||||
@@ -421,7 +421,7 @@ long
 | 
			
		||||
#> 3 c      0.260  0.0716
 | 
			
		||||
#> 4 d      0.540  0.508</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>And if you wanted the same structure as <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> you could pivot again:</p>
 | 
			
		||||
<p>And if you wanted the same structure as <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> you could pivot again:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">long |> 
 | 
			
		||||
  pivot_wider(
 | 
			
		||||
@@ -435,7 +435,7 @@ long
 | 
			
		||||
#>      <dbl>  <dbl>    <dbl>  <dbl>    <dbl>  <dbl>    <dbl>  <dbl>
 | 
			
		||||
#> 1   0.0380  0.205  -0.0163 0.0910    0.260 0.0716    0.540  0.508</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>This is a useful technique to know about because sometimes you’ll hit a problem that’s not currently possible to solve with <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>: when you have groups of columns that you want to compute with simultaneously. For example, imagine that our data frame contains both values and weights and we want to compute a weighted mean:</p>
 | 
			
		||||
<p>This is a useful technique to know about because sometimes you’ll hit a problem that’s not currently possible to solve with <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>: when you have groups of columns that you want to compute with simultaneously. For example, imagine that our data frame contains both values and weights and we want to compute a weighted mean:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df_paired <- tibble(
 | 
			
		||||
  a_val = rnorm(10),
 | 
			
		||||
@@ -448,7 +448,7 @@ long
 | 
			
		||||
  d_wts = runif(10)
 | 
			
		||||
)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>There’s currently no way to do this with <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code><span data-type="footnote">Maybe there will be one day, but currently we don’t see how.</span>, but it’s relatively straightforward with <code><a href="#chp-https://tidyr.tidyverse.org/reference/pivot_longer" data-type="xref">#chp-https://tidyr.tidyverse.org/reference/pivot_longer</a></code>:</p>
 | 
			
		||||
<p>There’s currently no way to do this with <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code><span data-type="footnote">Maybe there will be one day, but currently we don’t see how.</span>, but it’s relatively straightforward with <code><a href="https://tidyr.tidyverse.org/reference/pivot_longer.html">pivot_longer()</a></code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df_long <- df_paired |> 
 | 
			
		||||
  pivot_longer(
 | 
			
		||||
@@ -479,17 +479,17 @@ df_long |>
 | 
			
		||||
#> 3 c     -0.746 
 | 
			
		||||
#> 4 d     -0.0142</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>If needed, you could <code><a href="#chp-https://tidyr.tidyverse.org/reference/pivot_wider" data-type="xref">#chp-https://tidyr.tidyverse.org/reference/pivot_wider</a></code> this back to the original form.</p>
 | 
			
		||||
<p>If needed, you could <code><a href="https://tidyr.tidyverse.org/reference/pivot_wider.html">pivot_wider()</a></code> this back to the original form.</p>
 | 
			
		||||
</section>
 | 
			
		||||
 | 
			
		||||
<section id="exercises" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Exercises</h2>
 | 
			
		||||
<ol type="1"><li><p>Compute the number of unique values in each column of <code><a href="#chp-https://allisonhorst.github.io/palmerpenguins/reference/penguins" data-type="xref">#chp-https://allisonhorst.github.io/palmerpenguins/reference/penguins</a></code>.</p></li>
 | 
			
		||||
<ol type="1"><li><p>Compute the number of unique values in each column of <code><a href="https://allisonhorst.github.io/palmerpenguins/reference/penguins.html">palmerpenguins::penguins</a></code>.</p></li>
 | 
			
		||||
<li><p>Compute the mean of every column in <code>mtcars</code>.</p></li>
 | 
			
		||||
<li><p>Group <code>diamonds</code> by <code>cut</code>, <code>clarity</code>, and <code>color</code> then count the number of observations and the mean of each numeric column.</p></li>
 | 
			
		||||
<li><p>What happens if you use a list of functions, but don’t name them? How is the output named?</p></li>
 | 
			
		||||
<li><p>It is possible to use <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> inside <code><a href="#chp-https://dplyr.tidyverse.org/reference/filter" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/filter</a></code> where it’s equivalent to <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>. Can you explain why?</p></li>
 | 
			
		||||
<li><p>It is possible to use <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> inside <code><a href="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code> where it’s equivalent to <code><a href="https://dplyr.tidyverse.org/reference/across.html">if_all()</a></code>. Can you explain why?</p></li>
 | 
			
		||||
<li><p>Adjust <code>expand_dates()</code> to automatically remove the date columns after they’ve been expanded. Do you need to embrace any arguments?</p></li>
 | 
			
		||||
<li>
 | 
			
		||||
<p>Explain what each step of the pipeline in this function does. What special feature of <code>where()</code> are we taking advantage of?</p>
 | 
			
		||||
@@ -512,27 +512,27 @@ nycflights13::flights |> show_missing(c(year, month, day))</pre>
 | 
			
		||||
<section id="reading-multiple-files" data-type="sect1">
 | 
			
		||||
<h1>
 | 
			
		||||
Reading multiple files</h1>
 | 
			
		||||
<p>In the previous section, you learned how to use <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code> to repeat a transformation on multiple columns. In this section, you’ll learn how to use <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> to do something to every file in a directory. Let’s start with a little motivation: imagine you have a directory full of excel spreadsheets<span data-type="footnote">If you instead had a directory of csv files with the same format, you can use the technique from <a href="#sec-readr-directory" data-type="xref">#sec-readr-directory</a>.</span> you want to read. You could do it with copy and paste:</p>
 | 
			
		||||
<p>In the previous section, you learned how to use <code><a href="https://dplyr.tidyverse.org/reference/across.html">dplyr::across()</a></code> to repeat a transformation on multiple columns. In this section, you’ll learn how to use <code><a href="https://purrr.tidyverse.org/reference/map.html">purrr::map()</a></code> to do something to every file in a directory. Let’s start with a little motivation: imagine you have a directory full of excel spreadsheets<span data-type="footnote">If you instead had a directory of csv files with the same format, you can use the technique from <a href="#sec-readr-directory" data-type="xref">#sec-readr-directory</a>.</span> you want to read. You could do it with copy and paste:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">data2019 <- readxl::read_excel("data/y2019.xlsx")
 | 
			
		||||
data2020 <- readxl::read_excel("data/y2020.xlsx")
 | 
			
		||||
data2021 <- readxl::read_excel("data/y2021.xlsx")
 | 
			
		||||
data2022 <- readxl::read_excel("data/y2022.xlsx")</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>And then use <code><a href="#chp-https://dplyr.tidyverse.org/reference/bind_rows" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/bind_rows</a></code> to combine them all together:</p>
 | 
			
		||||
<p>And then use <code><a href="https://dplyr.tidyverse.org/reference/bind_rows.html">dplyr::bind_rows()</a></code> to combine them all together:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">data <- bind_rows(data2019, data2020, data2021, data2022)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>You can imagine that this would get tedious quickly, especially if you had hundreds of files, not just four. The following sections show you how to automate this sort of task. There are three basic steps: use <code><a href="#chp-https://rdrr.io/r/base/list.files" data-type="xref">#chp-https://rdrr.io/r/base/list.files</a></code> to list all the files in a directory, then use <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> to read each of them into a list, then use <code><a href="#chp-https://purrr.tidyverse.org/reference/list_c" data-type="xref">#chp-https://purrr.tidyverse.org/reference/list_c</a></code> to combine them into a single data frame. We’ll then discuss how you can handle situations of increasing heterogeneity, where you can’t do exactly the same thing to every file.</p>
 | 
			
		||||
<p>You can imagine that this would get tedious quickly, especially if you had hundreds of files, not just four. The following sections show you how to automate this sort of task. There are three basic steps: use <code><a href="https://rdrr.io/r/base/list.files.html">list.files()</a></code> to list all the files in a directory, then use <code><a href="https://purrr.tidyverse.org/reference/map.html">purrr::map()</a></code> to read each of them into a list, then use <code><a href="https://purrr.tidyverse.org/reference/list_c.html">purrr::list_rbind()</a></code> to combine them into a single data frame. We’ll then discuss how you can handle situations of increasing heterogeneity, where you can’t do exactly the same thing to every file.</p>
 | 
			
		||||
 | 
			
		||||
<section id="listing-files-in-a-directory" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Listing files in a directory</h2>
 | 
			
		||||
<p>As the name suggests, <code><a href="#chp-https://rdrr.io/r/base/list.files" data-type="xref">#chp-https://rdrr.io/r/base/list.files</a></code> lists the files in a directory. TO CONSIDER: why not use it via the more obvious name <code><a href="#chp-https://rdrr.io/r/base/list.files" data-type="xref">#chp-https://rdrr.io/r/base/list.files</a></code>? You’ll almost always use three arguments:</p>
 | 
			
		||||
<p>As the name suggests, <code><a href="https://rdrr.io/r/base/list.files.html">list.files()</a></code> lists the files in a directory. TO CONSIDER: why not use it via the more obvious name <code><a href="https://rdrr.io/r/base/list.files.html">list.files()</a></code>? You’ll almost always use three arguments:</p>
 | 
			
		||||
<ul><li><p>The first argument, <code>path</code>, is the directory to look in.</p></li>
 | 
			
		||||
<li><p><code>pattern</code> is a regular expression used to filter the file names. The most common pattern is something like <code>[.]xlsx$</code> or <code>[.]csv$</code> to find all files with a specified extension.</p></li>
 | 
			
		||||
<li><p><code>full.names</code> determines whether or not the directory name should be included in the output. You almost always want this to be <code>TRUE</code>.</p></li>
 | 
			
		||||
</ul><p>To make our motivating example concrete, this book contains a folder with 12 excel spreadsheets containing data from the gapminder package. Each file contains one year’s worth of data for 142 countries. We can list them all with the appropriate call to <code><a href="#chp-https://rdrr.io/r/base/list.files" data-type="xref">#chp-https://rdrr.io/r/base/list.files</a></code>:</p>
 | 
			
		||||
</ul><p>To make our motivating example concrete, this book contains a folder with 12 excel spreadsheets containing data from the gapminder package. Each file contains one year’s worth of data for 142 countries. We can list them all with the appropriate call to <code><a href="https://rdrr.io/r/base/list.files.html">list.files()</a></code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">paths <- list.files("data/gapminder", pattern = "[.]xlsx$", full.names = TRUE)
 | 
			
		||||
paths
 | 
			
		||||
@@ -587,7 +587,7 @@ gapminder_2007 <- readxl::read_excel("data/gapminder/2007.xlsx")</pre>
 | 
			
		||||
<h2>
 | 
			
		||||
<code>purrr::map()</code> and <code>list_rbind()</code>
 | 
			
		||||
</h2>
 | 
			
		||||
<p>The code to collect those data frames in a list “by hand” is basically just as tedious to type as code that reads the files one-by-one. Happily, we can use <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> to make even better use of our <code>paths</code> vector. <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> is similar to<code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>, but instead of doing something to each column in a data frame, it does something to each element of a vector.<code>map(x, f)</code> is shorthand for:</p>
 | 
			
		||||
<p>The code to collect those data frames in a list “by hand” is basically just as tedious to type as code that reads the files one-by-one. Happily, we can use <code><a href="https://purrr.tidyverse.org/reference/map.html">purrr::map()</a></code> to make even better use of our <code>paths</code> vector. <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> is similar to<code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>, but instead of doing something to each column in a data frame, it does something to each element of a vector.<code>map(x, f)</code> is shorthand for:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">list(
 | 
			
		||||
  f(x[[1]]),
 | 
			
		||||
@@ -596,7 +596,7 @@ gapminder_2007 <- readxl::read_excel("data/gapminder/2007.xlsx")</pre>
 | 
			
		||||
  f(x[[n]])
 | 
			
		||||
)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>So we can use <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> get a list of 12 data frames:</p>
 | 
			
		||||
<p>So we can use <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> get a list of 12 data frames:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">files <- map(paths, readxl::read_excel)
 | 
			
		||||
length(files)
 | 
			
		||||
@@ -614,8 +614,8 @@ files[[1]]
 | 
			
		||||
#> 6 Australia   Oceania      69.1  8691212    10040.
 | 
			
		||||
#> # … with 136 more rows</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>(This is another data structure that doesn’t display particularly compactly with <code><a href="#chp-https://rdrr.io/r/utils/str" data-type="xref">#chp-https://rdrr.io/r/utils/str</a></code> so you might want to load into RStudio and inspect it with <code><a href="#chp-https://rdrr.io/r/utils/View" data-type="xref">#chp-https://rdrr.io/r/utils/View</a></code>).</p>
 | 
			
		||||
<p>Now we can use <code><a href="#chp-https://purrr.tidyverse.org/reference/list_c" data-type="xref">#chp-https://purrr.tidyverse.org/reference/list_c</a></code> to combine that list of data frames into a single data frame:</p>
 | 
			
		||||
<p>(This is another data structure that doesn’t display particularly compactly with <code><a href="https://rdrr.io/r/utils/str.html">str()</a></code> so you might want to load into RStudio and inspect it with <code><a href="https://rdrr.io/r/utils/View.html">View()</a></code>).</p>
 | 
			
		||||
<p>Now we can use <code><a href="https://purrr.tidyverse.org/reference/list_c.html">purrr::list_rbind()</a></code> to combine that list of data frames into a single data frame:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">list_rbind(files)
 | 
			
		||||
#> # A tibble: 1,704 × 5
 | 
			
		||||
@@ -635,7 +635,7 @@ files[[1]]
 | 
			
		||||
  map(readxl::read_excel) |> 
 | 
			
		||||
  list_rbind()</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>What if we want to pass in extra arguments to <code>read_excel()</code>? We use the same technique that we used with <code><a href="#chp-https://dplyr.tidyverse.org/reference/across" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/across</a></code>. For example, it’s often useful to peak at the first few row of the data with <code>n_max = 1</code>:</p>
 | 
			
		||||
<p>What if we want to pass in extra arguments to <code>read_excel()</code>? We use the same technique that we used with <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>. For example, it’s often useful to peak at the first few row of the data with <code>n_max = 1</code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">paths |> 
 | 
			
		||||
  map(\(path) readxl::read_excel(path, n_max = 1)) |> 
 | 
			
		||||
@@ -658,7 +658,7 @@ files[[1]]
 | 
			
		||||
<h2>
 | 
			
		||||
Data in the path</h2>
 | 
			
		||||
<p>Sometimes the name of the file is itself data. In this example, the file name contains the year, which is not otherwise recorded in the individual files. To get that column into the final data frame, we need to do two things.</p>
 | 
			
		||||
<p>First, we name the vector of paths. The easiest way to do this is with the <code><a href="#chp-https://rlang.r-lib.org/reference/set_names" data-type="xref">#chp-https://rlang.r-lib.org/reference/set_names</a></code> function, which can take a function. Here we use <code><a href="#chp-https://rdrr.io/r/base/basename" data-type="xref">#chp-https://rdrr.io/r/base/basename</a></code> to extract just the file name from the full path:</p>
 | 
			
		||||
<p>First, we name the vector of paths. The easiest way to do this is with the <code><a href="https://rlang.r-lib.org/reference/set_names.html">set_names()</a></code> function, which can take a function. Here we use <code><a href="https://rdrr.io/r/base/basename.html">basename()</a></code> to extract just the file name from the full path:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">paths |> set_names(basename) 
 | 
			
		||||
#>                  1952.xlsx                  1957.xlsx 
 | 
			
		||||
@@ -680,7 +680,7 @@ Data in the path</h2>
 | 
			
		||||
  set_names(basename) |> 
 | 
			
		||||
  map(readxl::read_excel)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>That makes this call to <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> shorthand for:</p>
 | 
			
		||||
<p>That makes this call to <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> shorthand for:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">files <- list(
 | 
			
		||||
  "1952.xlsx" = readxl::read_excel("data/gapminder/1952.xlsx"),
 | 
			
		||||
@@ -704,7 +704,7 @@ Data in the path</h2>
 | 
			
		||||
#> 6 Australia   Oceania      70.9 10794968    12217.
 | 
			
		||||
#> # … with 136 more rows</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Then we use the <code>names_to</code> argument to <code><a href="#chp-https://purrr.tidyverse.org/reference/list_c" data-type="xref">#chp-https://purrr.tidyverse.org/reference/list_c</a></code> to tell it to save the names into a new column called <code>year</code> then use <code><a href="#chp-https://readr.tidyverse.org/reference/parse_number" data-type="xref">#chp-https://readr.tidyverse.org/reference/parse_number</a></code> to extract the number from the string.</p>
 | 
			
		||||
<p>Then we use the <code>names_to</code> argument to <code><a href="https://purrr.tidyverse.org/reference/list_c.html">list_rbind()</a></code> to tell it to save the names into a new column called <code>year</code> then use <code><a href="https://readr.tidyverse.org/reference/parse_number.html">readr::parse_number()</a></code> to extract the number from the string.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">paths |> 
 | 
			
		||||
  set_names(basename) |> 
 | 
			
		||||
@@ -722,7 +722,7 @@ Data in the path</h2>
 | 
			
		||||
#> 6  1952 Australia   Oceania      69.1  8691212    10040.
 | 
			
		||||
#> # … with 1,698 more rows</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>In more complicated cases, there might be other variables stored in the directory name, or maybe the file name contains multiple bits of data. In that case, use <code><a href="#chp-https://rlang.r-lib.org/reference/set_names" data-type="xref">#chp-https://rlang.r-lib.org/reference/set_names</a></code> (without any arguments) to record the full path, and then use <code><a href="#chp-https://tidyr.tidyverse.org/reference/separate_wider_delim" data-type="xref">#chp-https://tidyr.tidyverse.org/reference/separate_wider_delim</a></code> and friends to turn them into useful columns.</p>
 | 
			
		||||
<p>In more complicated cases, there might be other variables stored in the directory name, or maybe the file name contains multiple bits of data. In that case, use <code><a href="https://rlang.r-lib.org/reference/set_names.html">set_names()</a></code> (without any arguments) to record the full path, and then use <code><a href="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">tidyr::separate_wider_delim()</a></code> and friends to turn them into useful columns.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit"># NOTE: this chapter also depends on dev tidyr (in addition to dev purrr and dev dplyr)
 | 
			
		||||
paths |> 
 | 
			
		||||
@@ -759,14 +759,14 @@ write_csv(gapminder, "gapminder.csv")</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Now when you come back to this problem in the future, you can read in a single csv file.</p>
 | 
			
		||||
<p>If you’re working in a project, we’d suggest calling the file that does this sort of data prep work something like <code>0-cleanup.R.</code> The <code>0</code> in the file name suggests that this should be run before anything else.</p>
 | 
			
		||||
<p>If your input data files change over time, you might consider learning a tool like <a href="#chp-https://docs.ropensci.org/targets/" data-type="xref">#chp-https://docs.ropensci.org/targets/</a> to set up your data cleaning code to automatically re-run whenever one of the input files is modified.</p>
 | 
			
		||||
<p>If your input data files change over time, you might consider learning a tool like <a href="https://docs.ropensci.org/targets/">targets</a> to set up your data cleaning code to automatically re-run whenever one of the input files is modified.</p>
 | 
			
		||||
</section>
 | 
			
		||||
 | 
			
		||||
<section id="many-simple-iterations" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Many simple iterations</h2>
 | 
			
		||||
<p>Here we’ve just loaded the data directly from disk, and were lucky enough to get a tidy dataset. In most cases, you’ll need to do some additional tidying, and you have two basic basic options: you can do one round of iteration with a complex function, or do a multiple rounds of iteration with simple functions. In our experience most folks reach first for one complex iteration, but you’re often better by doing multiple simple iterations.</p>
 | 
			
		||||
<p>For example, imagine that you want to read in a bunch of files, filter out missing values, pivot, and then combine. One way to approach the problem is write a function that takes a file and does all those steps then call <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> once:</p>
 | 
			
		||||
<p>For example, imagine that you want to read in a bunch of files, filter out missing values, pivot, and then combine. One way to approach the problem is write a function that takes a file and does all those steps then call <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> once:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">process_file <- function(path) {
 | 
			
		||||
  df <- read_csv(path)
 | 
			
		||||
@@ -805,7 +805,7 @@ paths |>
 | 
			
		||||
<section id="heterogeneous-data" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Heterogeneous data</h2>
 | 
			
		||||
<p>Unfortunately sometimes it’s not possible to go from <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> straight to <code><a href="#chp-https://purrr.tidyverse.org/reference/list_c" data-type="xref">#chp-https://purrr.tidyverse.org/reference/list_c</a></code> because the data frames are so heterogeneous that <code><a href="#chp-https://purrr.tidyverse.org/reference/list_c" data-type="xref">#chp-https://purrr.tidyverse.org/reference/list_c</a></code> either fails or yields a data frame that’s not very useful. In that case, it’s still useful to start by loading all of the files:</p>
 | 
			
		||||
<p>Unfortunately sometimes it’s not possible to go from <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> straight to <code><a href="https://purrr.tidyverse.org/reference/list_c.html">list_rbind()</a></code> because the data frames are so heterogeneous that <code><a href="https://purrr.tidyverse.org/reference/list_c.html">list_rbind()</a></code> either fails or yields a data frame that’s not very useful. In that case, it’s still useful to start by loading all of the files:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">files <- paths |> 
 | 
			
		||||
  map(readxl::read_excel) </pre>
 | 
			
		||||
@@ -861,21 +861,21 @@ df_types(nycflights13::flights)
 | 
			
		||||
#> 6 1977.xlsx character character double  double double   
 | 
			
		||||
#> # … with 6 more rows</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>If the files have heterogeneous formats you might need to do more processing before you can successfully merge them. Unfortunately we’re now going to leave you to figure that out on your own, but you might want to read about <code><a href="#chp-https://purrr.tidyverse.org/reference/map_if" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map_if</a></code> and <code><a href="#chp-https://purrr.tidyverse.org/reference/map_if" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map_if</a></code>. <code><a href="#chp-https://purrr.tidyverse.org/reference/map_if" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map_if</a></code> allows you to selectively modify elements of a list based on their values; <code><a href="#chp-https://purrr.tidyverse.org/reference/map_if" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map_if</a></code> allows you to selectively modify elements based on their names.</p>
 | 
			
		||||
<p>If the files have heterogeneous formats you might need to do more processing before you can successfully merge them. Unfortunately we’re now going to leave you to figure that out on your own, but you might want to read about <code><a href="https://purrr.tidyverse.org/reference/map_if.html">map_if()</a></code> and <code><a href="https://purrr.tidyverse.org/reference/map_if.html">map_at()</a></code>. <code><a href="https://purrr.tidyverse.org/reference/map_if.html">map_if()</a></code> allows you to selectively modify elements of a list based on their values; <code><a href="https://purrr.tidyverse.org/reference/map_if.html">map_at()</a></code> allows you to selectively modify elements based on their names.</p>
 | 
			
		||||
</section>
 | 
			
		||||
 | 
			
		||||
<section id="handling-failures" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Handling failures</h2>
 | 
			
		||||
<p>Sometimes the structure of your data might be sufficiently wild that you can’t even read all the files with a single command. And then you’ll encounter one of the downsides of map: it succeeds or fails as a whole. <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> will either successfully read all of the files in a directory or fail with an error, reading zero files. This is annoying: why does one failure prevent you from accessing all the other successes?</p>
 | 
			
		||||
<p>Luckily, purrr comes with a helper to tackle this problem: <code><a href="#chp-https://purrr.tidyverse.org/reference/possibly" data-type="xref">#chp-https://purrr.tidyverse.org/reference/possibly</a></code>. <code><a href="#chp-https://purrr.tidyverse.org/reference/possibly" data-type="xref">#chp-https://purrr.tidyverse.org/reference/possibly</a></code> is what’s known as a function operator: it takes a function and returns a function with modified behavior. In particular, <code><a href="#chp-https://purrr.tidyverse.org/reference/possibly" data-type="xref">#chp-https://purrr.tidyverse.org/reference/possibly</a></code> changes a function from erroring to returning a value that you specify:</p>
 | 
			
		||||
<p>Sometimes the structure of your data might be sufficiently wild that you can’t even read all the files with a single command. And then you’ll encounter one of the downsides of map: it succeeds or fails as a whole. <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> will either successfully read all of the files in a directory or fail with an error, reading zero files. This is annoying: why does one failure prevent you from accessing all the other successes?</p>
 | 
			
		||||
<p>Luckily, purrr comes with a helper to tackle this problem: <code><a href="https://purrr.tidyverse.org/reference/possibly.html">possibly()</a></code>. <code><a href="https://purrr.tidyverse.org/reference/possibly.html">possibly()</a></code> is what’s known as a function operator: it takes a function and returns a function with modified behavior. In particular, <code><a href="https://purrr.tidyverse.org/reference/possibly.html">possibly()</a></code> changes a function from erroring to returning a value that you specify:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">files <- paths |> 
 | 
			
		||||
  map(possibly(\(path) readxl::read_excel(path), NULL))
 | 
			
		||||
 | 
			
		||||
data <- files |> list_rbind()</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>This works particularly well here because <code><a href="#chp-https://purrr.tidyverse.org/reference/list_c" data-type="xref">#chp-https://purrr.tidyverse.org/reference/list_c</a></code>, like many tidyverse functions, automatically ignores <code>NULL</code>s.</p>
 | 
			
		||||
<p>This works particularly well here because <code><a href="https://purrr.tidyverse.org/reference/list_c.html">list_rbind()</a></code>, like many tidyverse functions, automatically ignores <code>NULL</code>s.</p>
 | 
			
		||||
<p>Now you have all the data that can be read easily, and it’s time to tackle the hard part of figuring out why some files failed load and what do to about it. Start by getting the paths that failed:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">failed <- map_vec(files, is.null)
 | 
			
		||||
@@ -889,7 +889,7 @@ paths[failed]
 | 
			
		||||
<section id="saving-multiple-outputs" data-type="sect1">
 | 
			
		||||
<h1>
 | 
			
		||||
Saving multiple outputs</h1>
 | 
			
		||||
<p>In the last section, you learned about <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code>, which is useful for reading multiple files into a single object. In this section, we’ll now explore sort of the opposite problem: how can you take one or more R objects and save it to one or more files? We’ll explore this challenge using three examples:</p>
 | 
			
		||||
<p>In the last section, you learned about <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code>, which is useful for reading multiple files into a single object. In this section, we’ll now explore sort of the opposite problem: how can you take one or more R objects and save it to one or more files? We’ll explore this challenge using three examples:</p>
 | 
			
		||||
<ul><li>Saving multiple data frames into one database.</li>
 | 
			
		||||
<li>Saving multiple data frames into multiple csv files.</li>
 | 
			
		||||
<li>Saving multiple plots to multiple <code>.png</code> files.</li>
 | 
			
		||||
@@ -920,7 +920,7 @@ template
 | 
			
		||||
#> 6 Australia   Oceania      69.1  8691212    10040.  1952
 | 
			
		||||
#> # … with 136 more rows</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Now we can connect to the database, and use <code><a href="#chp-https://dbi.r-dbi.org/reference/dbCreateTable" data-type="xref">#chp-https://dbi.r-dbi.org/reference/dbCreateTable</a></code> to turn our template into database table:</p>
 | 
			
		||||
<p>Now we can connect to the database, and use <code><a href="https://dbi.r-dbi.org/reference/dbCreateTable.html">DBI::dbCreateTable()</a></code> to turn our template into database table:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">con <- DBI::dbConnect(duckdb::duckdb())
 | 
			
		||||
DBI::dbCreateTable(con, "gapminder", template)</pre>
 | 
			
		||||
@@ -933,7 +933,7 @@ DBI::dbCreateTable(con, "gapminder", template)</pre>
 | 
			
		||||
#> # … with 6 variables: country <chr>, continent <chr>, lifeExp <dbl>, pop <dbl>,
 | 
			
		||||
#> #   gdpPercap <dbl>, year <dbl></pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Next, we need a function that takes a single file path, reads it into R, and adds the result to the <code>gapminder</code> table. We can do that by combining <code>read_excel()</code> with <code><a href="#chp-https://dbi.r-dbi.org/reference/dbAppendTable" data-type="xref">#chp-https://dbi.r-dbi.org/reference/dbAppendTable</a></code>:</p>
 | 
			
		||||
<p>Next, we need a function that takes a single file path, reads it into R, and adds the result to the <code>gapminder</code> table. We can do that by combining <code>read_excel()</code> with <code><a href="https://dbi.r-dbi.org/reference/dbAppendTable.html">DBI::dbAppendTable()</a></code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">append_file <- function(path) {
 | 
			
		||||
  df <- readxl::read_excel(path)
 | 
			
		||||
@@ -942,11 +942,11 @@ DBI::dbCreateTable(con, "gapminder", template)</pre>
 | 
			
		||||
  DBI::dbAppendTable(con, "gapminder", df)
 | 
			
		||||
}</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Now we need to call <code>append_csv()</code> once for each element of <code>paths</code>. That’s certainly possible with <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code>:</p>
 | 
			
		||||
<p>Now we need to call <code>append_csv()</code> once for each element of <code>paths</code>. That’s certainly possible with <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">paths |> map(append_file)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>But we don’t care about the output of <code>append_file()</code>, so instead of <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> it’s slightly nicer to use <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code>. <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> does exactly the same thing as <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> but throws the output away:</p>
 | 
			
		||||
<p>But we don’t care about the output of <code>append_file()</code>, so instead of <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> it’s slightly nicer to use <code><a href="https://purrr.tidyverse.org/reference/map.html">walk()</a></code>. <code><a href="https://purrr.tidyverse.org/reference/map.html">walk()</a></code> does exactly the same thing as <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> but throws the output away:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">paths |> walk(append_file)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
@@ -972,7 +972,7 @@ DBI::dbCreateTable(con, "gapminder", template)</pre>
 | 
			
		||||
<section id="writing-csv-files" data-type="sect2">
 | 
			
		||||
<h2>
 | 
			
		||||
Writing csv files</h2>
 | 
			
		||||
<p>The same basic principle applies if we want to write multiple csv files, one for each group. Let’s imagine that we want to take the <code><a href="#chp-https://ggplot2.tidyverse.org/reference/diamonds" data-type="xref">#chp-https://ggplot2.tidyverse.org/reference/diamonds</a></code> data and save one csv file for each <code>clarity</code>. First we need to make those individual datasets. There are many ways you could do that, but there’s one way we particularly like: <code><a href="#chp-https://dplyr.tidyverse.org/reference/group_nest" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/group_nest</a></code>.</p>
 | 
			
		||||
<p>The same basic principle applies if we want to write multiple csv files, one for each group. Let’s imagine that we want to take the <code><a href="https://ggplot2.tidyverse.org/reference/diamonds.html">ggplot2::diamonds</a></code> data and save one csv file for each <code>clarity</code>. First we need to make those individual datasets. There are many ways you could do that, but there’s one way we particularly like: <code><a href="https://dplyr.tidyverse.org/reference/group_nest.html">group_nest()</a></code>.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">by_clarity <- diamonds |> 
 | 
			
		||||
  group_nest(clarity)
 | 
			
		||||
@@ -1003,7 +1003,7 @@ by_clarity
 | 
			
		||||
#> 6  1.04 Premium   G      62.2    58  2801  6.46  6.41  4   
 | 
			
		||||
#> # … with 735 more rows</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>While we’re here, lets create a column that gives the name of output file, using <code><a href="#chp-https://dplyr.tidyverse.org/reference/mutate" data-type="xref">#chp-https://dplyr.tidyverse.org/reference/mutate</a></code> and <code><a href="#chp-https://stringr.tidyverse.org/reference/str_glue" data-type="xref">#chp-https://stringr.tidyverse.org/reference/str_glue</a></code>:</p>
 | 
			
		||||
<p>While we’re here, lets create a column that gives the name of output file, using <code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> and <code><a href="https://stringr.tidyverse.org/reference/str_glue.html">str_glue()</a></code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">by_clarity <- by_clarity |> 
 | 
			
		||||
  mutate(path = str_glue("diamonds-{clarity}.csv"))
 | 
			
		||||
@@ -1028,7 +1028,7 @@ write_csv(by_clarity$data[[3]], by_clarity$path[[3]])
 | 
			
		||||
...
 | 
			
		||||
write_csv(by_clarity$by_clarity[[8]], by_clarity$path[[8]])</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>This is a little different to our previous uses of <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> because there are two arguments that are changing, not just one. That means we need a new function: <code><a href="#chp-https://purrr.tidyverse.org/reference/map2" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map2</a></code>, which varies both the first and second arguments. And because we again don’t care about the output, we want <code><a href="#chp-https://purrr.tidyverse.org/reference/map2" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map2</a></code> rather than <code><a href="#chp-https://purrr.tidyverse.org/reference/map2" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map2</a></code>. That gives us:</p>
 | 
			
		||||
<p>This is a little different to our previous uses of <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> because there are two arguments that are changing, not just one. That means we need a new function: <code><a href="https://purrr.tidyverse.org/reference/map2.html">map2()</a></code>, which varies both the first and second arguments. And because we again don’t care about the output, we want <code><a href="https://purrr.tidyverse.org/reference/map2.html">walk2()</a></code> rather than <code><a href="https://purrr.tidyverse.org/reference/map2.html">map2()</a></code>. That gives us:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">walk2(by_clarity$data, by_clarity$path, write_csv)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
@@ -1048,7 +1048,7 @@ carat_histogram(by_clarity$data[[1]])</pre>
 | 
			
		||||
<p><img src="iteration_files/figure-html/unnamed-chunk-70-1.png" class="img-fluid" width="576"/></p>
 | 
			
		||||
</div>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Now we can use <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> to create a list of many plots<span data-type="footnote">You can print <code>by_clarity$plot</code> to get a crude animation — you’ll get one plot for each element of <code>plots</code>. NOTE: this didn’t happen for me.</span> and their eventual file paths:</p>
 | 
			
		||||
<p>Now we can use <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> to create a list of many plots<span data-type="footnote">You can print <code>by_clarity$plot</code> to get a crude animation — you’ll get one plot for each element of <code>plots</code>. NOTE: this didn’t happen for me.</span> and their eventual file paths:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">by_clarity <- by_clarity |> 
 | 
			
		||||
  mutate(
 | 
			
		||||
@@ -1056,7 +1056,7 @@ carat_histogram(by_clarity$data[[1]])</pre>
 | 
			
		||||
    path = str_glue("clarity-{clarity}.png")
 | 
			
		||||
  )</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Then use <code><a href="#chp-https://purrr.tidyverse.org/reference/map2" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map2</a></code> with <code><a href="#chp-https://ggplot2.tidyverse.org/reference/ggsave" data-type="xref">#chp-https://ggplot2.tidyverse.org/reference/ggsave</a></code> to save each plot:</p>
 | 
			
		||||
<p>Then use <code><a href="https://purrr.tidyverse.org/reference/map2.html">walk2()</a></code> with <code><a href="https://ggplot2.tidyverse.org/reference/ggsave.html">ggsave()</a></code> to save each plot:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">walk2(
 | 
			
		||||
  by_clarity$path,
 | 
			
		||||
@@ -1084,8 +1084,8 @@ ggsave(by_clarity$path[[8]], by_clarity$plot[[8]], width = 6, height = 6)</pre>
 | 
			
		||||
<section id="summary" data-type="sect1">
 | 
			
		||||
<h1>
 | 
			
		||||
Summary</h1>
 | 
			
		||||
<p>In this chapter you’ve seen how to use explicit iteration to solve three problems that come up frequently when doing data science: manipulating multiple columns, reading multiple files, and saving multiple outputs. But in general, iteration is a super power: if you know the right iteration technique, you can easily go from fixing one problem to fixing all the problems. Once you’ve mastered the techniques in this chapter, we highly recommend learning more by reading the <a href="#chp-https://adv-r.hadley.nz/functionals" data-type="xref">#chp-https://adv-r.hadley.nz/functionals</a> of <em>Advanced R</em> and consulting the <a href="#chp-https://purrr.tidyverse" data-type="xref">#chp-https://purrr.tidyverse</a>.</p>
 | 
			
		||||
<p>If you know much about iteration in other languages you might be surprised that we didn’t discuss the <code>for</code> loop. That’s because R’s orientation towards data analysis changes how we iterate: in most cases you can rely on an existing idiom to do something to each columns or each group. And when you can’t, you can often use a functional programming tool like <code><a href="#chp-https://purrr.tidyverse.org/reference/map" data-type="xref">#chp-https://purrr.tidyverse.org/reference/map</a></code> that does something to each element of a list. However, you will see <code>for</code> loops in wild-caught code, so you’ll learn about them in the next chapter where we’ll discuss some important base R tools.</p>
 | 
			
		||||
<p>In this chapter you’ve seen how to use explicit iteration to solve three problems that come up frequently when doing data science: manipulating multiple columns, reading multiple files, and saving multiple outputs. But in general, iteration is a super power: if you know the right iteration technique, you can easily go from fixing one problem to fixing all the problems. Once you’ve mastered the techniques in this chapter, we highly recommend learning more by reading the <a href="https://adv-r.hadley.nz/functionals.html">Functionals chapter</a> of <em>Advanced R</em> and consulting the <a href="https://purrr.tidyverse.org">purrr website</a>.</p>
 | 
			
		||||
<p>If you know much about iteration in other languages you might be surprised that we didn’t discuss the <code>for</code> loop. That’s because R’s orientation towards data analysis changes how we iterate: in most cases you can rely on an existing idiom to do something to each columns or each group. And when you can’t, you can often use a functional programming tool like <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> that does something to each element of a list. However, you will see <code>for</code> loops in wild-caught code, so you’ll learn about them in the next chapter where we’ll discuss some important base R tools.</p>
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
</section>
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user