r4ds/oreilly/iteration.html

1083 lines
67 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<section data-type="chapter" id="chp-iteration">
<h1><span id="sec-iteration" class="quarto-section-identifier d-none d-lg-block"><span class="chapter-title">Iteration</span></span></h1>
<section id="introduction" data-type="sect1">
<h1>
Introduction</h1>
<p>In this chapter, youll 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, youd need to explicitly double each element of <code>x</code> 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="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="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a></code> plus <code><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code> computes a summary statistics for each subset.</li>
<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 its 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 well 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">
<h2>
Prerequisites</h2>
<div data-type="important"><div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon"/>
</div>
</div>
<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, well focus on tools provided by dplyr and purrr, both core members of the tidyverse. Youve seen dplyr before, but <a href="http://purrr.tidyverse.org/">purrr</a> is new. Were just going to use a couple of purrr functions in this chapter, but its a great package to explore as you improve your programming skills.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">library(tidyverse)</pre>
</div>
</section>
</section>
<section id="sec-across" data-type="sect1">
<h1>
Modifying multiple columns</h1>
<p>Imagine you have this simple tibble and you want to count the number of observations and compute the median of every column.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">df &lt;- tibble(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)</pre>
</div>
<p>You could do it with copy-and-paste:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">df |&gt; summarize(
n = n(),
a = median(a),
b = median(b),
c = median(c),
d = median(d),
)
#&gt; # A tibble: 1 × 5
#&gt; n a b c d
#&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 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="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">df |&gt; summarize(
n = n(),
across(a:d, median),
)
#&gt; # A tibble: 1 × 5
#&gt; n a b c d
#&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 10 -0.246 -0.287 -0.0567 0.144</pre>
</div>
<p><code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> has three particularly important arguments, which well discuss in detail in the following sections. Youll 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>. Well 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="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><a href="https://tidyselect.r-lib.org/reference/where.html">where()</a></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="r">df &lt;- tibble(
grp = sample(2, 10, replace = TRUE),
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
df |&gt;
group_by(grp) |&gt;
summarize(across(everything(), median))
#&gt; # A tibble: 2 × 5
#&gt; grp a b c d
#&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 1 -0.0935 -0.0163 0.363 0.364
#&gt; 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="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>, because theyre automatically preserved by <code><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code>.</p>
<p><code><a href="https://tidyselect.r-lib.org/reference/where.html">where()</a></code> allows you to select columns based on their type:</p>
<ul><li>
<code>where(is.numeric)</code> selects all numeric columns.</li>
<li>
<code>where(is.character)</code> selects all string columns.</li>
<li>
<code>where(is.Date)</code> selects all date columns.</li>
<li>
<code>where(is.POSIXct)</code> selects all date-time columns.</li>
<li>
<code>where(is.logical)</code> selects all logical columns.</li>
</ul><div class="cell">
<pre data-type="programlisting" data-code-language="r">df_types &lt;- tibble(
x1 = 1:3,
x2 = runif(3),
y1 = sample(letters, 3),
y2 = c("banana", "apple", "egg")
)
df_types |&gt;
summarize(across(where(is.numeric), mean))
#&gt; # A tibble: 1 × 2
#&gt; x1 x2
#&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 2 0.370
df_types |&gt;
summarize(across(where(is.character), str_flatten))
#&gt; # A tibble: 1 × 2
#&gt; y1 y2
#&gt; &lt;chr&gt; &lt;chr&gt;
#&gt; 1 kjh bananaappleegg</pre>
</div>
<p>Just like other selectors, you can combine these with Boolean algebra. For example, <code>!where(is.numeric)</code> selects all non-numeric columns, and <code>starts_with("a") &amp; where(is.logical)</code> selects all logical columns whose name starts with “a”.</p>
</section>
<section id="calling-a-single-function" data-type="sect2">
<h2>
Calling a single function</h2>
<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: were 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 functional programming language.</p>
<p>Its important to note that were 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, youll get an error:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">df |&gt;
group_by(grp) |&gt;
summarize(across(everything(), median()))
#&gt; Error in `summarize()`:
#&gt; In argument: `across(everything(), median())`.
#&gt; Caused by error in `is.factor()`:
#&gt; ! argument "x" is missing, with no default</pre>
</div>
<p>This error arises because youre calling the function with no input, e.g.:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">median()
#&gt; Error in is.factor(x): argument "x" is missing, with no default</pre>
</div>
</section>
<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="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="r">rnorm_na &lt;- function(n, n_na, mean = 0, sd = 1) {
sample(c(rnorm(n - n_na, mean = mean, sd = 1), rep(NA, n_na)))
}
df_miss &lt;- tibble(
a = rnorm_na(5, 1),
b = rnorm_na(5, 1),
c = rnorm_na(5, 2),
d = rnorm(5)
)
df_miss |&gt;
summarize(
across(a:d, median),
n = n()
)
#&gt; # A tibble: 1 × 5
#&gt; a b c d n
#&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt;
#&gt; 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="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="r">df_miss |&gt;
summarize(
across(a:d, function(x) median(x, na.rm = TRUE)),
n = n()
)
#&gt; # A tibble: 1 × 5
#&gt; a b c d n
#&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt;
#&gt; 1 0.429 -0.721 -0.796 0.704 5</pre>
</div>
<p>This is a little verbose, so R comes with a handy shortcut: for this sort of throw away, or <strong>anonymous</strong><span data-type="footnote">Anonymous, because we never explicitly gave it a name with <code>&lt;-</code>. Another term programmers use for this is “lambda function”.</span>, function you can replace <code>function</code> with <code>\</code><span data-type="footnote">In older code you might see syntax that looks like <code>~ .x + 1</code>. This is another way to write anonymous functions but it only works inside tidyverse functions and always uses the variable name <code>.x</code>. We now recommend the base syntax, <code>\(x) x + 1</code>.</span>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">df_miss |&gt;
summarize(
across(a:d, \(x) median(x, na.rm = TRUE)),
n = n()
)</pre>
</div>
<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="r">df_miss |&gt;
summarize(
a = median(a, na.rm = TRUE),
b = median(b, na.rm = TRUE),
c = median(c, na.rm = TRUE),
d = median(d, na.rm = TRUE),
n = n()
)</pre>
</div>
<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 were removed. 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="r">df_miss |&gt;
summarize(
across(a:d, list(
median = \(x) median(x, na.rm = TRUE),
n_miss = \(x) sum(is.na(x))
)),
n = n()
)
#&gt; # A tibble: 1 × 9
#&gt; a_median a_n_miss b_median b_n_miss c_median c_n_miss d_median d_n_miss
#&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; &lt;int&gt;
#&gt; 1 0.429 1 -0.721 1 -0.796 2 0.704 0
#&gt; # … with 1 more variable: n &lt;int&gt;</pre>
</div>
<p>If you look carefully, you might intuit that the columns are named using using a glue specification (<a href="#sec-glue" data-type="xref">#sec-glue</a>) like <code>{.col}_{.fn}</code> where <code>.col</code> is the name of the original column and <code>.fn</code> is the name of the function. Thats not a coincidence! As youll learn in the next section, you can use <code>.names</code> argument to supply your own glue spec.</p>
</section>
<section id="column-names" data-type="sect2">
<h2>
Column names</h2>
<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 cant 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="r">df_miss |&gt;
summarize(
across(
a:d,
list(
median = \(x) median(x, na.rm = TRUE),
n_miss = \(x) sum(is.na(x))
),
.names = "{.fn}_{.col}"
),
n = n(),
)
#&gt; # A tibble: 1 × 9
#&gt; median_a n_miss_a median_b n_miss_b median_c n_miss_c median_d n_miss_d
#&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; &lt;int&gt;
#&gt; 1 0.429 1 -0.721 1 -0.796 2 0.704 0
#&gt; # … with 1 more variable: n &lt;int&gt;</pre>
</div>
<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="r">df_miss |&gt;
mutate(
across(a:d, \(x) coalesce(x, 0))
)
#&gt; # A tibble: 5 × 4
#&gt; a b c d
#&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 0 -0.463 0 2.13
#&gt; 2 -0.382 -0.980 0 0.704
#&gt; 3 0.434 0 -1.06 0.715
#&gt; 4 1.06 1.21 -0.796 -1.09
#&gt; 5 0.424 -1.28 -0.785 0.402</pre>
</div>
<p>If youd like to instead create new columns, you can use the <code>.names</code> argument to give the output new names:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">df_miss |&gt;
mutate(
across(a:d, \(x) abs(x), .names = "{.col}_abs")
)
#&gt; # A tibble: 5 × 8
#&gt; a b c d a_abs b_abs c_abs d_abs
#&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 NA -0.463 NA 2.13 NA 0.463 NA 2.13
#&gt; 2 -0.382 -0.980 NA 0.704 0.382 0.980 NA 0.704
#&gt; 3 0.434 NA -1.06 0.715 0.434 NA 1.06 0.715
#&gt; 4 1.06 1.21 -0.796 -1.09 1.06 1.21 0.796 1.09
#&gt; 5 0.424 -1.28 -0.785 0.402 0.424 1.28 0.785 0.402</pre>
</div>
</section>
<section id="filtering" data-type="sect2">
<h2>
Filtering</h2>
<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">summarize()</a></code> and <code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> but its 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>&amp;</code>. Its 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="r">df_miss |&gt; filter(is.na(a) | is.na(b) | is.na(c) | is.na(d))
#&gt; # A tibble: 3 × 4
#&gt; a b c d
#&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 NA -0.463 NA 2.13
#&gt; 2 -0.382 -0.980 NA 0.704
#&gt; 3 0.434 NA -1.06 0.715
# same as:
df_miss |&gt; filter(if_any(a:d, is.na))
#&gt; # A tibble: 3 × 4
#&gt; a b c d
#&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 NA -0.463 NA 2.13
#&gt; 2 -0.382 -0.980 NA 0.704
#&gt; 3 0.434 NA -1.06 0.715
df_miss |&gt; filter(is.na(a) &amp; is.na(b) &amp; is.na(c) &amp; is.na(d))
#&gt; # A tibble: 0 × 4
#&gt; # … with 4 variables: a &lt;dbl&gt;, b &lt;dbl&gt;, c &lt;dbl&gt;, d &lt;dbl&gt;
# same as:
df_miss |&gt; filter(if_all(a:d, is.na))
#&gt; # A tibble: 0 × 4
#&gt; # … with 4 variables: a &lt;dbl&gt;, b &lt;dbl&gt;, c &lt;dbl&gt;, d &lt;dbl&gt;</pre>
</div>
</section>
<section id="across-in-functions" data-type="sect2">
<h2>
<code>across()</code> in functions</h2>
<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="r">library(lubridate)
expand_dates &lt;- function(df) {
df |&gt;
mutate(
across(where(is.Date), list(year = year, month = month, day = mday))
)
}
df_date &lt;- tibble(
name = c("Amy", "Bob"),
date = ymd(c("2009-08-03", "2010-01-16"))
)
df_date |&gt;
expand_dates()
#&gt; # A tibble: 2 × 5
#&gt; name date date_year date_month date_day
#&gt; &lt;chr&gt; &lt;date&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt;
#&gt; 1 Amy 2009-08-03 2009 8 3
#&gt; 2 Bob 2010-01-16 2010 1 16</pre>
</div>
<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="r">summarize_means &lt;- function(df, summary_vars = where(is.numeric)) {
df |&gt;
summarize(
across({{ summary_vars }}, \(x) mean(x, na.rm = TRUE)),
n = n()
)
}
diamonds |&gt;
group_by(clarity) |&gt;
summarize_means()
#&gt; # A tibble: 8 × 9
#&gt; clarity carat depth table price x y z n
#&gt; &lt;ord&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt;
#&gt; 1 I1 1.28 62.7 58.3 3924. 6.76 6.71 4.21 741
#&gt; 2 SI2 1.08 61.8 57.9 5063. 6.40 6.40 3.95 9194
#&gt; 3 SI1 0.850 61.9 57.7 3996. 5.89 5.89 3.64 13065
#&gt; 4 VS2 0.764 61.7 57.4 3925. 5.66 5.66 3.49 12258
#&gt; 5 VS1 0.727 61.7 57.3 3839. 5.57 5.58 3.44 8171
#&gt; 6 VVS2 0.596 61.7 57.0 3284. 5.22 5.23 3.22 5066
#&gt; # … with 2 more rows
diamonds |&gt;
group_by(clarity) |&gt;
summarize_means(c(carat, x:z))
#&gt; # A tibble: 8 × 6
#&gt; clarity carat x y z n
#&gt; &lt;ord&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt;
#&gt; 1 I1 1.28 6.76 6.71 4.21 741
#&gt; 2 SI2 1.08 6.40 6.40 3.95 9194
#&gt; 3 SI1 0.850 5.89 5.89 3.64 13065
#&gt; 4 VS2 0.764 5.66 5.66 3.49 12258
#&gt; 5 VS1 0.727 5.57 5.58 3.44 8171
#&gt; 6 VVS2 0.596 5.22 5.23 3.22 5066
#&gt; # … with 2 more rows</pre>
</div>
</section>
<section id="vs-pivot_longer" data-type="sect2">
<h2>
Vs<code>pivot_longer()</code>
</h2>
<p>Before we go on, its 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="r">df |&gt;
summarize(across(a:d, list(median = median, mean = mean)))
#&gt; # A tibble: 1 × 8
#&gt; a_median a_mean b_median b_mean c_median c_mean d_median d_mean
#&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 0.0380 0.205 -0.0163 0.0910 0.260 0.0716 0.540 0.508</pre>
</div>
<p>We could compute the same values by pivoting longer and then summarizing:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">long &lt;- df |&gt;
pivot_longer(a:d) |&gt;
group_by(name) |&gt;
summarize(
median = median(value),
mean = mean(value)
)
long
#&gt; # A tibble: 4 × 3
#&gt; name median mean
#&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 a 0.0380 0.205
#&gt; 2 b -0.0163 0.0910
#&gt; 3 c 0.260 0.0716
#&gt; 4 d 0.540 0.508</pre>
</div>
<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="r">long |&gt;
pivot_wider(
names_from = name,
values_from = c(median, mean),
names_vary = "slowest",
names_glue = "{name}_{.value}"
)
#&gt; # A tibble: 1 × 8
#&gt; a_median a_mean b_median b_mean c_median c_mean d_median d_mean
#&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 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 youll hit a problem thats 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="r">df_paired &lt;- tibble(
a_val = rnorm(10),
a_wts = runif(10),
b_val = rnorm(10),
b_wts = runif(10),
c_val = rnorm(10),
c_wts = runif(10),
d_val = rnorm(10),
d_wts = runif(10)
)</pre>
</div>
<p>Theres 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 dont see how.</span>, but its 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="r">df_long &lt;- df_paired |&gt;
pivot_longer(
everything(),
names_to = c("group", ".value"),
names_sep = "_"
)
df_long
#&gt; # A tibble: 40 × 3
#&gt; group val wts
#&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 a 0.404 0.678
#&gt; 2 b 1.74 0.650
#&gt; 3 c -0.921 0.261
#&gt; 4 d -0.953 0.327
#&gt; 5 a 2.04 0.665
#&gt; 6 b -1.64 0.815
#&gt; # … with 34 more rows
df_long |&gt;
group_by(group) |&gt;
summarize(mean = weighted.mean(val, wts))
#&gt; # A tibble: 4 × 2
#&gt; group mean
#&gt; &lt;chr&gt; &lt;dbl&gt;
#&gt; 1 a 0.109
#&gt; 2 b 0.585
#&gt; 3 c -0.746
#&gt; 4 d -0.0142</pre>
</div>
<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="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 dont name them? How is the output named?</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 its 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 theyve 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><a href="https://tidyselect.r-lib.org/reference/where.html">where()</a></code> are we taking advantage of?</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">show_missing &lt;- function(df, group_vars, summary_vars = everything()) {
df |&gt;
group_by(pick({{ group_vars }})) |&gt;
summarize(
across({{ summary_vars }}, \(x) sum(is.na(x))),
.groups = "drop"
) |&gt;
select(where(\(x) any(x &gt; 0)))
}
nycflights13::flights |&gt; show_missing(c(year, month, day))</pre>
</div>
</li>
</ol></section>
</section>
<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="https://dplyr.tidyverse.org/reference/across.html">dplyr::across()</a></code> to repeat a transformation on multiple columns. In this section, youll 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. Lets 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="r">data2019 &lt;- readxl::read_excel("data/y2019.xlsx")
data2020 &lt;- readxl::read_excel("data/y2020.xlsx")
data2021 &lt;- readxl::read_excel("data/y2021.xlsx")
data2022 &lt;- readxl::read_excel("data/y2022.xlsx")</pre>
</div>
<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="r">data &lt;- 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="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. Well then discuss how you can handle situations of increasing heterogeneity, where you cant 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="https://rdrr.io/r/base/list.files.html">list.files()</a></code> lists the files in a directory. Youll 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 years 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="r">paths &lt;- list.files("data/gapminder", pattern = "[.]xlsx$", full.names = TRUE)
paths
#&gt; [1] "data/gapminder/1952.xlsx" "data/gapminder/1957.xlsx"
#&gt; [3] "data/gapminder/1962.xlsx" "data/gapminder/1967.xlsx"
#&gt; [5] "data/gapminder/1972.xlsx" "data/gapminder/1977.xlsx"
#&gt; [7] "data/gapminder/1982.xlsx" "data/gapminder/1987.xlsx"
#&gt; [9] "data/gapminder/1992.xlsx" "data/gapminder/1997.xlsx"
#&gt; [11] "data/gapminder/2002.xlsx" "data/gapminder/2007.xlsx"</pre>
</div>
</section>
<section id="lists" data-type="sect2">
<h2>
Lists</h2>
<p>Now that we have these 12 paths, we could call <code>read_excel()</code> 12 times to get 12 data frames:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">gapminder_1952 &lt;- readxl::read_excel("data/gapminder/1952.xlsx")
gapminder_1957 &lt;- readxl::read_excel("data/gapminder/1957.xlsx")
gapminder_1962 &lt;- readxl::read_excel("data/gapminder/1962.xlsx")
...,
gapminder_2007 &lt;- readxl::read_excel("data/gapminder/2007.xlsx")</pre>
</div>
<p>But putting each sheet into its own variable is going to make it hard to work with them a few steps down the road. Instead, theyll be easier to work with if we put them into a single object. A list is the perfect tool for this job:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">files &lt;- list(
readxl::read_excel("data/gapminder/1952.xlsx"),
readxl::read_excel("data/gapminder/1957.xlsx"),
readxl::read_excel("data/gapminder/1962.xlsx"),
...,
readxl::read_excel("data/gapminder/2007.xlsx")
)</pre>
</div>
<p>Now that you have these data frames in a list, how do you get one out? You can use <code>files[[i]]</code> to extract the i-th element:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">files[[3]]
#&gt; # A tibble: 142 × 5
#&gt; country continent lifeExp pop gdpPercap
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 Afghanistan Asia 32.0 10267083 853.
#&gt; 2 Albania Europe 64.8 1728137 2313.
#&gt; 3 Algeria Africa 48.3 11000948 2551.
#&gt; 4 Angola Africa 34 4826015 4269.
#&gt; 5 Argentina Americas 65.1 21283783 7133.
#&gt; 6 Australia Oceania 70.9 10794968 12217.
#&gt; # … with 136 more rows</pre>
</div>
<p>Well come back to <code>[[</code> in more detail in <a href="#sec-subset-one" data-type="xref">#sec-subset-one</a>.</p>
</section>
<section id="purrrmap-and-list_rbind" data-type="sect2">
<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="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="r">list(
f(x[[1]]),
f(x[[2]]),
...,
f(x[[n]])
)</pre>
</div>
<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="r">files &lt;- map(paths, readxl::read_excel)
length(files)
#&gt; [1] 12
files[[1]]
#&gt; # A tibble: 142 × 5
#&gt; country continent lifeExp pop gdpPercap
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 Afghanistan Asia 28.8 8425333 779.
#&gt; 2 Albania Europe 55.2 1282697 1601.
#&gt; 3 Algeria Africa 43.1 9279525 2449.
#&gt; 4 Angola Africa 30.0 4232095 3521.
#&gt; 5 Argentina Americas 62.5 17876956 5911.
#&gt; 6 Australia Oceania 69.1 8691212 10040.
#&gt; # … with 136 more rows</pre>
</div>
<p>(This is another data structure that doesnt display particularly compactly with <code><a href="https://rdrr.io/r/utils/str.html">str()</a></code> so you might want to load it 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="r">list_rbind(files)
#&gt; # A tibble: 1,704 × 5
#&gt; country continent lifeExp pop gdpPercap
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 Afghanistan Asia 28.8 8425333 779.
#&gt; 2 Albania Europe 55.2 1282697 1601.
#&gt; 3 Algeria Africa 43.1 9279525 2449.
#&gt; 4 Angola Africa 30.0 4232095 3521.
#&gt; 5 Argentina Americas 62.5 17876956 5911.
#&gt; 6 Australia Oceania 69.1 8691212 10040.
#&gt; # … with 1,698 more rows</pre>
</div>
<p>Or we could do both steps at once in a pipeline:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">paths |&gt;
map(readxl::read_excel) |&gt;
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="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>. For example, its often useful to peak at the first few rows of the data with <code>n_max = 1</code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">paths |&gt;
map(\(path) readxl::read_excel(path, n_max = 1)) |&gt;
list_rbind()
#&gt; # A tibble: 12 × 5
#&gt; country continent lifeExp pop gdpPercap
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 Afghanistan Asia 28.8 8425333 779.
#&gt; 2 Afghanistan Asia 30.3 9240934 821.
#&gt; 3 Afghanistan Asia 32.0 10267083 853.
#&gt; 4 Afghanistan Asia 34.0 11537966 836.
#&gt; 5 Afghanistan Asia 36.1 13079460 740.
#&gt; 6 Afghanistan Asia 38.4 14880372 786.
#&gt; # … with 6 more rows</pre>
</div>
<p>This makes it clear that something is missing: theres no <code>year</code> column because that value is recorded in the path, not the individual files. Well tackle that problem next.</p>
</section>
<section id="sec-data-in-the-path" data-type="sect2">
<h2>
Data in the path</h2>
<p>Sometimes the name of the file is data itself. 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="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="r">paths |&gt; set_names(basename)
#&gt; 1952.xlsx 1957.xlsx
#&gt; "data/gapminder/1952.xlsx" "data/gapminder/1957.xlsx"
#&gt; 1962.xlsx 1967.xlsx
#&gt; "data/gapminder/1962.xlsx" "data/gapminder/1967.xlsx"
#&gt; 1972.xlsx 1977.xlsx
#&gt; "data/gapminder/1972.xlsx" "data/gapminder/1977.xlsx"
#&gt; 1982.xlsx 1987.xlsx
#&gt; "data/gapminder/1982.xlsx" "data/gapminder/1987.xlsx"
#&gt; 1992.xlsx 1997.xlsx
#&gt; "data/gapminder/1992.xlsx" "data/gapminder/1997.xlsx"
#&gt; 2002.xlsx 2007.xlsx
#&gt; "data/gapminder/2002.xlsx" "data/gapminder/2007.xlsx"</pre>
</div>
<p>Those names are automatically carried along by all the map functions, so the list of data frames will have those same names:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">files &lt;- paths |&gt;
set_names(basename) |&gt;
map(readxl::read_excel)</pre>
</div>
<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="r">files &lt;- list(
"1952.xlsx" = readxl::read_excel("data/gapminder/1952.xlsx"),
"1957.xlsx" = readxl::read_excel("data/gapminder/1957.xlsx"),
"1962.xlsx" = readxl::read_excel("data/gapminder/1962.xlsx"),
...,
"2007.xlsx" = readxl::read_excel("data/gapminder/2007.xlsx")
)</pre>
</div>
<p>You can also use <code>[[</code> to extract elements by name:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">files[["1962.xlsx"]]
#&gt; # A tibble: 142 × 5
#&gt; country continent lifeExp pop gdpPercap
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 Afghanistan Asia 32.0 10267083 853.
#&gt; 2 Albania Europe 64.8 1728137 2313.
#&gt; 3 Algeria Africa 48.3 11000948 2551.
#&gt; 4 Angola Africa 34 4826015 4269.
#&gt; 5 Argentina Americas 65.1 21283783 7133.
#&gt; 6 Australia Oceania 70.9 10794968 12217.
#&gt; # … with 136 more rows</pre>
</div>
<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="r">paths |&gt;
set_names(basename) |&gt;
map(readxl::read_excel) |&gt;
list_rbind(names_to = "year") |&gt;
mutate(year = parse_number(year))
#&gt; # A tibble: 1,704 × 6
#&gt; year country continent lifeExp pop gdpPercap
#&gt; &lt;dbl&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 1952 Afghanistan Asia 28.8 8425333 779.
#&gt; 2 1952 Albania Europe 55.2 1282697 1601.
#&gt; 3 1952 Algeria Africa 43.1 9279525 2449.
#&gt; 4 1952 Angola Africa 30.0 4232095 3521.
#&gt; 5 1952 Argentina Americas 62.5 17876956 5911.
#&gt; 6 1952 Australia Oceania 69.1 8691212 10040.
#&gt; # … 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="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="r"># NOTE: this chapter also depends on dev tidyr (in addition to dev purrr and dev dplyr)
paths |&gt;
set_names() |&gt;
map(readxl::read_excel) |&gt;
list_rbind(names_to = "year") |&gt;
separate_wider_delim(year, delim = "/", names = c(NA, "dir", "file")) |&gt;
separate_wider_delim(file, delim = ".", names = c("file", "ext"))
#&gt; # A tibble: 1,704 × 8
#&gt; dir file ext country continent lifeExp pop gdpPercap
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 gapminder 1952 xlsx Afghanistan Asia 28.8 8425333 779.
#&gt; 2 gapminder 1952 xlsx Albania Europe 55.2 1282697 1601.
#&gt; 3 gapminder 1952 xlsx Algeria Africa 43.1 9279525 2449.
#&gt; 4 gapminder 1952 xlsx Angola Africa 30.0 4232095 3521.
#&gt; 5 gapminder 1952 xlsx Argentina Americas 62.5 17876956 5911.
#&gt; 6 gapminder 1952 xlsx Australia Oceania 69.1 8691212 10040.
#&gt; # … with 1,698 more rows</pre>
</div>
</section>
<section id="save-your-work" data-type="sect2">
<h2>
Save your work</h2>
<p>Now that youve done all this hard work to get to a nice tidy data frame, its a great time to save your work:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">gapminder &lt;- paths |&gt;
set_names(basename) |&gt;
map(readxl::read_excel) |&gt;
list_rbind(names_to = "year") |&gt;
mutate(year = parse_number(year))
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 youre working in a project, wed 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="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 weve just loaded the data directly from disk, and were lucky enough to get a tidy dataset. In most cases, youll need to do some additional tidying, and you have two basic options: you can do one round of iteration with a complex function, or do multiple rounds of iteration with simple functions. In our experience most folks reach first for one complex iteration, but youre 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 to 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="r">process_file &lt;- function(path) {
df &lt;- read_csv(path)
df |&gt;
filter(!is.na(id)) |&gt;
mutate(id = tolower(id)) |&gt;
pivot_longer(jan:dec, names_to = "month")
}
paths |&gt;
map(process_file) |&gt;
list_rbind()</pre>
</div>
<p>Alternatively, you could perform each step of <code>process_file()</code> to every file:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">paths |&gt;
map(read_csv) |&gt;
map(\(df) df |&gt; filter(!is.na(id))) |&gt;
map(\(df) df |&gt; mutate(id = tolower(id))) |&gt;
map(\(df) df |&gt; pivot_longer(jan:dec, names_to = "month")) |&gt;
list_rbind()</pre>
</div>
<p>We recommend this approach because it stops you getting fixated on getting the first file right before moving on to the rest. By considering all of the data when doing tidying and cleaning, youre more likely to think holistically and end up with a higher quality result.</p>
<p>In this particular example, theres another optimization you could make, by binding all the data frames together earlier. Then you can rely on regular dplyr behavior:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">paths |&gt;
map(read_csv) |&gt;
list_rbind() |&gt;
filter(!is.na(id)) |&gt;
mutate(id = tolower(id)) |&gt;
pivot_longer(jan:dec, names_to = "month")</pre>
</div>
</section>
<section id="heterogeneous-data" data-type="sect2">
<h2>
Heterogeneous data</h2>
<p>Unfortunately, sometimes its 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 thats not very useful. In that case, its still useful to start by loading all of the files:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">files &lt;- paths |&gt;
map(readxl::read_excel) </pre>
</div>
<p>Then a very useful strategy is to capture the structure of the data frames so that you can explore it using your data science skills. One way to do so is with this handy <code>df_types</code> function that returns a tibble with one row for each column:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">df_types &lt;- function(df) {
tibble(
col_name = names(df),
col_type = map_chr(df, vctrs::vec_ptype_full),
n_miss = map_int(df, \(x) sum(is.na(x)))
)
}
df_types(starwars)
#&gt; # A tibble: 14 × 3
#&gt; col_name col_type n_miss
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;int&gt;
#&gt; 1 name character 0
#&gt; 2 height integer 6
#&gt; 3 mass double 28
#&gt; 4 hair_color character 5
#&gt; 5 skin_color character 0
#&gt; 6 eye_color character 0
#&gt; # … with 8 more rows
df_types(nycflights13::flights)
#&gt; # A tibble: 19 × 3
#&gt; col_name col_type n_miss
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;int&gt;
#&gt; 1 year integer 0
#&gt; 2 month integer 0
#&gt; 3 day integer 0
#&gt; 4 dep_time integer 8255
#&gt; 5 sched_dep_time integer 0
#&gt; 6 dep_delay double 8255
#&gt; # … with 13 more rows</pre>
</div>
<p>You can then apply this function to all of the files, and maybe do some pivoting to make it easier to see where the differences are. For example, this makes it easy to verify that the gapminder spreadsheets that weve been working with are all quite homogeneous:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">files |&gt;
map(df_types) |&gt;
list_rbind(names_to = "file_name") |&gt;
select(-n_miss) |&gt;
pivot_wider(names_from = col_name, values_from = col_type)
#&gt; # A tibble: 12 × 6
#&gt; file_name country continent lifeExp pop gdpPercap
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt;
#&gt; 1 1952.xlsx character character double double double
#&gt; 2 1957.xlsx character character double double double
#&gt; 3 1962.xlsx character character double double double
#&gt; 4 1967.xlsx character character double double double
#&gt; 5 1972.xlsx character character double double double
#&gt; 6 1977.xlsx character character double double double
#&gt; # … 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, were 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 cant even read all the files with a single command. And then youll 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 whats 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="r">files &lt;- paths |&gt;
map(possibly(\(path) readxl::read_excel(path), NULL))
data &lt;- files |&gt; list_rbind()</pre>
</div>
<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 its time to tackle the hard part of figuring out why some files failed to 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="r">failed &lt;- map_vec(files, is.null)
paths[failed]
#&gt; character(0)</pre>
</div>
<p>Then call the import function again for each failure and figure out what went wrong.</p>
</section>
</section>
<section id="saving-multiple-outputs" data-type="sect1">
<h1>
Saving multiple outputs</h1>
<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, well now explore sort of the opposite problem: how can you take one or more R objects and save it to one or more files? Well explore this challenge using three examples:</p>
<ul><li>Saving multiple data frames into one database.</li>
<li>Saving multiple data frames into multiple <code>.csv</code> files.</li>
<li>Saving multiple plots to multiple <code>.png</code> files.</li>
</ul>
<section id="sec-save-database" data-type="sect2">
<h2>
Writing to a database</h2>
<p>Sometimes when working with many files at once, its not possible to fit all your data into memory at once, and you cant do <code>map(files, read_csv)</code>. One approach to deal with this problem is to load your data into a database so you can access just the bits you need with dbplyr.</p>
<p>If youre lucky, the database package youre using will provide a handy function that takes a vector of paths and loads them all into the database. This is the case with duckdbs <code>duckdb_read_csv()</code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">con &lt;- DBI::dbConnect(duckdb::duckdb())
duckdb::duckdb_read_csv(con, "gapminder", paths)</pre>
</div>
<p>This would work well here, but we dont have csv files, instead we have excel spreadsheets. So were going to have to do it “by hand”. Learning to do it by hand will also help you when you have a bunch of csvs and the database that youre working with doesnt have one function that will load them all in.</p>
<p>We need to start by creating a table that will fill in with data. The easiest way to do this is by creating a template, a dummy data frame that contains all the columns we want, but only a sampling of the data. For the gapminder data, we can make that template by reading a single file and adding the year to it:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">template &lt;- readxl::read_excel(paths[[1]])
template$year &lt;- 1952
template
#&gt; # A tibble: 142 × 6
#&gt; country continent lifeExp pop gdpPercap year
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 Afghanistan Asia 28.8 8425333 779. 1952
#&gt; 2 Albania Europe 55.2 1282697 1601. 1952
#&gt; 3 Algeria Africa 43.1 9279525 2449. 1952
#&gt; 4 Angola Africa 30.0 4232095 3521. 1952
#&gt; 5 Argentina Americas 62.5 17876956 5911. 1952
#&gt; 6 Australia Oceania 69.1 8691212 10040. 1952
#&gt; # … with 136 more rows</pre>
</div>
<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 a database table:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">con &lt;- DBI::dbConnect(duckdb::duckdb())
DBI::dbCreateTable(con, "gapminder", template)</pre>
</div>
<p><code>dbCreateTable()</code> doesnt use the data in <code>template</code>, just the variable names and types. So if we inspect the <code>gapminder</code> table now youll see that its empty but it has the variables we need with the types we expect:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">con |&gt; tbl("gapminder")
#&gt; # Source: table&lt;gapminder&gt; [0 x 6]
#&gt; # Database: DuckDB 0.6.1 [root@Darwin 22.1.0:R 4.2.1/:memory:]
#&gt; # … with 6 variables: country &lt;chr&gt;, continent &lt;chr&gt;, lifeExp &lt;dbl&gt;,
#&gt; # pop &lt;dbl&gt;, gdpPercap &lt;dbl&gt;, year &lt;dbl&gt;</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="https://dbi.r-dbi.org/reference/dbAppendTable.html">DBI::dbAppendTable()</a></code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">append_file &lt;- function(path) {
df &lt;- readxl::read_excel(path)
df$year &lt;- parse_number(basename(path))
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>. Thats 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="r">paths |&gt; map(append_file)</pre>
</div>
<p>But we dont 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> its 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="r">paths |&gt; walk(append_file)</pre>
</div>
<p>Now we can see if we have all the data in our table:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">con |&gt;
tbl("gapminder") |&gt;
count(year)
#&gt; # Source: SQL [?? x 2]
#&gt; # Database: DuckDB 0.6.1 [root@Darwin 22.1.0:R 4.2.1/:memory:]
#&gt; year n
#&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 1952 142
#&gt; 2 1957 142
#&gt; 3 1962 142
#&gt; 4 1967 142
#&gt; 5 1972 142
#&gt; 6 1977 142
#&gt; # … with more rows</pre>
</div>
</section>
<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. Lets 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 theres 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="r">by_clarity &lt;- diamonds |&gt;
group_nest(clarity)
by_clarity
#&gt; # A tibble: 8 × 2
#&gt; clarity data
#&gt; &lt;ord&gt; &lt;list&lt;tibble[,9]&gt;&gt;
#&gt; 1 I1 [741 × 9]
#&gt; 2 SI2 [9,194 × 9]
#&gt; 3 SI1 [13,065 × 9]
#&gt; 4 VS2 [12,258 × 9]
#&gt; 5 VS1 [8,171 × 9]
#&gt; 6 VVS2 [5,066 × 9]
#&gt; # … with 2 more rows</pre>
</div>
<p>This gives us a new tibble with eight rows and two columns. <code>clarity</code> is our grouping variable and <code>data</code> is a list-column containing one tibble for each unique value of <code>clarity</code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">by_clarity$data[[1]]
#&gt; # A tibble: 741 × 9
#&gt; carat cut color depth table price x y z
#&gt; &lt;dbl&gt; &lt;ord&gt; &lt;ord&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
#&gt; 1 0.32 Premium E 60.9 58 345 4.38 4.42 2.68
#&gt; 2 1.17 Very Good J 60.2 61 2774 6.83 6.9 4.13
#&gt; 3 1.01 Premium F 61.8 60 2781 6.39 6.36 3.94
#&gt; 4 1.01 Fair E 64.5 58 2788 6.29 6.21 4.03
#&gt; 5 0.96 Ideal F 60.7 55 2801 6.37 6.41 3.88
#&gt; 6 1.04 Premium G 62.2 58 2801 6.46 6.41 4
#&gt; # … with 735 more rows</pre>
</div>
<p>While were 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="r">by_clarity &lt;- by_clarity |&gt;
mutate(path = str_glue("diamonds-{clarity}.csv"))
by_clarity
#&gt; # A tibble: 8 × 3
#&gt; clarity data path
#&gt; &lt;ord&gt; &lt;list&lt;tibble[,9]&gt;&gt; &lt;glue&gt;
#&gt; 1 I1 [741 × 9] diamonds-I1.csv
#&gt; 2 SI2 [9,194 × 9] diamonds-SI2.csv
#&gt; 3 SI1 [13,065 × 9] diamonds-SI1.csv
#&gt; 4 VS2 [12,258 × 9] diamonds-VS2.csv
#&gt; 5 VS1 [8,171 × 9] diamonds-VS1.csv
#&gt; 6 VVS2 [5,066 × 9] diamonds-VVS2.csv
#&gt; # … with 2 more rows</pre>
</div>
<p>So if we were going to save these data frames by hand, we might write something like:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">write_csv(by_clarity$data[[1]], by_clarity$path[[1]])
write_csv(by_clarity$data[[2]], by_clarity$path[[2]])
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="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 dont 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="r">walk2(by_clarity$data, by_clarity$path, write_csv)</pre>
</div>
</section>
<section id="saving-plots" data-type="sect2">
<h2>
Saving plots</h2>
<p>We can take the same basic approach to create many plots. Lets first make a function that draws the plot we want:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">carat_histogram &lt;- function(df) {
ggplot(df, aes(x = carat)) + geom_histogram(binwidth = 0.1)
}
carat_histogram(by_clarity$data[[1]])</pre>
<div class="cell-output-display">
<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="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 — youll get one plot for each element of <code>plots</code>. NOTE: this didnt happen for me.</span> and their eventual file paths:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">by_clarity &lt;- by_clarity |&gt;
mutate(
plot = map(data, carat_histogram),
path = str_glue("clarity-{clarity}.png")
)</pre>
</div>
<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="r">walk2(
by_clarity$path,
by_clarity$plot,
\(path, plot) ggsave(path, plot, width = 6, height = 6)
)</pre>
</div>
<p>This is shorthand for:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">ggsave(by_clarity$path[[1]], by_clarity$plot[[1]], width = 6, height = 6)
ggsave(by_clarity$path[[2]], by_clarity$plot[[2]], width = 6, height = 6)
ggsave(by_clarity$path[[3]], by_clarity$plot[[3]], width = 6, height = 6)
...
ggsave(by_clarity$path[[8]], by_clarity$plot[[8]], width = 6, height = 6)</pre>
</div>
<!--
### Exercises
1. Imagine you have a table of student data containing (amongst other variables) `school_name` and `student_id`. Sketch out what code you'd write if you want to save all the information for each student in file called `{student_id}.csv` in the `{school}` directory.
-->
</section>
</section>
<section id="summary" data-type="sect1">
<h1>
Summary</h1>
<p>In this chapter, youve 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 youve 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 didnt discuss the <code>for</code> loop. Thats because Rs 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 cant, 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 youll learn about them in the next chapter where well discuss some important base R tools.</p>
</section>
</section>