-
Notifications
You must be signed in to change notification settings - Fork 1
/
Tutorial_lookup.Rmd
96 lines (65 loc) · 2.35 KB
/
Tutorial_lookup.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
---
title: "Regression Commands"
author: "Chris Mainey"
date: "14/10/2019"
output:
pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,
comment = "#>",
collapse = TRUE,
fig.align = "center"
)
```
# Tutorial Cheatsheet
The tutorial on regression model uses many different commands, but most of them are simple and based on default `R` objects and methods. Never-the-less, it takes time to learn, search and try these commands out, so this document is a summary of the commands shown in the slides. The will use the `LOS_model` dataset from the `NHSRdatasets` package, but will not usually show the output of each command.
You can install/load the package and data with:
```{r pckload, eval=FALSE, message=FALSE, warning=FALSE}
install.packages("NHSRdatasets")
library(NHSRdatasets)
data(LOS_model)
```
# Correlation
Although we are not using correlation in the practical, it is mentioned in the slides.
```{r cor, eval=FALSE}
# Correlation coefficient for Age and LOS
cor(LOS_model$Age, LOS_model$LOS)
# With a significane test:
cor.test(LOS_model$Age, LOS_model$LOS)
# Correaltion matrix plot of the data. frame (numeric columns 3 - 5)
library(corrplot)
M <-cor(LOS_model[3:5])
corrplot(M, type="upper", order="hclust")
```
# Linear regression
Linear regression is the building block for what we are looking at, and we will treat regressions as 'object', i.e. assign each regression to a variable.
```{r reg1, eval=FALSE}
#Linear model
lm(LOS ~ Age, data=LOS_model)
# Linear model assigned to variable, this includes two parameters,
# age and death, with death as a categorical
mod1 <- lm(LOS ~ Age + factor(Death), data=LOS_model)
# View model summary
summary(mod1)
# Exctract coefficients
coef(mod1)
# calculate confidence interval
confint(model1)
# plot the residuals
plot(mod1)
# interaction model
mod2 <- lm(LOS ~ Age * factor(Death), data=LOS_model)
# Predict from your model
predict(mod2, newdata=my_newdata)
```
# Generalized Linear Models (GLM)
GLMs share most of the architecture of linear models, with the additional 'family' argument
```{r glm, eval=FALSE}
# GLM to nodel death as binary (binomial). We'll also mean-centre and scale then
mod3 <- glm(Death ~ scale(Age) + scale(LOS), data=LOS_model, family="binomial")
# Extract AIC
aic(mod3)
# predict on scasle of the data
predict(mod3, newdata=my_data, type = "response")
```