---
title: "Linear models example code"
author: "Statistical Consulting Centre"
output: 
  html_document:
    toc: true
---

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


```{r, message=FALSE}
library(tidyverse)
library(readxl)
library(performance)
library(emmeans)
library(gtsummary)
```

### Reading in the data
 
In this R Markdown file, the Excel file that is read in is called analytic_data.xlxs. The data frame is called EXAMPLE_DATA.  Replace these with the names of the files you wish to use.

```{r, message=FALSE}
EXAMPLE_DATA <- read_excel("analytic_data.xlsx")
EXAMPLE_DATA <- EXAMPLE_DATA %>% 
  mutate_if(is.character,as.factor)
```

In all of the code below, you will need to replace EXAMPLE_DATA with the name of your data frame.
You will need to use the appropriate variable names.

### Simple linear model with categorical predictor

```{r}
MY.MODEL <- lm(NUMERICAL_VARIABLE1 ~ FACTOR1, data=EXAMPLE_DATA)
```

A range of ways to explore the model

```{r}
summary(MY.MODEL)
model_performance(MY.MODEL)
check_model(MY.MODEL)
joint_tests(MY.MODEL)
tbl_regression(MY.MODEL)
emmeans(MY.MODEL, "FACTOR1")
emmeans(MY.MODEL, "FACTOR1") %>%
  pairs(adjust="none", infer=TRUE)
```

### Linear model with two predictors and interaction

```{r}
MY.MODEL <- lm(NUMERICAL_VARIABLE2 ~ FACTOR2+FACTOR3+FACTOR2:FACTOR3, data=EXAMPLE_DATA)
joint_tests(MY.MODEL)
```

```{r}
emmip(MY.MODEL, FACTOR2 ~ FACTOR3, CIs=TRUE)
```