<h1><spanid="sec-base-r"class="quarto-section-identifier d-none d-lg-block"><spanclass="chapter-title">A field guide to base R</span></span></h1><p>To finish off the programming section, we’re going to give you a quick tour of the most important base R functions that we don’t otherwise discuss in the book. These tools are particularly useful as you do more programming and will help you read code that you’ll encounter in the wild.</p><p>This is a good place to remind you that the tidyverse is not the only way to solve data science problems. We teach the tidyverse in this book because tidyverse packages share a common design philosophy, which increases the consistency across functions, making each new function or package a little easier to learn and use. It’s not possible to use the tidyverse without using base R, so we’ve actually already taught you a <strong>lot</strong> of base R functions: from <code><ahref="https://rdrr.io/r/base/library.html">library()</a></code> to load packages, to <code><ahref="https://rdrr.io/r/base/sum.html">sum()</a></code> and <code><ahref="https://rdrr.io/r/base/mean.html">mean()</a></code> for numeric summaries, to the factor, date, and POSIXct data types, and of course all the basic operators like <code>+</code>, <code>-</code>, <code>/</code>, <code>*</code>, <code>|</code>, <code>&</code>, and <code>!</code>. What we haven’t focused on so far is base R workflows, so we will highlight a few of those in this chapter.</p><p>After you read this book you’ll learn other approaches to the same problems using base R, data.table, and other packages. You’ll certainly encounter these other approaches when you start reading R code written by other people, particularly if you’re using StackOverflow. It’s 100% okay to write code that uses a mix of approaches, and don’t let anyone tell you otherwise!</p><p>In this chapter, we’ll focus on four big topics: subsetting with <code>[</code>, subsetting with <code>[[</code> and <code>$</code>, the apply family of functions, and <code>for</code> loops. To finish off, we’ll briefly discuss two important plotting functions.</p>
<p><code>[</code> is used to extract sub-components from vectors and data frames, and is called like <code>x[i]</code> or <code>x[i, j]</code>. In this section, we’ll introduce you to the power of <code>[</code>, first showing you how you can use it with vectors, then how the same principles extend in a straightforward way to two-dimensional (2d) structures like data frames. We’ll then help you cement that knowledge by showing how various dplyr verbs are special cases of <code>[</code>.</p>
<sectionid="subsetting-vectors"data-type="sect2">
<h2>
Subsetting vectors</h2>
<p>There are five main types of things that you can subset a vector with, i.e.that can be the <code>i</code> in <code>x[i]</code>:</p>
<oltype="1"><li>
<p><strong>A vector of positive integers</strong>. Subsetting with positive integers keeps the elements at those positions:</p>
<p><strong>A logical vector</strong>. Subsetting with a logical vector keeps all values corresponding to a <code>TRUE</code> value. This is most often useful in conjunction with the comparison functions.</p>
<p>Note that, unlike <code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code>, <code>NA</code> indices will be included in the output as <code>NA</code>s.</p>
<p>As with subsetting with positive integers, you can use a character vector to duplicate individual entries.</p>
</li>
<li><p><strong>Nothing</strong>. The final type of subsetting is nothing, <code>x[]</code>, which returns the complete <code>x</code>. This is not useful for subsetting vectors, but as we’ll see shortly it is useful when subsetting 2d structures like tibbles.</p></li>
<p>There are quite a few different ways<spandata-type="footnote">Read <ahref="https://adv-r.hadley.nz/subsetting.html#subset-multiple"class="uri">https://adv-r.hadley.nz/subsetting.html#subset-multiple</a> to see how you can also subset a data frame like it is a 1d object and how you can subset it with a matrix.</span> that you can use <code>[</code> with a data frame, but the most important way is to select rows and columns independently with <code>df[rows, cols]</code>. Here <code>rows</code> and <code>cols</code> are vectors as described above. For example, <code>df[rows, ]</code> and <code>df[, cols]</code> select just rows or just columns, using the empty subset to preserve the other dimension.</p>
# Select rows where `x` is greater than 1 and all columns
df[df$x > 1, ]
#> # A tibble: 2 × 3
#> x y z
#><int><chr><dbl>
#> 1 2 e 0.834
#> 2 3 f 0.601</pre>
</div>
<p>We’ll come back to <code>$</code> shortly, but you should be able to guess what <code>df$x</code> does from the context: it extracts the <code>x</code> variable from <code>df</code>. We need to use it here because <code>[</code> doesn’t use tidy evaluation, so you need to be explicit about the source of the <code>x</code> variable.</p>
<p>There’s an important difference between tibbles and data frames when it comes to <code>[</code>. In this book we’ve mostly used tibbles, which <em>are</em> data frames, but they tweak some older behaviors to make your life a little easier. In most places, you can use “tibble” and “data frame” interchangeably, so when we want to draw particular attention to R’s built-in data frame, we’ll write <code>data.frame</code>. If <code>df</code> is a <code>data.frame</code>, then <code>df[, cols]</code> will return a vector if <code>col</code> selects a single column and a data frame if it selects more than one column. If <code>df</code> is a tibble, then <code>[</code> will always return a tibble.</p>
<p><code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code> is equivalent to subsetting the rows with a logical vector, taking care to exclude missing values:</p>
<p>Another common technique in the wild is to use <code><ahref="https://rdrr.io/r/base/which.html">which()</a></code> for its side-effect of dropping missing values: <code>df[which(df$x > 1), ]</code>.</p>
<p><code><ahref="https://dplyr.tidyverse.org/reference/arrange.html">arrange()</a></code> is equivalent to subsetting the rows with an integer vector, usually created with <code><ahref="https://rdrr.io/r/base/order.html">order()</a></code>:</p>
<p>You can use <code>order(decreasing = TRUE)</code> to sort all columns in descending order or <code>-rank(col)</code> to individually sort columns in decreasing order.</p>
<p>Both <code><ahref="https://dplyr.tidyverse.org/reference/select.html">select()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/relocate.html">relocate()</a></code> are similar to subsetting the columns with a character vector:</p>
</ul><p>Base R also provides a function that combines the features of <code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code> and <code><ahref="https://dplyr.tidyverse.org/reference/select.html">select()</a></code><spandata-type="footnote">But it doesn’t handle grouped data frames differently and it doesn’t support selection helper functions like <code><ahref="https://tidyselect.r-lib.org/reference/starts_with.html">starts_with()</a></code>.</span> called <code><ahref="https://rdrr.io/r/base/subset.html">subset()</a></code>:</p>
<li><p>Why is <code>x[-which(x > 0)]</code> not the same as <code>x[x <= 0]</code>? Read the documentation for <code><ahref="https://rdrr.io/r/base/which.html">which()</a></code> and do some experiments to figure it out.</p></li>
<p><code>[</code>, which selects many elements, is paired with <code>[[</code> and <code>$</code>, which extract a single element. In this section, we’ll show you how to use <code>[[</code> and <code>$</code> to pull columns out of data frames, discuss a couple more differences between <code>data.frames</code> and tibbles, and emphasize some important differences between <code>[</code> and <code>[[</code> when used with lists.</p>
<p><code>[[</code> and <code>$</code> can be used to extract columns out of a data frame. <code>[[</code> can access by position or by name, and <code>$</code> is specialized for access by name:</p>
<p>They can also be used to create new columns, the base R equivalent of <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>:</p>
<p>There are a number of other base R approaches to creating new columns including with <code><ahref="https://rdrr.io/r/base/transform.html">transform()</a></code>, <code><ahref="https://rdrr.io/r/base/with.html">with()</a></code>, and <code><ahref="https://rdrr.io/r/base/with.html">within()</a></code>. Hadley collected a few examples at <ahref="https://gist.github.com/hadley/1986a273e384fb2d4d752c18ed71bedf"class="uri">https://gist.github.com/hadley/1986a273e384fb2d4d752c18ed71bedf</a>.</p>
<p>Using <code>$</code> directly is convenient when performing quick summaries. For example, if you just want to find the size of the biggest diamond or the possible values of <code>cut</code>, there’s no need to use <code><ahref="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code>:</p>
<p>dplyr also provides an equivalent to <code>[[</code>/<code>$</code> that we didn’t mention in <ahref="#chp-data-transform"data-type="xref">#chp-data-transform</a>: <code><ahref="https://dplyr.tidyverse.org/reference/pull.html">pull()</a></code>. <code><ahref="https://dplyr.tidyverse.org/reference/pull.html">pull()</a></code> takes either a variable name or variable position and returns just that column. That means we could rewrite the above code to use the pipe:</p>
<p>There are a couple of important differences between tibbles and base <code>data.frame</code>s when it comes to <code>$</code>. Data frames match the prefix of any variable names (so-called <strong>partial matching</strong>) and don’t complain if a column doesn’t exist:</p>
#> Warning in df$x: partial match of 'x' to 'x1'
#> [1] 1
df$z
#> NULL</pre>
</div>
<p>Tibbles are more strict: they only ever match variable names exactly and they will generate a warning if the column you are trying to access doesn’t exist:</p>
<p><code>[[</code> and <code>$</code> are also really important for working with lists, and it’s important to understand how they differ from <code>[</code>. Lets illustrate the differences with a list named <code>l</code>:</p>
</ul><p>The difference between <code>[</code> and <code>[[</code> is particularly important for lists because <code>[[</code> drills down into the list while <code>[</code> returns a new, smaller list. To help you remember the difference, take a look at the an unusual pepper shaker shown in <ahref="#fig-pepper-1"data-type="xref">#fig-pepper-1</a>. If this pepper shaker is your list <code>pepper</code>, then, <code>pepper[1]</code> is a pepper shaker containing a single pepper packet, as in <ahref="#fig-pepper-2"data-type="xref">#fig-pepper-2</a>. If we suppose this pepper shaker is a list <code>pepper</code>, then, <code>pepper[1]</code> is a pepper shaker containing a single pepper packet, as in <ahref="#fig-pepper-2"data-type="xref">#fig-pepper-2</a>. <code>pepper[2]</code> would look the same, but would contain the second packet. <code>pepper[1:2]</code> would be a pepper shaker containing two pepper packets. <code>pepper[[1]]</code> would extract the pepper packet itself, as in <ahref="#fig-pepper-3"data-type="xref">#fig-pepper-3</a>.</p>
<figureid="fig-pepper-1"><p><imgsrc="images/pepper.jpg"style="width:25.0%"alt="A photo of a glass pepper shaker. Instead of the pepper shaker containing pepper, it contains many packets of pepper."/></p>
<figcaption>A pepper shaker that Hadley once found in his hotel room.</figcaption>
<figureid="fig-pepper-2"><p><imgsrc="images/pepper-1.jpg"style="width:25.0%"alt="A photo of the glass pepper shaker containing just one packet of pepper."/></p>
<oltype="1"><li><p>What happens when you use <code>[[</code> with a positive integer that’s bigger than the length of the vector? What happens when you subset with a name that doesn’t exist?</p></li>
<li><p>What would <code>pepper[[1]][1]</code> be? What about <code>pepper[[1]][[1]]</code>?</p></li>
<p>In <ahref="#chp-iteration"data-type="xref">#chp-iteration</a>, you learned tidyverse techniques for iteration like <code><ahref="https://dplyr.tidyverse.org/reference/across.html">dplyr::across()</a></code> and the map family of functions. In this section, you’ll learn about their base equivalents, the <strong>apply family</strong>. In this context apply and map are synonyms because another way of saying “map a function over each element of a vector” is “apply a function over each element of a vector”. Here we’ll give you a quick overview of this family so you can recognize them in the wild.</p>
<p>The most important member of this family is <code><ahref="https://rdrr.io/r/base/lapply.html">lapply()</a></code>, which is very similar to <code><ahref="https://purrr.tidyverse.org/reference/map.html">purrr::map()</a></code><spandata-type="footnote">It just lacks convenient features like progress bars and reporting which element caused the problem if there’s an error.</span>. In fact, because we haven’t used any of <code><ahref="https://purrr.tidyverse.org/reference/map.html">map()</a></code>’s more advanced features, you can replace every <code><ahref="https://purrr.tidyverse.org/reference/map.html">map()</a></code> call in <ahref="#chp-iteration"data-type="xref">#chp-iteration</a> with <code><ahref="https://rdrr.io/r/base/lapply.html">lapply()</a></code>.</p>
<p>There’s no exact base R equivalent to <code><ahref="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> but you can get close by using <code>[</code> with <code><ahref="https://rdrr.io/r/base/lapply.html">lapply()</a></code>. This works because under the hood, data frames are lists of columns, so calling <code><ahref="https://rdrr.io/r/base/lapply.html">lapply()</a></code> on a data frame applies the function to each column.</p>
<p>The code above uses a new function, <code><ahref="https://rdrr.io/r/base/lapply.html">sapply()</a></code>. It’s similar to <code><ahref="https://rdrr.io/r/base/lapply.html">lapply()</a></code> but it always tries to simplify the result, hence the <code>s</code> in its name, here producing a logical vector instead of a list. We don’t recommend using it for programming, because the simplification can fail and give you an unexpected type, but it’s usually fine for interactive use. purrr has a similar function called <code><ahref="https://purrr.tidyverse.org/reference/map.html">map_vec()</a></code> that we didn’t mention in <ahref="#chp-iteration"data-type="xref">#chp-iteration</a>.</p>
<p>Base R provides a stricter version of <code><ahref="https://rdrr.io/r/base/lapply.html">sapply()</a></code> called <code><ahref="https://rdrr.io/r/base/lapply.html">vapply()</a></code>, short for <strong>v</strong>ector apply. It takes an additional argument that specifies the expected type, ensuring that simplification occurs the same way regardless of the input. For example, we could replace the <code><ahref="https://rdrr.io/r/base/lapply.html">sapply()</a></code> call above with this <code><ahref="https://rdrr.io/r/base/lapply.html">vapply()</a></code> where we specify that we expect <code><ahref="https://rdrr.io/r/base/numeric.html">is.numeric()</a></code> to return a logical vector of length 1:</p>
<p>The distinction between <code><ahref="https://rdrr.io/r/base/lapply.html">sapply()</a></code> and <code><ahref="https://rdrr.io/r/base/lapply.html">vapply()</a></code> is really important when they’re inside a function (because it makes a big difference to the function’s robustness to unusual inputs), but it doesn’t usually matter in data analysis.</p>
<p>Another important member of the apply family is <code><ahref="https://rdrr.io/r/base/tapply.html">tapply()</a></code> which computes a single grouped summary:</p>
<p>Unfortunately <code><ahref="https://rdrr.io/r/base/tapply.html">tapply()</a></code> returns its results in a named vector which requires some gymnastics if you want to collect multiple summaries and grouping variables into a data frame (it’s certainly possible to not do this and just work with free floating vectors, but in our experience that just delays the work). If you want to see how you might use <code><ahref="https://rdrr.io/r/base/tapply.html">tapply()</a></code> or other base techniques to perform other grouped summaries, Hadley has collected a few techniques <ahref="https://gist.github.com/hadley/c430501804349d382ce90754936ab8ec">in a gist</a>.</p>
<p>The final member of the apply family is the titular <code><ahref="https://rdrr.io/r/base/apply.html">apply()</a></code>, which works with matrices and arrays. In particular, watch out for <code>apply(df, 2, something)</code>, which is a slow and potentially dangerous way of doing <code>lapply(df, something)</code>. This rarely comes up in data science because we usually work with data frames and not matrices.</p>
<p><code>for</code> loops are the fundamental building block of iteration that both the apply and map families use under the hood. <code>for</code> loops are powerful and general tools that are important to learn as you become a more experienced R programmer. The basic structure of a <code>for</code> loop looks like this:</p>
<p>The most straightforward use of <code>for</code> loops is to achieve the same affect as <code><ahref="https://purrr.tidyverse.org/reference/map.html">walk()</a></code>: call some function with a side-effect on each element of a list. For example, in <ahref="#sec-save-database"data-type="xref">#sec-save-database</a> instead of using walk:</p>
<p>Things get a little trickier if you want to save the output of the <code>for</code> loop, for example reading all of the excel files in a directory like we did in <ahref="#chp-iteration"data-type="xref">#chp-iteration</a>:</p>
<p>There are a few different techniques that you can use, but we recommend being explicit about what the output is going to look like upfront. In this case, we’re going to want a list the same length as <code>paths</code>, which we can create with <code><ahref="https://rdrr.io/r/base/vector.html">vector()</a></code>:</p>
<p>Then instead of iterating over the elements of <code>paths</code>, we’ll iterate over their indices, using <code><ahref="https://rdrr.io/r/base/seq.html">seq_along()</a></code> to generate one index for each element of paths:</p>
<p>To combine the list of tibbles into a single tibble you can use <code><ahref="https://rdrr.io/r/base/do.call.html">do.call()</a></code> + <code><ahref="https://rdrr.io/r/base/cbind.html">rbind()</a></code>:</p>
<p>We recommend avoiding this pattern because it can become very slow when the vector is very long. This is the source of the persistent canard that <code>for</code> loops are slow: they’re not, but iteratively growing a vector is.</p>
<p>Many R users who don’t otherwise use the tidyverse prefer ggplot2 for plotting due to helpful features like sensible defaults, automatic legends, and a modern look. However, base R plotting functions can still be useful because they’re so concise — it takes very little typing to do a basic exploratory plot.</p>
<p>There are two main types of base plot you’ll see in the wild: scatterplots and histograms, produced with <code><ahref="https://rdrr.io/r/graphics/plot.default.html">plot()</a></code> and <code><ahref="https://rdrr.io/r/graphics/hist.html">hist()</a></code> respectively. Here’s a quick example from the diamonds dataset:</p>
<p>Note that base plotting functions work with vectors, so you need to pull columns out of the data frame using <code>$</code> or some other technique.</p>
<p>In this chapter, we’ve shown you a selection of base R functions useful for subsetting and iteration. Compared to approaches discussed elsewhere in the book, these functions tend to have more of a “vector” flavor than a “data frame” flavor because base R functions tend to take individual vectors, rather than a data frame and some column specification. This often makes life easier for programming and so becomes more important as you write more functions and begin to write your own packages.</p>
<p>This chapter concludes the programming section of the book. You’ve made a solid start on your journey to becoming not just a data scientist who uses R, but a data scientist who can <em>program</em> in R. We hope these chapters have sparked your interested in programming and that you’re looking forward to learning more outside of this book.</p>