Import Data
# excel file
soccer <- read_excel("../00_data/mydata.xlsx")
soccer
## # A tibble: 380 × 22
## Date HomeTeam AwayTeam FTHG FTAG FTR HTHG HTAG HTR Referee HS
## <chr> <chr> <chr> <dbl> <dbl> <chr> <dbl> <dbl> <chr> <chr> <dbl>
## 1 13/08/20… Brentfo… Arsenal 2 0 H 1 0 H M Oliv… 8
## 2 14/08/20… Man Uni… Leeds 5 1 H 1 0 H P Tier… 16
## 3 14/08/20… Burnley Brighton 1 2 A 1 0 H D Coote 14
## 4 14/08/20… Chelsea Crystal… 3 0 H 2 0 H J Moss 13
## 5 14/08/20… Everton Southam… 3 1 H 0 1 A A Madl… 14
## 6 14/08/20… Leicest… Wolves 1 0 H 1 0 H C Paws… 9
## 7 14/08/20… Watford Aston V… 3 2 H 2 0 H M Dean 13
## 8 14/08/20… Norwich Liverpo… 0 3 A 0 1 A A Marr… 14
## 9 15/08/20… Newcast… West Ham 2 4 A 2 1 H M Atki… 17
## 10 15/08/20… Tottenh… Man City 1 0 H 0 0 D A Tayl… 13
## # ℹ 370 more rows
## # ℹ 11 more variables: AS <dbl>, HST <dbl>, AST <dbl>, HF <dbl>, AF <dbl>,
## # HC <dbl>, AC <dbl>, HY <dbl>, AY <dbl>, HR <dbl>, AR <dbl>
Introduction
Questions
Variation
Visualizing distributions
soccer %>%
ggplot(aes(x = FTR)) +
geom_bar()

soccer %>%
ggplot(mapping = aes(x = HS)) +
geom_histogram(binwidth = 1)

soccer %>%
filter(HS < 25) %>%
ggplot(aes(x = HS)) +
geom_histogram(binwidth = 1)

soccer %>%
ggplot(aes(x = HS, color = FTR)) +
geom_freqpoly()
## `stat_bin()` using `bins = 30`. Pick better value `binwidth`.

Typical values
soccer %>%
# Filter out high home shot counts
filter(HS < 25) %>%
# Plot
ggplot(aes(x = HS)) +
geom_histogram(binwidth = 1)

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

Unusual values
soccer %>%
ggplot(aes(x = AS)) +
geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value `binwidth`.

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

Missing Values
soccer %>%
# filter(AS < 0 | AS > 30) %>%
mutate(AS = ifelse(AS < 0 | AS > 30, NA, AS)) %>%
# Plot
ggplot(aes(x = HS, y = AS)) +
geom_point()
## Warning: Removed 1 row containing missing values or values outside the scale range
## (`geom_point()`).

Covariation
A categorical and continuous variable
soccer %>%
ggplot(aes(x = FTR, y = HS)) +
geom_boxplot()

Two categorical variables
soccer %>%
count(HomeTeam, FTR) %>%
ggplot(aes(x = HomeTeam, y = FTR, fill = n)) +
geom_tile(na.rm = TRUE)

Two continous variables
library(hexbin)
soccer %>%
ggplot(aes(x = HS, y = AS)) +
geom_hex()

soccer %>%
filter(HS < 25) %>%
ggplot(aes(x = HS, y = AS)) +
geom_boxplot(aes(group = cut_width(HS, 5)))
## Warning: Orientation is not uniquely specified when both the x and y aesthetics are
## continuous. Picking default orientation 'x'.

Patterns and models
library(modelr)
mod <- lm(log(HS) ~ log(AS), data = soccer)
soccer2 <- soccer %>%
modelr::add_residuals(mod) %>%
mutate(resid = exp(resid))
soccer2 %>%
ggplot(aes(AS, resid)) +
geom_point()

soccer2 %>%
ggplot(aes(FTR, resid)) +
geom_boxplot()
