This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path06-data-subsetting.Rmd
727 lines (580 loc) · 16.2 KB
/
06-data-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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
---
layout: page
title: R for reproducible scientific analysis
subtitle: Subsetting data
minutes: 45
---
```{r, include=FALSE}
source("tools/chunk-options.R")
# Silently load in the data so the rest of the lesson works
gapminder <- read.csv("data/gapminder-FiveYearData.csv", header=TRUE)
```
> ## Learning objectives {.objectives}
>
> * To be able to subset vectors, factors, matrices, lists, and data frames
> * To be able to extract individual and multiple elements:
> * by index,
> * by name,
> * using comparison operations
> * To be able to skip and remove elements from various data structures.
>
R has many powerful subset operators and mastering them will allow you to
easily perform complex operations on any kind of dataset.
There are six different ways we can subset any kind of object, and three
different subsetting operators for the different data structures.
Let's start with the workhorse of R: atomic vectors.
```{r}
x <- c(5.4, 6.2, 7.1, 4.8, 7.5)
names(x) <- c('a', 'b', 'c', 'd', 'e')
x
```
So now that we've created a dummy vector to play with, how do we get at its
contents?
### Accessing elements using their indices
To extract elements of a vector we can give their corresponding index, starting
from one:
```{r}
x[1]
```
```{r}
x[4]
```
The square brackets operator is just like any other function. For atomic vectors
(and matrices), it means "get me the nth element".
We can ask for multiple elements at once:
```{r}
x[c(1, 3)]
```
Or slices of the vector:
```{r}
x[1:4]
```
the `:` operator just creates a sequence of numbers from the left element to the right.
I.e. `x[1:4]` is equivalent to `x[c(1,2,3,4)]`.
We can ask for the same element multiple times:
```{r}
x[c(1,1,3)]
```
If we ask for a number outside of the vector, R will return missing values:
```{r}
x[6]
```
This is a vector of length one containing an `NA`, whose name is also `NA`.
If we ask for the 0th element, we get an empty vector:
```{r}
x[0]
```
But what about negative values?
### Skipping and removing elements
If we use a negative number, R will return every element *except* for the
one specified:
```{r}
x[-2]
```
We can skip multiple elements:
```{r}
x[c(-1, -5)] # or x[-c(1,5)]
```
> #### Tip: Order of operations {.callout}
>
> A common trip up for novices occurs when trying to skip
> slices of a vector. Most people first try to negate a
> sequence like so:
>
> ```{r, error=TRUE}
> x[-1:3]
> ```
>
> This gives a somewhat cryptic error:
>
> But remember the order of operations. `:` is really a function, so
> what happens is it takes its first argument as -1, and second as 3,
> so generates the sequence of numbers: `c(-1, 0, 1, 2, 3)`.
>
> The correct solution is to wrap that function call in brackets, so
> that the `-` operator applies to the results:
>
> ```{r}
> x[-(1:3)]
> ```
>
To remove elements from a vector, we need to assign the results back
into the variable:
```{r}
x <- x[-4]
x
```
> #### Challenge 1 {.challenge}
>
> Given the following code:
>
> ```{.r}
> x <- c(5.4, 6.2, 7.1, 4.8, 7.5)
> names(x) <- c('a', 'b', 'c', 'd', 'e')
> print(x)
> ```
>
> 1. Come up with at least 3 different commands that will produce the following output:
>
> ```{.r, echo=FALSE}
> x[2:4]
> ```
>
> 2. Compare notes with your neighbour. Did you have different strategies?
>
### Subsetting by name
We can extract elements by using their name, instead of index:
```{r}
x[c("a", "c")]
```
This is usually a much more reliable way to subset objects: the
position of various elements can often change when chaining together
subsetting operations, but the names will always remain the same!
Unfortunately we can't skip or remove elements so easily.
To skip (or remove) a single named element:
```{r}
x[-which(names(x) == "a")]
```
The `which` function returns the indices of all `TRUE` elements of its argument.
Remember that expressions evaluate before being passed to functions. Let's break
this down so that its clearer what's happening.
First this happens:
```{r}
names(x) == "a"
```
The condition operator is applied to every name of the vector `x`. Only the
first name is "a" so that element is TRUE.
`which` then converts this to an index:
```{r}
which(names(x) == "a")
```
Only the first element is `TRUE`, so `which returns 1. Now that we have indices
the skipping works because we have a negative index!
Skipping multiple named indices is similar, but uses a different comparison
operator:
```{r}
x[-which(names(x) %in% c("a", "c"))]
```
The `%in%` goes through each element of its left argument, in this case the
names of `x`, and asks, "Does this element occur in the second argument?".
> #### Tip: Getting help for operators {.callout}
>
> Remember you can search for help on operators by wrapping them in quotes:
> `help("%in%")` or `?"%in%"`.
>
So why can't we use `==` like before? That's an excellent question.
Let's take a look at just the comparison component:
```{r}
names(x) == c('a', 'c')
```
Obviously "c" is in the names of `x`, so why didn't this work? `==` works
slightly differently to `%in%`. It will compare each element of its left argument
to the corresponding element of its right argument.
Here's a mock illustration:
```{r, eval=FALSE}
c("a", "b", "c", "e") # names of x
| | | | # The elements == is comparing
c("a", "c")
```
When one vector is shorter than the other, it gets *recycled*:
```{r, eval=FALSE}
c("a", "b", "c", "e") # names of x
| | | | # The elements == is comparing
c("a", "c", "a", "c")
```
In this case R simply repeats `c("a", "c")` twice. If the longer
vector length isn't a multiple of the shorter vector length, then
R will also print out a warning message:
```{r}
names(x) == c('a', 'c', 'e')
```
This difference between `==` and `%in%` is important to remember,
because it can introduce hard to find and subtle bugs!
### Subsetting through other logical operations
We can also more simply subset through logical operations:
```{r}
x[c(TRUE, TRUE, FALSE, FALSE)]
```
Note that in this case, the logical vector is also recycled to the
length of the vector we're subsetting!
```{r}
x[c(TRUE, FALSE)]
```
Since comparison operators evaluate to logical vectors, we can also
use them to succinctly subset vectors:
```{r}
x[x > 7]
```
> #### Tip: Chaining logical operations {.callout}
>
> There are many situations in which you will wish to combine multiple conditions.
> To do so several logical operations exist in R:
>
> * `|` logical OR: returns `TRUE`, if either the left or right are `TRUE`.
> * `&` logical AND: returns `TRUE` if both the left and right are `TRUE`
> * `!` logical NOT: converts `TRUE` to `FALSE` and `FALSE` to `TRUE`
> * `&&` and `||` compare the individual elements of two vectors. Recycling rules
> also apply here.
>
> #### Challenge {.challenge}
>
> Given the following code:
>
> ```{r}
> x <- c(5.4, 6.2, 7.1, 4.8, 7.5)
> names(x) <- c('a', 'b', 'c', 'd', 'e')
> print(x)
> ```
>
> 1. Write a subsetting command to return the values in x that are greater than 4 and less than 7.
>
#### Handling special values
At some point you will encounter functions in R which cannot handle missing, infinite,
or undefined data.
There are a number of special functions you can use to filter out this data:
* `is.na` will return all positions in a vector, matrix, or data.frame
containing `NA`.
* likewise, `is.nan`, and `is.infinite` will do the same for `NaN` and `Inf`.
* `is.finite` will return all positions in a vector, matrix, or data.frame
that do not contain `NA`, `NaN` or `Inf`.
* `na.omit` will filter out all missing values from a vector
### Factor subsetting
Now that we've explored the different ways to subset vectors, how
do we subset the other data structures?
Factor subsetting works the same way as vector subsetting.
```{r}
f <- factor(c("a", "a", "b", "c", "c", "d"))
f[f == "a"]
f[f %in% c("b", "c")]
f[1:3]
```
An important note is that skipping elements will not remove the level
even if no more of that category exists in the factor:
```{r}
f[-3]
```
### Matrix subsetting
Matrices are also subsetted using the `[` function. In this case
it takes two arguments: the first applying to the rows, the second
to its columns:
```{r}
set.seed(1)
m <- matrix(rnorm(6*4), ncol=4, nrow=6)
m[3:4, c(3,1)]
```
You can leave the first or second arguments blank to retrieve all the
rows or columns respectively:
```{r}
m[, c(3,4)]
```
If we only access one row or column, R will automatically convert the result
to a vector:
```{r}
m[3,]
```
If you want to keep the output as a matrix, you need to specify a *third* argument;
`drop = FALSE`:
```{r}
m[3, , drop=FALSE]
```
Unlike vectors, if we try to access a row or column outside of the matrix,
R will throw an error:
```{r}
m[, c(3,6)]
```
> #### Tip: Higher dimensional arrays {.callout}
>
> when dealing with multi-dimensional arrays, each argument to `[`
> corresponds to a dimension. For example, a 3D array, the first three
> arguments correspond to the rows, columns, and depth dimension.
>
Because matrices are really just vectors underneath the hood, we can
also subset using only one argument:
```{r}
m[5]
```
This usually isn't useful. However it is useful to note that matrices
are laid out in *column-major format* by default. That is the elements of the
vector are arranged column-wise:
```{r}
matrix(1:6, nrow=2, ncol=3)
```
Matrices can also be subsetted using their rownames and column names
instead of their row and column indices.
> #### Challenge 2 {.challenge}
>
> Given the following code:
>
> ```{r}
> m <- matrix(1:18, nrow=3, ncol=6)
> print(m)
> ```
>
> 1. Which of the following commands will extract the values 11 and 14?
>
> A. `m[2,4,2,5]`
>
> B. `m[2:5]`
>
> C. `m[4:5,2]`
>
> D. `m[2,c(4,5)]`
>
### List subsetting
Now we'll introduce some new subsetting operators. There are three functions
used to subset lists. `[`, as we've seen for atomic vectors and matrices,
as well as `[[` and `$`.
Using `[` will always return a list. If you want to *subset* a list, but not
*extract* an element, then you will likely use `[`.
```{r}
xlist <- list(a = "Software Carpentry", b = 1:10, data = head(iris))
xlist[1]
```
This returns a *list with one element*.
We can subset elements of a list exactly the same was as atomic
vectors using `[`. Comparison operations however won't work as
they're not recursive, they will try to condition on the data structures
in each element of the list, not the individual elements within those
data structures.
```{r}
xlist[1:2]
```
To extract individual elements of a list, you need to use the double-square
bracket function: `[[`.
```{r}
xlist[[1]]
```
Notice that now the result is a vector, not a list.
You can't extract more than one element at once:
```{r, error=TRUE}
xlist[[1:2]]
```
Nor use it to skip elements:
```{r, error=TRUE}
xlist[[-1]]
```
But you can use names to both subset and extract elements:
```{r}
xlist[["a"]]
```
The `$` function is a shorthand way for extracting elements by name:
```{r}
xlist$data
```
> #### Challenge 3 {.challenge}
> Given the following list:
>
> ```{r, eval=FALSE}
> xlist <- list(a = "Software Carpentry", b = 1:10, data = head(iris))
> ```
>
> Using your knowledge of both list and vector subsetting, extract the number 2 from xlist.
> Hint: the number 2 is contained within the "b" item in the list.
> #### Challenge 4 {.challenge}
> Given a linear model:
>
> ```{r, eval=FALSE}
> mod <- aov(pop ~ lifeExp, data=gapminder)
> ```
>
> Extract the residual degrees of freedom (hint: `attributes()` will help you)
>
### Data frames
Remember the data frames are lists underneath the hood, so similar rules
apply. However they are also two dimensional objects:
`[` with one argument will act the same was as for lists, where each list
element corresponds to a column. The resulting object will be a data frame:
```{r}
head(gapminder[3])
```
Similarly, `[[` will act to extract *a single column*:
```{r}
head(gapminder[["lifeExp"]])
```
And `$` provides a convenient shorthand to extract columns by name:
```{r}
head(gapminder$year)
```
With two arguments, `[` behaves the same way as for matrices:
```{r}
gapminder[1:3,]
```
If we subset a single row, the result will be a data frame (because
the elements are mixed types):
```{r}
gapminder[3,]
```
But for a single column the result will be a vector (this can
be changed with the third argument, `drop = FALSE`).
> #### Challenge 5 {.challenge}
>
> Fix each of the following common data frame subsetting errors:
>
> 1. Extract observations collected for the year 1957
>
> ```{r, eval=FALSE}
> gapminder[gapminder$year = 1957,]
> ```
>
> 2. Extract all columns except 1 through to 4
>
> ```{r, eval=FALSE}
> gapminder[,-1:4]
> ```
>
> 3. Extract the rows where the life expectancy is longer the 80 years
>
> ```{r, eval=FALSE}
> gapminder[gapminder$lifeExp > 80]
> ```
>
> 4. Extract the first row, and the fourth and fifth columns
> (`lifeExp` and `gdpPercap`).
>
> ```{r, eval=FALSE}
> gapminder[1, 4, 5]
> ```
>
> 5. Advanced: extract rows that contain information for the years 2002
> and 2007
>
> ```{r, eval=FALSE}
> gapminder[gapminder$year == 2002 | 2007,]
> ```
>
> #### Challenge 6 {.challenge}
>
> 1. Why does `gapminder[1:20]` return an error? How does it differ from `gapminder[1:20, ]`?
>
>
> 2. Create a new `data.frame` called `gapminder_small` that only contains rows 1 through 9
> and 19 through 23. You can do this in one or two steps.
>
## Challenge solutions
> #### Solution to challenge 1 {.challenge}
>
> Given the following code:
>
> ```{r}
> x <- c(5.4, 6.2, 7.1, 4.8, 7.5)
> names(x) <- c('a', 'b', 'c', 'd', 'e')
> print(x)
> ```
>
> 1. Come up with at least 3 different commands that will produce the following output:
>
> ```{r, echo=FALSE}
> x[2:4]
> ```
>
> ```{r, eval=FALSE}
> x[2:4]
> x[-c(1,5)]
> x[c("b", "c", "d")]
> x[c(2,3,4)]
> ```
>
>
> #### Solution to challenge 2 {.challenge}
>
> Given the following code:
>
> ```{r}
> m <- matrix(1:18, nrow=3, ncol=6)
> print(m)
> ```
>
> 1. Which of the following commands will extract the values 11 and 14?
>
> A. `m[2,4,2,5]`
>
> B. `m[2:5]`
>
> C. `m[4:5,2]`
>
> D. `m[2,c(4,5)]`
>
> Answer: D
> #### Solution to challenge 3 {.challenge}
> Given the following list:
>
> ```{r}
> xlist <- list(a = "Software Carpentry", b = 1:10, data = head(iris))
> ```
>
> Using your knowledge of both list and vector subsetting, extract the number 2 from xlist.
> Hint: the number 2 is contained within the "b" item in the list.
>
> ```{r, eval=FALSE}
> xlist$b[2]
> xlist[[2]][2]
> xlist[["b"]][2]
> ```
> #### Solution to challenge 4 {.challenge}
> Given a linear model:
>
> ```{r}
> mod <- aov(pop ~ lifeExp, data=gapminder)
> ```
>
> Extract the residual degrees of freedom (hint: `attributes()` will help you)
>
> ```{r, eval=FALSE}
> attributes(mod) ## `df.residual` is one of the names of `mod`
> mod$df.residual
> ```
> #### Solution to challenge 5 {.challenge}
>
> Fix each of the following common data frame subsetting errors:
>
> 1. Extract observations collected for the year 1957
>
> ```{r, eval=FALSE}
> # gapminder[gapminder$year = 1957,]
> gapminder[gapminder$year == 1957,]
> ```
>
> 2. Extract all columns except 1 through to 4
>
> ```{r, eval=FALSE}
> # gapminder[,-1:4]
> gapminder[,-c(1:4)]
> ```
>
> 3. Extract the rows where the life expectancy is longer the 80 years
>
> ```{r, eval=FALSE}
> # gapminder[gapminder$lifeExp > 80]
> gapminder[gapminder$lifeExp > 80,]
> ```
>
> 4. Extract the first row, and the fourth and fifth columns
> (`lifeExp` and `gdpPercap`).
>
> ```{r, eval=FALSE}
> # gapminder[1, 4, 5]
> gapminder[1, c(4, 5)]
> ```
>
> 5. Advanced: extract rows that contain information for the years 2002
> and 2007
>
> ```{r, eval=FALSE}
> # gapminder[gapminder$year == 2002 | 2007,]
> gapminder[gapminder$year == 2002 | gapminder$year == 2007,]
> gapminder[gapminder$year %in% c(2002, 2007),]
> ```
>
> #### Solution to challenge 6 {.challenge}
>
> 1. Why does `gapminder[1:20]` return an error? How does it differ from `gapminder[1:20, ]`?
>
> Answer: `gapminder` is a data.frame so needs to be subsetted on two dimensions. `gapminder[1:20, ]` subsets the data to give the first 20 rows and all columns.
>
> 2. Create a new `data.frame` called `gapminder_small` that only contains rows 1 through 9
> and 19 through 23. You can do this in one or two steps.
>
> ```{r}
> gapminder_small <- gapminder[c(1:9, 19:23),]
> ```
>