---
title: "ETC 1010 Lab 2"
output: html_document
---

```{r, echo = FALSE, message = FALSE, warning = FALSE, warning = FALSE}
knitr::opts_chunk$set(
  message = FALSE,
  warning = FALSE,
  error = FALSE, 
  collapse = TRUE,
  comment = "",
  fig.height = 8,
  fig.width = 12,
  fig.align = "center",
  cache = FALSE
)
```

# Instructions

In this week's lab, the main goal is to learn how to tidy a data set. On the due date, turn in your Rmd file and the html product. 

## Exercise 1

Open your project for this class. Make sure all your work is done relative to this project.

Open the `lab2.Rmd` file provided with the instructions. You can add your answers to questions from this document.

## Exercise 2 

These are warmups for the later questions. We will work through the examples in the lecture notes, and make sure that they all work for you, and that you know what each function does.

a. Tidy the genes data. 
    i. Which function makes the long tidy form? 
    ii. Which function separates the text strings into two variables? 
    iii. What two functions create new text values that have no leading "W"?

```{r}
library(tidyverse)
genes <- read_csv("genes.csv")
gtidy <- genes %>%
  gather(variable, expr, -id) %>%
  separate(variable, c("trt", "leftover"), "-") %>%
  separate(leftover, c("time", "rep"), "\\.") %>%
  mutate(trt = sub("W", "", trt)) %>%
  mutate(rep = sub("R", "", rep))
```

b. Tidy the Melbourne weather station data. 
    i. What does the function `read.fwf` do? What does the argument `c(11, 4, 2, 4, rep(c(5, 1, 1, 1), 31))` do in the function?
    ii. What is the difference between `[]` and `()`? What does `[,c(1,2,3,4,seq(5,128,4))]` do in the second line?
    iii. Which function removes records other than the temperature and precipitation?
    iv. What does the `spread` function do here?
    v. Why do the raw temperature and precipitation values get divided by 10?

```{r echo=TRUE}
melbtemp <- read.fwf("ASN00086282.dly", 
                     c(11, 4, 2, 4, rep(c(5, 1, 1, 1), 31)), fill=T)
melbtemp <- melbtemp[,c(1,2,3,4,seq(5,128,4))]
colnames(melbtemp) <- c("id", "year", "month", "var", paste0("V",1:31))
melbtemp <- melbtemp %>% 
  gather(day, value, V1:V31) %>%
  mutate(day = sub("V", "", day)) %>%
  mutate(value=ifelse(value==-9999, NA, value)) %>%
  filter(var %in% c("PRCP", "TMAX", "TMIN")) %>%
  spread(var, value) %>%
  mutate(PRCP=PRCP/10, TMAX=TMAX/10, TMIN=TMIN/10)
```

## Exercise 3

[41% Of Fliers Think You’re Rude If You Recline Your Seat](http://fivethirtyeight.com/datalab/airplane-etiquette-recline-seat/). In the following table, V1 is a response to the question "Is it rude to recline your seat on a plane?", and V2 is the response to the question "Do you ever recline your seat when you fly?". 

```{r}
fly_tbl <- read_csv("fly_tbl.csv")
library(knitr)
kable(fly_tbl)
```

a. What are the variables in this data?
b. Tidy the data. 

## Exercise 4

For the data set, `rates.csv`, 

```{r}
rates <- read_csv("rates.csv")
head(rates)
```

a. Write down what the variables are.
b. Make a time series (line plot) of the Australian dollar cross rate with the USA. What day was the best day to exchange USD into AUD?
c. Focusing on the five currencies, AUD, GBP, JPY, CNY, CAD, make it into tidy form, show the code.
d. Make a facetted time series plot of the five currencies, where each currency is shown on its own scale. Is there a predominant pattern among these 5 currencies, of rate relative to the USD? Is there a currency trending differently?


## Exercise 5

Read in the billboard top 100 music data, which contains N'Sync and Backstreet Boys songs that entered the billboard charts in the year 2000.

```{r}
billboard <- read_csv("billboard.csv")
```

a. What's in this data? What's `1`-`76`? What are the variables?
b. Convert this data into a long format appropriate for plotting a time series (date on the x axis, chart position on the y axis)
c. Make a time series plot, where each song is its own line, and the line is coloured by the artist. It should look like this. Which song was the most successful? What song was the least successful? (Explain your reasoning, or metrics, for saying a song is more or less successful.)

![](lab2_songs.png)

```{r echo=FALSE, fig.height=3, eval=FALSE}
long_billboard <- billboard %>% 
  gather(key = week, value = rank, `1`:`76`) %>%
  mutate(week = as.numeric(week), rank=as.numeric(rank)) %>%
  filter(!is.na(rank))

ggplot(data = long_billboard, 
       aes(x=week, y=rank, colour = artist, group = track)) +
  geom_line() +
  scale_y_reverse() +
  theme(legend.position="bottom")
ggplotly()
```

## Exercise 6

This data was pulled from [https://www.whaleshark.org](https://www.whaleshark.org) in 2013. It lists verified encounters with whale sharks across the globe. 

```{r}
whalesharks <- read_csv("whaleshark-encounters.csv")
```
a. Is a whale shark, a whale?
b. What are the observations is this data?
c. What info potentially is replicated on multiple lines? That is, the records are an example of repeated measurements, sometimes called longitudinal or panel data.
d. Compute the number of records for each whale shark, where their identity is known, `Marked Individual`. What individual has the most sightings? How many unmarked individuals are recorded in the database?
e. Let's make a map of the encounters. Code is below. What part of the code below draws the map? What part adds points for the encounters?
f. Change the code colour males and females differently. Do males and females roam the same locations?

```{r fig.height=3, fig.width=5}
library(maps)
library(ggthemes)
world_map <- map_data("world")
ggplot(world_map) + 
  geom_polygon(aes(x=long, y=lat, group=group), 
               fill="grey90", colour="white") + 
  theme_map() +
  geom_point(data=whalesharks, aes(x=Longitude, y=Latitude),
             colour="salmon", alpha=0.5)
```

```{r eval=FALSE}
ggplot(world_map) + 
  geom_polygon(aes(x=long, y=lat, group=group), 
               fill="grey90", colour="white") + 
  theme_map() +
  geom_point(data=filter(whalesharks, !is.na(Sex)),
             aes(x=Longitude, y=Latitude,
                                   colour=Sex),
             alpha=0.5)
```

## Exercise 7

The file `budapest.csv` has a subset of web click through data related to hotel searches for Budapest. Each line in this data corresponds to a summary of a person looking for a hotel on the Expedia web site. For these questions, the answer don't require you to code, but to map out what operations you need to make on the data.

```{r}
budapest <- read_csv("budapest.csv")
```

a. Is the data in tidy form? What are the observations, and list a couple of the variables.
b. If I want to answer this question __"What proportion of people searching, actually booked a hotel room?"__ what would I need to do to the data? (The variable recording the searcher's final decision is CLICK_THRU_TYP_ID , and the code indicating a booking is `3406`).
c. If I want to answer the question __"What day of the week are most people seaching for hotels?"__ what would I need to do with the data? (There are two date variables in the data, one when they are searching, SRCH_DATETM, and the other what dates they want to hotel room, SRCH_BEGIN_USE_DATE, SRCH_END_USE_DATE.)
d. If I want to answer the question __"How far ahead of the check-in date do people typically search for a hotel room?"__ what needs to done with the data.
e. If I want to answer the question __"Does the existence of a promotion, IS_PROMO_FLAG, tend to result in a higher likelihood of a booking?"__ what operations do you need to do on the data.
f. There are a lot of missing values in the data, number of NAs, particularly this is true for the booking variable. If an NA essentially means that the person searching quit the site without doing a booking, how would you recode the missing value?
