# Linear Regression
 
We will go through the regression example from the book, and I'll show how to do this type of analysis in R. This is the "Janka Hardness vs. Wood Density" data, see Table 15.5 and Ch 22

You can find the data here:
https://users.cs.utah.edu/~jeffp/teaching/ProbStats/R-examples/janka.txt
(just save the text file in your current working directory for R)

First, we load the data into a dataframe like so:
```{r}
janka = read.table("janka.txt", header=TRUE)
```
or straight from the url
```{r}
janka = read.table("https://users.cs.utah.edu/~jeffp/teaching/ProbStats/R-examples/janka.txt", header=TRUE)
```
The "header=TRUE" option tells R to use the first line as column names.  
Try typing just "janka" into the command line to see the raw data
```{r}
janka
```

A scatterplot of the data is simple in R
```{r}
plot(janka, main="Hardness vs. Density of Timber")
```

This is the same as calling the following command
(but notice the axes are labeled different)
```{r}
plot(janka$hardness ~ janka$dens, main="Hardness vs. Density of Timber")
```

The "y ~ x" means y is the dependent variable and x is the independent variable
The "lm" command stands for "linear model" and will fit a linear regression to paired data. It uses the same "y ~ x" syntax.
```{r}
janka.model = lm(hardness ~ dens, data=janka)
```

The output of "lm" is an object with lots of information about the linear regression fit. Type the following command to see what variables it contains.
```{r}
names(janka.model)
```

The first item to look at is the "coefficients" this is the intercept (alpha) and slope (beta)
```{r}
janka.model$coefficients
```

The command "abline" will add a line to the plot with a certain intercept a (first parameter) and slope b (second parameter)
```{r}
plot(janka, main="Hardness vs. Density of Timber")
abline(janka.model$coefficients[1], janka.model$coefficients[2], col="red")
```

The abline command is smart enough to know when you pass it a regression fit.
The above command can be simplified like so:
```{r}
plot(janka, main="Hardness vs. Density of Timber")
abline(janka.model, col="red")
```

The next thing we can look at is the residuals between the data and the model
```{r}
hist(janka.model$residuals, main="Residuals of Janka Regression")
```

Here we plot the residual values vs. the independent variable
```{r}
plot(janka.model$residuals ~ janka$hardness, main="Residuals vs. Hardness")
```
