Correlations are used when you are interested in the relationship between two (unsually numerical) variables. The ‘relationship’ is defined as how the variables vary together ie the degree of covariance.

The three types of correlation you will use in basic statistics are

1: **Pearson’s**- for normally distributed numeric data.

2: **Spearman’s**- for ordinal data. Non-parametric.

3: **Kendall’s** correlations -non parametric numeric data.

For this page the input is going to be the amount of sedation given and the time spent doing the endoscopy

```
Midazolam<-sample(1:10, 100, replace=TRUE)
Fentanyl<-sample(1:100, 100, replace=TRUE)
Age<-sample(1:100, 100, replace=TRUE)
TimeSpentDoingEndoscopy<-sample(1:50, 100, replace=TRUE)
EndoCr<-data.frame(Midazolam,Fentanyl,Age,TimeSpentDoingEndoscopy,stringsAsFactors=F)
```

The basic function to do correlation is as follows

```
cor(x, y, method = c("pearson", "kendall", "spearman"))
cor.test(x, y, method=c("pearson", "kendall", "spearman"))
```

An example is as follows:

`cor.test(EndoCr$Midazolam, EndoCr$Fentanyl, method = "kendall", use = "complete.obs")`

```
##
## Kendall's rank correlation tau
##
## data: EndoCr$Midazolam and EndoCr$Fentanyl
## z = -0.65423, p-value = 0.513
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
## tau
## -0.04669055
```

For Spearman’s rank correlation, the samples have to be ranked first. cor.test does this for you:

```
mySpearman<-cor.test(x=EndoCr$Midazolam, y=EndoCr$Fentanyl, method = 'spearman')
mySpearman
```

```
##
## Spearman's rank correlation rho
##
## data: EndoCr$Midazolam and EndoCr$Fentanyl
## S = 176260, p-value = 0.5689
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
## rho
## -0.05764619
```

To access the results from cor.test use the variables as you would a data frame. Therefore to get the p-value do:

`mySpearman$p.value`

`## [1] 0.568889`

There are many ways to visualise correlations. One useful way is a correlogram using the package ‘corrplot’. The data needs to be converted into a matrix which can be done with the function cor

```
library(corrplot)
EndoMatrix<-cor(EndoCr)
corrplot(EndoMatrix, method="number")
```

Another method is as follows using scattergram which compares all numeric data with all numeric data

`pairs(EndoCr)`

A final nice way is to use the PerformanceAnalytics package which gives scatter, bar and numerical output:

```
library("PerformanceAnalytics")
chart.Correlation(EndoCr, histogram=TRUE, pch=19)
```

Further information can be found here: http://www.sthda.com/english/wiki/visualize-correlation-matrix-using-correlogram#visualization-methods