---
title: "SML201 Linear Regression: Inference"

output: html_document
---

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

## Linear Regression assumptions

* The response ($y$) is approximately linear in the input $x$
$$y_i \approx a_0 + a_1 x_1^{(i)} + ... + a_m x_m^{(i)}$$

* The residuals are idependent of each other, and are normally distributed with equal variance and zero mean
$$e_i = (a_0 + a_1 x_1^{(i)} + ... + a_m x_m^{(i)}  )$$
$$e_i \sim N(0, \sigma^2)$$

* There is no multicollinearity
$$x_3^{(i)} \neq b_0 + b_1 x_1^{(i)} + b_2 x_2^{(i)}$$

* The x's are exogenuous
** $e_i$ is independent of $x^{(i)}$ (e.g., residulas are not larger for larger x's)

## Gapminder in 1980

```{r}
gap <- gapminder %>% filter(year == 1982)
ggplot(gap, mapping = aes(x = gdpPercap, y = lifeExp)) + 
  geom_point() + 
  geom_smooth(method = "lm")
```

This fails the first assumption: the relationship is not linear.

```{r}
gap <- gap %>% mutate(logGdpPercap = log(gdpPercap))
ggplot(gap, mapping = aes(x = logGdpPercap, y = lifeExp)) + 
  geom_point() + 
  geom_smooth(method = "lm")
```

Let's fit a model and plot the diagnostics.

```{r}
library(ggfortify)
fit <- lm(lifeExp ~ logGdpPercap, data = gap)
autoplot(fit)
```

Which countries see like outliers? The big errors are for

```{r}
gap[c(113, 4, 46),]
```

The counties with a lot of leverage (i.e., influence on the estimate) are

```{r}
gap[c(110, 88),]
```

If we are satisfied that the assumptions are roughly correct, we can test the hypothesis that higher gdp per capita is associate with higher life expenctancy:

```{r}
summary(fit)
```

We can reject the hypothesis that there is no pattern there.

What if we add the continent as a predictor? This is called "controlling" for a variable.

```{r}
fit.cont <- lm(lifeExp ~ logGdpPercap + continent, data = gap)
autoplot(fit)
```

We will peek at the summary, but we don't get to test two hypotheses

```{r}
summary(fit.cont)
```