---
title: "Homework 3 - Wrangling Spatial Data"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(eval = TRUE)
```

```{r warning = FALSE, message = FALSE}
library(tidyverse)
```

This exercise continues what we started in Lab 5 by looking more closely at the actual distances between Denny&rsquo;s restaurants and La Quinta motels.

## The Document

Start by creating a new RMarkdown document named `hw3-laquinta.Rmd`  using the standard homework format.

## The Purpose

Our goal is to continue our consideration of the validity of the claim and La Quinta Hotels are often next to Denny&rsquo;s restaurants.

## Loading Data

Upload copies of the [datasets](./data) and load them as you did in the lab.

```{r load-data, message=FALSE}
dennys <- read_rds("data/dennys.rds")
laquinta <- read_rds("data/laquinta.rds")
states <- read_csv("data/states.csv", col_types = cols(
  name = col_character(),
  abbreviation = col_character(),
  area = col_double()
))
```

Note here that some of the dataset files use the RDS format, which differs from the CSV format in that it is binary (not readable using a text editor) and represents R data structures more directly and more efficiently.

## Exercises

1.  Filter the Denny&rsquo;s dataframe for Alaska (AK) and save the result as `dn_ak`. How many Denny&rsquo;s locations are there in Alaska?

2.  Filter the La Quinta dataframe for Alaska (AK) and save the result as `lq_ak`. How many La Quinta locations are there in Alaska?

Next we'll calculate the distance between all Denny&rsquo;s and all La Quinta locations in Alaska.
Let's take this step by step:

**Step 1:** There are 3 Denny&rsquo;s and 2 La Quinta locations in Alaska.
(If you answered differently above, you might want to recheck your answers.)

![](images/dennys-laquinta-sketches.001.png){width="200px"}

**Step 2:** Let's focus on the first Denny&rsquo;s location.
We'll need to calculate two distances for it: (1) distance between Denny&rsquo;s 1 and La Quinta 1 and (2) distance between Denny&rsquo;s 1 and La Quinta (2).

![](images/dennys-laquinta-sketches.002.png){width="250px"}

**Step 3:** Now let's consider all Denny&rsquo;s locations.

![](images/dennys-laquinta-sketches.003.png){width="250px"}

3.  How many pairings are there between all Denny&rsquo;s and all La Quinta locations in Alaska, i.e. how many distances do we need to calculate between the locations of these establishments in Alaska?

In order to calculate these distances we need to first restructure our data to pair the Denny&rsquo;s and La Quinta locations. To do so, join the two data frames **by `state`** using the form of join that keeps all rows and columns from both `dn_ak` and `lq_ak` data frames. Name the result `dn_lq_ak`.

4.  How many observations are in the joined `dn_lq_ak` data frame? What are the names of the variables in this data frame?

Notice the suffixes `.x` and `.y` on the variable names.
The two data frames both had the same variables, so how could we tell which data came from which data frame?
The `.x` comes from the first dataframe, `.y` from the second. But that's not very informative, so: add `suffix = c("_dn", "_lq")` as an argument to the join function so that the variables have informative names.

Now that we have the data in the format we wanted, all that is left is to calculate the distances between the pairs.

5. Add a new variable, called `distance` to the `dn_lq_ak` data frame that contains
    the distances between each Denny&rsquo;s and La Quinta locations. Make sure to
    save the result back to `dn_lq_ak` so that you can use it later.

Because the Earth is spherical rather than flat, we use the great-circle distance, which can be calculated using the Haversine distance formula. Because this is not a built-in function, we've provided an implementation for you; just paste this code chunk (including attribution) into your Rmd file:

```{r}
# Great-circle distance, Implementation from dsbox
haversine <- function(long1, lat1, long2, lat2) {
  # convert to radians
  long1 = long1 * pi / 180
  lat1  = lat1  * pi / 180
  long2 = long2 * pi / 180
  lat2  = lat2  * pi / 180
  
  # Earth mean radius in km (WGS84 ellipsoid)
  R = 6371.009
  
  # Compute the distance in km
  a = sin((lat2 - lat1)/2)^2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)^2
  d = R * 2 * asin(sqrt(a))
  return(d)
}
```

This function takes four arguments:

-   Longitude and latitude of the first location
-   Longitude and latitude of the second location

**Note**: Longitude comes first!

Here is an example call to this function, to measure the distance between North Hall and the Ecosystem Preserve.

```{r}
longitude_northhall <- -85.58896068095257
latitude_northhall  <-  42.93194236658063
longitude_preserve  <- -85.58222583860328
latitude_preserve   <-  42.931890017996466
haversine(longitude_northhall, latitude_northhall, longitude_preserve, latitude_preserve)
```

When I measure this distance on Google Maps, I get about 520 meters (about 1700 feet) -- well within the margin of error of my clicking.


6.  For each La Quinta location, calculate the distance to the nearest Denny&rsquo;s.
    To do so, group by La Quinta locations (consider the `address` as a unique identifier) and compute the `min()` of all of the corresponding `distance` values. Assign this to a new data frame.
    
    Hint: this data frame will have one row for each La Quinta's location in Alaska.

    Here&rsquo;s what we get (once I put latitude and longitude in the right order):
    
```
# A tibble: 2 × 2
  address_lq         dist_to_nearest
  <chr>                        <dbl>
1 3501 Minnesota Dr.            2.03
2 4920 Dale Rd                  5.20
```

> Alternative, if it makes more sense to you:
>
> - Group by La Quinta location, then 
> - Sort by `distance`, then
> - `slice_head()` to pick out the first row in each group.
>
> This results in:
> 
> ```
> # A tibble: 2 × 5
> # Groups:   address_lq, city_lq [2]
>   address_lq         city_lq       address_dn       city_dn   distance
>   <chr>              <chr>         <chr>            <chr>        <dbl>
> 1 3501 Minnesota Dr. "\nAnchorage" 2900 Denali      Anchorage     2.03
> 2 4920 Dale Rd       "\nFairbanks" 1929 Airport Way Fairbanks     5.20
> ```

7.  Are there any La Quinta locations in Alaska that are &ldquo;next to Denny&rsquo;s&rdquo;? Refer to the result of the previous exercise.

8. Pick another state and perform the same analysis as you did above. What are the results and are they any different from what you found for Alaska?

<!--
THESE ARE BASED ON FUNCTIONS. SKIP THEM IN HW 3.

8.  Write a function to perform the analysis for a given state. The function should take a state name (e.g., `"NC"`) and
return the distances from each La Quinta location in that state to the closest Denny&rsquo;s. 

Remember that functions:

- Let us bundle up a multi-part computation (like our distance calculations here) and give it a name.
- Can take *parameters*, which work like placeholders that can get filled in with different values (like different states).
- Have a *local scope*: variables you define inside a function stay inside of it.
- Can *return* a value: when we evaluate `sqrt(4) - 1`, the `sqrt` function *returns* 2... and that gets substituted on the left side of the subtraction so we evaluate `2 - 1` to get 1.

R functions work pretty much the same way as Python functions. The syntax is slightly different so I'll help you with it. Here&rsquo;s the outline of how to write an R function for this:

```{r eval=FALSE}
compute_closest_dennys <- function(the_state) {
  dn_state <- dennys %>% 
    filter(state == the_state)
  lq_state <- laquinta %>% 
    filter(state == the_state)
  
  # join to get all possible pairings
  
  # compute distances
  
  # compute distance to closest Denny's for each La Quinta location,
  # assign it to "dist_to_closest"
  dist_to_closest <- ...
  
  return(dist_to_closest)
}
```

*Caution*: You should copy and paste from your earlier code, but be sure to change everything from Alaska-specific.

*Optional aside*: It turns out that a full join isn't quite the best join for this. Can you think of a case where `full_join` gives some unwanted results?

9. Use the function you just wrote to compute the distances-to-closest-Denny&rsquo;s for NC. Then, describe the distribution of the distances using **summary statistics** (median, min, etc.) and an **appropriate visualization**.

Note: If you end up grouping by more than one variable, you may need to `ungroup()` before computing a summary statistic, depending on how you do it.

Here&rsquo;s what we get for NC:

```
## # A tibble: 12 x 3
##    address_lq                   city_lq           dist_to_nearest
##    <chr>                        <chr>                       <dbl>
##  1 4900 South Tryon St          "\nCharlotte"                1.78
##  2 2211 Summit Park Ln          "\nRaleigh"                  5.04
##  3 4414 Durham Chapel Hill Blvd "\nDurham"                   5.06
##  4 1910 Westpark Dr             "\nDurham"                   6.30
##  5 3127 Sloan Dr                "\nCharlotte"                9.17
##  6 191 Crescent Commons         "\nCary"                    11.9 
##  7 1001 Hospitality Ct          "\nMorrisville"             14.5 
##  8 1001 Aerial Center Pkwy      "\nMorrisville"             14.6 
##  9 1201 Lanada Rd               "\nGreensboro"              19.1 
## 10 2020 Griffith Rd             "\nWinston-Salem"           20.1 
## 11 1607 Fairgrove Church Rd     "\nConover"                 38.5 
## 12 165 Hwy 105 Extension        "\nBoone"                   55.4
```

```
## # A tibble: 1 x 2
##   `min(dist_to_nearest)` `median(dist_to_nearest)`
##                    <dbl>                     <dbl>
## 1                   1.78                      13.2
```

10.  Repeat the same analysis for Texas.

11. Repeat the same analysis for a state of your choosing, different than the ones we covered so far.

12. Among the states you examined, where is Mitch Hedberg's joke most likely to hold true?
    Explain your reasoning.
-->
