-
Notifications
You must be signed in to change notification settings - Fork 3
/
groupSummarize.Rmd
68 lines (51 loc) · 2.18 KB
/
groupSummarize.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
## Grouping and Summarizing Data
## Grouping and Summarizing Data
A very common task is to look at group-based statistics
We can use <span class='func'>group_by</span> and <span class="func">summarize</span>
```{r groupby, eval=TRUE, cache=TRUE}
scoringDat %>%
group_by(Pos) %>% # can group by more than one variable
summarize(meanTrueShooting = mean(trueShooting, na.rm = TRUE)) # potentially any function can work
```
## Grouping and Summarizing Data
Use do on grouped data to go further
```{r do, cache=T}
state.x77 %>%
data.frame() %>%
mutate(Region=state.region) %>%
group_by(Region) %>%
do(PopIncCorr=cor(.$Population, .$Income)) %>%
data.frame()
```
## Grouping and Summarizing Data
Use do on grouped data to go further
```{r do2, eval=1:4}
library(nycflights13)
carriers = group_by(flights, carrier)
group_size(carriers)
mods = do(carriers, mod = lm(arr_delay ~ dep_time, data = .)) # reminder that data frames are lists
sapply(mods$mod, summary)
```
## Your Turn
## Putting it all together
`?state.x77`
Using one pipe sequence
- $1.$ convert <span class="objclass">state.x77</span> (a base R object) to a data frame (<span class='func'>data.frame</span> )
- $2.$ create a new variable called **Region** that is equal to <span class="objclass">state.region</span> (<span class='func'>mutate</span> )
- $3.$ create a new variable called **State** that is equal to <span class="objclass">state.name</span>
- $4.$ <span class='func'>filter</span> only if Population is greater than 1000 (thousands)
- $5.$ <span class='func'>select</span> **Region** and variables beginning with the letter **I**
- $6.$ group by **Region** (<span class='func'>group_by</span> )
- $7.$ <span class='func'>summarize</span> **Income**, **Illiteracy** or **Both**, using the <span class="func">mean</span> function
## Example
```{r yourturnDataManipExample, eval=TRUE, cache=TRUE}
state.x77 %>%
data.frame %>%
mutate(Region = state.region,
State = state.name) %>%
filter(Population > 1000) %>%
select(Region, starts_with('I')) %>%
group_by(Region) %>%
summarize(meanInc=mean(Income),
meanIll=mean(Illiteracy))
```