 
---
title: "Lab 9: Probability"
author: "Insert Name"
output:
  pdf_document
 
---

## Instructions

**Due: Before lab, April, 8th or 9th**

Read through the following document (it may be helpful to have both the .rmd and .pdf files open side-by-side). Interspersed throughout the text are 14 **Exercises**. Answer these questions in the .rmd file by inserting a code chunk or typing text between the stars directly below the exercise statement.


```{r, include=FALSE}
# Do not edit this code block/chunk
knitr::opts_chunk$set(echo = TRUE, message=FALSE, warning = FALSE, fig.width = 5, fig.height = 3)
```

### Load packages

For this lab we will read be using the `tidyverse` for data wrangling
and visualization and `oilabs` for the data set. `infer` is included as well, in case you decide to use it.

```{r, include=FALSE, message = FALSE, warning = FALSE}
library(tidyverse)
library(knitr)
library(oilabs)
library(infer)

set.seed(271)
```

## Background

The Graduate Record Exam (GRE) is a standardized test which serves as an admission requirement for many graduate schools, and has an analytic writing section and two multiple choice sections: Verbal Reasoning and Quantitative Reasoning. Due to forced Normalization in scores, both sections are approximately Normal. The mean score for Verbal Reasoning section was 462 with a standard deviation of 119, and the mean score for the Quantitative Reasoning was 584 with a standard deviation of 151.

We will use the above information to explore the use of the R functions `pnorm` and `qnorm`.

 * `pnorm` will return the **percentile**, or cumulative area of the curve to the left of a point on the x-axis, $q$, called a **quantile**.  
 
 * `qnorm` will return the value on the x-axis for a given **percentile**.
 
 
## Using `pnorm`
 
For instance, say a student earns a score of 650 on the Verbal Reasoning section of the exam.  Then to find the percentile for this student.

```{r}

tibble(
  percentile = pnorm(650,mean=462,sd=119)
)

```

Thus we see that the student is in the 94th percentile.  That is 94% of the values in the distribution are to the left of 650.  This is shown as the shaded region in the visualization below.

```{r, echo=FALSE}

min_val<-0
max_val<-1000

score = 650
m = 462
std = 119

ggplot(data.frame(x = c(min_val, max_val)), aes(x = x)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std), xlim = c(min_val, score),
                  geom = "area", fill = "#84CA72", alpha = .9) +
    scale_x_continuous(name = "Score", breaks = seq(min_val, max_val, std)) +
    scale_y_continuous(name="",breaks=NULL)

```

If we wanted to know what percentage of students scored better than 650, we calculate 1 minus the percentage to the left of the value.

```{r}

tibble(
  percent_better = 1 - pnorm(650,mean=462,sd=119)
)

```

The visualization below shows that this is, appropriately, in the right tail of the distribution.

```{r, echo=FALSE}

min_val<-0
max_val<-1000

score = 650
m = 462
std = 119

ggplot(data.frame(x = c(min_val, max_val)), aes(x = x)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std), xlim = c(score, max_val),
                  geom = "area", fill = "#84CA72", alpha = .9) +
    scale_x_continuous(name = "Score", breaks = seq(min_val, max_val, std)) +
    scale_y_continuous(name="",breaks=NULL)

```

## Using `qnorm`

Now lets imagine that a student is told that they scored in the 57% percentile on the Quantitative Reasoning section of the exam.  To find their score for this student.

```{r}

tibble(
  score = qnorm(.57,mean=584, sd = 151)
)

```

This student's score is thus a 610.

```{r, echo=FALSE}

min_val<-0
max_val<-1000

score = 610
m = 584
std = 151

ggplot(data.frame(x = c(min_val, max_val)), aes(x = x)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std), xlim = c(min_val, score),
                  geom = "area", fill = "#84CA72", alpha = .9) +
    scale_x_continuous(name = "Score", breaks = seq(min_val, max_val, std))+
    scale_y_continuous(name="",breaks=NULL)

```

### Exercise 1

What is the percentage of the students who score between 590 and 630 on the Quantitative Reasoning section?

*********************************************************************************

*********************************************************************************


### Exercise 2

What is the probability that a randomly selected student earns obtains a score greater than 600 on both multiple choice sections (assume, somewhat unrealistically, that scores on the two sections are independent)?

*********************************************************************************

*********************************************************************************

### Exercise 3

What score is needed on the Verbal Reasoning section to place in the top 10\%? What score is needed on the Quantitative Reasing section?

*********************************************************************************

*********************************************************************************


#### Standard Normal

Often it is useful to use the *Standard Normal*.  This is a normal distribution with a mean of 0 and a standard deviation of 1.  If we know that a value, $x$, is drawn from a normal distribution with a mean of $\mu$ and a standard deviation of $\sigma$, we can standardize it using the following formula:
$$
z = \frac{x - \mu}{\sigma}
$$
These standardized values are called **z-scores**.  We can calculate the z-score for the student who scored a 650 on the Verbal Reasoning section of the exam.

```{r}

score = 650
mu = 462
sigma = 119

tibble(
  z_score = (score - mu) / sigma
)

```

Note that for scores that are less than the mean, the z-score will be negative.  Imagine a student scored a 550 on the Quantitiative Reasoning section.

```{r}

score = 550
mu = 584
sigma = 151

tibble(
  z_score = (score - mu) / sigma
)

```

They have a z-score of -0.23.

### Exercise 4

A college senior scores 620 on the Verbal Reasoning section and 670 on the Quantitative Reasoning section. Calculate the student's z-scores for each section. 

*********************************************************************************

*********************************************************************************

### Exercise 5

In general, what does a z-score represent? On which section did the student in the previous part do better on (relative to the student's peers)? Find the student's percentile scores for the two sections.

*********************************************************************************

*********************************************************************************




## Hot Hands

Basketball players who make several baskets in succession are described as having a hot hand. Fans and players have long believed in the hot hand phenomenon, which refutes the assumption that each shot is independent of the next. However, a 1985 [paper](http://www.cs.colorado.edu/~mozer/Teaching/syllabi/7782/readings/gilovich%20vallone%20tversky.pdf) by Gilovich, Vallone, and Tversky collected evidence that contradicted this belief and showed that successive shots are independent events. This paper started a great controversy that continues to this day, as you can see by Googling **hot hand basketball**.

We do not expect to resolve this controversy today. However, we’ll apply one approach to answering questions like this. Over the next few exercises, we will (1) think about the effects of independent and dependent events, (2) learn how to simulate shooting streaks in R, and (3) to compare a simulation to actual data in order to determine if the hot hand phenomenon appears to be real.

These questions are modified from the following [lab](http://htmlpreview.github.io/?https://github.com/andrewpbray/oiLabs-base-R/blob/master/probability/probability.html) that uses the [Creative Commons License](https://creativecommons.org/licenses/by-sa/3.0/).



Our investigation will focus on the performance of one player: Kobe Bryant of the Los Angeles Lakers. His performance against the Orlando Magic in the 2009 NBA finals earned him the title **Most Valuable Player** and many spectators commented on how he appeared to show a hot hand. Let’s load some data from those games and look at the first several rows.

Run the following code chunk to download the data and the associated function `calc_streak`.

```{r}


download.file("http://www.openintro.org/stat/data/kobe.RData", destfile = "kobe.RData")
load("kobe.RData")
head(kobe)

```
 
In this data frame, every row records a shot taken by Kobe Bryant. If he hit the shot (made a basket), a hit, "H", is recorded in the column named `basket`, otherwise a miss, "M", is recorded.

Just looking at the string of hits and misses, it can be difficult to gauge whether or not it seems like Kobe was shooting with a hot hand. One way we can approach this is by considering the belief that hot hand shooters tend to go on shooting streaks. For this lab, we define the length of a shooting streak to be the number of consecutive baskets made until a miss occurs.

For example, in Game 1 Kobe had the following sequence of hits and misses from his nine shot attempts in the first quarter:
$$
H M | M | H H M | M | M | M
$$

This can be verified using the following code:
```{r}

kobe %>% 
  select(basket) %>% 
  head(9)

```


Within the nine shot attempts, there are six streaks, which are separated by a “|” above. Their lengths are one, zero, two, zero, zero, zero (in order of occurrence).

### Exercise 6

What does a streak length of 1 mean, i.e. how many hits and misses are in a streak of 1? What about a streak length of 0?

*********************************************************************************

*********************************************************************************


The custom function `calc_streak`, which was loaded in with the data, may be used to calculate the lengths of all shooting streaks and then look at the distribution. 
 
```{r}
 
streak <- kobe %>% 
  select(basket) %>% 
  pull() %>%  # calc_streak takes a vector as input 
  calc_streak()

# We need a dataframe for ggplot and streak is just a vector
streak <- tibble(
  consecutive_hits = streak
)


streak %>% 
  ggplot(aes(x=consecutive_hits)) +
  geom_bar() +
  labs(
    title = "Kobe Bryant Shooting Streaks: \n Game 1 2009 NBA Finals",
    x = "Consecutive Hits"
  )
```
 
## Compared to What?

We’ve shown that Kobe had some long shooting streaks, but are they long enough to support the belief that he had hot hands? What can we compare them to?

To answer these questions, let’s return to the idea of independence. Two processes are independent if the outcome of one process doesn’t effect the outcome of the second. If each shot that a player takes is an independent process, having made or missed your first shot will not affect the probability that you will make or miss your second shot.

A shooter with a hot hand will have shots that are **not** independent of one another. Specifically, if the shooter makes his first shot, the hot hand model says he will have a **higher** probability of making his second shot.

Let’s suppose for a moment that the hot hand model is valid for Kobe. During his career, the percentage of time Kobe makes a basket (i.e. his shooting percentage) is about 45%, or in probability notation,
$$
P(\rm{shot}~1 = H)=0.45
$$
If he makes the first shot and has a hot hand (**not** independent shots), then the probability that he makes his second shot would go up to, let’s say, 60%,
$$
P(\rm{shot}~2 = H~|~\rm{shot}~1 = H)=0.60
$$
As a result of these increased probabilites, you’d expect Kobe to have longer streaks. Compare this to the skeptical perspective where Kobe does not have a hot hand, where each shot is independent of the next. If he hit his first shot, the probability that he makes the second is still 0.45.
$$
P(\rm{shot}~2 = H~|~\rm{shot}~1 = H)=0.45
$$
In other words, making the first shot did nothing to effect the probability that he’d make his second shot. If Kobe’s shots are independent, then he’d have the same probability of hitting every shot regardless of his past shots: 45%.

Now that we’ve phrased the situation in terms of independent shots, let’s return to the question: how do we tell if Kobe’s shooting streaks are long enough to indicate that he has hot hands? We can compare his streak lengths to someone without hot hands: an independent shooter.
 
## Simulations in R

While we don’t have any data from a shooter we know to have independent shots, that sort of data is very easy to simulate in R. In a simulation, you set the ground rules of a random process and then the computer uses random numbers to generate an outcome that adheres to those rules. As a simple example, you can simulate flipping a fair coin with the following.

```{r}

coin <- tibble(
  outcomes = c("heads", "tails")
)

coin %>% 
  select(outcomes) %>% 
  pull() %>% # sample takes a vector
  sample(size=1,replace=TRUE) %>% 
  as_tibble() 

```

The tibble `coin` can be thought of as a hat with two slips of paper in it: one slip says "heads" and the other says "tails". The function `sample_n` draws one slip from the hat and tells us if it was a head or a tail.

Run the second command listed above several times. Just like when flipping a coin, sometimes you’ll get a heads, sometimes you’ll get a tails, but in the long run, you’d expect to get roughly equal numbers of each.

If you wanted to simulate flipping a fair coin 100 times, you could either run the function 100 times or, more simply, adjust the `size argument`, which governs how many samples to draw (the `replace = TRUE` argument indicates we put the slip of paper back in the hat before drawing again). Save the resulting vector of heads and tails in a new object called `sim_fair_coin`.

```{r}

sim_fair_coin <- coin %>% 
  select(outcomes) %>% 
  pull() %>% # sample takes a vector
  sample(size=100,replace=TRUE) %>% 
  as_tibble() 

sim_fair_coin %>% 
  group_by(value) %>% 
  summarize(count=n()) %>% 
  mutate(proportion=count/sum(count))
```
Since there are only two elements in `coin`, the probability that we “flip” a coin and it lands heads is 0.5. Say we’re trying to simulate an unfair coin that we know only lands heads 20% of the time. We can adjust for this by adding an argument called prob, which provides a vector of two probability weights.

```{r}

sim_unfair_coin <- coin %>% 
  select(outcomes) %>% 
  pull() %>% # sample takes a vector
  sample(size=100,replace=TRUE,prob=c(0.2,0.8)) %>% 
  as_tibble() 

sim_unfair_coin %>% 
  group_by(value) %>% 
  summarize(count=n()) %>% 
  mutate(proportion=count/sum(count))
```
`prob=c(0.2, 0.8)` indicates that for the two elements in the `coin` tibble, we want to select the first one, "heads", with probability 0.2 and the second one, "tails" with probability 0.8. Another way of thinking about this is to think of the outcome space as a bag of 10 chips, where 2 chips are labeled “head” and 8 chips “tail”. Therefore at each draw, the probability of drawing a chip that says “head”" is 20%, and “tail” is 80%.


### Exercise 7

In your simulation of flipping the unfair coin 100 times, how many flips came up heads?

*********************************************************************************

*********************************************************************************

In a sense, we’ve shrunken the size of the slip of paper that says “heads”, making it less likely to be drawn and we’ve increased the size of the slip of paper saying “tails”, making it more likely to be drawn. When we simulated the fair coin, both slips of paper were the same size. This happens by default if you don’t provide a `prob` argument; all elements in the `coin` tibble have an equal probability of being drawn.

If you want to learn more about sample or any other function, recall that you can always check out its help file.

```{r,include=FALSE}

?sample

```


## Simulating the Independent Shooter

Simulating a basketball player who has independent shots uses the same mechanism that we use to simulate a coin flip. To simulate a single shot from an independent shooter with a shooting percentage of 50% we type,

```{r}

shot <- tibble(
  outcomes = c("H", "M")
)

shot %>% 
  select(outcomes) %>% 
  pull() %>% # sample takes a vector
  sample(size=1,replace=TRUE) %>% 
  as_tibble() %>% 
  rename(basket = value)


```

To make a valid comparison between Kobe and our simulated independent shooter, we need to align both their shooting percentage and the number of attempted shots.

### Exercise 8

What change needs to be made to the `sample` function so that it reflects a shooting percentage of 45%? Make this adjustment, then run a simulation to sample 133 shots. Assign the output of this simulation to a new object called `sim_basket`.

*********************************************************************************

*********************************************************************************

With the results of the simulation saved as `sim_basket`, we have the data necessary to compare Kobe to our independent shooter. We can look at Kobe’s data alongside our simulated data.

##Comparing Kobe Bryant to the Independent Shooter

### Exercise 9

Using `calc_streak`, compute the streak lengths of `sim_basket`.  Describe the distribution of streak lengths. What is the typical streak length for this simulated independent shooter with a 45% shooting percentage? How long is the player’s longest streak of baskets in 133 shots?

*********************************************************************************

*********************************************************************************

### Exercise 10

If you were to run the simulation of the independent shooter a second time, how would you expect its streak distribution to compare to the distribution from the question above? Exactly the same? Somewhat similar? Totally different? Explain your reasoning.

*********************************************************************************

*********************************************************************************



### Exercise 11

How does Kobe Bryant’s distribution of streak lengths compare to the distribution of streak lengths for the simulated shooter? Using this comparison, do you have evidence that the hot hand model fits Kobe’s shooting patterns? Explain.

*********************************************************************************

*********************************************************************************


