---
title: "Setting up a Simple Linear Model"
subtitle: "Chapter 4.6-4.9"
author: "Qi Yi"
date: "04.09.2025"
format: 
  revealjs:
    code-line-numbers: true
    transition: slide
    transition-speed: fast
    incremental: true
    footer: "Quarto presentation is DOPE 🤓"
    logo: logo.png
    title-slide-attributes: 
      data-background-image: front page background.png
    theme: [simple,theme.scss] 
    linestretch: 1.7
presentation: slide
editor: visual
---

## In today's session, we will cover {background-image="content background1.png"}

-   how to use `library(tidyverse)` `library(broom)` `library(ggplot)`

-   setting up a simple linear model,

-   creating a scatterplot with a regression line

-   Intercept placeholder

## A few definitions {visibility="hidden" background-image="content background1.png"}

# Q1. What is a Linear Regression Model? {background-image="content background1.png"}

## A model ... {auto-animate="true" background-image="content background1.png"}

-   is a **mathematical representation** of the **relationship or association** between two or more variables.

-   is also **a mathematical construct** that we use to interpret the mechanism of generating the observed data (Rencher et al., 2008, p.2).

-   consists of two components, `variables` and `parameters`, or coefficients (they are the estimate of parameters) (Heumann et al., p.269).

## What is Linear & Non Linear {auto-animate="true" background-image="content background1.png"}

-   It's indeed a broad and difficult question.

-   Simply saying, it is determined by the parameters (or the coefficients), for example, if the parameter is $β_1^{2}$ , the model is non-linear (Heumann et al., 2022, p.269).

## What is Regression {auto-animate="true" background-image="content background1.png"}

-   Regression analysis is used to analyze a **relationship** between two or more variables in which one of the variables can be predicted or explained by the information given by the other variables (Mohr et al., 2022, p.302).

# Q2 What is simple linear regression? {auto-animate="true" background-image="content background1.png"}

## In a simple linear regression, {auto-animate="true" background-image="content background1.png"}

there is only one variable, **x**, to predict the response of, **y**. The model can be written as

. . .

$$
y=b_0+b_1x+e
$$

. . .

$b_0$ *is the intercept,* $b_1$ *is the coefficient.*

## A regression line ... {auto-animate="true" background-image="content background1.png"}

-   describes how the dependent variable `y` changes as independent variable `x` changes.

-   The process of modeling is to find the best fitting line through the data points, which leads to the least squares of errors between the observed data point and the predicted data point.

# Part 2: Model Setup {.center auto-animate="true" background-image="content background2.png"}

Based on the given equation, let's start to set up a simply linear regression

```{r}
#| echo: true
library(tidyverse)

```

## The First Model: The relationship between alcohol percentage in wine and wine taste {.scrollable .small auto-animate="true" background-image="content background2.png"}

*Background:*

::: {style="font-size: 0.8em;"}
-   The `WineQuality.csv` dataset was created to investigate the relationship between wine preference and wine physicochemical properties.

-   Samples all came from a unique type of Portugese wine *vinho verde* 🍷 from the northwest region of Portugal.

-   Each sample was tasted by three tasters, and the final sensory score was determined by the median of score. The score ranged from 0-10, 0 meant very bad 👎, 10 meant excellent 🤤.
:::

## ***🐾 Step 1- load the csv file*** {.scrollable auto-animate="true" background-image="content background1.png"}

```{r}
#| label: wine quality vs alcohol
#| echo: true
#| output-location: fragment
#| code-line-numbers: True 


wine_quality <- read_csv('WineQuality.csv')
wine_quality

```

## Zoom into the data {auto-animate="true" background-image="content background1.png"}

```{r}
#| label: show headings
#| echo: true
#| code-line-numbers: "1|2"
colnames(wine_quality)
range(wine_quality$quality)
```

## ***🐾 Step 2 - Create a simple linear regression model*** {.scrollable auto-animate="true" background-image="content background1.png"}

::: {style="font-size: 0.8em;"}
```{r}
#| label: null model 
#| echo: true
#| code-line-numbers: "1|2"
#| output-location: fragment
model_null <- lm(quality~1, data =wine_quality)
model_null
```

-   What does the intercept mean?

-   Average score
:::

## Why is there "1" in the null model? {auto-animate="true" background-image="content background1.png"}

-   1 represents the intercept place holder. In R, the shorthand notation 'y \~ x' fits the model corresponding to the formula y \~ 1+x. The intercept is by default. Therefore, when building a null model, we use y \~ 1.

## Sep up a Simple Linear Model {.scrollable auto-animate="true" background-image="content background1.png"}

```{r}
#| label: model1
#| echo: true
#| code-line-numbers: "1|2"
#| output-location: fragment
model1 <- lm(quality~alcohol,data=wine_quality)
model1
```

-   $$
    Wine\ taste\ score = 1.887 + 0.361 *  alcohol\ percentage 
    $$

## ***🐾 Step 3 - Produce a scatterplot of alocohol percentage versus wine taste*** {.scrollable auto-animate="true" background-image="content background1.png"}

By using `geom_smooth()`, we can plot a linear model by specifying the argument `method='lm'`

. . .

```{r}
#| label: scatterplot
#| echo: true
#| code-line-numbers: "1|2-7"
#| output-location: fragment

ggplot(wine_quality,aes(x=alcohol,y=quality))+
  geom_point(alpha=0.3,color="#314F94")+
  geom_smooth(method='lm',formula = y ~ x,color='#EAC655',fill = "lightgrey")+
  labs(x="alcohol percentage", y="wine taste score",title="Relationship between alcohol percentage and wine taste")+
  theme(plot.title = element_text(size = 17, face = "bold",hjust = 0.5, color ='#BC734A'),
        axis.title = element_text(size = 11, face = "bold"),
        panel.background = element_rect(fill = "#EFE8DF", color = 'grey'))
```

. . .

The gray ribbon around the regression line is the '95% confidence interval' (see Chapter 9)

## ***🐾 Step 4 - Retrieve information from the model*** {auto-animate="true" background-image="content background1.png"}

-   We can use `fitted()` to retrieve the model's fitted values.

. . .

```{r}
#| label: fitted()
#| echo: true
#| output-location: fragment
head(fitted(model1))
```

-   *5.280798* is the prediction for the first data point.

## We can use `residuals()` to retrieve the model's fitted residuals {auto-animate="true" background-image="content background1.png"}

```{r}
#| label: residuals()
#| echo: true
#| output-location: fragment
head(residuals(model1))
```

## Use `summary()` to get a coefficient table which includes useful summary statistics for the overall model fit. {auto-animate="true" background-image="content background1.png"}

```{r}
#| label: summary()
#| echo: true
#| output-location: fragment
summary(model1)

```

## Use `coef()` to retrieve the coefficients of a linear model. The output is a vector. {auto-animate="true" background-image="content background1.png"}

```{r}
#| label: coef()
#| echo: true
#| output-location: fragment
#| code-line-numbers: True
coef(model1)

```

. . .

```{r}
#| label: coef_index
#| echo: true
#| output-location: fragment
#| code-line-numbers: True
coef(model1)[1]
```

## Alternative way of indexing by name {auto-animate="true" background-image="content background1.png"}

```{r}
#| label: coef3()
#| echo: true
#| output-location: fragment

coef(model1)['alcohol']
```

## ***🐾 Step 5 - Using the setup model to predict values*** {.scrollable auto-animate="true" background-image="content background1.png"}

-   We can generate predictions for a given sequence of numbers by using `predict()` .

. . .

`predict(object, newdata)`

. . .

-   Then use `seq()` to create a numeric vector

. . .

`seq(from= , to= , by= )`

. . .

```{r}
#| label: coef2()
#| echo: true
#| output-location: fragment
#| code-line-numbers: "1|2|3|4"
alcohol_values<-seq(from=11, to=13, by= 0.2)
mypreds<-tibble(alcohol=alcohol_values)
mypreds$score<- predict(model1,newdata=mypreds)
mypreds
```

------------------------------------------------------------------------

## The Second Model: The relationship between volatile acidity in wine and wine taste {.scrollable auto-animate="true" background-image="content background1.png"}

. . .

Now let's use set up another simple linear model by using `library(broom).`

. . .

This time we want to look into the relationship between volatile acidity and wine taste.

. . .

::: callout-tip
#### Fun fact: What is Volatile Acidity (VA)? 🍷

VA measures the of amount of acids in wine that evaporate easily (mainly acetic acid). Excessive levels of VA will effect the taste of the wine and are considered as a wine fault. A small amount can add complexity. It is a key quality control measure in winemaking.

VA Unit: *g(acetic acid)/dm3*, means grams of acetic acid per cubic decimeter
:::

## ***🐾 Step 1 - Load data, set up a null model*** {auto-animate="true" background-image="content background1.png"}

```{r}
#| label: nullmodel2
#| echo: true
#| output-location: fragment
#| code-line-numbers: "1|2|3"
null_model3 <- lm(quality~1,data =wine_quality)
null_model3
```

## *🐾 **Step 2 - Set up a simple linear model*** {.scrollable auto-animate="true" background-image="content background1.png"}

```{r}
#| label: VA vs score
#| echo: true
#| output-location: fragment
#| code-line-numbers: "1|2|3"
library(broom)
new_model<- lm(quality~`volatile acidity`, data=wine_quality)
new_model 
```

. . .

```{r}
#| label: scatterplot2
#| echo: true
#| output-location: fragment
#| code-line-numbers: "1|2|3|4|5"
ggplot(wine_quality,aes(x=`volatile acidity`,y=quality))+
  geom_point(alpha=0.3,color="skyblue")+
  geom_smooth(method='lm',formula = y ~ x,color='purple')+
  theme_classic()+
  labs(x="volatile acidity", y="wine taste")
```

## Instead of using `summary()`, {.scrollable auto-animate="true" background-image="content background1.png"}

we can use `tidy()` to provide a model output. The advantage of `tidy()`is that its output is a data frame, which allows you to easily index the relevant columns.

```{r}
#| label: tidy()
#| echo: true
#| output-location: fragment
tidy(new_model)  
```

. . .

```{r}
#| label: summary ()
#| echo: true
#| output-location: fragment
#compare with summary(), the latter gives more information
summary(new_model)
```

## ***🐾 Step 3 - Extract information from the model output*** {.scrollable auto-animate="true" background-image="content background1.png"}

Though `tidy()` gives less information about the model compared to `summary()`, `glance()` gives detailed model performance.

```{r}
#| label: tidy2()
#| echo: true
#| output-location: fragment
tidy(new_model)$estimate
```

. . .

```{r}
#| label: glance()
#| echo: true
#| output-location: fragment
# View model performance
glance(new_model)
```

------------------------------------------------------------------------

# WHO'S NEXT? {.center auto-animate="true" background-image="content background2.png"}

Next?Next Next? ...

------------------------------------------------------------------------

## References

::: {style="text-indent: -1.5em; padding-left: 1.5em;"}
Heumann, C., Schomaker, M., & Shalabh. (2022). <i>Introduction to statistics and data analysis: with exercises, solutions and applications in R</i> (Second edition.). Springer. <https://doi.org/10.1007/978-3-031-11833-3>

Mohr, D. L., Wilson, W. J., & Freund, R. J. (2022). Linear regression. In D. L. Mohr, W. J. Wilson, & R. J. Freund (Eds.), *Statistical methods* (4th ed., pp. 301–349). Academic Press. [https://doi.org/10.1016/B978-0-12-823043-5.00007-2](https://doi.org/10.1016/B978-0-12-823043-5.00007-2?utm_source=chatgpt.com)

Rencher, A. C., Schaalje, G. B., & Wiley InterScience. (2008). *Linear models in statistics* (2nd ed.). Wiley-Interscience.r
:::
