---
title: "Quick look at the Digits data"
output: 
  html_document:
    toc: true
    theme: united
---


```{r setup, include=FALSE}
# Set global options
knitr::opts_chunk$set(warning=FALSE, message=FALSE)
```

# Intro
Hi! This is a short script that separates out the digits by label and plots the pixel-wise mean, median and standard deviation of the digits data for each of the ten labels.

```{r read data}
# Load libraries
library(readr)

# Read in data
train <- read.csv('../input/train.csv', header=TRUE)
test <- read.csv('../input/test.csv', header=TRUE)
```

First we will separate out the digits into separate lists according to which label they have

```{r split data}
#split training data into list by label number
digit_groups <- split(train, train$label)
```


Next we remove the label column from every image because we do not want it to affect our calculations involving the raw pixels.
We also define a function called `pixel-wise`. This is the function we will use to compute our pixel based statistics.

```{r function}
# Remove label column in each
dg2 <- lapply(digit_groups, function(x) { x["label"] <- NULL; x })

gs1 = grey(c(0:128)/128)


# Pixel-wise function
pixel_wise <- function(df, func) {
  output <- apply(t(df),1,func)
  u <- matrix(output, ncol = 28)
  v <- u
  for(i in 1:28)  {
    v[i,] <- rev(u[i,])
  }
  image(v, col = gs1, axes = FALSE)
}
```

# Plotting
## Mean
First we will visualise the mean of each digit that we previously separated into their own lists.

```{r plot mean, fig.height=10}
# Plot each digits mean
par(mfrow=c(4,3))
plot <- lapply(dg2, pixel_wise, func = mean)
title("Pixel-wise Mean", outer=TRUE, line = -2)
```

## Median
Next we will do the same for each digits median.

```{r plot median, fig.height=10}
# Plot each digits median
par(mfrow=c(4,3))
plot <- lapply(dg2, pixel_wise, func = median)
title("Pixel-wise Median", outer=TRUE, line = -2)
```

## Standard Deviation
Finally we look at each digits standard deviation, this will give us an idea of how each digit varies in their respective samples.

```{r plot sd, fig.height=10}
par(mfrow=c(4,3))
# Plot each digits standard deviation
plot <- lapply(dg2, pixel_wise, func = sd)
title("Pixel-wise Standard Deviation", outer=TRUE, line = -2)
```

Great! That was a quick look at the digits data and how they vary. Hope you enjoyed it!
