---
title: "Homework 7: Loops, Functions, and Apply"
author: "YOUR NAME"
date: "DATE"
output: 
  html_document:
    preserve_yaml: true
    toc: true
    toc_float: true
published: false
---


```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(tidyr)
library(readr)
library(ggplot2)
```

# 1. For and While Loops

### Question 1.1: Write in words the difference between a `for` loop and a `while` loop.

> ANSWER: YOUR ANSWER HERE

### Question 1.2: Preallocate a matrix of NAs with 3 rows and 8 columns, called `double_matrix`. Manually specify the first column equal to the values 1, 2, and 3. Using a nested loop, fill in the matrix, row by row, such that each value is double that to its left.

For example, the first row of the matrix should be: `r c(1,2,4,8,16,32,64,128)`

```{r}
# [YOUR CODE HERE]
```

### Question 1.3: Ask ChatGPT the following question: "Write a while loop in R that samples the integers randomly between 1 and 100 until the number 50 is selected. Print how many iterations it took." Then, display the code ChatGPT wrote, say if it worked or not, and describe the steps ChatGPT took to reach a solution! (If it does not run, change the chunk option to `eval=FALSE`). ChatGPT can be accessed at chat.openai.com.

```{r eval=TRUE}
# [ChatGPT's CODE HERE]
```

> ANSWER: YOUR ANSWER HERE

### Question 1.4: Write a while loop that keeps "flipping 5 coins" until you get 5 heads. Have the function count how many sets of 5 coin flips it took until getting 5 heads, and return that number.

*Hint:* You can flip 5 coins using the code `rbinom(n=1,size=5,prob=.5)`. You have gotten 5 heads when the output is `5`.

```{r}
# [YOUR CODE HERE]
```


# 2. Functions

### Question 2.1: Pick a built-in R function and describe its input(s) and output(s).

> ANSWER: YOUR ANSWER HERE

### Question 2.2: Write a function, called `doubler`, that takes a single number as its input and returns a vector of length 8. The vector should contain the initial value, doubled consecutive times. Be sure to check if a single number was given!

*Hint:* If input is 1, output should be `c(1,2,4,8,16,32,64,128)`.

```{r}
# [YOUR CODE HERE]
```

### Question 2.3: Use `doubler` on the inputs 1, 2, and 3. Do you get the same values as in question 1.2? (You should!)

```{r}
# [YOUR CODE HERE]
```

# 3. Apply

### Question 3.1 Write an `apply()` statement to take the median value of each column in the `cars` dataset.

*Hint: Use the `median()` function inside your `apply()` command!*

```{r}
# [YOUR CODE HERE]
```

### Question 3.2 Using `ggplot`, make a scatterplot of the `speed` and `dist` variables in `cars`. Then, add an appropriate horizontal and vertical line symbolizing the median value of each variable.

*Hint:* Using the layers `geom_vline(xintercept = )` and `geom_hline(yintercept = )`

```{r}
# [YOUR CODE HERE]
```



