R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Introduction

Question 2

Variation

Visualising Distributions

diamonds %>%
    ggplot(aes(x = cut)) +
    geom_bar()

diamonds %>%
    ggplot(mapping = aes(x = carat)) +
    geom_histogram(binwidth = 0.5)

diamonds %>%
    
    filter(carat < 3) %>%
    
    ggplot(aes(x = carat)) +
    geom_histogram(binwidth = 0.5)

diamonds %>%
    ggplot(aes(x = carat, color = cut)) +
    geom_freqpoly()
## `stat_bin()` using `bins = 30`. Pick better value `binwidth`.

Typical Values

diamonds %>%
    
     # Filter out diamonds > than 3
    filter(carat < 3) %>%
    
    # Plot
    ggplot(aes(x = carat)) + 
    geom_histogram(binwidth = 0.01)

faithful %>%
    ggplot(aes(eruptions)) +
    geom_histogram(binwidth = 0.25)

Unusual Values

diamonds %>%
    ggplot(aes(y)) +
    geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value `binwidth`.

diamonds %>%
    ggplot(aes(y)) +
    geom_histogram() +
    coord_cartesian(ylim = c(0, 50))
## `stat_bin()` using `bins = 30`. Pick better value `binwidth`.

Missing Values

diamonds %>%
   
    # filter(y < 3 | y > 20) %>%
    mutate(y = ifelse(y < 3 | y > 20, NA, y)) %>%
    
    #Plot
    ggplot(aes(x = x,y = y)) +
    geom_point()
## Warning: Removed 9 rows containing missing values or values outside the scale range
## (`geom_point()`).

Covariance

A Categorial and Continous Variables

diamonds %>%
    
    ggplot(aes(x = cut, y = price)) +
    geom_boxplot()

Two categorical variables

diamonds %>%
    
    count(color, cut) %>%
    ggplot(mapping= aes(x = color, y = cut, fill = n)) + 
    geom_tile()

Two continous Variables

diamonds %>%
    ggplot() +
    geom_bin2d(mapping = aes(x = carat, y = price))
## `stat_bin2d()` using `bins = 30`. Pick better value `binwidth`.

diamonds %>%
    filter(carat < 3) %>%
    ggplot(aes(x = carat, y = price)) +
    geom_boxplot(aes(group = cut_width(carat, 0.1)))

Patterns and models

library(modelr)
mod <- lm(log(price) ~ log(carat), data = diamonds)

diamonds2 <- diamonds %>%
    modelr::add_residuals(mod) %>%
    mutate(resid = exp(resid))

diamonds2 %>%
    ggplot(aes(cut, resid)) + 
    geom_boxplot()