Overview:

1. Getting started 
2. Descriptive statistics tables 
3. Descriptive statistics plots 
4. Manipulating data for descriptive statistics
5. Bonus Practice

## 1. GETTING STARTED

```{r}
#install.packages('gtsummary') 
#install.packages('dplyr')
#install.packages('beanplot')
#remove the #s if you need to install these packages. 

library(gtsummary) #descriptive statistics package
library(dplyr) #data manipulation package
library(beanplot) #data visualization package

data(iris) #built in dataset
data(storms) #dataset from dplyr
```

Inspecting our data: 
```{r}
head(storms) #inspecting first 6 lines of data 
head(iris)
```

Data summary and structure:
```{r}
summary(storms) #looking at a summary for each variable
summary(iris)

str(storms) #looking at the structure of the data 
str(iris)
```

We can investigate individual summary statistics by column through a number of base R functions:
```{r}
#mean 
mean(storms$year)
```
```{r}
#median 
median(storms$year)
```

```{r}
#standard deviation 
sd(storms$year)
```

```{r}
#standard error
sd(storms$year)/sqrt(length(storms$year))
```

```{r}
#interquartile range
IQR(storms$year)
```

```{r}
#minimum
min(storms$year)
```

```{r}
#maximum
max(storms$year)
```

Often, we want some or all of these statistics for numerous columns in our data in the form of a table. 

## 2. DESCRIPTIVE STATISTICS TABLES

R does not have ideal summary tables built-in for descriptive statistics, but there are a number of packages that do. We will be using the gtsummary but there are many others. 

```{r}
library(gtsummary)
tbl_summary(storms)
```

This code gives us the proportions for each category in our character/factor data, and median and IQR for our numerical data, but we can further modify this table to make it more informative. 

For example, we can drop the first column (storm name) from our summary, and summarize our data by storm category:
```{r}
tbl_summary(storms[,-1], 
            by = category)
```

We can add more descriptive statistics to our table, like mean, standard deviation, min, max, etc.: 
```{r}
names(storms)
sum_tbl <- tbl_summary(storms[,-c(1,3:5,12,13)], #data (dropping more uninformative                                 cols)
            by = category, #grouping
            #specifying continuous variable stats 
            type = all_continuous() ~ "continuous2",
            statistic = list(all_continuous() ~ 
                                 c("{mean} ({sd})", 
                                   "{median} ({min},{max})"),
            #specifying categorical variable stats 
            all_categorical() ~ "{n} ({p}%)"), 
            #specifying number of digits for continuous variables
            digits = all_continuous() ~ 1)

sum_tbl
```

You can pass your summary table object to additional functions through piping (%>%) for furthur modifications: 
```{r}
sum_tbl %>%
modify_caption(caption = '**Summary table of storm dataset**') %>%
modify_header(label = '**Storm category**')
```

These tables are powerful, but the coding for them is a little complicated. Tutorials are available online 
(https://www.danieldsjoberg.com/gtsummary/articles/tbl_summary.html), as well as the function documentation (?tbl_summary). 

## 2.1 PRACTICE 

Using the code above, create a table of descriptive statistics for the iris dataset with the following specifications: 

-group the data by Species
-summarize the continuous data in 2 rows: 
    mean (min, max)
    median
-have 2 digits in your numerical data

(note that there is no categorical data to worry about in this example)

```{r}
head(iris)

#ANSWER:

```

## 3. DESCRIPTIVE PLOTS 

There are number of plots available in base R that are useful for describing data: 

- stripcharts (univariate distribution of data)
- histograms (distribution of continuous data)
- bar plots (distribution of categorical data)
- boxplots (distribution of continuous data by groups)
- beanplots (like a boxplot, but more detailed)

ggplot2 and associated packages also have a number of additional descriptive plots available: 

- violin plots (similar to bean plots)
- density plots (continuous distribution of variable)
- ridgeline plots (overlapping density plots)

we offer a workshop on data visualization with ggplot if interested: 

workshops: 
https://researchcommons.library.ubc.ca/workshops/

data viz workshop materials:
https://ubc-library-rc.github.io/R-viz/

stripcharts:
```{r}
#distribution of sepal length in iris data: 
stripchart(iris$Sepal.Length)
```

histograms:
```{r}
#distribution of sepal length in iris data: 
hist(iris$Sepal.Length)

#add more bins
hist(iris$Sepal.Length, breaks = 15)
```

barplots:
```{r, echo=TRUE, fig.keep='all'}
counts <-table(iris$Species) #have to convert to table for barplot in base R 

#distribution of species in iris data: 
barplot(counts)
```

boxplots:
```{r}
#grouped distributions of height: 
boxplot(Petal.Length ~ Species, iris)
```

beanplots:
```{r}
#same as the boxplot above, but as a beanplot: 
beanplot(Petal.Length ~ Species, iris)

#can modify the colours: 
beanplot(Petal.Length ~ Species, iris, col = c('white','black','grey','red'))
  #col = c(fill, data lines, data lines, mean)

#we can also modify what details are included:

beanplot(Petal.Length ~ Species, iris, col = c('white','black','grey','red'), what = c(0,1,1,0))
  #what = c(total mean, density, mean, data lines)

#for details on modifications, see:
?beanplot
```

## 4. MANIPULATING DATA FOR DESCRIPTIVE STATISTICS

Lets say we wanted to create a new variable in our storms data set to group storms by latitude. 
```{r}
hist(storms$lat, breaks = 20)
summary(storms$lat)
```

We can see from this histogram that there is a natural break in the distribution of our data around 24. This is also very close to both the mean and median in our data. We might decide to set our groups based on one of these variables (e.g Median, 24.6). 
```{r}
storms$zone[storms$lat < 24.6] <- 'South'
storms$zone[storms$lat >= 24.6] <- 'North'

#if we wanted to do this for multiple categorical variables, we could use the %in% operator, e.g grouping by status: 

storms$type[storms$status %in% c("tropical depression", "tropical storm")]<- "storm"

storms$type[storms$status == "hurricane"] <- "hurricane"
```

We could then summarize/describe our data based on this grouping variable:
```{r}
boxplot(category ~ zone, data = storms)

#OR 

boxplot(pressure ~ type, data = storms)
```

### 4.1 PRACTICE: 

create a beanplot of pressure vs zone for the storms dataset. 
```{r}

#ANSWER: 


#what = c(total mean, density, mean, data lines)

```

Using our code from above, we could summarize our data by zone. 
```{r}
tbl_summary(storms[,-c(1,3:5)], #data (dropping more uninformative                                 cols)
            by = zone, #grouping
            #specifying continuous variable stats 
            type = all_continuous() ~ "continuous2",
            statistic = list(all_continuous() ~ 
                                 c("{mean} ({sd})", 
                                   "{median} ({min},{max})"),
            #specifying categorical variable stats 
            all_categorical() ~ "{n} ({p}%)"), 
            #specifying number of digits for continuous variables
            digits = all_continuous() ~ 1)
```

When saving outputs, like plots or a summary table, it is easiest to do so from the viewer/plots pane. 

### 4.2 BONUS PRACTICE: 

Create a grouped variable called 'GoodOrBad' for the following characters in the starwars dataset:

Luke Skywalker
BB8
Palpatine
Yoda
Han Solo
Obi-Wan Kenobi
R2-D2

Assign the list of characters however you want to either 'good' or 'bad'. 

```{r}
head(starwars)

#RUN THIS FIRST: 
#limiting dataset to those names:
starwars <- starwars[starwars$name %in% c(
  'Luke Skywalker','BB8','Palpatine','Yoda',
  'Han Solo','Obi-Wan Kenobi','R2-D2'),-c(12:14)]

#ANSWER:

```

Create a boxplot of birth_year of good vs. bad individuals. 

```{r}

#ANSWER: 

```

Create a beanplot of birth_year of good vs. bad individuals. Only show the total mean and density. 

'what' argument usage: 
what = c(total mean, density, mean, data lines)

```{r}

#ANSWER: 

```