---
title: "Tables 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(gt)
library(readxl)
```

### Reading in the data
 
The Excel file read in this example is analytic_data.xlxs.  Replace this with your Excel file.

In this R Markdown file, the data frame is called EXAMPLE_DATA.  Replace this with the name of the file you wish to use.

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

The examples here will use a summarised data frame created from EXAMPLE_DATA.
In all of the code below, you will need to replace SUMMARISED with the name of your data frame.
You will need to use the appropriate variable names.

```{r}
SUMMARISED_DATA <- EXAMPLE_DATA %>%
  group_by(CATEGORICAL_VARIABLE1, CATEGORICAL_VARIABLE2) %>%
  summarise(
    mean_NV1 = mean(NUMERICAL_VARIABLE1),
    sd_NV1 = sd(NUMERICAL_VARIABLE1)
  ) %>%
  ungroup()
```

### Making a table from a data frame

```{r}
SUMMARISED_DATA %>%
  gt()
```

### Controlling decimal places

```{r}
SUMMARISED_DATA %>%
  gt() %>%
  fmt_number(c(mean_NV1, sd_NV1), decimals = 2)
```

### Alignment of columns

```{r}
SUMMARISED_DATA %>%
  gt() %>%
  fmt_number(c(mean_NV1, sd_NV1), decimals = 2) %>%
  cols_align("left", columns = c(CATEGORICAL_VARIABLE1, CATEGORICAL_VARIABLE2))
```

### Column headings

```{r}
SUMMARISED_DATA %>%
  gt() %>%
  fmt_number(c(mean_NV1, sd_NV1), decimals = 2) %>%
  cols_label(
    CATEGORICAL_VARIABLE1 = "First variable",
    CATEGORICAL_VARIABLE2 = "Second variable",
    mean_NV1 = "NV1 (Mean)",
    sd_NV1 = "NV1 (SD)"
  )
```

### Grouping rows

```{r}
SUMMARISED_DATA %>%
  group_by(CATEGORICAL_VARIABLE1) %>%
  gt() %>%
  fmt_number(c(mean_NV1, sd_NV1), decimals = 2)
```


© Statistical Consulting Centre, University of Melbourne, 2023