# External Functions
library(smallstuff)
library(ggplot2)
library(Matrix)
library(matlib)
library(readxl)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(faraway)
library(sur)
library(Matrix)
library(Stat2Data)
library(readr)
library(clipr) 
## Welcome to clipr. See ?write_clip for advisories on writing to the clipboard in R.
library(ggpubr)
library(ggeasy) 
library(stringr)
library(extrafont)
## Registering fonts with R
library(scales)
## 
## Attaching package: 'scales'
## The following object is masked from 'package:readr':
## 
##     col_factor
library(RColorBrewer)
library(gfonts)
library(mlbench)
library(forcats)

# Save the environment 
parSave=par(no.readonly = TRUE)
#par(parSave)

Read the data in:

file_path = '../data/model_data_no_category.xlsx'
model_data = read_excel(file_path) %>% as.data.frame()

# Check data
head(model_data)
##   Game        Team Goals Scored assists conceded goals
## 1    1       QATAR            0       0              2
## 2    1     ECUADOR            2       1              0
## 3    2     ENGLAND            6       6              2
## 4    2        IRAN            2       1              6
## 5    3     SENEGAL            0       0              2
## 6    3 NETHERLANDS            2       1              0
##   goals shot inside the penalty area total attempts on target attempts
## 1                                  0              5                  0
## 2                                  2              6                  3
## 3                                  6             13                  7
## 4                                  2              8                  3
## 5                                  0             14                  3
## 6                                  2              9                  3
##   off target attempts possession possession in contest
## 1                   5       0.42                  0.08
## 2                   3       0.50                  0.08
## 3                   3       0.72                  0.09
## 4                   4       0.19                  0.09
## 5                   8       0.44                  0.11
## 6                   5       0.45                  0.11
##   defensive pressures applied
## 1                         256
## 2                         279
## 3                         139
## 4                         416
## 5                         263
## 6                         251
summary(model_data)
##       Game           Team            Goals Scored      assists      
##  Min.   : 1.00   Length:128         Min.   :0.000   Min.   :0.0000  
##  1st Qu.:16.75   Class :character   1st Qu.:0.000   1st Qu.:0.0000  
##  Median :32.50   Mode  :character   Median :1.000   Median :1.0000  
##  Mean   :32.50                      Mean   :1.344   Mean   :0.9531  
##  3rd Qu.:48.25                      3rd Qu.:2.000   3rd Qu.:1.0000  
##  Max.   :64.00                      Max.   :7.000   Max.   :6.0000  
##  conceded goals  goals shot inside the penalty area total attempts 
##  Min.   :0.000   Min.   :0.000                      Min.   : 0.00  
##  1st Qu.:0.000   1st Qu.:0.000                      1st Qu.: 8.00  
##  Median :1.000   Median :1.000                      Median :10.00  
##  Mean   :1.344   Mean   :1.227                      Mean   :11.21  
##  3rd Qu.:2.000   3rd Qu.:2.000                      3rd Qu.:14.00  
##  Max.   :7.000   Max.   :7.000                      Max.   :32.00  
##  on target attempts off target attempts   possession     possession in contest
##  Min.   : 0.000     Min.   : 0.000      Min.   :0.1400   Min.   :0.0800       
##  1st Qu.: 2.000     1st Qu.: 3.000      1st Qu.:0.3500   1st Qu.:0.1000       
##  Median : 3.500     Median : 4.000      Median :0.4500   Median :0.1200       
##  Mean   : 3.977     Mean   : 4.867      Mean   :0.4408   Mean   :0.1191       
##  3rd Qu.: 5.250     3rd Qu.: 6.250      3rd Qu.:0.5300   3rd Qu.:0.1300       
##  Max.   :13.000     Max.   :17.000      Max.   :0.7800   Max.   :0.1900       
##  defensive pressures applied
##  Min.   :139.0              
##  1st Qu.:232.8              
##  Median :285.5              
##  Mean   :291.5              
##  3rd Qu.:328.0              
##  Max.   :637.0

Check for errors:

# Missing values:
apply(model_data, 2, function(x) sum(is.na(x)))
##                               Game                               Team 
##                                  0                                  0 
##                       Goals Scored                            assists 
##                                  0                                  0 
##                     conceded goals goals shot inside the penalty area 
##                                  0                                  0 
##                     total attempts                 on target attempts 
##                                  0                                  0 
##                off target attempts                         possession 
##                                  0                                  0 
##              possession in contest        defensive pressures applied 
##                                  0                                  0
# None

# Verify column data types:
lapply(model_data, class) 
## $Game
## [1] "numeric"
## 
## $Team
## [1] "character"
## 
## $`Goals Scored`
## [1] "numeric"
## 
## $assists
## [1] "numeric"
## 
## $`conceded goals`
## [1] "numeric"
## 
## $`goals shot inside the penalty area`
## [1] "numeric"
## 
## $`total attempts`
## [1] "numeric"
## 
## $`on target attempts`
## [1] "numeric"
## 
## $`off target attempts`
## [1] "numeric"
## 
## $possession
## [1] "numeric"
## 
## $`possession in contest`
## [1] "numeric"
## 
## $`defensive pressures applied`
## [1] "numeric"
# Modify the column names so everything is lower case and any blank spaces are replaced with underscores:
model_data = model_data %>% rename_all(~tolower(gsub(" ", "_", .)))
# Add an index column:
model_data = model_data %>% mutate(index = row_number())
# Check the modified column names:
colnames(model_data) 
##  [1] "game"                               "team"                              
##  [3] "goals_scored"                       "assists"                           
##  [5] "conceded_goals"                     "goals_shot_inside_the_penalty_area"
##  [7] "total_attempts"                     "on_target_attempts"                
##  [9] "off_target_attempts"                "possession"                        
## [11] "possession_in_contest"              "defensive_pressures_applied"       
## [13] "index"

Remove rows: (Remove the championship game’s results from data because this is the game that the model(s) are going to predict the outcome of).

# Remove game 64, rows 128 & 129 of the dataset.

# Confirm game number:
model_data[model_data$team=='ARGENTINA', ] 
##     game      team goals_scored assists conceded_goals
## 9      5 ARGENTINA            1       0              2
## 47    24 ARGENTINA            2       2              0
## 78    39 ARGENTINA            2       2              0
## 99    50 ARGENTINA            2       1              1
## 116   58 ARGENTINA            2       1              2
## 121   61 ARGENTINA            3       1              0
## 127   64 ARGENTINA            3       1              3
##     goals_shot_inside_the_penalty_area total_attempts on_target_attempts
## 9                                    1             14                  6
## 47                                   1              5                  2
## 78                                   2             25                 13
## 99                                   2             14                  5
## 116                                  2             15                  6
## 121                                  3             10                  7
## 127                                  3             21                  9
##     off_target_attempts possession possession_in_contest
## 9                     5       0.64                  0.12
## 47                    3       0.50                  0.14
## 78                    8       0.67                  0.09
## 99                    7       0.53                  0.12
## 116                   8       0.44                  0.11
## 121                   2       0.34                  0.12
## 127                   9       0.46                  0.14
##     defensive_pressures_applied index
## 9                           163     9
## 47                          220    47
## 78                          141    78
## 99                          240    99
## 116                         323   116
## 121                         321   121
## 127                         280   127
# Create new dataframe of just the final game:
final_game_data = model_data[model_data$game == '64', ]; final_game_data
##     game      team goals_scored assists conceded_goals
## 127   64 ARGENTINA            3       1              3
## 128   64    FRANCE            3       1              3
##     goals_shot_inside_the_penalty_area total_attempts on_target_attempts
## 127                                  3             21                  9
## 128                                  3             10                  5
##     off_target_attempts possession possession_in_contest
## 127                   9       0.46                  0.14
## 128                   3       0.40                  0.14
##     defensive_pressures_applied index
## 127                         280   127
## 128                         409   128
# Modify the original model_data to remove the records where game == 64
model_data = model_data[model_data$game != '64', ]

# Establish the n variable (number of rows) of this dataset:
(n = nrow(model_data))
## [1] 126
# Check data:
# Goals per game (by index, so only 1 datapoint per row):
ggscatter(
  model_data,
  #x = 'on_target_attempts',
  #x = 'game',
  x = 'index',
  y = 'goals_scored',
  title = 'Goals scored by each team in each game')

From simple to most complex, the models will be:

lmod_a_mean = the 1 model lmod_b_ontarget = use a single predictor (on target attempts) lmod_c_possession = use a single predictor (possession) lmod_d_multiple_pred = Using 5 variables (possession, defensive pressures applied, total attempts, on target attempts, and off target attempts) lmod_e_full = using all predictors except game and team

Procedure: Check for identifiability Perform linear regression on the data set Report on unusual observations: leverages, outliers, etc.

Breakdown for each model: Is it full rank (identifiable)? What is the model equation? What is the RSS? What is the R^2? What is the % improvement between this model and the 1 predictor? What does the fitted values vs. actual values plot look like? Are there have high leverage values?

The 1-model:

(lmod_a_mean = lm(goals_scored ~ 1, model_data))
## 
## Call:
## lm(formula = goals_scored ~ 1, data = model_data)
## 
## Coefficients:
## (Intercept)  
##       1.317
summary(lmod_a_mean) 
## 
## Call:
## lm(formula = goals_scored ~ 1, data = model_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -1.3175 -1.3175 -0.3175  0.6825  5.6825 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   1.3175     0.1191   11.06   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.337 on 125 degrees of freedom
# Looks like the mean goals scored was 1.318

# Is it full rank?
# Establish p for this set:
(p_a = length(coef(lmod_a_mean)))      # p = 1 
## [1] 1
# Does the rank of X (model_matrix) = p
X_a = model.matrix(lmod_a_mean)
all.equal(rankMatrix(X_a)[[1]], p_a) 
## [1] TRUE
# True so yes it is identifiable
# Note : the 1-model is always identifiable because it only has one column

# What is the model equation?
# goals_scored = 1.318 + res

# What is the RSS?
RSS_a = deviance(lmod_a_mean); RSS_a        # 223.3
## [1] 223.3016
# What is the R^2?
rsq_a = summary(lmod_a_mean)$r.sq 
# It is 0 because this is just the 1 predictor

# What is the % improvement between this model and the 1 predictor?
# Cannot calculate for this model because it is the 1 predictor

# What does the actual values vs. each game plot look like?
# Remember, every game number will have 2 response values:
plot(model_data$goals_scored ~ model_data$game,
     xlab = 'Game Number',
     ylab = 'Predicted goals scored',
     xlim = c(0,64),
     ylim = c(0,7))
abline(lmod_a_mean,
       col = 'green')

# Are any of these high leverage values?
# Leverages can be found using the "hatvalues" function:
hatv_a=hatvalues(lmod_a_mean)
# Are any of these greater than 2 * the average
hatv_a[hatv_a>(2*(mean(hatv_a)))] # none, because this is the 1 model
## named numeric(0)

Model with predictor(s): on target attempts

(lmod_b_ontarget = lm(goals_scored~ on_target_attempts,model_data))
## 
## Call:
## lm(formula = goals_scored ~ on_target_attempts, data = model_data)
## 
## Coefficients:
##        (Intercept)  on_target_attempts  
##             0.1577              0.2952
summary(lmod_b_ontarget) 
## 
## Call:
## lm(formula = goals_scored ~ on_target_attempts, data = model_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -2.4051 -0.7481 -0.0433  0.6615  4.7758 
## 
## Coefficients:
##                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         0.15769    0.17766   0.888    0.376    
## on_target_attempts  0.29521    0.03775   7.821 1.96e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.098 on 124 degrees of freedom
## Multiple R-squared:  0.3303, Adjusted R-squared:  0.3249 
## F-statistic: 61.16 on 1 and 124 DF,  p-value: 1.958e-12
# Is it full rank?
# Establish p for this set:
(p_b = length(coef(lmod_b_ontarget)))       # p = 2
## [1] 2
# Does the rank of X (model_matrix) = p
X_b = model.matrix(lmod_b_ontarget)
all.equal(rankMatrix(X_b)[[1]], p_b) 
## [1] TRUE
# True, so yes it is identifiable

# What is the model equation?
# goals_scored = 0.157 + 0.295*on_target_attempts + res

# What is the RSS?
RSS_b = deviance(lmod_b_ontarget); RSS_b      # 149.5
## [1] 149.5401
# What is the R^2?
rsq_b = summary(lmod_b_ontarget)$r.sq; rsq_b               # rsq = 0.33 
## [1] 0.3303224
# What is the % improvement between this model and the 1 predictor?
# RSS_model we are comparing / RSS of the 1 predictor model * 100
# (RSS_lmods - RSS_lmod) / RSS_lmods * 100
((RSS_a - RSS_b) / RSS_a) * 100 
## [1] 33.03224
# It is the full 33% improvement which will always equals the r^2 value
# if we are simply comparing the improvement over the 1 model.

# What does the actual values vs. on_target_attempts plot look like?
# Remember, every game number will have 2 response values:
plot(model_data$goals_scored ~ model_data$on_target_attempts,
     xlab = 'On target attempts',
     ylab = 'Actual goals scored',
     xlim = c(0,15),
     ylim = c(0,7),
     pch = 20,
     main = 'On target attempted shots predicting goals scored')
abline(lmod_b_ontarget,col = 'green')

# Are any of these high leverage values?
# Leverages can be found using the "hatvalues" function:
hatv_b=hatvalues(lmod_b_ontarget)

# Find the high leverage values for this model:
(hl_b=hatv_b[hatv_b>2*mean(hatv_b)]); hl_b     # multiple high leverage values
##         19         31         53         78         80         88        107 
## 0.03832485 0.05149051 0.05149051 0.10516593 0.05149051 0.06701925 0.03832485 
##        111        114 
## 0.03832485 0.06701925
##         19         31         53         78         80         88        107 
## 0.03832485 0.05149051 0.05149051 0.10516593 0.05149051 0.06701925 0.03832485 
##        111        114 
## 0.03832485 0.06701925
# Set the index for the high leverage values:
idx_b=as.numeric(names(hl_b)); idx_b
## [1]  19  31  53  78  80  88 107 111 114
# Mark the points of high leverage on the plot:
points(goals_scored ~ on_target_attempts,
       model_data[idx_b,],
       pch="X",
       col=2)

# High leverage values need to use standardized residual plots
# Once there is a single high leverage value, then use rstandard plots

Model with predictor(s): posession

(lmod_c_possession = lm(goals_scored ~ possession,model_data))
## 
## Call:
## lm(formula = goals_scored ~ possession, data = model_data)
## 
## Coefficients:
## (Intercept)   possession  
##      0.6635       1.4832
summary(lmod_c_possession) 
## 
## Call:
## lm(formula = goals_scored ~ possession, data = model_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -1.6720 -1.1789 -0.2938  0.7915  5.2390 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)   0.6635     0.4527   1.465    0.145
## possession    1.4832     0.9909   1.497    0.137
## 
## Residual standard error: 1.33 on 124 degrees of freedom
## Multiple R-squared:  0.01775,    Adjusted R-squared:  0.009825 
## F-statistic:  2.24 on 1 and 124 DF,  p-value: 0.137
# Is it full rank?
# Establish p for this set:
(p_c = length(coef(lmod_c_possession)))       # p = 2
## [1] 2
# Does the rank of X (model_matrix) = p
X_c = model.matrix(lmod_c_possession)
all.equal(rankMatrix(X_c)[[1]], p_c) 
## [1] TRUE
# True, so yes it is identifiable

# What is the model equation?
# goals_scored = 0.664 + 1.483*possession + res

# What is the RSS?
RSS_c = deviance(lmod_c_possession); RSS_c      # 219.3
## [1] 219.3387
# What is the R^2?
rsq_c = summary(lmod_c_possession)$r.sq                 # rsq = 0.018

# What is the % improvement between this model and the 1 predictor?
# RSS_model we are comparing / RSS of the 1 predictor model * 100
# (RSS_lmods - RSS_lmod) / RSS_lmods * 100
((RSS_a - RSS_c) / RSS_a) * 100 
## [1] 1.774677
# It is only a 1.78% improvement

# What does the actual values vs. possession plot look like?
# Remember, every game number will have 2 response values:
plot(model_data$goals_scored ~ model_data$possession,
     xlab = 'Posession',
     ylab = 'Actual goals scored',
     xlim = c(0,1),
     ylim = c(0,7),
     main = 'Portion of total possession predicting goals scored')
abline(lmod_c_possession, col = 'green')
# Interesting to see the prediction line based solely on possession is so low.
# Must be because possession on its own is not a strong predictor, you still
# need to have shots to make goals happen.

# Are any of these high leverage values?
# Leverages can be found using the "hatvalues" function:
hatv_c=hatvalues(lmod_c_possession)

# Find the high leverage values for this model:
(hl_c=hatv_c[hatv_c>2*mean(hatv_c)]); hl_c    # multiple high leverage values
##          3          4         19         20         21         22         78 
## 0.05116059 0.04289493 0.03219477 0.03503634 0.05757858 0.04868909 0.03705848 
##         85         86        109        110        117        118 
## 0.05821297 0.07174678 0.03503634 0.03965686 0.03503634 0.03219477
##          3          4         19         20         21         22         78 
## 0.05116059 0.04289493 0.03219477 0.03503634 0.05757858 0.04868909 0.03705848 
##         85         86        109        110        117        118 
## 0.05821297 0.07174678 0.03503634 0.03965686 0.03503634 0.03219477
# Set the index for the high leverage values:
idx_c=as.numeric(names(hl_c)); idx_c
##  [1]   3   4  19  20  21  22  78  85  86 109 110 117 118
points(goals_scored ~ possession,
       model_data[idx_c,],
       pch="X",
       col=2)

Model with predictor(s): possession, defensive pressures applied, total attempts, on target attempts, off target attempts

(lmod_d_multiple_pred = lm(goals_scored~ possession + 
                             defensive_pressures_applied + 
                             total_attempts + 
                             on_target_attempts + 
                             off_target_attempts, 
                           data = model_data))
## 
## Call:
## lm(formula = goals_scored ~ possession + defensive_pressures_applied + 
##     total_attempts + on_target_attempts + off_target_attempts, 
##     data = model_data)
## 
## Coefficients:
##                 (Intercept)                   possession  
##                   0.3815901                    0.0816203  
## defensive_pressures_applied               total_attempts  
##                   0.0001484                   -0.1190360  
##          on_target_attempts          off_target_attempts  
##                   0.4569135                    0.0800415
summary(lmod_d_multiple_pred) 
## 
## Call:
## lm(formula = goals_scored ~ possession + defensive_pressures_applied + 
##     total_attempts + on_target_attempts + off_target_attempts, 
##     data = model_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -2.4466 -0.7422 -0.1143  0.6950  4.7154 
## 
## Coefficients:
##                               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                  0.3815901  1.1270838   0.339   0.7355    
## possession                   0.0816203  1.4256230   0.057   0.9544    
## defensive_pressures_applied  0.0001484  0.0019611   0.076   0.9398    
## total_attempts              -0.1190360  0.0553981  -2.149   0.0337 *  
## on_target_attempts           0.4569135  0.0757260   6.034 1.83e-08 ***
## off_target_attempts          0.0800415  0.0734256   1.090   0.2779    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.085 on 120 degrees of freedom
## Multiple R-squared:  0.3669, Adjusted R-squared:  0.3405 
## F-statistic: 13.91 on 5 and 120 DF,  p-value: 1.024e-10
# Note that on-target attempts is the most significant predictor in this model.

# Is it full rank?
# Establish p for this set:
p_d = length(coef(lmod_d_multiple_pred)); p_d       # p = 6
## [1] 6
# Does the rank of X (model_matrix) = p
X_d = model.matrix(lmod_d_multiple_pred)
all.equal(rankMatrix(X_d)[[1]], p_d) 
## [1] TRUE
# True so yes it is identifiable

# What is the model equation?
# goals_scored = 0.381 + 0.082(possession) + 0.00015(defensive_pressures_applied)
# − 0.119(total_attempts) + 0.457(on_target_attempts) + 0.08(off_target_attempts)
# + res

# What is the RSS?
RSS_d = deviance(lmod_d_multiple_pred); RSS_d # 141.4
## [1] 141.3713
# What is the R^2?
rsq_d = summary(lmod_d_multiple_pred)$r.sq          # rsq = 0.367

# What is the % improvement between this model and the 1 predictor?
# RSS_model we are comparing / RSS of the 1 predictor model * 100
# (RSS_lmods - RSS_lmod) / RSS_lmods * 100
((RSS_a - RSS_d) / RSS_a) * 100 # It is a 36.7% improvement
## [1] 36.69041
# What does the fitted values vs. strongest predictor look like?
# Remember, every game number will have 2 response values:
plot(lmod_d_multiple_pred$fitted.values ~ model_data$goals_scored,
     xlab = 'Actual goals scored',
     ylab = 'Predicted goals scored',
     xlim = c(0,7),
     ylim = c(0,7),
     main = 'Predicted goals scored with lmod_d')
# abline not useful here because that only works when plotting a single
# predictor vs the actual goals
#abline(lmod_c_possession, col = 'green')

# Are any of these high leverage values?
# Leverages can be found using the "hatvalues" function:
hatv_d=hatvalues(lmod_d_multiple_pred)

# Find the high leverage values for this model:
(hl_d=hatv_d[hatv_d>2*mean(hatv_d)]); hl_d     # multiple high leverage values
##         17         22         24         34         53         78         85 
## 0.09708076 0.12099212 0.10073834 0.16455414 0.09762688 0.11609004 0.15791442 
##         86         88        109        110        114 
## 0.11965266 0.20378369 0.11953073 0.10826797 0.13648235
##         17         22         24         34         53         78         85 
## 0.09708076 0.12099212 0.10073834 0.16455414 0.09762688 0.11609004 0.15791442 
##         86         88        109        110        114 
## 0.11965266 0.20378369 0.11953073 0.10826797 0.13648235
# Set the index for the high leverage values:
idx_d=as.numeric(names(hl_d)); idx_d
##  [1]  17  22  24  34  53  78  85  86  88 109 110 114
# See the hat values on this prediction graph:
points(lmod_d_multiple_pred$fitted.values[idx_d] ~ 
         model_data$goals_scored[idx_d] ,
       pch = "X",
       col = 2)

Model with predictor(s): ALL

(lmod_e_full = lm(goals_scored ~ . - game - team - index, data = model_data))
## 
## Call:
## lm(formula = goals_scored ~ . - game - team - index, data = model_data)
## 
## Coefficients:
##                        (Intercept)                             assists  
##                          0.1119431                           0.1994477  
##                     conceded_goals  goals_shot_inside_the_penalty_area  
##                         -0.0070217                           0.8065027  
##                     total_attempts                  on_target_attempts  
##                         -0.0029350                           0.0283281  
##                off_target_attempts                          possession  
##                         -0.0141358                          -0.1078966  
##              possession_in_contest         defensive_pressures_applied  
##                          0.6007939                           0.0000843
summary(lmod_e_full) 
## 
## Call:
## lm(formula = goals_scored ~ . - game - team - index, data = model_data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.35442 -0.16256 -0.10146  0.02919  1.07432 
## 
## Coefficients:
##                                      Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                         0.1119431  0.4937105   0.227    0.821    
## assists                             0.1994477  0.0487177   4.094 7.87e-05 ***
## conceded_goals                     -0.0070217  0.0207649  -0.338    0.736    
## goals_shot_inside_the_penalty_area  0.8065027  0.0450900  17.886  < 2e-16 ***
## total_attempts                     -0.0029350  0.0161236  -0.182    0.856    
## on_target_attempts                  0.0283281  0.0241250   1.174    0.243    
## off_target_attempts                -0.0141359  0.0209609  -0.674    0.501    
## possession                         -0.1078966  0.4772430  -0.226    0.822    
## possession_in_contest               0.6007939  1.4325506   0.419    0.676    
## defensive_pressures_applied         0.0000843  0.0006559   0.129    0.898    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3042 on 116 degrees of freedom
## Multiple R-squared:  0.9519, Adjusted R-squared:  0.9482 
## F-statistic: 255.2 on 9 and 116 DF,  p-value: < 2.2e-16
# Is it full rank?
# Establish p for this set:
p_e = length(coef(lmod_e_full)); p_e       # p = 10
## [1] 10
# Does the rank of X (model_matrix) = p
X_e = model.matrix(lmod_e_full)
all.equal(rankMatrix(X_e)[[1]], p_e) 
## [1] TRUE
# True, so yes it is identifiable

# What is the model equation?
# goals_scored = 0.112 +
# 0.199*assists +
# -0.007*conceded_goals +
# 0.8065*goals_shot_inside_the_penalty_area +
# -0.0029*total_attempts +
# 0.0283*on_target_attempts +
# -0.0141*off_target_attempts +
# -0.1079*possession + 
# 0.6008*possession_in_contest +
# 0.0000843*defensive_pressures_applied
# + res

# What is the RSS?
RSS_e = deviance(lmod_e_full); RSS_e       # 10.7
## [1] 10.73419
# What is the R^2?
rsq_e = summary(lmod_e_full)$r.sq                  # rsq = 0.952

# What is the % improvement between this model and the 1 predictor?
# RSS_model we are comparing / RSS of the 1 predictor model * 100
# (RSS_lmods - RSS_lmod) / RSS_lmods * 100
((RSS_a - RSS_e) / RSS_a) * 100 # It is a 95.2% improvement
## [1] 95.19296
# What does the fitted values vs. actual goals look like?
# Remember, every game number will have 2 response values:
plot(lmod_e_full$fitted.values ~ model_data$goals_scored,
     xlab = 'Actual goals scored',
     ylab = 'Predicted goals scored',
     xlim = c(0,7),
     ylim = c(0,7),
     main = 'Predicted goals scored with lmod_e_full')
# abline not useful here because that only works when plotting a single
# predictor vs the actual goals
#abline(lmod_c_possession, col = 'green')

# Are any of these high leverage values?
# Leverages can be found using the "hatvalues" function:
hatv_e=hatvalues(lmod_e_full)

# Find the high leverage values for this model:
(hl_e=hatv_e[hatv_e>2*mean(hatv_e)]); hl_e     # multiple high leverage values
##         3         4        21        22        34        78        85        87 
## 0.2319717 0.1599473 0.3184760 0.2403180 0.1718373 0.1871965 0.1898261 0.1613927 
##        88       114 
## 0.2443718 0.1707754
##         3         4        21        22        34        78        85        87 
## 0.2319717 0.1599473 0.3184760 0.2403180 0.1718373 0.1871965 0.1898261 0.1613927 
##        88       114 
## 0.2443718 0.1707754
# Set the index for the high leverage values:
idx_e=as.numeric(names(hl_e)); idx_e
##  [1]   3   4  21  22  34  78  85  87  88 114
# Indicate the high leverage values from model e:
points(lmod_e_full$fitted.values[idx_e] ~
         model_data$goals_scored[idx_e],
       pch = "X",
       col = 2)

# Let's look at all the high leverage values and see if any common ones
# across the different models:
# Determine the maximum length vector to then use that to fill NA values:
max_length = max(length(idx_b), length(idx_c), length(idx_d), length(idx_e))

# Create a new function which takes the idx vector as an input and the 
# max length value as the 2nd input:
pad_with_na = function(x, n) {
  if (length(x) < n) {
    c(x, rep_len(NA, n - length(x)))
  } else {
    x
  }
}

# Combine the vectors into a dataframe using the new function:
(df_high_leverages = data.frame(
  idx_b = pad_with_na(idx_b, max_length),
  idx_c = pad_with_na(idx_c, max_length),
  idx_d = pad_with_na(idx_d, max_length),
  idx_e = pad_with_na(idx_e, max_length)))
##    idx_b idx_c idx_d idx_e
## 1     19     3    17     3
## 2     31     4    22     4
## 3     53    19    24    21
## 4     78    20    34    22
## 5     80    21    53    34
## 6     88    22    78    78
## 7    107    78    85    85
## 8    111    85    86    87
## 9    114    86    88    88
## 10    NA   109   109   114
## 11    NA   110   110    NA
## 12    NA   117   114    NA
## 13    NA   118    NA    NA
# Which values show up more than once?
# 3, 4, 19, 21, 22, 34, 53, 78, 85, 86, 88, 109, 110, 114

Hypothesis Testing:

Note: Must be subsets of each other, cannot do “a” and “b” compared to a model that just uses “c”. They must be subsets.

Hypothesis test # 1 H0: lmod_a_mean (1 model) is a better model than using lmod_b_ontarget H1: lmod_b_ontarget is a better model than using lmod_a_mean

anova(lmod_a_mean,lmod_b_ontarget) 
## Analysis of Variance Table
## 
## Model 1: goals_scored ~ 1
## Model 2: goals_scored ~ on_target_attempts
##   Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
## 1    125 223.30                                  
## 2    124 149.54  1    73.762 61.164 1.958e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

P-value = 1.95E-12 so effectively 0 Since p < 0.05, we must reject the null hypothesis and accept that lmod_b_ontarget is the better model.

Hypothesis test # 2 Compare the 2 models which use only 1 predictor each (on target shots vs possession) Note: Possession can be seen quite early in the game (10 minutes in) but on target shots take longer to develop within the game. H0: lmod_c_possession is the better model H1: lmod_b_ontarget

Need to just compare their R^2 values here since they both only use a single predictor (on target shots vs. possession) rsq_b = 0.33 and rsq_c = 0.018 so we would choose model b.

Hypothesis test # 3 H0: lmod_b_ontarget is the better model H1: lmod_d_multiple_pred is the better model

anova(lmod_b_ontarget,lmod_d_multiple_pred) 
## Analysis of Variance Table
## 
## Model 1: goals_scored ~ on_target_attempts
## Model 2: goals_scored ~ possession + defensive_pressures_applied + total_attempts + 
##     on_target_attempts + off_target_attempts
##   Res.Df    RSS Df Sum of Sq      F Pr(>F)
## 1    124 149.54                           
## 2    120 141.37  4    8.1687 1.7335  0.147

P-value = 0.147 Since p > 0.05, we accept the null hypothesis and conclude that lmod_b_ontarget is the better model.

Hypothesis test (additional hypothesis test, not on powerpoint) H0: lmod_c_possession is the better model H1: lmod_d_mult_pred is the better model

anova(lmod_c_possession,lmod_d_multiple_pred) 
## Analysis of Variance Table
## 
## Model 1: goals_scored ~ possession
## Model 2: goals_scored ~ possession + defensive_pressures_applied + total_attempts + 
##     on_target_attempts + off_target_attempts
##   Res.Df    RSS Df Sum of Sq      F   Pr(>F)    
## 1    124 219.34                                 
## 2    120 141.37  4    77.967 16.545 8.01e-11 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

P = 8.01E-11 so we reject H0 and accept H1 that lmod_d is a better model.

Long method to double check:

(n=nrow(model_data))                            
## [1] 126
(p=length(coef(lmod_d_multiple_pred)))                       
## [1] 6
(df=df.residual(lmod_d_multiple_pred))                        
## [1] 120
(q=length(coef(lmod_c_possession)))                     
## [1] 2
(sigma2=deviance(lmod_d_multiple_pred)/df)                    
## [1] 1.178094
# test statistic 
(f=((deviance(lmod_c_possession)-deviance(lmod_d_multiple_pred))/(p-q))/sigma2)  
## [1] 16.54523
# p-value
(p_value = 1-pf(f,p-q,df)) 
## [1] 8.009615e-11

P-value = 8.009x10^-11 Since p < 0.05, we reject the null and conclude that lmod_d_mult pred is the better model.

Hypothesis test # 4 H0: lmod_d_mult_pred is the better model H1: lmod_e_full is the better model

anova(lmod_d_multiple_pred,lmod_e_full)
## Analysis of Variance Table
## 
## Model 1: goals_scored ~ possession + defensive_pressures_applied + total_attempts + 
##     on_target_attempts + off_target_attempts
## Model 2: goals_scored ~ (game + team + assists + conceded_goals + goals_shot_inside_the_penalty_area + 
##     total_attempts + on_target_attempts + off_target_attempts + 
##     possession + possession_in_contest + defensive_pressures_applied + 
##     index) - game - team - index
##   Res.Df     RSS Df Sum of Sq      F    Pr(>F)    
## 1    120 141.371                                  
## 2    116  10.734  4    130.64 352.94 < 2.2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

p-value = 2.2x10^-16 Since p < 0.05, we reject the null hypothesis and conclude that lmod_e_full is the better model.

Hypothesis test # 5 H0: lmod_b_ontarget is the better model H1: lmod_e_full is the better model

anova(lmod_b_ontarget,lmod_e_full)
## Analysis of Variance Table
## 
## Model 1: goals_scored ~ on_target_attempts
## Model 2: goals_scored ~ (game + team + assists + conceded_goals + goals_shot_inside_the_penalty_area + 
##     total_attempts + on_target_attempts + off_target_attempts + 
##     possession + possession_in_contest + defensive_pressures_applied + 
##     index) - game - team - index
##   Res.Df     RSS Df Sum of Sq     F    Pr(>F)    
## 1    124 149.540                                 
## 2    116  10.734  8    138.81 187.5 < 2.2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

p-value = 2.2x10^-16 Since p < 0.05, we reject the null hypothesis and conclude that lmod_e_full is the better model.

Overall conclusion: Based on the r-squared values, lmod_d_multiple_pred and lmod_e_full are the best at predicting goals scored. Respectively their r-squared values are 0.367 and 0.952. Hypothesis 4 compared both models to one another. Results: p-value < 0.05, therefore we rejected the null hypothesis and accepted lmod_e_full as the better model when compared to lmod_d_multiple_pred, which is a subset. Overall, lmod_e_full is the best model.

Evaluate the models using diagnostics (residual plots, normality, etc.):

Residual Plot lmod_a_mean: Using rstandard to evaluate all of these because there were high leverage values.

res_a = rstandard(lmod_a_mean); head(res_a)
##          1          2          3          4          5          6 
## -0.9896392  0.5127047  3.5173925  0.5127047 -0.9896392  0.5127047
plot(res_a~fitted(lmod_a_mean),xlab="Fitted",ylab="Residuals",
     main="Residual Plot Of lmod_a_mean",
     pch = 20,
     xlim = c(0, 7),
     ylim = c(-2,7))

# Add the line at 0, because we expect the residuals to have a mean of 0:
abline(h=0,col=2)

Residual Plot lmod_b_ontarget:

res_b = rstandard(lmod_b_ontarget); head(res_b)
##          1          2          3          4          5          6 
## -0.1455088  0.8750776  3.4715693  0.8750776 -0.9543509  0.8750776
#Residual plot
plot(res_b~fitted(lmod_b_ontarget),xlab="Fitted",ylab="Residuals",
     main="Residual Plot Of lmod_b_ontarget",
     pch = 20)

# Add the line at 0, because we expect the residuals to have a mean of 0:
abline(h=0,col=2)

# Do a hypothesis test on the residuals using the sqrt of the absolute value 
# (magnitude) of the residuals:
summary(lm(sqrt(abs(rstandard(lmod_b_ontarget)))~ fitted(lmod_b_ontarget)))
## 
## Call:
## lm(formula = sqrt(abs(rstandard(lmod_b_ontarget))) ~ fitted(lmod_b_ontarget))
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.65176 -0.21689  0.00805  0.22721  1.13616 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(>|t|)    
## (Intercept)              0.56451    0.05829   9.685  < 2e-16 ***
## fitted(lmod_b_ontarget)  0.17750    0.03826   4.640 8.73e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3286 on 124 degrees of freedom
## Multiple R-squared:  0.1479, Adjusted R-squared:  0.141 
## F-statistic: 21.53 on 1 and 124 DF,  p-value: 8.732e-06

p-value is far below 0.05 so we reject the null hypothesis of homoscedasticity and conclude the funnel shape is real, which must be addressed.

Look at the qqnorm plots for this model:

qqnorm(rstandard(lmod_b_ontarget))
qqline(rstandard(lmod_b_ontarget))

The shape is nicely on the line between -1 and 2 but starts to go up after that. It slightly resembles a happy face.

Let’s do a Shapiro test to confirm:

shapiro.test(residuals(lmod_b_ontarget))
## 
##  Shapiro-Wilk normality test
## 
## data:  residuals(lmod_b_ontarget)
## W = 0.94237, p-value = 4.061e-05

p-value=4.06E-5 <.05, we reject the null hypothesis of normality.

Yes, there is a happy face, but that just means that the residuals are positively skewed. This is not a problem for the analysis since there is more than 30 observations.

Residual Plot lmod_c_possession:

res_c = rstandard(lmod_c_possession)
head(res_c)
##          1          2          3          4          5          6 
## -0.9711976  0.4495695  3.2949510  0.8106259 -0.9934711  0.5051237
plot(res_c~fitted(lmod_c_possession),xlab="Fitted",ylab="Residuals",
     pch = 20,
     main="Residual Plot Of lmod_c_possession")

# Add the line at 0, because we expect the residuals to have a mean of 0:
abline(h=0,col=2)

Not doing further analysis on this model because all our previous analysis shows this model is not a good model.

Residual Plot lmod_d_multiple_pred:

res_d = rstandard(lmod_d_multiple_pred)
head(res_d)
##          1          2          3          4          5          6 
## -0.2436434  0.5991075  3.5096923  0.7571226 -0.7482536  0.7850242
plot(res_d~fitted(lmod_d_multiple_pred),xlab="Fitted",ylab="Residuals",
     pch = 20,
     main="Residual Plot Of lmod_d_multiple_pred")

# Add the line at 0, because we expect the residuals to have a mean of 0:
abline(h=0,col=2)

# Do a hypothesis test on the residuals using the sqrt of the absolute
# value (magnitude) of the residuals:
summary(lm(sqrt(abs(rstandard(lmod_d_multiple_pred)))~fitted(lmod_d_multiple_pred)))
## 
## Call:
## lm(formula = sqrt(abs(rstandard(lmod_d_multiple_pred))) ~ fitted(lmod_d_multiple_pred))
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.69062 -0.20519 -0.00522  0.20517  1.16301 
## 
## Coefficients:
##                              Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                   0.58841    0.05292  11.119  < 2e-16 ***
## fitted(lmod_d_multiple_pred)  0.16635    0.03426   4.856 3.54e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3101 on 124 degrees of freedom
## Multiple R-squared:  0.1598, Adjusted R-squared:  0.153 
## F-statistic: 23.58 on 1 and 124 DF,  p-value: 3.54e-06

p-value is far below 0.05 so we reject the null hypothesis of homoscedasticity and conclude the funnel shape is real and need to address this issue.

qqnorm(rstandard(lmod_d_multiple_pred))
qqline(rstandard(lmod_d_multiple_pred))

The shape is nicely on the line between -1 and 1 but starts to go up after that. It slightly resembles the long tailed residuals plot but only slightly.

Let’s do a Shapiro test to confirm:

shapiro.test(residuals(lmod_d_multiple_pred))
## 
##  Shapiro-Wilk normality test
## 
## data:  residuals(lmod_d_multiple_pred)
## W = 0.94519, p-value = 6.466e-05

p-value=6.46E-5 <.05, we reject the null hypothesis of normality.

Yes, this can cause a problem in the analysis.

Residual Plot lmod_e_full:

res_e = rstandard(lmod_e_full); head(res_e)
##          1          2          3          4          5          6 
## -0.1266815  0.1123515 -0.8981561  0.1582948 -0.2333912  0.1644943
plot(res_e~fitted(lmod_e_full),xlab="Fitted",ylab="Residuals",
     pch = 20,
     main="Residual Plot Of lmod_e_full")

# Add the line at 0, because we expect the residuals to have a mean of 0:
abline(h=0,col=2)

# Do a hypothesis test on the residuals using the sqrt of the absolute
# value (magnitude) of the residuals:
summary(lm(sqrt(abs(rstandard(lmod_e_full)))~fitted(lmod_e_full)))
## 
## Call:
## lm(formula = sqrt(abs(rstandard(lmod_e_full))) ~ fitted(lmod_e_full))
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.60956 -0.21355 -0.05218  0.10765  1.15708 
## 
## Coefficients:
##                     Estimate Std. Error t value Pr(>|t|)    
## (Intercept)          0.72567    0.04702  15.434   <2e-16 ***
## fitted(lmod_e_full)  0.01644    0.02541   0.647    0.519    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3705 on 124 degrees of freedom
## Multiple R-squared:  0.003364,   Adjusted R-squared:  -0.004674 
## F-statistic: 0.4185 on 1 and 124 DF,  p-value: 0.5189

p-value is 0.654 so we accept the null hypothesis of homoscedasticity and conclude the funnel shape is not real.

qqnorm(rstandard(lmod_e_full));qqline(rstandard(lmod_e_full))

The shape is nicely on the line between -1 and 1 but starts to go up afterthat. Something certaily happens have 1 and resembles a strong long tailed reponse.

Let’s do a Shapiro test to confirm:

shapiro.test(residuals(lmod_e_full))
## 
##  Shapiro-Wilk normality test
## 
## data:  residuals(lmod_e_full)
## W = 0.73042, p-value = 6.496e-14

p-value=6.50E-14 <.05, we reject the null hypothesis of normality.

Yes, this can cause a problem in the analysis.

Very odd residual plots, difficult to discern “funnel shapes”. Believe this is because the response data, goals scored, is only integer values so it makes the residuals more pattern based.

Check for collinearity:

Note: Don’t measure for collinearity when there are less than 2 predictors. Therefore, do not measure it for the following models: lmod_a_mean ; lmod_b_ontarget ; lmod_c_ontarget

# lmod_d_multiple_pred
vif(lmod_d_multiple_pred)
##                  possession defensive_pressures_applied 
##                    3.107851                    2.909552 
##              total_attempts          on_target_attempts 
##                    9.340073                    4.119680 
##         off_target_attempts 
##                    4.018611
# None are above 10, so all predictors have an acceptable VIF.
# Note that total_attempts is VERY close to being at the threshold.

#lmod_e_full
vif(lmod_e_full)
##                            assists                     conceded_goals 
##                           4.455505                           1.040490 
## goals_shot_inside_the_penalty_area                     total_attempts 
##                           4.790548                          10.072921 
##                 on_target_attempts                off_target_attempts 
##                           5.323269                           4.169376 
##                         possession              possession_in_contest 
##                           4.434030                           1.583388 
##        defensive_pressures_applied 
##                           4.142936
# The predictor, total_attempts, is greater than 10 so it must be removed.

# Set this equal to a knew model:
lmod_e_partial = update(lmod_e_full, . ~ . - total_attempts)
summary(lmod_e_partial)
## 
## Call:
## lm(formula = goals_scored ~ assists + conceded_goals + goals_shot_inside_the_penalty_area + 
##     on_target_attempts + off_target_attempts + possession + possession_in_contest + 
##     defensive_pressures_applied, data = model_data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.35691 -0.16490 -0.10101  0.03383  1.07460 
## 
## Coefficients:
##                                      Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                         1.260e-01  4.856e-01   0.260   0.7957    
## assists                             1.999e-01  4.844e-02   4.128  6.9e-05 ***
## conceded_goals                     -6.934e-03  2.067e-02  -0.335   0.7379    
## goals_shot_inside_the_penalty_area  8.068e-01  4.487e-02  17.982  < 2e-16 ***
## on_target_attempts                  2.479e-02  1.427e-02   1.738   0.0848 .  
## off_target_attempts                -1.729e-02  1.174e-02  -1.473   0.1435    
## possession                         -1.282e-01  4.621e-01  -0.277   0.7819    
## possession_in_contest               5.536e-01  1.403e+00   0.395   0.6939    
## defensive_pressures_applied         7.046e-05  6.487e-04   0.109   0.9137    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3029 on 117 degrees of freedom
## Multiple R-squared:  0.9519, Adjusted R-squared:  0.9486 
## F-statistic: 289.5 on 8 and 117 DF,  p-value: < 2.2e-16
# Check the vif for this new model:
vif(lmod_e_partial)
##                            assists                     conceded_goals 
##                           4.441607                           1.039928 
## goals_shot_inside_the_penalty_area                 on_target_attempts 
##                           4.783263                           1.877068 
##                off_target_attempts                         possession 
##                           1.318941                           4.191459 
##              possession_in_contest        defensive_pressures_applied 
##                           1.531513                           4.087313
# Much better, removing total_attempts helped and now all predictors have an
# acceptable VIF.

# Now, lets redo parts 4,5,7 for lmod_e_partial:

# Is it full rank?
# Establish p for this set:
p_ep = length(coef(lmod_e_partial)); p_ep       # p = 9
## [1] 9
# Does the rank of X (model_matrix) = p
X_ep = model.matrix(lmod_e_partial)
all.equal(rankMatrix(X_ep)[[1]], p_ep) 
## [1] TRUE
# True, so yes it is identifiable

What is the model equation? goals_scored = 0.126 + 0.200assists + -0.0069conceded_goals + 0.807goals_shot_inside_the_penalty_area + 0.0248on_target_attempts + 0.0173off_target_attempts + -0.128possession + 0.554possession_in_contest + 0.0000705defensive_pressures_applied + res

What is the RSS?

(RSS_ep = deviance(lmod_e_partial))
## [1] 10.73726

What is the R^2?

(rsq_ep = summary(lmod_e_partial)$r.sq)                  
## [1] 0.9519159

What is the % improvement between this model and the lmod_e_full? RSS_model we are comparing / RSS of the 1 predictor model * 100 (RSS_lmods - RSS_lmod) / RSS_lmods * 100

((RSS_e - RSS_ep) / RSS_e) * 100 # It is a 2.8% decrease
## [1] -0.02856412

So by removing the collinear acting variable, we actually see a slight decrease in performance based on RSS.

What does the fitted values vs. actual goals look like? Remember, every game number will have 2 response values:

plot(lmod_e_partial$fitted.values ~ model_data$goals_scored,
     xlab = 'Actual goals scored',
     ylab = 'Predicted goals scored',
     xlim = c(0, 7),
     ylim = c(0, 7),
     main = 'Predicting goals scored with lmod_e_partial',
     ##main = "Predicting Goals Scored",
     cex = 1,  
     col.lab = 'orange',
     col = 'orange',
     pch = 20)

# abline not useful here because that only works when plotting a single
# predictor vs the actual goals
# abline(lmod_c_possession, col = 'green')

# Are any of these high leverage values?
# Leverages can be found using the "hatvalues" function:
hatv_ep=hatvalues(lmod_e_partial)

# Find the high leverage values for this model:
(hl_ep=hatv_ep[hatv_ep>2*mean(hatv_ep)]); hl_ep # multiple high leverage values
##         3         4        21        22        78        85        87        88 
## 0.2302267 0.1584411 0.3142255 0.2399302 0.1860309 0.1896401 0.1591099 0.2422303 
##       111       112       114 
## 0.1429142 0.1499385 0.1687528
##         3         4        21        22        78        85        87        88 
## 0.2302267 0.1584411 0.3142255 0.2399302 0.1860309 0.1896401 0.1591099 0.2422303 
##       111       112       114 
## 0.1429142 0.1499385 0.1687528
# Set the index for the high leverage values:
(idx_ep=as.numeric(names(hl_ep)))
##  [1]   3   4  21  22  78  85  87  88 111 112 114
# View the high leverage values for this model:
points(lmod_e_partial$fitted.values[idx_ep] ~
         model_data$goals_scored[idx_ep],
       pch = "X",
       col = 2,
       cex = .7)

# Residual analysis for the model:
res_ep = rstandard(lmod_e_partial); head(res_ep)
##          1          2          3          4          5          6 
## -0.1177916  0.1294269 -0.9095701  0.1510779 -0.2401234  0.1735552
#Residual plot
plot(res_ep~fitted(lmod_e_partial),
     xlab="Fitted",
     ylab="Residuals",
     main="Residual Plot Of lmod_e_partial",
     ##main = "Residual Plot",
     pch = 20,
     cex = 1,  
     col.lab = 'darkgreen',
     col = 'darkgreen')

# Add the line at 0, because we expect the residuals to have a mean of 0:
abline(h=0,col=2)

# Do a hypothesis test on the residuals using the sqrt of the absolute
# value (magnitude) of the residuals:
summary(lm(sqrt(abs(rstandard(lmod_e_partial)))~fitted(lmod_e_partial)))
## 
## Call:
## lm(formula = sqrt(abs(rstandard(lmod_e_partial))) ~ fitted(lmod_e_partial))
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.66744 -0.22674 -0.05565  0.10873  1.15993 
## 
## Coefficients:
##                        Estimate Std. Error t value Pr(>|t|)    
## (Intercept)             0.72656    0.04672   15.55   <2e-16 ***
## fitted(lmod_e_partial)  0.01692    0.02525    0.67    0.504    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3682 on 124 degrees of freedom
## Multiple R-squared:  0.003606,   Adjusted R-squared:  -0.00443 
## F-statistic: 0.4487 on 1 and 124 DF,  p-value: 0.5042
# p-value = 0.504
# p-value > 0.05 so we accept the null hypothesis of homoscedasticity and 
# conclude the funnel shape is not real.

qqnorm(rstandard(lmod_e_partial));qqline(rstandard(lmod_e_partial))

# The shape is nicely on the line between -1 and 1 but starts to go up after 
# that.  It slightly resembles the long tailed residuals plot but only slightly.

# Let's do a Shapiro test to confirm:
shapiro.test(residuals(lmod_e_partial))
## 
##  Shapiro-Wilk normality test
## 
## data:  residuals(lmod_e_partial)
## W = 0.73161, p-value = 7.003e-14

p-value = 1.561x10^-13 < .05, therefore, we reject the null hypothesis of normality.

Yes, this can cause a problem in the analysis.

What about outliers, check for these using standardized residuals: anything greater than 3 is a possible outlier

# Create the standardized residuals:
res_student_lmod_e = rstudent(lmod_e_partial)

# Do any of these have a magnitude greater than 3?
res_student_lmod_e[which(abs(res_student_lmod_e) >=3)] # yes, index 63 and 83
##       63       83 
## 3.822883 3.307356
# Order these by magnitude:
res_student_lmod_e[order(abs(rstudent(lmod_e_partial)), decreasing = T)]
##           63           83          100           84           70          108 
##  3.822882739  3.307356062  2.900335125  2.802612315  2.799155135  2.765699756 
##           34           80           58           37           47           85 
##  2.643762284  2.595504180  2.281083691  2.240262492  2.236869059  2.094807118 
##          120           75           21           53          114           78 
##  1.997845929  1.961389857  1.700608037  1.442613508 -1.295984640 -1.089090596 
##           57          123           94           73           97            3 
## -1.088396277  1.085215166 -1.014777531 -0.955063732 -0.919429013 -0.908893873 
##           98           17          109           61           68           42 
## -0.805566636 -0.773716297 -0.767920223 -0.766629791  0.749524063 -0.748334857 
##           72          105          112           67           95          101 
## -0.743964884 -0.733208555  0.713832821 -0.712351269 -0.704955083 -0.686272805 
##           66           41           52          103           50           89 
## -0.668815619 -0.651513468 -0.625103122 -0.624467457 -0.616574980 -0.615918893 
##           56           26          111          115          117           45 
## -0.614715445 -0.612217412 -0.597970336 -0.595087217 -0.590707377 -0.575631319 
##           11           13           22           25           15           81 
## -0.562667231 -0.558436774 -0.553972032 -0.551519265 -0.551054145 -0.544009518 
##           59           48           49           33           86           18 
## -0.543187082 -0.524713936 -0.520057129 -0.515871408 -0.511133978 -0.506083732 
##           14           88           76           30           54           55 
## -0.490905982 -0.488617032 -0.483426087 -0.472487657 -0.471080146 -0.466909144 
##           71           39           64           77           62           82 
## -0.459359775 -0.452852928 -0.433248284 -0.431134688 -0.419796581 -0.418279324 
##           23          106           92           51           69           32 
## -0.417406656 -0.409465913 -0.402594182 -0.387589336 -0.385186391 -0.375796859 
##          125           79           16          113          126           87 
## -0.374225320 -0.367636108 -0.359286231 -0.353605333  0.336879154  0.332054442 
##           44           74           96           46          104          118 
## -0.328018682 -0.323824562 -0.319716987 -0.314808512 -0.305037190 -0.303294494 
##            7           90           28           40          102           12 
## -0.296519673 -0.271726419 -0.268969407 -0.263672861  0.260271244 -0.252429583 
##          122          121            5           35           36           91 
## -0.249280678  0.241733073 -0.239153959 -0.214305495  0.184828421 -0.183955026 
##           31            6           65           19           99           27 
## -0.180123505  0.172834177  0.170513177  0.166282232  0.163165374 -0.163009899 
##           93            4           10          107           24           38 
##  0.156699175  0.150445531 -0.147944752 -0.144610328 -0.135577948 -0.133353723 
##          124            2          116            1          110            8 
## -0.130600600  0.128881786  0.122576592 -0.117294115 -0.105456633  0.086167761 
##           43            9           60           20           29          119 
## -0.082192947  0.077612240 -0.067839839  0.064514011 -0.032530787  0.005753401
# The top 2 are above the threshold, so set these to an index:
idx=order(abs(rstudent(lmod_e_partial)), decreasing = T)[1:2]; idx
## [1] 63 83
# Check these with the index:
rstudent(lmod_e_partial)[idx]
##       63       83 
## 3.822883 3.307356
model_data[idx, ] 
##    game     team goals_scored assists conceded_goals
## 63   32 PORTUGAL            2       0              0
## 83   42   CANADA            1       0              2
##    goals_shot_inside_the_penalty_area total_attempts on_target_attempts
## 63                                  1             14                  4
## 83                                  0              5                  0
##    off_target_attempts possession possession_in_contest
## 63                   7       0.53                  0.12
## 83                   4       0.52                  0.12
##    defensive_pressures_applied index
## 63                         226    63
## 83                         224    83
# Both games had goals scored without an assist which is OK so leave this data alone.

# Cooks distance:
sort(cooks.distance(lmod_e_partial),decreasing=T) 
##           21           85          108           80          100           58 
## 1.448969e-01 1.108919e-01 9.457775e-02 8.696084e-02 7.155036e-02 5.985308e-02 
##           63           70           83           34           47          120 
## 5.873344e-02 5.529198e-02 4.918804e-02 4.900389e-02 4.396602e-02 4.096858e-02 
##           37          114           53           75           78            3 
## 3.768003e-02 3.766716e-02 3.726223e-02 3.008208e-02 3.007269e-02 2.749304e-02 
##           84          123           57           22          109          112 
## 1.862357e-02 1.735499e-02 1.202840e-02 1.082792e-02 1.073350e-02 1.002854e-02 
##           68           88           94           73           42          111 
## 9.895821e-03 8.535340e-03 8.202190e-03 7.550701e-03 7.122569e-03 6.661301e-03 
##           97           41           98           67           66          115 
## 5.022367e-03 4.993735e-03 4.481141e-03 4.379563e-03 4.220025e-03 4.059392e-03 
##           86          101           17           61           15          105 
## 3.908303e-03 3.789704e-03 3.679619e-03 3.611446e-03 3.345193e-03 3.084155e-03 
##          117          103           87           59           95           50 
## 2.728093e-03 2.619728e-03 2.335873e-03 2.206154e-03 2.060820e-03 2.019064e-03 
##           52           33           54           79           18           89 
## 1.945249e-03 1.931730e-03 1.886886e-03 1.671738e-03 1.599335e-03 1.567168e-03 
##           13           72           14           26           81           11 
## 1.488749e-03 1.473452e-03 1.430247e-03 1.326506e-03 1.320202e-03 1.304780e-03 
##          106           30           45           77           16           82 
## 1.250706e-03 1.249575e-03 1.231221e-03 1.179665e-03 1.133753e-03 1.126207e-03 
##           39           48           56           76           62           96 
## 1.113722e-03 1.063615e-03 1.047467e-03 9.780208e-04 9.735259e-04 8.621394e-04 
##          121           49           55           69           74           25 
## 8.615932e-04 8.422063e-04 8.323928e-04 8.237235e-04 7.593413e-04 7.164036e-04 
##          113          125           44           64           51           28 
## 7.151052e-04 6.671218e-04 6.580289e-04 5.983167e-04 5.688182e-04 5.635895e-04 
##          118           12           32           40           23            4 
## 5.205315e-04 5.179405e-04 5.042967e-04 4.898892e-04 4.790941e-04 4.774661e-04 
##           90          126          104           71           92            7 
## 4.655846e-04 4.446136e-04 4.126780e-04 4.112091e-04 3.732018e-04 3.730927e-04 
##           19          122          102           31            5           46 
## 3.606447e-04 3.279016e-04 3.128055e-04 3.102769e-04 2.738414e-04 2.531812e-04 
##           35           24           65           10           36          107 
## 2.324629e-04 2.321289e-04 2.308715e-04 1.882175e-04 1.796944e-04 1.731905e-04 
##           27           91           93            1            6          110 
## 1.556520e-04 1.488914e-04 1.411459e-04 1.379382e-04 1.327505e-04 1.285081e-04 
##            2           38           99          124          116           20 
## 1.173164e-04 9.389461e-05 7.970617e-05 7.709791e-05 6.760712e-05 5.309771e-05 
##            9           43           60            8           29          119 
## 4.650441e-05 4.107607e-05 4.063681e-05 3.800117e-05 7.093012e-06 2.963941e-07
# Nothing above 0.5 so nothing is considered "influential." Largest value is only 0.145

Predictions: The “best” model is lmod_e_partial so use that model to predict who will win in the world cup 2022 final. Next: Predict Argentina & France goals in the finale based on their performance from the prior round games.

# Just Argentina's data:
agg_argentina = model_data %>% filter(
  team == 'ARGENTINA') %>% as.data.frame()

# What is some important info on Argentina?
summary(agg_argentina)
##       game           team            goals_scored    assists     
##  Min.   : 5.00   Length:6           Min.   :1     Min.   :0.000  
##  1st Qu.:27.75   Class :character   1st Qu.:2     1st Qu.:1.000  
##  Median :44.50   Mode  :character   Median :2     Median :1.000  
##  Mean   :39.50                      Mean   :2     Mean   :1.167  
##  3rd Qu.:56.00                      3rd Qu.:2     3rd Qu.:1.750  
##  Max.   :61.00                      Max.   :3     Max.   :2.000  
##  conceded_goals   goals_shot_inside_the_penalty_area total_attempts 
##  Min.   :0.0000   Min.   :1.000                      Min.   : 5.00  
##  1st Qu.:0.0000   1st Qu.:1.250                      1st Qu.:11.00  
##  Median :0.5000   Median :2.000                      Median :14.00  
##  Mean   :0.8333   Mean   :1.833                      Mean   :13.83  
##  3rd Qu.:1.7500   3rd Qu.:2.000                      3rd Qu.:14.75  
##  Max.   :2.0000   Max.   :3.000                      Max.   :25.00  
##  on_target_attempts off_target_attempts   possession     possession_in_contest
##  Min.   : 2.00      Min.   :2.00        Min.   :0.3400   Min.   :0.0900       
##  1st Qu.: 5.25      1st Qu.:3.50        1st Qu.:0.4550   1st Qu.:0.1125       
##  Median : 6.00      Median :6.00        Median :0.5150   Median :0.1200       
##  Mean   : 6.50      Mean   :5.50        Mean   :0.5200   Mean   :0.1167       
##  3rd Qu.: 6.75      3rd Qu.:7.75        3rd Qu.:0.6125   3rd Qu.:0.1200       
##  Max.   :13.00      Max.   :8.00        Max.   :0.6700   Max.   :0.1400       
##  defensive_pressures_applied     index       
##  Min.   :141.0               Min.   :  9.00  
##  1st Qu.:177.2               1st Qu.: 54.75  
##  Median :230.0               Median : 88.50  
##  Mean   :234.7               Mean   : 78.33  
##  3rd Qu.:300.8               3rd Qu.:111.75  
##  Max.   :323.0               Max.   :121.00
# Now, extract the mean values for all predictors in lmod_e_partial:
mean_arg = agg_argentina %>%
  select_if(is.numeric) %>%  
  select(-game, -goals_scored, -total_attempts) %>%   
  summarise_all(mean, na.rm = TRUE) 

# vector
mean_vec_arg = round2(unlist(mean_arg), 2); mean_vec_arg
##                            assists                     conceded_goals 
##                               1.17                               0.83 
## goals_shot_inside_the_penalty_area                 on_target_attempts 
##                               1.83                               6.50 
##                off_target_attempts                         possession 
##                               5.50                               0.52 
##              possession_in_contest        defensive_pressures_applied 
##                               0.12                             234.67 
##                              index 
##                              78.33
# Just France's data:
agg_france = model_data %>% filter(
  team == 'FRANCE'
) %>%
  as.data.frame()

# What is some important info on France?
summary(agg_france)
##       game           team            goals_scored      assists     
##  Min.   : 8.00   Length:6           Min.   :0.000   Min.   :0.000  
##  1st Qu.:26.75   Class :character   1st Qu.:2.000   1st Qu.:0.500  
##  Median :44.50   Mode  :character   Median :2.000   Median :2.000  
##  Mean   :40.33                      Mean   :2.167   Mean   :1.833  
##  3rd Qu.:57.75                      3rd Qu.:2.750   3rd Qu.:2.750  
##  Max.   :62.00                      Max.   :4.000   Max.   :4.000  
##  conceded_goals   goals_shot_inside_the_penalty_area total_attempts 
##  Min.   :0.0000   Min.   :0.00                       Min.   : 9.00  
##  1st Qu.:1.0000   1st Qu.:1.25                       1st Qu.:10.25  
##  Median :1.0000   Median :2.00                       Median :15.00  
##  Mean   :0.8333   Mean   :2.00                       Mean   :15.17  
##  3rd Qu.:1.0000   3rd Qu.:2.75                       3rd Qu.:19.75  
##  Max.   :1.0000   Max.   :4.00                       Max.   :22.00  
##  on_target_attempts off_target_attempts   possession     possession_in_contest
##  Min.   :2.00       Min.   :3.00        Min.   :0.3400   Min.   :0.0900       
##  1st Qu.:3.50       1st Qu.:4.75        1st Qu.:0.3800   1st Qu.:0.1000       
##  Median :5.50       Median :7.50        Median :0.4600   Median :0.1050       
##  Mean   :5.00       Mean   :6.50        Mean   :0.4567   Mean   :0.1100       
##  3rd Qu.:6.75       3rd Qu.:8.00        3rd Qu.:0.5400   3rd Qu.:0.1175       
##  Max.   :7.00       Max.   :9.00        Max.   :0.5600   Max.   :0.1400       
##  defensive_pressures_applied     index       
##  Min.   :202.0               Min.   : 15.00  
##  1st Qu.:227.5               1st Qu.: 52.75  
##  Median :259.5               Median : 88.50  
##  Mean   :262.8               Mean   : 80.00  
##  3rd Qu.:298.2               3rd Qu.:115.25  
##  Max.   :328.0               Max.   :123.00
# Now, extract the mean values for all predictors in lmod_e_partial:
mean_fra = agg_france %>%
  select_if(is.numeric) %>%  
  select(-game, -goals_scored, -total_attempts) %>%   
  summarise_all(mean, na.rm = TRUE)

# vector
mean_vec_fra = round2(unlist(mean_fra), 2); mean_vec_fra
##                            assists                     conceded_goals 
##                               1.83                               0.83 
## goals_shot_inside_the_penalty_area                 on_target_attempts 
##                               2.00                               5.00 
##                off_target_attempts                         possession 
##                               6.50                               0.46 
##              possession_in_contest        defensive_pressures_applied 
##                               0.11                             262.83 
##                              index 
##                              80.00
# make it into a data frame:
combined_df = data.frame(Argentina = mean_vec_arg, 
                         France = mean_vec_fra); combined_df
##                                    Argentina France
## assists                                 1.17   1.83
## conceded_goals                          0.83   0.83
## goals_shot_inside_the_penalty_area      1.83   2.00
## on_target_attempts                      6.50   5.00
## off_target_attempts                     5.50   6.50
## possession                              0.52   0.46
## possession_in_contest                   0.12   0.11
## defensive_pressures_applied           234.67 262.83
## index                                  78.33  80.00
# Need to remove index from this predictor dataframe:
combined_df = combined_df[1:8, ]; combined_df
##                                    Argentina France
## assists                                 1.17   1.83
## conceded_goals                          0.83   0.83
## goals_shot_inside_the_penalty_area      1.83   2.00
## on_target_attempts                      6.50   5.00
## off_target_attempts                     5.50   6.50
## possession                              0.52   0.46
## possession_in_contest                   0.12   0.11
## defensive_pressures_applied           234.67 262.83
# Predict the goals scored for both Argentina and France using their
# data from the prior games played in the world cup.  
(y1 = predict(lmod_e_partial, 
             new = data.frame(t(combined_df)), 
             interval = "conf", 
             level = 0.99))
##                fit      lwr      upr
## Argentina 1.913058 1.797231 2.028885
## France    2.131839 2.017793 2.245884

There is a 99% chance that an average game between these 2 teams will result in a 2-2 tie based upon their previous games performance in this tournament.

Conclusion: The rounded expected goals is 2 & 2. At the end of the regular 90 minute period the actual finale was also 2-2!! After extra time the score was 3-3 and Argentina ended up winning in penalties (4-2).

Out of curiosity, what does the prediction look like using model b (the strongest model that did not use assists or the other troublesome predictors). Predict the goals scored for both Argentina and France using their data from the prior games played in the world cup.

# Modify the predictor dataframe:
(combined_df_model_b = combined_df["on_target_attempts",])
##                    Argentina France
## on_target_attempts       6.5      5
# Create the new prediction:
(y2 = predict(lmod_b_ontarget, 
             new = data.frame(t(combined_df_model_b)), 
             interval = "conf", 
             level = 0.99))
##                fit      lwr      upr
## Argentina 2.076584 1.716052 2.437116
## France    1.633762 1.356819 1.910705