---
title: "Lab 5 Linear Regression with Categorical Variables"
output: pdf_document
---

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

# Due: 12am night before lab

# Instructions
Work through the problems below, and submit this document as a knitted .pdf file with answers to the Problem Set 5 assignment on Gradescope. 

**In some problems, an incomplete R chunk has been provided. To evaluate the chunk, follow the given instructions, and then change `eval=FALSE` to `eval=TRUE`.**

**For each problem, put your solution between the bars of red stars.**


--

In this problem set, we will learn how to use the `lm()` function for multiple linear regression.

 

### R Packages
Run the following to load the necessary packages for this problem set:
```{r warning = F, message = F}
library(ggplot2)
library(dplyr)
library(tidyverse)
library(moderndive)
```

### The data
We will again work with the `pdxTrees` data package. Run the following code chunk to obtain a data frame of the four parks closest to Reed.  This data frame includes some additional modification that you performed during last weeks lab.

```{r}
library(pdxTrees)
near_reed <- get_pdxTrees_parks() %>% 
  filter(Park %in% c("Crystal Springs Rhododendron Garden",
                                          "Kenilworth Park", 
                                          "Eastmoreland Garden",
                                          "Berkeley Park")) %>% 
  mutate(Functional_Type2 = case_when(
   Functional_Type == "BD" | Functional_Type == "CD" ~ "Deciduous",
   Functional_Type == "ED" | Functional_Type == "CE" ~ "Evergreen"
  )) %>% 
  mutate(Crown_Width = (Crown_Width_NS + Crown_Width_EW)/2) %>% 
   drop_na(Functional_Type2) 
```



Our first goal will be to describe the relationship between the variables `Carbon_Sequestration_lb` and tree `Genus`. Before we can create a linear model, we will need to do some data exploration and data wrangling.

Carbon sequestration is the process by which carbon dioxide is taken up by trees, grasses and other plants through photosynthesis and stored as carbon in biomass. It is one way to offset carbon emissions from other sources into the atmosphere. The `Carbon_Sequestration_lb` variable in the `near_reed` data set measures the amount of carbon (in lbs.) that the tree removes from the atmosphere, annually.

### Exercise 1

Create a data visualization showing the distribution of `Carbon_Sequestration_lb` among all trees in the `near_reed` dataframe.

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


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

### Exercise 2

Determine how many different tree genera are present in the `near_reed` data set. Then identify the 4 most frequent genera.

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


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

### Exercise 3

For each of the 4 genera identified in the previous problem, use `dplyr` verbs to find the most frequently appearing `Common_Name` in each genus.

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



********************************
### Exercise 4

Create a new dataframe called `near_reed_top_4` consisting of just those trees in the 4 most frequent genera.

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



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

### Exercise 5

Since `Carbon_Sequestration_lb` is quantitative and `Genus` is categorical, the relationship between the two variables can be most easily visualized by a side-by-side boxplot. Create such a boxplot and comment on any trends you observe.

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



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

### Exercise 6

We now want to construct a linear model to analyze the differences in the `Carbon_Sequestration_lb` for each level in `Genus`.  We can do so using the same `lm` function we previously used to create linear regression models comparing two quantitative variables.

Use the `lm()` function to construct the linear model.  Print the regression coefficients using `get_regression_table()`.

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



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

### Exercise 7

How many indicator variables are displayed in the regression table, and what are they? Which level of the `Genus` variable does not have an indicator variable?

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



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

### Exercise 8

The intercept term in estimate in the regression model corresponds to the mean response value for the baseline level of the explanatory variable.

Compute the mean `Carbon_Sequestration_lb` for trees in the Acer genus, and compare to the corresponding value in the regression table.

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



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

### Exercise 9

The "slopes" on each of the indicator variables in the regression table show the difference in mean value of the response for that level compared to the mean for the baseline.

Compute the mean `Carbon_Sequestration_lb` for trees in the Cornus, Pseudotsuga, and Quercus genera, and then compute the difference between each of these means and the mean for trees in the Acer genus.

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



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


### Exercise 10

Write down the formula for the linear model for `Carbon_Sequestration_lb` as a function of `Genus`.

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



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


### Exercise 11

By default, R chooses the alphabetically first level of the explanatory variable to serve as the baseline. But this can be changed using `fct_relevel` inside the `mutate` verb. 

Mutate the `near_reed_top_4` datagrame so that the values of `Genus` appear in the order "Pseudotsuga", "Acer", "Quercus", "Cornus". 

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




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

### Exercise 12

Create a new linear model for `Carbon_Sequestration_lb` as a function of `Genus`. Comment on how the coefficients in the estimates column have changed.

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



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

### Exercise 13

Suppose a particular tree is a Bigleaf Maple, which is in the Acer genus. What is the predicted Carbon Sequestration using the model constructed in Exercise 6? What is the predicted Carbon Sequestration using the model constructed in Exercise 12? How do the predictions compare?


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


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


### Application

Lets consider again the relationship between `Tree_Height` and `Crown_Width` for both "Deciduous" and "Evergreen" trees in the `Functional_Type2` variable here.  Last week, we built two linear models, one for each functional type.  This week, we will build a single model incorporating both explanatory variables, `Crown_Width` and `Functional_Type2`.

a. Create a scatterplot showing the relationship between Tree Height and Crown Width, colored by Functional Type 2. Use the `geom_parallel_slopes` function from `moderndive` to plot trendlines for each functional type.


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




********************************
b.  Build a multiple linear regression model of `Tree_Height` as a function of `Crown_Width` and `Functional_Type2`. Display the linear model using the `get_regression_table` function.

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



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

c. Write the formula for the MLR model. Interpret the slope coefficient for the `Crown_Width` term.

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



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

d. Based on the multilinear regression model, what is the formula for the least squares regression line for Tree Height as a function of Crown Width, just among Deciduous trees.

Similarly, what is the formula just among Evergreen trees.

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



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

e. Compare and contrast the slope and intercepts for the two models you described in the previous part. 

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




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

f. Discuss how this MLR model is different from the two separate linear models you created in Exercise 17 of Lab 4.

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




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


