-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_formatting.Rmd
409 lines (335 loc) · 16.9 KB
/
data_formatting.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
---
title: "Data Formatting & Augmentation"
output:
distill::distill_article:
toc: true
toc_depth: 4
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r echo=F}
library(ggmap)
library(rmarkdown)
library(sf)
library(tidyverse)
library(tools)
```
## Overview
It is nigh time to really soup up the data: we will augment some of it (tie-in other useful datasets or descriptions) and continue to reformat much of it. However, as discussed in **Data Intro**, some of the the data must, lamentably, be cleaned up by-hand. The following steps were done following the previous page but before the code of the present page:
* Rewrite some entries in the `Location` and `Place` data to be specific enough for geocoding via Google's API or my own knowledge. For example, "Brick Oven Pizza" was updated to "Brick oven Pizza New Haven," "my dorm" was updated to "Stiles Dorm," and so on.
* Fix wrong entries of "Off-campus" and "Not in New Haven" (`Dorm1`, `Dorm5`) if the response does not correctly correspond to the approximate location data (`Loc1`, `Loc5`). For example, if the listed dorm information is "Off-campus" but the corresponding location is outside of New Haven, it is updated to "Not in New Haven."
* Fix some cells where students write-in their own version of "NA."
* Delete a row which was obviously the same student who resubmitted in more detail some days later, after their initial survey draft had been finalized due to timeout.
Ideally the cleanup could all be done programatically; however, the only address validation offered by Qualtrics is for U.S. zipcodes, which was not granular enough for `Place` data and too restrictive for student `Location` data (given international travel). In addition, some important Stiles and Yale locations are too specific for geocoding services such as Google's to know (e.g. "Stiles Library" or "Stiles Game Room"), hence the need for some manual intervention. The resultant dataframes, one for general survey responses (cleaned up `Location` data) and one for meaningful/nostalgic places (cleaned up `Place` data), were then saved as CSVs with the `_locclean` suffix to the filename.
In the sections to follow, a nomenclature for talking about the different time periods of 2020 is developed, and then the data is finally prepped for **Connectedness (Feeling Connected)**, **Student Locations (Mapping Moose)**, and **Meaningful/Nostalgic (Key) Places**.
<!-- TODO: also for Missing moose!!!
Some data is also a handmade set of geographic polygons corresponding to the different dorms that have housed Stiles students.-->
```{r}
t <- "20201227_235052"
data.students.loc <- read.csv(paste0("data/students_", t, "_locclean.csv")) %>%
select(-c(Email, starts_with("Place"))) %>%
# New variable: we couldn't do this in the last page since the data wasn't fully cleaned.
mutate(Housing.F20=case_when(
grepl("Stiles", Dorm5) ~ "Stiles",
grepl("Vanderbilt|LW", Dorm5) ~ "Old Campus",
Dorm5 == "Off-campus" ~ "Off-Campus",
Dorm5 == "Not in New Haven" ~ "Remote",
T ~ Dorm5))
```
## Prep for Mapping Moose
### Epochs & Waypoints
For each time period ("epoch" as dicussed on the [previous page](data_intro.html#interpretation)), students could list an arbitrary number of locations in which they resided over that time. Let's expand those places into new columns ("waypoints"), each named Loc<sub>e,w</sub> where `e` is the epoch (time period) and `w` is the numbered waypoint. For the sake of these visualizations, we assume that the waypoints are equally spaced in time. This interpolation is obviously not the case, but seems a reasonable compromise for not making respondents fill in every single precise date.
#### Lengthen
```{r}
data.locations <- data.students.loc %>%
# Convert each Location column from a string (delimited by ";") to a str vector
mutate(across(c(Loc1, Loc2, Loc2.5, Loc3, Loc4, Loc5, Loc6), str_split, pattern=";")) %>%
# First lengthening: pivot Location columns into rows (clarifying that Location is an address)
pivot_longer(c(Loc1, Loc2, Loc2.5, Loc3, Loc4, Loc5, Loc6),
names_to=c("Epoch"),
names_pattern="Loc(.*)",
values_to="Address") %>%
# Second lengthening: un-nest the string vector we made, essentially pivoting
# each with containing vectors to multiple rows containing elements. The number
# of places that a respondent lists becomes the number of "Waypoints" that
# they go through in a given epoch.
unnest_longer(Address, indices_to="Waypoint") %>%
# Cleanup
mutate(Address=trimws(Address)) %>%
arrange(ID, Epoch, Waypoint)
# How many Waypoints end up in each Epoch?
mw <- data.locations %>% group_by(Epoch) %>% summarize(MaxWaypoint=max(Waypoint))
mw
```
Note that many respondents don't have data listed for some Waypoints, since not everyone listed the same number of locations in each epoch. (In fact, the majority didn't move around that much within each epoch.) We just assume that their location stays constant until the next-provided location.
#### Identify Epochs & Waypoints
We now add in a couple of ways to help the visualizations make a bit more sense out of the Epoch/Waypoint nomenclature. In one we'll convert Epoch/Waypoint to days of the year (from 1 to 365), and in another just a string combination of the Epoch/Waypoint labels.
First: approximate dates of 2020.
```{r}
# Compute day of the year
epoch_days <- c("1"=13, "2"=67, "2.5"=76, "3"=83, "4"=128, "5"=244, "6"=327, "7"=366)
n_waypoints <- setNames(
mw$MaxWaypoint,
nm=mw$Epoch
)
epoch_lengths <- setNames(
epoch_days[2:8] - epoch_days[1:7],
mw$Epoch
)
waypoint_days <- data.locations %>%
select(Epoch, Waypoint) %>%
unique() %>%
mutate(days_no_waypt=epoch_days[Epoch]) %>%
mutate(waypt_duration=round(
(epoch_lengths[Epoch] / n_waypoints[Epoch]) * (as.numeric(Waypoint) - 1)
)) %>%
mutate(Day=(days_no_waypt + waypt_duration)) %>%
select(-c(days_no_waypt, waypt_duration)) %>%
arrange(Day, Waypoint)
waypoint_days <- waypoint_days %>%
mutate(EndDay=c(waypoint_days$Day[2:n()] - 1, 365))
waypoint_start <- waypoint_days %>%
select(!EndDay) %>%
pivot_wider(names_from=Waypoint, values_from=c(Day)) %>%
column_to_rownames("Epoch")
waypoint_end <- waypoint_days %>%
select(!Day) %>%
pivot_wider(names_from=Waypoint, values_from=c(EndDay)) %>%
column_to_rownames("Epoch")
# The above computation is equivalent to the following (except in ragged matrix form):
# waypoint_days <- matrix(nrow=7, ncol=max(n_waypoints), dimnames=list(c(1, 2, "2.5", 3, 4, 5, 6), NULL))
# for (e in 1:nrow(waypoint_days)) {
# for (w in 1:n_waypoints[e]) {
# duration_we <- round(epoch_lengths[e] / n_waypoints[e]) * (w - 1)
# waypoint_days[e, w] <- epoch_days[e] + duration_we
# }
# }
```
Now we augment the data just a little bit more to complete our assumption that people's locations stayed constant until the next-provided location. In order to make for sane interpolations when animating people's movements on a map, we want to clarify their location immediately prior to the next epoch. Otherwise, some people might slowly interpolate across the country over a series of many days.
```{r}
get_day.V <- Vectorize(function(e, w) {
return(as.numeric(waypoint_start[e, w]))
})
get_endday.V <- Vectorize(function(id, e, w) {
s <- data.locations %>% filter(ID==id & Epoch==e)
last_waypoint_overall <- n_waypoints[e]
last_waypoint_student <- max(s$Waypoint)
last_waypoint <- ifelse(w != last_waypoint_student, w, last_waypoint_overall)
return(as.numeric(waypoint_end[e, last_waypoint]))
})
data.locations <- data.locations %>%
mutate(start=get_day.V(Epoch, Waypoint)) %>%
mutate(end=get_endday.V(ID, Epoch, Waypoint)) %>%
pivot_longer(c(start, end), values_to="Day", names_to="DayType")
```
```{r}
# Sorry, this isn't tidy in the slightest. It involves selectively duplicating
# and then modifying rows, which is much more readable and approachable via loops.
# for s in students
# for (id in unique(data.locations$ID)) {
# s <- data.locations %>% filter(ID==id)
# # for e in epochs
# for (e in c(1, 2, "2.5", 3, 4, 5, 6)) {
# # get the students' last waypoint in epoch t
# w <- s %>% filter(Epoch==e)
# mw <- max(w$Waypoint)
# # copy that row, but set Waypoint to "end" and Day to (next epoch start - 1)
# new_row <- w %>% filter(Waypoint==mw) %>%
# mutate(Waypoint="end") %>%
# mutate(Day=epoch_days[which(names(epoch_days)==e)+1]-1)
# data.locations <- data.locations %>% rbind(new_row)
# }
# }
```
Finally: a simple label that pastes Epoch-Waypoint together, and a formatted Y-M-D date.
```{r}
data.locations <- data.locations %>%
mutate(TimeEW=paste0("t", Epoch, "-", Waypoint, DayType)) %>%
select(!DayType) %>%
mutate(Date=as.Date(Day, origin="2020-01-01", tz=UTC))
```
```{r}
data.locations.conn <- data.locations
data.locations <- data.locations %>% select(-c(Conn1:Conn6))
```
```{r echo=F, eval=F}
# We used to to this MUCH less tidily, and then it was modified when I returned
# to make the "-end" waypoint to help make interpolations more realistic for
# Mapping Moose. Code is saved for posterity.
# Given a vector of strings representing locations, returns the jth location if
# available, else the last location in the vector. Used to "extract" locations
# after the original data has been split into a vector with str_split.
extract_location <- function(vec, j) {
if (length(vec) >= j) return(trimws(vec[j]))
else return(trimws(vec[length(vec)]))
}
extract_location.V <- Vectorize(extract_location)
# Expand waypoints into new columns. For each epoch, the number of waypoints is
# the maximum number of locations (separated by ";") that any respondent lists.
# For responses which list fewer locations than the maximum at that time period,
# duplicate those locations through the remaining waypoints as necessary.
is <- c(1, 2, "2.5", 3, 4, 5, 6)
for (i in is) {
loc <- paste0("Loc", i)
# Split each epoch of locations into a vector by the ";" delimiter.
data.students.loc <- data.students.loc %>%
mutate(across(.data[[loc]], str_split, pattern=";"))
# Extract those vectors into new waypoint columns, duplicating information
# when necessary.
n_waypoints <- max(sapply(map(data.students.loc[[loc]], length), max)) # [1]
for (j in 1:n_waypoints) {
loc_j <- paste0(loc, "_", j,)
data.students.loc <- data.students.loc %>%
mutate("{loc_j}" := extract_location.V(.data[[loc]], j)) # [2]
}
}
# [1] https://stackoverflow.com/questions/11498155/by-commandto-find-out-the-maximum-number-from-a-list
# [2] https://dplyr.tidyverse.org/reference/dplyr_data_masking.html#dot-dot-dot-
# This shows the number of waypoints for each epoch. Column names for each
# waypoint W in each epoch E should be "LocE_W."
data.students.loc <- data.students.loc %>%
select(-c(Loc1, Loc2, Loc2.5, Loc3, Loc4, Loc5, Loc6))
colnames(data.students.loc)
```
```{r eval=F, echo=F}
# Old code that re-merged Connectedness with Location data. Again kept for posterity.
get_connectedness <- function(epoch, id) {
return(as.numeric(data.connectedness %>%
filter(Epoch==ifelse(epoch=="2.5", "2", epoch) & ID==id) %>%
select(Connectedness))
)
}
get_connectedness.V <- Vectorize(get_connectedness)
data.locations.conn <- data.locations %>%
mutate(Connectedness=get_connectedness.V(Epoch, ID))
```
### Geocode with Google
Final and most important augmentation here.
```{r eval=F}
# Reduce the list of many locations into unique locations, and geocode those
locations_unique <- data.locations %>%
# Get just unique addressess
select(Address) %>%
unique() %>%
# Geocode
mutate_geocode(Address) %>%
st_as_sf(coords=c("lon", "lat"), crs=4326) # Note that order should be LON, LAT
# Lookup those geocoded coordinates for each (non-unique) location in the full table
get_location_sf.V <- Vectorize(function(address) { return((locations_unique %>% filter(Address==address))$geometry) })
data.locations <- data.locations %>%
mutate(geometry=get_location_sf.V(Address)) %>%
st_as_sf()
# Save
saveRDS(data.locations, file=paste0("data/locations_", t, ".rds"))
```
Converts to Simple Features, which we love <3. Final product in the table below.
### Data Table (Mapping Moose)
```{r}
data.locations <- readRDS(paste0("data/locations_", t, ".rds"))
paged_table(sample_n(data.locations, n()))
```
## Prep for Connectedness
### Lengthen
```{r}
# N.b., Waypoint data was not collected for Connectedness
data.connectedness <- data.students.loc %>%
select(-c(Loc1:Loc6)) %>%
pivot_longer(Conn1:Conn6,
names_to="Epoch",
names_pattern="Conn(.*)",
values_to="Connectedness")
```
### Calculate Day of Year
Thankfully most of the setup work for this was done in the previous section :-).
```{r}
data.connectedness <- data.connectedness %>% mutate(Day=epoch_days[Epoch])
```
We also want to extend the data through 2020 (the 365th day) for the sake of visualizing estimated Connectedness through the year.
```{r}
data.connectedness <- data.connectedness %>%
rbind(data.connectedness %>%
filter(Epoch==6) %>%
mutate(Epoch=7, Day=365))
```
### Data Table (Connectedness)
```{r}
paged_table(sample_n(data.connectedness, n()))
write.csv(data.connectedness, paste("data/connectedness_", t, ".csv", sep=""), row.names=F)
```
## Prep for Nostalgia/Meaning
Similarly, we want to Geocode the "Place" data asking about nostalgia/meaning. However, as with the student Location data, we first needed to hand-clean the Place data in order to clarify certain locations. In addition, some places were removed for being vague or not specific enough, and some incorrect labels of Physical or Virtual were corrected.
Note, however, that there are some special places which aren't lookup-able by Google or other geocoding services:
* Stiles common room
* Stiles dining hall
* Stiles dorm
* Stiles library
* Stiles buttery
* Stiles game room
* Stiles kitchen
* Stiles courtyard
* Stiles gym
* Stiles music room
* Crescent courtyard
These occurrences are separated from the table and mapped to coordinates by manual lookup data. The remaining physical locations are geocoded as above.
```{r}
data.places <- read.csv(paste0("data/places_", t, "_locclean.csv")) %>%
mutate(Name=trimws(toTitleCase(Name)))
data.places.stiles <- data.places %>%
filter(Type=="Physical" & str_detect(Name, "(?i)stiles")) # ?i is case-insensitive regex
data.places.yale <- data.places %>%
filter(Type=="Physical" & !str_detect(Name, "(?i)stiles"))
data.places.virt <- data.places %>%
filter(Type=="Virtual")
```
### Geocode by Hand
```{r}
# Map stiles spots to GPS
places.yale <- read.csv("data/yale.locations.csv")
# Although this could be done with tidy functions (leaning heavily on case_when),
# I think this approach is more readable and is much less repetitive. With small
# data, the performance is no problem.
get_yale_coord <- function(name, col) {
n <- case_when(
str_detect(name, "(?i)common") ~ "Common Room",
str_detect(name, "(?i)dining") ~ "Dining Hall",
str_detect(name, "(?i)dorm") ~ "Dorm",
str_detect(name, "(?i)library") ~ "Library",
str_detect(name, "(?i)buttery") ~ "Buttery",
str_detect(name, "(?i)game") ~ "Game Room",
str_detect(name, "(?i)kitchen") ~ "Kitchen",
str_detect(name, "(?i)crescent") ~ "Crescent Courtyard",
str_detect(name, "(?i)music") ~ "Music Room",
str_detect(name, "(?i)gym") ~ "Gym",
str_detect(name, "(?i)courtyard") ~ "Courtyard",
T ~ "Stiles"
)
return(places.yale %>% filter(Name==n) %>% select(col))
}
get_yale_coord.V <- Vectorize(get_yale_coord)
data.places.stiles <- data.places.stiles %>%
mutate(lon=get_yale_coord.V(Name, "Lon")) %>%
mutate(lat=get_yale_coord.V(Name, "Lat"))
```
### Geocode by Google
```{r eval=F}
# Automocatically geocode (google) all other spots to GPS
data.places.yale <- data.places.yale %>%
mutate_geocode(Name)
# Sanity check
range(data.places.yale$lon[is.finite(data.places.yale$lon)]) # [1] -73.32775 -72.89932
range(data.places.yale$lat[is.finite(data.places.yale$lat)]) # [1] 41.11225 41.34746
```
### Save!
(A sufficient data table was given on the previous page.)
```{r eval=F}
# Merge & save
data.places.physical <- data.places.yale %>%
rbind(data.places.stiles) %>%
mutate(lon=unlist(lon), lat=unlist(lat))
write.csv(data.places.physical, paste0("data/places.physical_" , t, ".csv"), row.names=F)
```
Virtual places must remain as-is, as Science has not yet determined how to map the virtual realm onto the real world of latitude, longitude coordinates. Instead we will make a WORD CLOUD :D.
```{r}
write.csv(data.places.virt, paste0("data/places.virt_" , t, ".csv", sep=""), row.names=F)
```