-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04_exercisesAME1.Rmd
510 lines (371 loc) · 21.9 KB
/
04_exercisesAME1.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
---
title: 'Weekly Exercises #4'
author: "Ana Espeleta"
output:
html_document:
keep_md: TRUE
toc: TRUE
toc_float: TRUE
df_print: paged
code_download: true
---
```{r setup, include=FALSE}
#knitr::opts_chunk$set(echo = TRUE, error=TRUE, message=FALSE, warning=FALSE)
```
```{r libraries}
library(tidyverse) # for data cleaning and plotting
library(lubridate) # for date manipulation
library(openintro) # for the abbr2state() function
library(palmerpenguins)# for Palmer penguin data
library(maps) # for map data
library(ggmap) # for mapping points on maps
library(gplots) # for col2hex() function
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
library(leaflet) # for highly customizable mapping
library(carData) # for Minneapolis police stops data
library(ggthemes) # for more themes (including theme_map())
theme_set(theme_minimal())
```
```{r data}
# Starbucks locations
Starbucks <- read_csv("https://www.macalester.edu/~ajohns24/Data/Starbucks.csv")
starbucks_us_by_state <- Starbucks %>%
filter(Country == "US") %>%
count(`State/Province`) %>%
mutate(state_name = str_to_lower(abbr2state(`State/Province`)))
# Lisa's favorite St. Paul places - example for you to create your own data
favorite_stp_by_lisa <- tibble(
place = c("Home", "Macalester College", "Adams Spanish Immersion",
"Spirit Gymnastics", "Bama & Bapa", "Now Bikes",
"Dance Spectrum", "Pizza Luce", "Brunson's"),
long = c(-93.1405743, -93.1712321, -93.1451796,
-93.1650563, -93.1542883, -93.1696608,
-93.1393172, -93.1524256, -93.0753863),
lat = c(44.950576, 44.9378965, 44.9237914,
44.9654609, 44.9295072, 44.9436813,
44.9399922, 44.9468848, 44.9700727)
)
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
```
## Put your homework on GitHub!
If you were not able to get set up on GitHub last week, go [here](https://github.com/llendway/github_for_collaboration/blob/master/github_for_collaboration.md) and get set up first. Then, do the following (if you get stuck on a step, don't worry, I will help! You can always get started on the homework and we can figure out the GitHub piece later):
* Create a repository on GitHub, giving it a nice name so you know it is for the 4th weekly exercise assignment (follow the instructions in the document/video).
* Copy the repo name so you can clone it to your computer. In R Studio, go to file --> New project --> Version control --> Git and follow the instructions from the document/video.
* Download the code from this document and save it in the repository folder/project on your computer.
* In R Studio, you should then see the .Rmd file in the upper right corner in the Git tab (along with the .Rproj file and probably .gitignore).
* Check all the boxes of the files in the Git tab under Stage and choose commit.
* In the commit window, write a commit message, something like "Initial upload" would be appropriate, and commit the files.
* Either click the green up arrow in the commit window or close the commit window and click the green up arrow in the Git tab to push your changes to GitHub.
* Refresh your GitHub page (online) and make sure the new documents have been pushed out.
* Back in R Studio, knit the .Rmd file. When you do that, you should have two (as long as you didn't make any changes to the .Rmd file, in which case you might have three) files show up in the Git tab - an .html file and an .md file. The .md file is something we haven't seen before and is here because I included `keep_md: TRUE` in the YAML heading. The .md file is a markdown (NOT R Markdown) file that is an interim step to creating the html file. They are displayed fairly nicely in GitHub, so we want to keep it and look at it there. Click the boxes next to these two files, commit changes (remember to include a commit message), and push them (green up arrow).
* As you work through your homework, save and commit often, push changes occasionally (maybe after you feel finished with an exercise?), and go check to see what the .md file looks like on GitHub.
* If you have issues, let me know! This is new to many of you and may not be intuitive at first. But, I promise, you'll get the hang of it!
## Instructions
* Put your name at the top of the document.
* **For ALL graphs, you should include appropriate labels.**
* Feel free to change the default theme, which I currently have set to `theme_minimal()`.
* Use good coding practice. Read the short sections on good code with [pipes](https://style.tidyverse.org/pipes.html) and [ggplot2](https://style.tidyverse.org/ggplot2.html). **This is part of your grade!**
* When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don't do it before then, or else you might miss some important warnings and messages.
## Warm-up exercises from tutorial
These exercises will reiterate what you learned in the "Mapping data with R" tutorial. If you haven't gone through the tutorial yet, you should do that first.
### Starbucks locations (`ggmap`)
1. Add the `Starbucks` locations to a world map. Add an aesthetic to the world map that sets the color of the points according to the ownership type. What, if anything, can you deduce from this visualization?
```{r}
world <- get_stamenmap(
bbox = c(left = -180, bottom = -57, right = 179, top = 82.1),
maptype = "terrain",
zoom = 2)
ggmap(world) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude, color = `Ownership Type`),
alpha = 0.5,
size = 0.5) +
theme_map()+
theme(legend.background = element_blank())+
guides(colour = guide_legend(override.aes = list(size = 7)))+
labs(title = "Starbucks Around the World by Ownership Type")
```
>There seems to be more company owned stores than any other type of ownership.
2. Construct a new map of Starbucks locations in the Twin Cities metro area (approximately the 5 county metro area).
```{r}
new_starbucks_map <- get_stamenmap(
bbox = c(left = -94.1116, bottom = 44.4553, right = -92.6040, top = 45.4649),
maptype = "terrain",
zoom = 9)
ggmap(new_starbucks_map) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude),
alpha = 1,
size = 1) +
theme_map()+
labs(title = "Starbucks Stores in the Twin Cities Metro Area")
```
3. In the Twin Cities plot, play with the zoom number. What does it do? (just describe what it does - don't actually include more than one map).
>The higher the zoom number the more detail we get from the map. So, for smaller areas, we want to have a higher zoom number and for larger areas, we want a lower zoom number.
4. Try a couple different map types (see `get_stamenmap()` in help and look at `maptype`). Include a map with one of the other map types.
```{r}
new_starbucks_map2 <- get_stamenmap(
bbox = c(left = -94.1116, bottom = 44.4553, right = -92.6040, top = 45.4649),
maptype = "toner",
zoom = 9)
ggmap(new_starbucks_map2) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude),
alpha = 1,
size = 1) +
theme_map()+
labs(title = "Starbucks Stores in the Twin Cities Metro Area")
```
5. Add a point to the map that indicates Macalester College and label it appropriately. There are many ways you can do this, but I think it's easiest with the `annotate()` function (see `ggplot2` cheatsheet).
```{r}
new_starbucks_map <- get_stamenmap(
bbox = c(left = -94.1116, bottom = 44.4553, right = -91.6040, top = 45.4649),
maptype = "toner",
zoom = 9)
ggmap(new_starbucks_map) +
annotate('rect',xmin =-93.1793 , ymin=44.9340 , xmax =-93.1593 , ymax= 44.9416, color = 'red', fill = 'white' )+
annotate('text', x=-93.25, y=45.02, label = 'Macalester College', colour = I("red"), size = 5)+
annotate('segment', x=-93.25, xend=-93.1693, y=45, yend=44.9350,
colour=I('red'), arrow = arrow(length=unit(0.3,"cm")), size = 1) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude),
alpha = 1,
size = 1) +
theme_map()+
labs(title = "Starbucks Stores in the Twin Cities Metro Area")
```
### Choropleth maps with Starbucks data (`geom_map()`)
The example I showed in the tutorial did not account for population of each state in the map. In the code below, a new variable is created, `starbucks_per_10000`, that gives the number of Starbucks per 10,000 people. It is in the `starbucks_with_2018_pop_est` dataset.
```{r}
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
starbucks_with_2018_pop_est <-
starbucks_us_by_state %>%
left_join(census_pop_est_2018,
by = c("state_name" = "state")) %>%
mutate(starbucks_per_10000 = (n/est_pop_2018)*10000)
census_pop_est_2018
```
6. **`dplyr` review**: Look through the code above and describe what each line of code does.
Separate the state name from the extra characters in the string. Get rid of dot column by selecting everything but that variable. We then mutate another column that takes state name and changes it to lowercase.
Then, we joining the census data to the Starbucks data by state name and mutate another variable to get the number of Starbucks per 10000 people in each state.
7. Create a choropleth map that shows the number of Starbucks per 10,000 people on a map of the US. Use a new fill color, add points for all Starbucks in the US (except Hawaii and Alaska), add an informative title for the plot, and include a caption that says who created the plot (you!). Make a conclusion about what you observe.
```{r}
states_map <- map_data("state")
starbucks_with_2018_pop_est %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state_name,
fill = n)) +
expand_limits(x = states_map$long, y = states_map$lat) +
geom_point(data = Starbucks %>% filter(`Country` == "US", `State/Province` != "hawaii",`State/Province` != "alaska"),
aes(x = Longitude, y = Latitude),
size = .05,
alpha = .2,
color = "khaki1") +
scale_fill_viridis_c(option = "turbo")+
theme_map()+
labs(title = "Starbucks Stores per 10000 People by State in the U.S.")
```
>There is a larger density of Starbucks in big cities, as well as in more populated states. The West and East coasts seem to have the largest densities overall.
### A few of your favorite things (`leaflet`)
8. In this exercise, you are going to create a single map of some of your favorite places! The end result will be one map that satisfies the criteria below.
* Create a data set using the `tibble()` function that has 10-15 rows of your favorite places. The columns will be the name of the location, the latitude, the longitude, and a column that indicates if it is in your top 3 favorite locations or not. For an example of how to use `tibble()`, look at the `favorite_stp_by_lisa` I created in the data R code chunk at the beginning.
```{r}
favorite_running_spots <- tibble(
place = c("University of MN", "Minnehaha Falls", "MN State Capitol",
"Dunn Brothers (Minneapolis)","Highland Golf Course", "Lake Como", "Lake of the Isles", "Afton State Park", "Mendota Trail", "Crosby Farm"),
long = c(-93.1908, -93.21223,-93.10347,-93.20736,-93.1719,-93.1599,-93.3288,-92.8649, -93.2331,-93.1958),
lat = c(44.9734,44.91580, 44.95566, 44.94902, 44.9199, 44.9876,44.9646,44.8880, 44.9209, 44.9206),
favorite= c("not_fav", "fav", "not_fav", "fav", "not_fav", "fav", "not_fav", "not_fav", "not_fav", "not_fav")
)
```
* Create a `leaflet` map that uses circles to indicate your favorite places. Label them with the name of the place. Choose the base map you like best. Color your 3 favorite places differently than the ones that are not in your top 3 (HINT: `colorFactor()`). Add a legend that explains what the colors mean.
```{r}
pal <- colorFactor(
palette = c('red', 'blue'),
domain = favorite_running_spots$favorite
)
leaflet(data = favorite_running_spots) %>%
addTiles() %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~place,
color = ~pal(favorite)) %>%
addLegend(pal = pal,
values = ~favorite,
title = "My Favorite Running Spots",
position = "bottomright") %>%
addPolylines(lng = ~long,
lat = ~lat,
color = col2hex("firebrick2"),
opacity = 0.5)
```
* Connect all your locations together with a line in a meaningful way (you may need to order them differently in the original data).
* If there are other variables you want to add that could enhance your plot, do that now.
## Revisiting old datasets
This section will revisit some datasets we have used previously and bring in a mapping component.
### Bicycle-Use Patterns
The data come from Washington, DC and cover the last quarter of 2014.
Two data tables are available:
- `Trips` contains records of individual rentals
- `Stations` gives the locations of the bike rental stations
Here is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with `{r cache = TRUE}` rather than the usual `{r}`. This code reads in the large dataset right away.
```{r cache=TRUE}
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
```
9. Use the latitude and longitude variables in `Stations` to make a visualization of the total number of departures from each station in the `Trips` data. Use either color or size to show the variation in number of departures. This time, plot the points on top of a map. Use any of the mapping tools you'd like.
```{r}
Trips2 <- Trips %>%
group_by(sstation) %>%
summarize(station_count = n()) %>%
left_join(Stations,
by = c("sstation" = "name")) %>%
select("sstation", "station_count", "lat", "long")
DC <- get_stamenmap(
bbox = c(left = -77.3836, bottom = 38.7230, right = -76.6351, top = 39.0773),
maptype = "terrain",
zoom = 11)
ggmap(DC) +
geom_point(data = Trips2,
aes(x = long, y = lat, color = station_count),
size = .5)+
labs(title = "Total Bike Departures from Each Station", x = "Longitude", y = "Latitude")
```
10. Only 14.4% of the trips in our data are carried out by casual users. Create a plot that shows which area(s) have stations with a much higher percentage of departures by casual users. What patterns do you notice? Also plot this on top of a map. I think it will be more clear what the patterns are.
```{r}
Trips3 <- Trips %>%
left_join(Stations,
by = c("sstation" = "name")) %>%
group_by(lat, long) %>%
mutate(client_binary = ifelse(client == "Casual", 1, 0)) %>%
summarize(prop = sum(client == "Casual")/n())
ggmap(DC) +
geom_point(data = Trips3,
aes(x = long, y = lat, color = prop),
size = .5)+
labs(title = "Proportion of Casual Bike Departures from Each Station", x = "Longitude", y = "Latitude")
```
>The proportion of casual users is much higher where the city borders the river. This might be because there is a river parkway where people like to go on bikerides.
### COVID-19 data
The following exercises will use the COVID-19 data from the NYT.
11. Create a map that colors the states by the most recent cumulative number of COVID-19 cases (remember, these data report cumulative numbers so you don't need to compute that). Describe what you see. What is the problem with this map?
states_map <- map_data("state")
```{r}
recent_cases <-
covid19 %>%
group_by(state) %>%
mutate(order = 1:n()) %>%
filter(order == 1) %>%
mutate(state_name = str_to_lower(state))
recent_cases
covid_map <- map_data("state")
recent_cases %>%
ggplot() +
geom_map(map = covid_map,
aes(map_id = state_name,
fill = cases)) +
expand_limits(x = covid_map$long, y = covid_map$lat) +
labs(title = "Most Recent Cumulative Count of Covid-19 Cases per State in the U.S.", fill = "Covid Cases")+
theme_map()
```
>Many of the states had a very small number of first cases, so their colors are almost identical, which makes it hard to distinguish each state on the map.
12. Now add the population of each state to the dataset and color the states by most recent cumulative cases/10,000 people. See the code for doing this with the Starbucks data. You will need to make some modifications.
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
```{r}
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
covid_with_2018_pop_est <-
recent_cases %>%
left_join(census_pop_est_2018,
by = c("state_name" = "state")) %>%
mutate(covid_per_10000 = (cases/est_pop_2018)*10000)
covid_with_2018_pop_est %>%
ggplot() +
geom_map(map = covid_map,
aes(map_id = state_name,
fill = covid_with_2018_pop_est$covid_per_10000)) +
expand_limits(x = covid_map$long, y = covid_map$lat) +
labs(title = "Most Recent Cumulative Count of Covid-19 Cases per 10000 People by State in the U.S.", fill = "Cases per
10000 People")+
theme_map()+
theme(legend.background = element_blank())
```
## Minneapolis police stops
These exercises use the datasets `MplsStops` and `MplsDemo` from the `carData` library. Search for them in Help to find out more information.
14. Use the `MplsStops` dataset to find out how many stops there were for each neighborhood and the proportion of stops that were for a suspicious vehicle or person. Sort the results from most to least number of stops. Save this as a dataset called `mpls_suspicious` and display the table.
```{r}
mpls_suspicious <-
MplsStops %>%
group_by(neighborhood) %>%
mutate(binary = ifelse(problem == "suspicious", 1, 0)) %>% summarise(prop = mean(binary)) %>%
arrange(desc(prop))
mpls_suspicious
```
15. Use a `leaflet` map and the `MplsStops` dataset to display each of the stops on a map as a small point. Color the points differently depending on whether they were for suspicious vehicle/person or a traffic stop (the `problem` variable). HINTS: use `addCircleMarkers`, set `stroke = FAlSE`, use `colorFactor()` to create a palette.
```{r}
pal <- colorFactor(
palette = c('red','orange'),
domain = MplsStops$problem)
leaflet(data = MplsStops) %>%
addTiles() %>%
addCircleMarkers(lng = ~long,
lat = ~lat,
label = ~neighborhood,
color = ~pal(problem),
stroke = FALSE)
```
16. Save the folder from moodle called Minneapolis_Neighborhoods into your project/repository folder for this assignment. Make sure the folder is called Minneapolis_Neighborhoods. Use the code below to read in the data and make sure to **delete the `eval=FALSE`**. Although it looks like it only links to the .shp file, you need the entire folder of files to create the `mpls_nbhd` data set. These data contain information about the geometries of the Minneapolis neighborhoods. Using the `mpls_nbhd` dataset as the base file, join the `mpls_suspicious` and `MplsDemo` datasets to it by neighborhood (careful, they are named different things in the different files). Call this new dataset `mpls_all`.
```{r}
mpls_nbhd <- st_read("Minneapolis_Neighborhoods/Minneapolis_Neighborhoods.shp", quiet = TRUE)
```
```{r}
mpls_all <-
mpls_nbhd %>%
full_join(mpls_suspicious,
by = c("BDNAME"="neighborhood")) %>%
left_join(MplsDemo,
by = c("BDNAME"="neighborhood"))
mpls_all
```
17. Use `leaflet` to create a map from the `mpls_all` data that colors the neighborhoods by `prop_suspicious`. Display the neighborhood name as you scroll over it. Describe what you observe in the map.
```{r}
pal <- colorNumeric("RdYlBu",
domain = mpls_all$prop)
leaflet(data = mpls_all) %>%
addTiles() %>%
addPolygons(
color = "black",
fillColor = ~pal(prop),
fillOpacity = 1,
label = ~BDNAME)
```
>The Southeastern neighborhoods tend to have a higher proportion of stops from "suspicious activity" than the northeastern neighborhoods. This could be because the Northern Minneapolis neighborhoods have more rutinary police stops due to higher crime rates, as opposed to less rutinary police stopping in the southern Minneapolis neighborhoods.
18. Use `leaflet` to create a map of your own choosing. Come up with a question you want to try to answer and use the map to help answer that question. Describe what your map shows.
>Does the education level of detained people have any relation to the geographic location at which they are stopped?
```{r}
pal <- colorNumeric(
"Spectral",
domain = mpls_all$collegeGrad)
leaflet(data = mpls_all) %>%
addTiles() %>%
addPolygons(fillColor = ~pal(collegeGrad),
color = "black",
fillOpacity = 1,
label = ~collegeGrad)
```
## GitHub link
19. Below, provide a link to your GitHub page with this set of Weekly Exercises. Specifically, if the name of the file is 04_exercises.Rmd, provide a link to the 04_exercises.md file, which is the one that will be most readable on GitHub.
**DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?**