-
Notifications
You must be signed in to change notification settings - Fork 3
/
filter.Rmd
70 lines (47 loc) · 1.71 KB
/
filter.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
## Filtering Observations
## Filtering Observations
Recall this bit of code?
```{r bballRecall, eval=FALSE}
bball = read_html(url) %>%
html_nodes("#totals_stats") %>%
html_table %>%
data.frame %>%
filter(Rk != "Rk")
```
You will notice the <span class="func">filter</span> line at the end
We sometimes want to see a very specific portion of the data
## Filtering Observations
>- <span class='func'>filter</span> returns rows with matching conditions.
>- <span class='func'>slice</span> allows for a numeric indexing approach.
>- Say we want too look at forwards (SF or PF) over the age of 35...
```{r filter1, eval=FALSE}
bball %>%
filter(Age > 35, Pos == "SF" | Pos == "PF")
```
>- or the first 10 rows...
```{r filter2, eval=FALSE}
bball %>%
slice(1:10)
```
## Filtering Observations
This can be done with things that are created on the fly...
```{r uniteFilterArrange, cache=TRUE}
bball %>%
unite("posTeam", Pos, Tm) %>% # create a new variable
filter(posTeam == "PF_SAS") %>% # use it for filtering
arrange(desc(PTS/PF)) %>% # order by on-the-fly operation
select(1:10)
```
## Your turn
## Your turn
A brief exercise:
- $1.$ <span class='func'>filter</span> the iris data set to only the `r "virginica"` species (var <span class='func'>==</span> value)
- $2.$ show only **Petal.Length** and **Petal.Width** variables (<span class='func'>select</span>)
- $3.$ <span class="emph">bonus</span>: redo, but instead, filter if the ratio of **Petal.Length** to **Petal.Width** is greater than 5.
- Which species do these observations belong to?
## Example
```{r yourTurnFilterExample, cache=TRUE}
iris %>%
filter(Petal.Length/Petal.Width > 5) %>%
summary
```