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

# About this exercise

This exercise goes with **Chapter 3, R Basics**. It should take you about **one hour**. Read this whole section before you start.

## Purpose

**Skills you'll practice.** By the end of this exercise you will be able to:

1. Run the chunks of an R Markdown file in order, and use **Restart R and Run All Chunks** to check that a file will knit.
2. Install a package once (with the Packages tab) and load it in every file (with `library()`).
3. Make vectors of each of R's four basic data types (logical, integer, numeric, and character) and check them with `class()`.
4. Spot and fix **coercion**, when one stray value turns a column of numbers into text.
5. Name variables clearly and consistently in snake_case.
6. Read an error message, find the broken line, and fix it.
7. Use a help page to learn how a function works.

**Knowledge you'll gain.** You'll learn how much six North Carolina cities grew between the 2010 and 2020 Censuses.

**Why this matters.** Every map and analysis in this course is built on these pieces. Most of the problems students hit in the first few weeks come from one of them: chunks run out of order, a package that was never loaded, a number stored as text, or an error message nobody read. If you can catch these problems yourself, you'll spend much less time stuck later on. Checking that numbers really are numbers is also a skill professional analysts use every day, because real data is messy.

## Task

Work through Parts 1 to 8 in order, top to bottom. In each part:

- Read the short explanation, then do each step marked with a bullet (•).
- Wherever you see `___`, replace it with the missing code **before** you run the chunk. A chunk with `___` in it won't run.
- Answer each question (**Q1**, **Q2**, ...) in a sentence or two of Markdown, where it says *Your answer here.* Delete *Your answer here.* when you write your answer.
- Run each chunk with the green arrow or Ctrl+Enter (Cmd+Return on a Mac), and look at the output before you move on.

| Part | What you'll do | About |
|:-----|:---------------|:------|
| 1 | Set up your file | 5 min |
| 2 | See why the order you run code in matters | 8 min |
| 3 | Install and load a package, and read a help page | 10 min |
| 4 | Make vectors of each data type and do math with them | 12 min |
| 5 | Find and fix coercion | 8 min |
| 6 | Rename badly named variables | 5 min |
| 7 | Debug broken code | 10 min |
| 8 | Learn a new function from its help page | 5 min |
| 9 | Reflect, knit, and turn in | 5 min |

**Turn in** your `.Rmd` file and your knitted `.html` file on Canvas.

## Criteria for success

Use this checklist before you turn your work in. Each item matches a row of the rubric below.

- [ ] The file knits to HTML with no errors, and the author and date at the top are yours.
- [ ] Every `___` has been filled in, and every chunk runs.
- [ ] No `install.packages()` line is anywhere in the file.
- [ ] Every question (Q1 to Q12) has an answer in complete sentences.
- [ ] Each answer explains *why*, not just *what*. (See the examples below.)
- [ ] All the variable names you create are in snake_case and say what they hold.
- [ ] The pipe `|>` is used where the instructions ask for it.
- [ ] The broken code in Part 7 has been fixed, and the chunk now runs.
- [ ] The three reflection questions are answered.

| Criterion | Full credit | Partial credit | No credit |
|:----------|:------------|:---------------|:----------|
| Knits (2 pts) | Knits to HTML with no errors | Knits, but some chunks have errors shown | Doesn't knit, or no HTML turned in |
| Code (4 pts) | Every blank filled in correctly; every chunk runs | Most blanks correct | Many blanks missing or wrong |
| Questions (8 pts) | Q1 to Q12 answered correctly, with reasons | Some answers missing, wrong, or with no reason | Most answers missing |
| Style (3 pts) | snake_case names that say what they hold; pipe used where asked; no `install.packages()` in the file | One or two style problems | Many style problems |
| Debugging (2 pts) | All six lines in Part 7 fixed, with the mistake named | Some lines fixed | None fixed |
| Reflection (1 pt) | All three answered | | Missing |

**What a good answer looks like.** Here is a question, a weak answer, and a strong one.

> *Question:* Why does `mean(c("5", "10"))` return `NA`?
>
> *Weak answer:* "Because it's wrong."
>
> *Strong answer:* "The numbers are in quotation marks, so R stores them as character (text), not numeric. `mean()` can only average numbers, so it returns `NA` with a warning. Removing the quotation marks fixes it."

The strong answer says what happened, why it happened, and how to fix it. It doesn't need to be long.

**IMPORTANT!** Save often. Before you knit, choose **Run > Restart R and Run All Chunks** to make sure every chunk works from a fresh start.

# Part 1. Set Up Your File (5 min)

- Make a folder called `r-basics-exercise` inside your `geog215` folder, and save this file there. Don't work out of your Downloads folder or your Desktop.
- Change `author:` at the top of the file to your name and `date:` to today's date.
- Knit the file now, before you change anything else, to check that knitting works. The HTML file should appear in the same folder.

# Part 2. Order Matters (8 min)

R runs code one line at a time, and it only knows what you have run *so far*, in the order you ran it. Here are three chunks.

```{r visits-start}
visits <- 0
```

```{r visits-add}
visits <- visits + 1
```

```{r visits-print}
visits
```

- Run the three chunks above in order, top to bottom. Write down what `visits-print` shows.
- Now run the `visits-add` chunk **two more times**, then run `visits-print` again.

**Q1.** What did `visits` show the first time, and what did it show after you ran `visits-add` two more times? Why did the value change when the code in the file didn't?

*Your answer here.*

**Q2.** Predict: when you knit this file, what value of `visits` will appear in the HTML? Why? (Hint: knitting starts a fresh R session and runs every chunk once, from top to bottom.)

*Your answer here.*

- Choose **Run > Restart R and Run All Chunks**. Look at the Environment pane. Was your prediction in Q2 right?

# Part 3. Packages and Help Pages (10 min)

A **package** adds data and functions to R. You install a package **once** on each computer, and load it with `library()` in **every** file. We'll use the **spData** package, which comes with spatial data sets you'll use all semester.

- In the bottom-right pane, open the **Packages** tab, click **Install**, type `spData`, and click **Install**. (Don't type `install.packages()` in this file.)
- Fill in the blank to load spData, then run the chunk.

```{r load-libraries, warning=FALSE, message=FALSE}
library(___)
```

- Now type this in the **Console** (not in this file), and press Enter: `library(spdata)`

**Q3.** What error did you get from `library(spdata)`? What is wrong with that line? (Look carefully at each letter.)

*Your answer here.*

**Q4.** Why should `library(spData)` go in your `.Rmd` file, while installing spData should *not*? What would happen every time you knit if `install.packages("spData")` were in the file?

*Your answer here.*

spData comes with a table called `us_states_df`. Every data set in a package has a help page, just like a function.

- In the Console, type `?us_states_df` and press Enter. Read the help page in the Help tab.

**Q5.** According to the help page, how many observations and variables does `us_states_df` have, and what is the source of the data? Read the descriptions of `median_income_10` and `median_income_15` closely. Does each description match the variable's name? What does that tell you about help pages?

*Your answer here.*

# Part 4. Data Types (12 min)

Here are the populations of six North Carolina cities in the 2010 and 2020 Censuses, and whether each city is its county's county seat.

| City | Population 2010 | Population 2020 | County seat? |
|:-----|------:|------:|:-----|
| Charlotte | 731,424 | 874,579 | Yes |
| Raleigh | 403,892 | 467,665 | Yes |
| Greensboro | 269,666 | 299,035 | Yes |
| Durham | 228,330 | 283,506 | Yes |
| Winston-Salem | 229,617 | 249,545 | Yes |
| Chapel Hill | 57,233 | 61,960 | No (Hillsborough is) |

## Making vectors

Each column of the table becomes one vector. A vector holds values of just **one** data type. The first two vectors are done for you.

- Fill in the blanks to make `pop_2020` and `is_county_seat`. Type the numbers **without commas**, and type `TRUE` and `FALSE` in capitals with **no quotation marks**. Keep the cities in the same order as the table.

```{r make-vectors}
# Six North Carolina cities, in the order of the table above
city_name <- c("Charlotte", "Raleigh", "Greensboro",
               "Durham", "Winston-Salem", "Chapel Hill")

# Population in the 2010 Census
pop_2010 <- c(731424, 403892, 269666, 228330, 229617, 57233)

# Population in the 2020 Census
pop_2020 <- c(___)

# Is the city its county's county seat?
is_county_seat <- c(___)

# The year of the most recent Census
census_year <- 2020L
```

- Use `class()` to check the type of each vector. The first one is done for you.

```{r check-classes}
class(city_name)
class(pop_2010)
class(___)
class(___)
class(census_year)
```

**Q6.** Which of R's four basic data types does each of the five variables have? Why is `census_year` a different type from `pop_2010`, even though both hold whole numbers?

*Your answer here.*

## Doing math with vectors

R does math on a whole vector at once. Subtracting one vector from another subtracts each element from the matching element, so there's no need to do each city separately.

- Fill in the blanks to calculate each city's growth from 2010 to 2020, first as a number of people and then as a percent. Percent growth is (new - old) / old * 100.

```{r growth}
# Number of new residents, 2010 to 2020
pop_change <- pop_2020 - ___
pop_change

# Percent growth, 2010 to 2020, rounded to one decimal place
pct_growth <- round((pop_2020 - pop_2010) / ___ * 100, digits = 1)
pct_growth
```

**Q7.** Which city added the most new residents? Which city grew the fastest by percent? Why aren't they the same city?

*Your answer here.*

The pipe `|>` passes the result on its left into the function on its right. Read it as "and then."

- Fill in the blanks to find the **total** 2020 population of the six cities with `sum()`, and the **average** 2020 population with `mean()`, rounded to a whole number. Use the pipe for both.

```{r totals}
# Total 2020 population of the six cities
pop_2020 |>
  ___()

# Average 2020 population, rounded to a whole number
pop_2020 |>
  ___() |>
  round()
```

# Part 5. Coercion (8 min)

Suppose a classmate copies the 2020 populations out of a spreadsheet, and they come in looking like this:

```{r messy-data}
# 2020 populations, copied from a spreadsheet
pop_2020_messy <- c("874,579", "467,665", "299,035", "283,506", "249,545", "61,960")

class(pop_2020_messy)
mean(pop_2020_messy)
```

**Q8.** What type is `pop_2020_messy`? Why does `mean()` return `NA`, and what does the warning tell you? How would you fix the vector? (You already did in Part 4.)

*Your answer here.*

A vector can only hold one type, so when you mix types, R converts (**coerces**) everything to the type that can hold all of them.

- **Before you run the next chunk**, predict what type each vector will be. Then run it and check.

```{r coercion}
class(c(1, 2, 3.5))
class(c(TRUE, FALSE, 1))
class(c(1, "2", 3))
class(c(TRUE, "FALSE"))
```

**Q9.** Which result surprised you, if any? Explain the rule R uses to choose a type when you mix types in one vector.

*Your answer here.*

# Part 6. Naming Variables (5 min)

The chunk below works, but its names are terrible: one doesn't say what it holds, one uses a different convention, and one won't run at all because it has a space (that line is commented out with `#`).

```{r bad-names}
x <- 61960
PopDurham2020 <- 283506
# Pop Raleigh 2020 <- 467665
```

- In the chunk below, rewrite all three lines with **snake_case** names that say what each variable holds (for example, `pop_chapel_hill_2020`). Remove the `#` from the third line once you've fixed its name.

```{r good-names}
# your three lines here
```

**Q10.** Why does a name with a space in it break the code? Why is `x` a poor name, even though it works?

*Your answer here.*

# Part 7. Debugging (10 min)

Each line in the chunk below has **one** mistake. The chunk has `eval=FALSE` in its header, so R skips it and the file still knits.

- Fix each line. Use the error messages to help: copy one line at a time into the Console and run it to see its error.
- After the line, add a comment saying what the mistake was. The first fix is shown as an example, in the comment at the top.
- When every line is fixed, change `eval=FALSE` to `eval=TRUE` in the chunk header and run the chunk. It should run with no errors or warnings.

```{r debug, eval=FALSE}
# Example: `my_age -> 39` becomes `my_age <- 39`  # the arrow pointed the wrong way

home_town -> "Chapel Hill"
nc_cities <- c("Raleigh", "Durham, "Chapel Hill")
round(mean(c(61960, 57233), digits = 0)
Library(spData)
mean(c("61960", "57233"))
pop_change_durham <- 283506 - pop_durham_2010
```

**Q11.** Which of the three "most common mistakes" from Chapter 3 (not programming sequentially, not storing files consistently, missing parentheses, commas, and quotation marks) caused the most bugs in the chunk above? Which bug was the hardest to find, and how did you find it?

*Your answer here.*

# Part 8. Learning a New Function (5 min)

You don't have to memorize every function. You can learn one when you need it from its help page.

- In the Console, run `?round`. Read the description of the `digits` argument. What happens when `digits` is a **negative** number?
- Fill in the blank so the chunk rounds the 2020 populations to the nearest **thousand**.

```{r round-thousands}
round(pop_2020, digits = ___)
```

- In the Console, run `?seq`. Read about the `from`, `to`, and `by` arguments, and try the Examples at the bottom of the page.
- Fill in the blanks to make the vector of every Census year from 1950 to 2020: 1950, 1960, ..., 2020.

```{r census-years}
census_years <- seq(from = ___, to = ___, by = ___)
census_years
```

**Q12.** What does a negative `digits` do in `round()`? Why might a map legend or a report show populations rounded to the nearest thousand instead of the exact count?

*Your answer here.*

# Part 9. Reflection Questions (5 min)

1. How long did the exercise take you to complete?

*Your answer here.*

2. Where did you get stuck? Where did you go for help?

*Your answer here.*

3. Did you find any errors in the exercise?

*Your answer here.*

- Choose **Run > Restart R and Run All Chunks** one last time, then knit your file into HTML.
- Turn in your `.Rmd` file and your `.html` file on Canvas.
