# 5 Subsetting

## 5.1 Introduction

R’s subsetting operators are powerful and fast. Mastery of subsetting allows you to succinctly express complex operations in a way that few other languages can match. Subsetting is hard to learn because you need to master a number of interrelated concepts:

• The three subsetting operators.

• The six types of subsetting.

• Important differences in behaviour for different objects (e.g., vectors, lists, factors, matrices, and data frames).

• The use of subsetting in conjunction with assignment.

This chapter helps you master subsetting by starting with the simplest type of subsetting: subsetting an atomic vector with [. It then gradually extends your knowledge, first to more complicated data types (like arrays and lists), and then to the other subsetting operators, [[ and $. You’ll then learn how subsetting and assignment can be combined to modify parts of an object, and, finally, you’ll see a large number of useful applications. Subsetting is a natural complement to str(). str() shows you the structure of any object, and subsetting allows you to pull out the pieces that you’re interested in. ### Quiz Take this short quiz to determine if you need to read this chapter. If the answers quickly come to mind, you can comfortably skip this chapter. Check your answers in answers. 1. What is the result of subsetting a vector with positive integers, negative integers, a logical vector, or a character vector? 2. What’s the difference between [, [[, and$ when applied to a list?

3. When should you use drop = FALSE?

4. If x is a matrix, what does x[] <- 0 do? How is it different to x <- 0?

5. How can you use a named vector to relabel categorical variables?

### Outline

• Data types starts by teaching you about [. You’ll start by learning the six types of data that you can use to subset atomic vectors. You’ll then learn how those six data types act when used to subset lists, matrices, data frames, and S3 objects.

• Subsetting operators expands your knowledge of subsetting operators to include [[ and $, focussing on the important principles of simplifying vs. preserving. • In Subsetting and assignment you’ll learn the art of subassignment, combining subsetting and assignment to modify parts of an object. • Applications leads you through eight important, but not obvious, applications of subsetting to solve problems that you often encounter in a data analysis. ## 5.2 Selecting multiple elements It’s easiest to learn how subsetting works for atomic vectors, and then how it generalises to higher dimensions and other more complicated objects. We’ll start with [, the most commonly used operator which allows you to extract any number of elements. Selecting a single element will cover [[ and$, used to extra a single element from a data structure.

### 5.2.1 Atomic vectors

Let’s explore the different types of subsetting with a simple vector, x.

Note that the number after the decimal point gives the original position in the vector.

There are five things that you can use to subset a vector:

If the vector is named, you can also use:

$is a shorthand operator: x$y is roughly equivalent to x[["y"]]. It’s often used to access variables in a data frame, as in mtcars$cyl or diamonds$carat. One common mistake with $is to try and use it when you have the name of a column stored in a variable: There’s one important difference between$ and [[. $does partial matching: To help avoid this behaviour I highly recommend setting the global option warnPartialMatchDollar to TRUE: (For data frames specifically, you can avoid this problem by using tibbles instead: they never do partial matching.) ### 5.3.2 Missing/out of bounds indices It’s useful to understand what happens with [ and [[ when you use an “invalid” index. The following tables summarise what happen when you subset a logical vector, list, and NULL with an out-of-bounds value (OOB), a missing value (i.e NA_integer_), and a zero-length object (like NULL or logical()) with [ and [[. Each cell shows the result of subsetting the data structure named in the row by the type of index described in the column. I’ve only shown the results for logical vectors, but other atomic vectors behave similarly, returning elements of the same type. row[col] Zero-length OOB Missing NULL NULL NULL NULL Logical logical(0) NA NA List list() list(NULL) list(NULL) With [, it doesn’t matter whether the OOB index is a position or a name, but it does for [[: row[[col]] Zero-length OOB (int) OOB (chr) Missing NULL NULL NULL NULL NULL Atomic Error Error Error Error List Error Error NULL NULL If the input vector is named, then the names of OOB, missing, or NULL components will be "<NA>". ### 5.3.3pluck() The inconsistency of the [[ table above lead to the development of purrr::pluck(), which solves the inconsistency by always returning NULL: pluck(row, col) Zero-length OOB (int) OOB (chr) Missing NULL NULL NULL NULL NULL Atomic NULL NULL NULL NULL List NULL NULL NULL NULL (A future function will solve the inconsistency in the other direction: by consistently throwing an error whenever the component is absent.) The behaviour of pluck() makes it well suited for indexing into deeply nested data structures where the component you want does not exist always exist (this is common when working with JSON data from web APIs). pluck() also allows you to mingle integer and character indexes, and to provide an alternative default value if the item does not exist: ### 5.3.4 Exercises 1. Come up with as many way as possible to extract the third value from the cyl variable in the mtcars dataset. 2. Given a linear model, e.g., mod <- lm(mpg ~ wt, data = mtcars), extract the residual degrees of freedom. Extract the R squared from the model summary (summary(mod)) ## 5.4 Subsetting and assignment All subsetting operators can be combined with assignment to modify selected values of the input vector. Subsetting with nothing can be useful in conjunction with assignment because it will preserve the original object class and structure. Compare the following two expressions. In the first, mtcars will remain as a data frame. In the second, mtcars will become a list. With lists, you can use [[ + assignment + NULL to remove components from a list. To add a literal NULL to a list, use [ and list(NULL): ## 5.5 Applications The basic principles described above give rise to a wide variety of useful applications. Some of the most important are described below. Many of these basic techniques are wrapped up into more concise functions (e.g., subset(), merge(), dplyr::arrange()), but it is useful to understand how they are implemented with basic subsetting. This will allow you to adapt to new situations that are not dealt with by existing functions. ### 5.5.1 Lookup tables (character subsetting) Character matching provides a powerful way to make lookup tables. Say you want to convert abbreviations: If you don’t want names in the result, use unname() to remove them. ### 5.5.2 Matching and merging by hand (integer subsetting) You may have a more complicated lookup table which has multiple columns of information. Suppose we have a vector of integer grades, and a table that describes their properties: We want to duplicate the info table so that we have a row for each value in grades. An elegant way to do this is by combining match() and integer subsetting: If you have multiple columns to match on, you’ll need to first collapse them to a single column (with e.g. interaction()), but typically you are better off switching to a function design specifically for joining multiple tables like merge(), or dplyr::left_join(). ### 5.5.3 Random samples/bootstrap (integer subsetting) You can use integer indices to perform random sampling or bootstrapping of a vector or data frame. sample() generates a vector of indices, then subsetting accesses the values: The arguments of sample() control the number of samples to extract, and whether sampling is performed with or without replacement. ### 5.5.4 Ordering (integer subsetting) order() takes a vector as input and returns an integer vector describing how the subsetted vector should be ordered: To break ties, you can supply additional variables to order(), and you can change from ascending to descending order using decreasing = TRUE. By default, any missing values will be put at the end of the vector; however, you can remove them with na.last = NA or put at the front with na.last = FALSE. For two or more dimensions, order() and integer subsetting makes it easy to order either the rows or columns of an object: You can sort vectors directly with sort(), or use dplyr::arrange() or similar to sort a data frame. ### 5.5.5 Expanding aggregated counts (integer subsetting) Sometimes you get a data frame where identical rows have been collapsed into one and a count column has been added. rep() and integer subsetting make it easy to uncollapse the data by subsetting with a repeated row index: ### 5.5.6 Removing columns from data frames (character subsetting) There are two ways to remove columns from a data frame. You can set individual columns to NULL: Or you can subset to return only the columns you want: If you know the columns you don’t want, use set operations to work out which colums to keep: ### 5.5.7 Selecting rows based on a condition (logical subsetting) Because it allows you to easily combine conditions from multiple columns, logical subsetting is probably the most commonly used technique for extracting rows out of a data frame. Remember to use the vector boolean operators & and |, not the short-circuiting scalar operators && and || which are more useful inside if statements. Don’t forget De Morgan’s laws, which can be useful to simplify negations: • !(X & Y) is the same as !X | !Y • !(X | Y) is the same as !X & !Y For example, !(X & !(Y | Z)) simplifies to !X | !!(Y|Z), and then to !X | Y | Z. subset() is a specialised shorthand function for subsetting data frames, and saves some typing because you don’t need to repeat the name of the data frame. You’ll learn how it works in metaprogramming. ### 5.5.8 Boolean algebra vs. sets (logical & integer subsetting) It’s useful to be aware of the natural equivalence between set operations (integer subsetting) and boolean algebra (logical subsetting). Using set operations is more effective when: • You want to find the first (or last) TRUE. • You have very few TRUEs and very many FALSEs; a set representation may be faster and require less storage. which() allows you to convert a boolean representation to an integer representation. There’s no reverse operation in base R but we can easily create one: Let’s create two logical vectors and their integer equivalents and then explore the relationship between boolean and set operations. When first learning subsetting, a common mistake is to use x[which(y)] instead of x[y]. Here the which() achieves nothing: it switches from logical to integer subsetting but the result will be exactly the same. In more general cases, there are two important differences. First, when the logical vector contains NA, logical subsetting replaces these values by NA while which() drops these values. Second, x[-which(y)] is not equivalent to x[!y]: if y is all FALSE, which(y) will be integer(0) and -integer(0) is still integer(0), so you’ll get no values, instead of all values. In general, avoid switching from logical to integer subsetting unless you want, for example, the first or last TRUE value. ### 5.5.9 Exercises 1. How would you randomly permute the columns of a data frame? (This is an important technique in random forests.) Can you simultaneously permute the rows and columns in one step? 2. How would you select a random sample of m rows from a data frame? What if the sample had to be contiguous (i.e., with an initial row, a final row, and every row in between)? 3. How could you put the columns in a data frame in alphabetical order? ## 5.6 Answers 1. Positive integers select elements at specific positions, negative integers drop elements; logical vectors keep elements at positions corresponding to TRUE; character vectors select elements with matching names. 2. [ selects sub-lists. It always returns a list; if you use it with a single positive integer, it returns a list of length one. [[ selects an element within a list.$ is a convenient shorthand: x\$y is equivalent to x[["y"]].

3. Use drop = FALSE if you are subsetting a matrix, array, or data frame and you want to preserve the original dimensions. You should almost always use it when subsetting inside a function.

4. If x is a matrix, x[] <- 0 will replace every element with 0, keeping the same number of rows and columns. x <- 0 completely replaces the matrix with the value 0.

5. A named character vector can act as a simple lookup table: c(x = 1, y = 2, z = 3)[c("y", "z", "x")]