# Regression examples

```{r examps, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide", warning = FALSE,message = FALSE)
```

This chapter provides code, but the output is hidden. You should try to run the examples yourself in order to practice applying regression.

## Fit a calibration regression to the mussels data

```{r}
library(tidyverse)
library(performance)
library(aqm)
library(mgcv)
library(lubridate)
library(ggforce)
```


```{r}
data(mussels)
d<-mussels
```

```{r, eval=FALSE}
g0<-ggplot(d,aes(x=Lshell, y=BTVolume)) + geom_point() 
 g0 +geom_smooth(method="lm")
```

```{r}
mod<-lm(data=d,BTVolume~Lshell)
summary(mod)
```


```{r, eval=FALSE}
check_model(mod)
```


## 2. Fit a regression model to allometric data from oak trees.

The data includes the diamater at breast height measured in cm and the height of the trees in meters. Is a straight line an appropriate description of the relationship? If not, does the relationship approximate to a stright line for some parts of its trajectory? 


```{r}
data(oaks)
d<-oaks
```


```{r, results='hide', eval=FALSE}
g0<-ggplot(d,aes(x=diam, y=ht)) + geom_point() 
 g0 +geom_smooth(method="lm")

```

```{r, results='hide'}
mod<-lm(data=d,ht~diam)
summary(mod)
```

```{r, results='hide',eval=FALSE}
check_model(mod)
```


```{r, eval=FALSE}
g0 + geom_smooth( method="gam", formula =y~s(x)) + 
  geom_smooth( method="lm", se=FALSE,colour="red")
```

## Climate data

The CET global temperature data set can be simplified to yearly temperatures since 1880 by the code below.

```{r}
data(cet)
cet$year<-year(cet$date)
cet %>% filter(year>1880) %>% group_by(year) %>% summarise(mtemp=mean(temp)) ->cet
```


How well is this trend modelled by linear regression?

```{r, eval=FALSE}

ggplot(cet,aes(x=year,y=mtemp)) + geom_point() +
  geom_smooth(method="gam",formula=y~s(x))

```

Alternative approach the breaks the data into groups. This is provided as an answer to a question asked in class regarding how to achieve this type of figure in R. It is not necessarily good practice, but it can sometimes be useful. 

```{r, eval=FALSE}
cet$breaks<-as.factor(cut(cet$year,c(1879,1920,1970,2021)))
levels(cet$breaks)<-c("1880-1920","1921-1970","1970-2021")
ggplot(cet,aes(x=year,y=mtemp, col=breaks))  +
  geom_point() +
  geom_smooth(method="lm")


```

