Conditional Indexing
Data frames and matrices allow for conditional indexing in R, which is often very useful. Instead of creating the goodair vector using a loop, we could directly extract the good air quality days using conditional indexing, using the single command below:
> airqualfull[airqualfull$Ozone < 60,]
It is worthwhile to keep in mind that many things in R can be done avoiding loops, and using conditional indexing can save a lot of time and effort! However, there are other times when using loops may be the only (or best) way to do things.
Conditional indexing is also useful for extracting groups of data from data frames, or splitting data into groups according to some criterion (or data which is already grouped according to some factor). For example, to get sets of ozone measurements for days with temperatures higher and lower than 80 degrees F, we can use:
> split(airqualfull$Ozone, airqualfull$Temp < 80)
$`FALSE`
[1] 45 29 71 39 23 135 49 32 64 40 77 97 97 85 27 7 48 35
[19] 61 79 63 80 108 20 52 82 50 64 59 39 9 16 122 89 110 44
[37] 28 65 168 73 76 118 84 85 96 78 73 91 47 32 20 44 16 36
$`TRUE`
[1] 41 36 12 18 23 19 8 16 11 14 18 14 34 6 30 11 1 11
[19] 4 32 23 115 37 21 37 20 12 13 10 16 22 59 23 31 44 21
[37] 9 45 23 21 24 21 28 9 13 46 18 13 24 13 23 7 14 30
[55] 14 18 20
Using conditional indexing, write an R command to replicate the results of the preceding exercise questtion. (Hint: use single &, not double &&.) |