---
title: "Statistical tests 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(broom)
library(gt)
```

### 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.

### Two sample t-test

Without assuming equal variances
```{r}
t.test(NUMERICAL_VARIABLE1 ~ CATEGORICAL_VARIABLE1, data = EXAMPLE_DATA, conf.level=0.95)
```

Assuming equal variances
```{r}
t.test(NUMERICAL_VARIABLE1 ~ CATEGORICAL_VARIABLE1, data = EXAMPLE_DATA, var.equal=TRUE, conf.level=0.95)
```

A way to present the output
```{r}
independentsamples <- t.test(NUMERICAL_VARIABLE1 ~ CATEGORICAL_VARIABLE1, data = EXAMPLE_DATA, conf.level=0.95)
tidy(independentsamples) %>%
    select(estimate, conf.low, conf.high, p.value) %>%
  gt() %>%
  fmt_number(c(estimate, conf.low, conf.high),
             decimals = 2) %>%
  fmt_number(p.value, decimals = 3) %>%
  cols_merge_range(conf.low, conf.high, sep = " to ") %>%
  cols_align("center", everything()) %>%
  cols_label(estimate = "Estimate of the difference of means", conf.low = "95% CI ",
              p.value = "P-value") 
```

### Wilcoxon test

```{r}
wilcox.test(x=EXAMPLE_DATA$NUMERICAL_VARIABLE1, y=EXAMPLE_DATA$NUMERICAL_VARIABLE2, conf.int=T)
```

### Paired t-test

```{r}
t.test(EXAMPLE_DATA$NUMERICAL_VARIABLE1, EXAMPLE_DATA$NUMERICAL_VARIABLE2, paired = TRUE)
```

### Wilcoxon signed rank test


```{r}
wilcox.test(x=EXAMPLE_DATA$NUMERICAL_VARIABLE1, y=EXAMPLE_DATA$NUMERICAL_VARIABLE2, paired = T, conf.int=T)
```

### Correlation

```{r}
cor.test(~NUMERICAL_VARIABLE1 + NUMERICAL_VARIABLE2, EXAMPLE_DATA)
```

### Fisher's exact test

```{r}
fisher.test(EXAMPLE_DATA$CATEGORICAL_VARIABLE1, EXAMPLE_DATA$CATEGORICAL_VARIABLE2)
```

### Chi-squared test

```{r}
chisq.test(EXAMPLE_DATA$CATEGORICAL_VARIABLE1, EXAMPLE_DATA$CATEGORICAL_VARIABLE2)

```


© Statistical Consulting Centre, University of Melbourne, 2023