forked from rdpeng/rprogdatascience
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubsetting.Rmd
271 lines (193 loc) · 6.34 KB
/
subsetting.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# Subsetting R Objects
```{r,echo=FALSE}
knitr::opts_chunk$set(comment = NA, prompt = TRUE, collapse = TRUE)
```
[Watch a video of this section](https://youtu.be/VfZUZGUgHqg)
There are three operators that can be used to extract subsets of R
objects.
- The `[` operator always returns an object of the same class as the
original. It can be used to select multiple elements of an object
- The `[[` operator is used to extract elements of a list or a data
frame. It can only be used to extract a single element and the class
of the returned object will not necessarily be a list or data frame.
- The `$` operator is used to extract elements of a list or data frame
by literal name. Its semantics are similar to that of `[[`.
## Subsetting a Vector
Vectors are basic objects in R and they can be subsetted using the `[`
operator.
```{r}
x <- c("a", "b", "c", "c", "d", "a")
x[1] ## Extract the first element
x[2] ## Extract the second element
```
The `[` operator can be used to extract multiple elements of a vector
by passing the operator an integer sequence. Here we extract the first
four elements of the vector.
```{r}
x[1:4]
```
The sequence does not have to be in order; you can specify any
arbitrary integer vector.
```{r}
x[c(1, 3, 4)]
```
We can also pass a logical sequence to the `[` operator to extract
elements of a vector that satisfy a given condition. For example, here
we want the elements of `x` that come lexicographically *after* the
letter "a".
```{r}
u <- x > "a"
u
x[u]
```
Another, more compact, way to do this would be to skip the creation of
a logical vector and just subset the vector directly with the logical
expression.
```{r}
x[x > "a"]
```
## Subsetting a Matrix
[Watch a video of this section](https://youtu.be/FzjXesh9tRw)
Matrices can be subsetted in the usual way with (_i,j_) type
indices. Here, we create simple $2\times3$ matrix with the `matrix`
function.
```{r}
x <- matrix(1:6, 2, 3)
x
```
We can access the $(1,2)$ or the $(2,1)$ element of this matrix
using the appropriate indices.
```{r}
x[1, 2]
x[2, 1]
```
Indices can also be missing. This behavior is used to access entire
rows or columns of a matrix.
```{r}
x[1, ] ## Extract the first row
x[, 2] ## Extract the second column
```
### Dropping matrix dimensions
By default, when a single element of a matrix is retrieved, it is
returned as a vector of length 1 rather than a $1\times1$
matrix. Often, this is exactly what we want, but this behavior can be
turned off by setting `drop = FALSE`.
```{r}
x <- matrix(1:6, 2, 3)
x[1, 2]
x[1, 2, drop = FALSE]
```
Similarly, when we extract a single row or column of a matrix, R by
default drops the dimension of length 1, so instead of getting a
$1\times3$ matrix after extracting the first row, we get a vector of
length 3. This behavior can similarly be turned off with the `drop =
FALSE` option.
```{r}
x <- matrix(1:6, 2, 3)
x[1, ]
x[1, , drop = FALSE]
```
**Be careful of R's automatic dropping of dimensions**. This is a
feature that is often quite useful during interactive work, but can
later come back to bite you when you are writing longer programs or
functions.
## Subsetting Lists
[Watch a video of this section](https://youtu.be/DStKguVpuDI)
Lists in R can be subsetted using all three of the operators mentioned
above, and all three are used for different purposes.
```{r}
x <- list(foo = 1:4, bar = 0.6)
x
```
The `[[` operator can be used to extract *single* elements from a
list. Here we extract the first element of the list.
```{r}
x[[1]]
```
The `[[` operator can also use named indices so that you don't have to
remember the exact ordering of every element of the list. You can also
use the `$` operator to extract elements by name.
```{r}
x[["bar"]]
x$bar
```
Notice you don't need the quotes when you use the `$` operator.
One thing that differentiates the `[[` operator from the `$` is that
the `[[` operator can be used with _computed_ indices. The `$`
operator can only be used with literal names.
```{r}
x <- list(foo = 1:4, bar = 0.6, baz = "hello")
name <- "foo"
## computed index for "foo"
x[[name]]
## element "name" doesn’t exist! (but no error here)
x$name
## element "foo" does exist
x$foo
```
## Subsetting Nested Elements of a List
The `[[` operator can take an integer sequence if you want to extract
a nested element of a list.
```{r}
x <- list(a = list(10, 12, 14), b = c(3.14, 2.81))
## Get the 3rd element of the 1st element
x[[c(1, 3)]]
## Same as above
x[[1]][[3]]
## 1st element of the 2nd element
x[[c(2, 1)]]
```
## Extracting Multiple Elements of a List
The `[` operator can be used to extract *multiple* elements from a
list. For example, if you wanted to extract the first and third
elements of a list, you would do the following
```{r}
x <- list(foo = 1:4, bar = 0.6, baz = "hello")
x[c(1, 3)]
```
Note that `x[c(1, 3)]` is NOT the same as `x[[c(1, 3)]]`.
Remember that the `[` operator always returns an object of the same
class as the original. Since the original object was a list, the `[`
operator returns a list. In the above code, we returned a list with
two elements (the first and the third).
## Partial Matching
[Watch a video of this section](https://youtu.be/q3BNhHHVCu4)
Partial matching of names is allowed with `[[` and `$`. This is often
very useful during interactive work if the object you're working with
has very long element names. You can just abbreviate those names and R
will figure out what element you're referring to.
```{r}
x <- list(aardvark = 1:5)
x$a
x[["a"]]
x[["a", exact = FALSE]]
```
In general, this is fine for interactive work, but you shouldn't
resort to partial matching if you are writing longer scripts,
functions, or programs. In those cases, you should refer to the full
element name if possible. That way there's no ambiguity in your code.
## Removing NA Values
[Watch a video of this section](https://youtu.be/TtJxmwXbwo0)
A common task in data analysis is removing missing values (`NA`s).
```{r}
x <- c(1, 2, NA, 4, NA, 5)
bad <- is.na(x)
print(bad)
x[!bad]
```
What if there are multiple R objects and you want to take the subset with
no missing values in any of those objects?
```{r}
x <- c(1, 2, NA, 4, NA, 5)
y <- c("a", "b", NA, "d", NA, "f")
good <- complete.cases(x, y)
good
x[good]
y[good]
```
You can use `complete.cases` on data frames too.
```{r}
head(airquality)
good <- complete.cases(airquality)
head(airquality[good, ])
```