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

# Plan For Today

- prepping your data for analysis
- using the `lm()` package & interpreting the output
- visualizing your results

# Some general tips

- not sure what a function does? look at the documentation by running `?function_name` in the console (or using google!)

# Setting up your R environment

```{r, echo = F}

# load some packages
library(tidyverse)
library(car)

```

# Prepping your data for analysis

In order to easily use the `lm()` package — and to more easily interpret your results — you'll need to make sure you wrangle your data into a useable format. In the past few weeks, you've already a little bit familiar with how to read in data from files (e.g., csv, excel) and how to clean and/or reshape it as needed.

```{r}

# first, let's load in some data
# we're going to use a dataset from within the `car` package called Prestige
# this contains information about various types of jobs (e.g., average income, education, etc.)
df <- Prestige


# take a peek at the dataframe
head(df)

# for simplicity, we just want to look at blue collar and white collar jobs
df <- df %>%
  filter(type != "prof")

# check that the filtering worked
head(df)


```

In order to use the `lm()` (and related) functions, it's important that all of your variables of interest exist in separate columns. In our case, the Prestige dataset is already set up like this, so there's no need to make any adjustments. But it's not uncommon for datasets to require some restructuring in advance.

## Variable coding & centering

Coding of Xs (variables), including continuous and categorical Xs, matters for interpreting our results, so we probably want to check the coding and centering of our variables in advance. This is especially important for when we have interaction effects in our model. But even in models without interaction effects, how we code variables will affect our interpretation of the intercept. 

### Continuous variables

Typically, **continuous Xs will be mean-centered** (which means we subtract the variable mean from each observation, such that the mean value becomes 0).

```{r}

# let's start by centering prestige
# there are two ways we can quickly accomplish this

# option 1: doing the math
df$prestige.c <- df$prestige - mean(df$prestige)

# option 2: using the scale function
# (note: if you set scale = TRUE, you will effectively be z-scoring your variable)
# if you go with option 2, make sure you confirm the variable is numeric afterward
df$prestige.c <- scale(df$prestige, center = TRUE, scale = FALSE)
df$prestige.c <- as.numeric(df$prestige.c)

# now the mean of this variable should be (very very close to) zero
mean(df$prestige.c)

```

### Categorical variables

There are multiple ways of turning categorical variables into numbers (which you need to do in order to run a regression model), and many statistical packages will do this for you "under the hood." However, unless you recode your variables yourself, you might not know what different R packages/functions are actually doing, which may make it tricky to accurately interpret your results.

For categorical variables, it's particularly important that **zero** is meaningful — as this will allow us to interpret the intercept of our model. (since the intercept = the value of our outcome variables when all predictors/moderators are set to 0)

The most common types of coding for categorical variables are: *dummy coding* and *effect coding*. Neither is better or worse; your choice will depend on your preference (and/or how you want to be able to interpret your output).

For simplicity, we will work with examples of categorical Xs involving two levels only (e.g., blue collar and white collar).

#### Dummy coding

In dummy coding (with two levels), you simply need to set one level of X as 0, and the other as 1. In this case, 0 will correspond to a specific level/category of X. 

```{r}

# let's dummy code the job `type` variable
# blue collar (bc) = 0, and white collar (wc) = 1
df$type.d <- dplyr::recode(df$type, "bc" = 0, "wc" = 1)
head(df)

```

#### Effect coding

In effect coding, all of your levels/categories of X should sum up to 0.

In a case where your categorical variable has two levels, a common choice is to pick the values -0.5 and 0.5, or -1 and 1. Neither of these options will change the overall results of your model, but they will impact your interpretation of the slope. 

```{r}

# let's also effect code the job `type` variable
# blue collar (bc) = -0.5, and white collar (wc) = 0.5
df$type.e <- dplyr::recode(df$type, "bc" = -0.5, "wc" = 0.5)

# note: the 'dplyr::' tells R which package to look in for the recode function
# while this isn't always necessary to do before calling a function, it's good practice
# it IS necessary to do, however, when multiple packages you've loaded have a function with the same name

head(df)

```

# Running a regression using `lm()`
> - Say we're interested in how prestige and job type affect income
> - First, we'll look at prestige and job type separately
> - `lm()` code is equation based
> - Follows the basic equation DV ~ IV(s)

## One Continuous Variable

> - For example, let's say we want to predict income as a function of prestige:

- What does the estimate for `Intercept` tell us?
- What does the estimate for `prestige.c` tell us?

```{r}

# fit model
# we want to make sure we're using the centered version of prestige

# look at the results

```

> - With a continuous X (IV), the intercept will refer to the average Y (DV) for the 0 point of the X (e.g., mean prestige, because prestige is centered).
> - The estimate for prestige X will then tell us the change in income for every unit increase in prestige. 

In other words: Our intercept tells us that for jobs with average prestige, we predict that the income will be ~5264. Our prestige.c slope tells us that for each additional unit of prestige, we can expect income to go up by ~117.

## One Categorical Variable

### Dummy Coded X

- What does the estimate for `Intercept` tell us?
- What does the estimate for `type.d` tell us?

```{r}

# fit model


```

> - Using dummy coding, the intercept will refer to the average Y for the group coded as 0 (in this case, the average income for blue collar jobs).
> - For the estimate (beta) for type.d, the difference between values is 1, then the beta will be the difference between the two levels.

In other words: Our intercept tells us that **for the average blue collar job**, we predict that the income will be ~5374. Our type.d slope tells us that as we move from a blue collar job to a white collar job, we can expect income to decrease by ~322. However, this effect is **not** statistically significant, so we can't draw meaningful conclusions about how job type impacts income.

### Effect Coded X
- Does the interpretation of the estimate for `Intercept` change?
- What about `type.e`?

```{r}

# fit model

```

> - Using effect coding, the intercept will refer to the average Y for the group coded as 0 (in this case, the average income for all job types).
> - For the estimate (beta) for type.e, the difference between values is 1 (because we coded the variable as -.5 and .5), so the beta will still be the difference between the two levels.

In other words: Our intercept tells us that **for the average job (across both blue & white collar)**, we predict that the income will be ~5374. Our type.d slope tells us that as we move from a blue collar job to a white collar job, we can expect income to decrease by ~322. (Though again, this effect isn't significant.)

# Models with multiple predictors

In many cases, you may want multiple predictors in your linear model (i.e., multiple Xs). This is pretty easy to do in the lm() package: in your equation, you can include as many Xs as you want to (in theory) with the + operator.

One common case in which you might want to create a model with two Xs is if you want to **control** for one variable while modeling the relationship between your main predictor X and your Y.

For example, let's say we're primarily interested in the effect of prestige on income, but we want to control for the effect of different job types.

```{r}

# let's predict income based on prestige, while also accounting for job type
# note that we're using the effect-coded version of type


```

You'll see now that because we're accounting for both X variables in the same model, our results change to some degree. Here we find that **both prestige and job type significantly influence income**.

>- The intercept tells us that for jobs with **average prestige**, averaging across **both job types**, we can expect an income of ~5072.
>- The prestige slope tells us that with each additional unit of prestige we expect income to increase by ~135.
>- The type slope tells us that as we move from blue collar to white collar jobs we can expect income to decrease by ~1225.

We'll talk more about running and interpreting models with multiple predictors — including how to model interactions — in the next few weeks!

# Data Challenge!

Go to the file challenge.Rmd file (download from the SIPPS website) for your data challenge. Remember to use the help command in R (?<function name>) and google as necessary.
